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 <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.h"
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
845 /*
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
849 */
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s\n", git_url);
1699 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1700 server_path, verbosity);
1701 if (error)
1702 goto done;
1704 if (!list_refs_only) {
1705 error = got_repo_init(repo_path, NULL);
1706 if (error)
1707 goto done;
1708 error = got_repo_pack_fds_open(&pack_fds);
1709 if (error != NULL)
1710 goto done;
1711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1712 if (error)
1713 goto done;
1716 fpa.last_scaled_size[0] = '\0';
1717 fpa.last_p_indexed = -1;
1718 fpa.last_p_resolved = -1;
1719 fpa.verbosity = verbosity;
1720 fpa.create_configs = 1;
1721 fpa.configs_created = 0;
1722 fpa.repo = repo;
1723 fpa.config_info.symrefs = &symrefs;
1724 fpa.config_info.wanted_branches = &wanted_branches;
1725 fpa.config_info.wanted_refs = &wanted_refs;
1726 fpa.config_info.proto = proto;
1727 fpa.config_info.host = host;
1728 fpa.config_info.port = port;
1729 fpa.config_info.remote_repo_path = server_path;
1730 fpa.config_info.git_url = git_url;
1731 fpa.config_info.fetch_all_branches = fetch_all_branches;
1732 fpa.config_info.mirror_references = mirror_references;
1733 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1734 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1735 fetch_all_branches, &wanted_branches, &wanted_refs,
1736 list_refs_only, verbosity, fetchfd, repo,
1737 fetch_progress, &fpa);
1738 if (error)
1739 goto done;
1741 if (list_refs_only) {
1742 error = list_remote_refs(&symrefs, &refs);
1743 goto done;
1746 if (pack_hash == NULL) {
1747 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1748 "server sent an empty pack file");
1749 goto done;
1751 error = got_object_id_str(&id_str, pack_hash);
1752 if (error)
1753 goto done;
1754 if (verbosity >= 0)
1755 printf("\nFetched %s.pack\n", id_str);
1756 free(id_str);
1758 /* Set up references provided with the pack file. */
1759 TAILQ_FOREACH(pe, &refs, entry) {
1760 const char *refname = pe->path;
1761 struct got_object_id *id = pe->data;
1762 char *remote_refname;
1764 if (is_wanted_ref(&wanted_refs, refname) &&
1765 !mirror_references) {
1766 error = create_wanted_ref(refname, id,
1767 GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 verbosity - 1, repo);
1769 if (error)
1770 goto done;
1771 continue;
1774 error = create_ref(refname, id, verbosity - 1, repo);
1775 if (error)
1776 goto done;
1778 if (mirror_references)
1779 continue;
1781 if (strncmp("refs/heads/", refname, 11) != 0)
1782 continue;
1784 if (asprintf(&remote_refname,
1785 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1786 refname + 11) == -1) {
1787 error = got_error_from_errno("asprintf");
1788 goto done;
1790 error = create_ref(remote_refname, id, verbosity - 1, repo);
1791 free(remote_refname);
1792 if (error)
1793 goto done;
1796 /* Set the HEAD reference if the server provided one. */
1797 TAILQ_FOREACH(pe, &symrefs, entry) {
1798 struct got_reference *target_ref;
1799 const char *refname = pe->path;
1800 const char *target = pe->data;
1801 char *remote_refname = NULL, *remote_target = NULL;
1803 if (strcmp(refname, GOT_REF_HEAD) != 0)
1804 continue;
1806 error = got_ref_open(&target_ref, repo, target, 0);
1807 if (error) {
1808 if (error->code == GOT_ERR_NOT_REF) {
1809 error = NULL;
1810 continue;
1812 goto done;
1815 error = create_symref(refname, target_ref, verbosity, repo);
1816 got_ref_close(target_ref);
1817 if (error)
1818 goto done;
1820 if (mirror_references)
1821 continue;
1823 if (strncmp("refs/heads/", target, 11) != 0)
1824 continue;
1826 if (asprintf(&remote_refname,
1827 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1828 refname) == -1) {
1829 error = got_error_from_errno("asprintf");
1830 goto done;
1832 if (asprintf(&remote_target,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 target + 11) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 free(remote_refname);
1837 goto done;
1839 error = got_ref_open(&target_ref, repo, remote_target, 0);
1840 if (error) {
1841 free(remote_refname);
1842 free(remote_target);
1843 if (error->code == GOT_ERR_NOT_REF) {
1844 error = NULL;
1845 continue;
1847 goto done;
1849 error = create_symref(remote_refname, target_ref,
1850 verbosity - 1, repo);
1851 free(remote_refname);
1852 free(remote_target);
1853 got_ref_close(target_ref);
1854 if (error)
1855 goto done;
1857 if (pe == NULL) {
1859 * We failed to set the HEAD reference. If we asked for
1860 * a set of wanted branches use the first of one of those
1861 * which could be fetched instead.
1863 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1864 const char *target = pe->path;
1865 struct got_reference *target_ref;
1867 error = got_ref_open(&target_ref, repo, target, 0);
1868 if (error) {
1869 if (error->code == GOT_ERR_NOT_REF) {
1870 error = NULL;
1871 continue;
1873 goto done;
1876 error = create_symref(GOT_REF_HEAD, target_ref,
1877 verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1881 break;
1884 if (!fpa.configs_created && pe != NULL) {
1885 error = create_config_files(fpa.config_info.proto,
1886 fpa.config_info.host, fpa.config_info.port,
1887 fpa.config_info.remote_repo_path,
1888 fpa.config_info.git_url,
1889 fpa.config_info.fetch_all_branches,
1890 fpa.config_info.mirror_references,
1891 fpa.config_info.symrefs,
1892 fpa.config_info.wanted_branches,
1893 fpa.config_info.wanted_refs, fpa.repo);
1894 if (error)
1895 goto done;
1899 if (verbosity >= 0)
1900 printf("Created %s repository '%s'\n",
1901 mirror_references ? "mirrored" : "cloned", repo_path);
1902 done:
1903 if (pack_fds) {
1904 const struct got_error *pack_err =
1905 got_repo_pack_fds_close(pack_fds);
1906 if (error == NULL)
1907 error = pack_err;
1909 if (fetchpid > 0) {
1910 if (kill(fetchpid, SIGTERM) == -1)
1911 error = got_error_from_errno("kill");
1912 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1913 error = got_error_from_errno("waitpid");
1915 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1916 error = got_error_from_errno("close");
1917 if (repo) {
1918 const struct got_error *close_err = got_repo_close(repo);
1919 if (error == NULL)
1920 error = close_err;
1922 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1923 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1924 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1925 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1926 free(pack_hash);
1927 free(proto);
1928 free(host);
1929 free(port);
1930 free(server_path);
1931 free(repo_name);
1932 free(default_destdir);
1933 free(git_url);
1934 return error;
1937 static const struct got_error *
1938 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1939 int replace_tags, int verbosity, struct got_repository *repo)
1941 const struct got_error *err = NULL;
1942 char *new_id_str = NULL;
1943 struct got_object_id *old_id = NULL;
1945 err = got_object_id_str(&new_id_str, new_id);
1946 if (err)
1947 goto done;
1949 if (!replace_tags &&
1950 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1951 err = got_ref_resolve(&old_id, repo, ref);
1952 if (err)
1953 goto done;
1954 if (got_object_id_cmp(old_id, new_id) == 0)
1955 goto done;
1956 if (verbosity >= 0) {
1957 printf("Rejecting update of existing tag %s: %s\n",
1958 got_ref_get_name(ref), new_id_str);
1960 goto done;
1963 if (got_ref_is_symbolic(ref)) {
1964 if (verbosity >= 0) {
1965 printf("Replacing reference %s: %s\n",
1966 got_ref_get_name(ref),
1967 got_ref_get_symref_target(ref));
1969 err = got_ref_change_symref_to_ref(ref, new_id);
1970 if (err)
1971 goto done;
1972 err = got_ref_write(ref, repo);
1973 if (err)
1974 goto done;
1975 } else {
1976 err = got_ref_resolve(&old_id, repo, ref);
1977 if (err)
1978 goto done;
1979 if (got_object_id_cmp(old_id, new_id) == 0)
1980 goto done;
1982 err = got_ref_change_ref(ref, new_id);
1983 if (err)
1984 goto done;
1985 err = got_ref_write(ref, repo);
1986 if (err)
1987 goto done;
1990 if (verbosity >= 0)
1991 printf("Updated %s: %s\n", got_ref_get_name(ref),
1992 new_id_str);
1993 done:
1994 free(old_id);
1995 free(new_id_str);
1996 return err;
1999 static const struct got_error *
2000 update_symref(const char *refname, struct got_reference *target_ref,
2001 int verbosity, struct got_repository *repo)
2003 const struct got_error *err = NULL, *unlock_err;
2004 struct got_reference *symref;
2005 int symref_is_locked = 0;
2007 err = got_ref_open(&symref, repo, refname, 1);
2008 if (err) {
2009 if (err->code != GOT_ERR_NOT_REF)
2010 return err;
2011 err = got_ref_alloc_symref(&symref, refname, target_ref);
2012 if (err)
2013 goto done;
2015 err = got_ref_write(symref, repo);
2016 if (err)
2017 goto done;
2019 if (verbosity >= 0)
2020 printf("Created reference %s: %s\n",
2021 got_ref_get_name(symref),
2022 got_ref_get_symref_target(symref));
2023 } else {
2024 symref_is_locked = 1;
2026 if (strcmp(got_ref_get_symref_target(symref),
2027 got_ref_get_name(target_ref)) == 0)
2028 goto done;
2030 err = got_ref_change_symref(symref,
2031 got_ref_get_name(target_ref));
2032 if (err)
2033 goto done;
2035 err = got_ref_write(symref, repo);
2036 if (err)
2037 goto done;
2039 if (verbosity >= 0)
2040 printf("Updated %s: %s\n", got_ref_get_name(symref),
2041 got_ref_get_symref_target(symref));
2044 done:
2045 if (symref_is_locked) {
2046 unlock_err = got_ref_unlock(symref);
2047 if (unlock_err && err == NULL)
2048 err = unlock_err;
2050 got_ref_close(symref);
2051 return err;
2054 __dead static void
2055 usage_fetch(void)
2057 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2058 "[-R reference] [-r repository-path] [remote-repository]\n",
2059 getprogname());
2060 exit(1);
2063 static const struct got_error *
2064 delete_missing_ref(struct got_reference *ref,
2065 int verbosity, struct got_repository *repo)
2067 const struct got_error *err = NULL;
2068 struct got_object_id *id = NULL;
2069 char *id_str = NULL;
2071 if (got_ref_is_symbolic(ref)) {
2072 err = got_ref_delete(ref, repo);
2073 if (err)
2074 return err;
2075 if (verbosity >= 0) {
2076 printf("Deleted %s: %s\n",
2077 got_ref_get_name(ref),
2078 got_ref_get_symref_target(ref));
2080 } else {
2081 err = got_ref_resolve(&id, repo, ref);
2082 if (err)
2083 return err;
2084 err = got_object_id_str(&id_str, id);
2085 if (err)
2086 goto done;
2088 err = got_ref_delete(ref, repo);
2089 if (err)
2090 goto done;
2091 if (verbosity >= 0) {
2092 printf("Deleted %s: %s\n",
2093 got_ref_get_name(ref), id_str);
2096 done:
2097 free(id);
2098 free(id_str);
2099 return NULL;
2102 static const struct got_error *
2103 delete_missing_refs(struct got_pathlist_head *their_refs,
2104 struct got_pathlist_head *their_symrefs,
2105 const struct got_remote_repo *remote,
2106 int verbosity, struct got_repository *repo)
2108 const struct got_error *err = NULL, *unlock_err;
2109 struct got_reflist_head my_refs;
2110 struct got_reflist_entry *re;
2111 struct got_pathlist_entry *pe;
2112 char *remote_namespace = NULL;
2113 char *local_refname = NULL;
2115 TAILQ_INIT(&my_refs);
2117 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2118 == -1)
2119 return got_error_from_errno("asprintf");
2121 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2122 if (err)
2123 goto done;
2125 TAILQ_FOREACH(re, &my_refs, entry) {
2126 const char *refname = got_ref_get_name(re->ref);
2127 const char *their_refname;
2129 if (remote->mirror_references) {
2130 their_refname = refname;
2131 } else {
2132 if (strncmp(refname, remote_namespace,
2133 strlen(remote_namespace)) == 0) {
2134 if (strcmp(refname + strlen(remote_namespace),
2135 GOT_REF_HEAD) == 0)
2136 continue;
2137 if (asprintf(&local_refname, "refs/heads/%s",
2138 refname + strlen(remote_namespace)) == -1) {
2139 err = got_error_from_errno("asprintf");
2140 goto done;
2142 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2143 continue;
2145 their_refname = local_refname;
2148 TAILQ_FOREACH(pe, their_refs, entry) {
2149 if (strcmp(their_refname, pe->path) == 0)
2150 break;
2152 if (pe != NULL)
2153 continue;
2155 TAILQ_FOREACH(pe, their_symrefs, entry) {
2156 if (strcmp(their_refname, pe->path) == 0)
2157 break;
2159 if (pe != NULL)
2160 continue;
2162 err = delete_missing_ref(re->ref, verbosity, repo);
2163 if (err)
2164 break;
2166 if (local_refname) {
2167 struct got_reference *ref;
2168 err = got_ref_open(&ref, repo, local_refname, 1);
2169 if (err) {
2170 if (err->code != GOT_ERR_NOT_REF)
2171 break;
2172 free(local_refname);
2173 local_refname = NULL;
2174 continue;
2176 err = delete_missing_ref(ref, verbosity, repo);
2177 if (err)
2178 break;
2179 unlock_err = got_ref_unlock(ref);
2180 got_ref_close(ref);
2181 if (unlock_err && err == NULL) {
2182 err = unlock_err;
2183 break;
2186 free(local_refname);
2187 local_refname = NULL;
2190 done:
2191 got_ref_list_free(&my_refs);
2192 free(remote_namespace);
2193 free(local_refname);
2194 return err;
2197 static const struct got_error *
2198 update_wanted_ref(const char *refname, struct got_object_id *id,
2199 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2201 const struct got_error *err, *unlock_err;
2202 char *remote_refname;
2203 struct got_reference *ref;
2205 if (strncmp("refs/", refname, 5) == 0)
2206 refname += 5;
2208 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2209 remote_repo_name, refname) == -1)
2210 return got_error_from_errno("asprintf");
2212 err = got_ref_open(&ref, repo, remote_refname, 1);
2213 if (err) {
2214 if (err->code != GOT_ERR_NOT_REF)
2215 goto done;
2216 err = create_ref(remote_refname, id, verbosity, repo);
2217 } else {
2218 err = update_ref(ref, id, 0, verbosity, repo);
2219 unlock_err = got_ref_unlock(ref);
2220 if (unlock_err && err == NULL)
2221 err = unlock_err;
2222 got_ref_close(ref);
2224 done:
2225 free(remote_refname);
2226 return err;
2229 static const struct got_error *
2230 delete_ref(struct got_repository *repo, struct got_reference *ref)
2232 const struct got_error *err = NULL;
2233 struct got_object_id *id = NULL;
2234 char *id_str = NULL;
2235 const char *target;
2237 if (got_ref_is_symbolic(ref)) {
2238 target = got_ref_get_symref_target(ref);
2239 } else {
2240 err = got_ref_resolve(&id, repo, ref);
2241 if (err)
2242 goto done;
2243 err = got_object_id_str(&id_str, id);
2244 if (err)
2245 goto done;
2246 target = id_str;
2249 err = got_ref_delete(ref, repo);
2250 if (err)
2251 goto done;
2253 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2254 done:
2255 free(id);
2256 free(id_str);
2257 return err;
2260 static const struct got_error *
2261 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2263 const struct got_error *err = NULL;
2264 struct got_reflist_head refs;
2265 struct got_reflist_entry *re;
2266 char *prefix;
2268 TAILQ_INIT(&refs);
2270 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2271 err = got_error_from_errno("asprintf");
2272 goto done;
2274 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2275 if (err)
2276 goto done;
2278 TAILQ_FOREACH(re, &refs, entry)
2279 delete_ref(repo, re->ref);
2280 done:
2281 got_ref_list_free(&refs);
2282 return err;
2285 static const struct got_error *
2286 cmd_fetch(int argc, char *argv[])
2288 const struct got_error *error = NULL, *unlock_err;
2289 char *cwd = NULL, *repo_path = NULL;
2290 const char *remote_name;
2291 char *proto = NULL, *host = NULL, *port = NULL;
2292 char *repo_name = NULL, *server_path = NULL;
2293 const struct got_remote_repo *remotes, *remote = NULL;
2294 int nremotes;
2295 char *id_str = NULL;
2296 struct got_repository *repo = NULL;
2297 struct got_worktree *worktree = NULL;
2298 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2299 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2300 struct got_pathlist_entry *pe;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL;
2309 TAILQ_INIT(&refs);
2310 TAILQ_INIT(&symrefs);
2311 TAILQ_INIT(&wanted_branches);
2312 TAILQ_INIT(&wanted_refs);
2314 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2315 switch (ch) {
2316 case 'a':
2317 fetch_all_branches = 1;
2318 break;
2319 case 'b':
2320 error = got_pathlist_append(&wanted_branches,
2321 optarg, NULL);
2322 if (error)
2323 return error;
2324 break;
2325 case 'd':
2326 delete_refs = 1;
2327 break;
2328 case 'l':
2329 list_refs_only = 1;
2330 break;
2331 case 'q':
2332 verbosity = -1;
2333 break;
2334 case 'R':
2335 error = got_pathlist_append(&wanted_refs,
2336 optarg, NULL);
2337 if (error)
2338 return error;
2339 break;
2340 case 'r':
2341 repo_path = realpath(optarg, NULL);
2342 if (repo_path == NULL)
2343 return got_error_from_errno2("realpath",
2344 optarg);
2345 got_path_strip_trailing_slashes(repo_path);
2346 break;
2347 case 't':
2348 replace_tags = 1;
2349 break;
2350 case 'v':
2351 if (verbosity < 0)
2352 verbosity = 0;
2353 else if (verbosity < 3)
2354 verbosity++;
2355 break;
2356 case 'X':
2357 delete_remote = 1;
2358 break;
2359 default:
2360 usage_fetch();
2361 break;
2364 argc -= optind;
2365 argv += optind;
2367 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2368 option_conflict('a', 'b');
2369 if (list_refs_only) {
2370 if (!TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('l', 'b');
2372 if (fetch_all_branches)
2373 option_conflict('l', 'a');
2374 if (delete_refs)
2375 option_conflict('l', 'd');
2376 if (delete_remote)
2377 option_conflict('l', 'X');
2379 if (delete_remote) {
2380 if (fetch_all_branches)
2381 option_conflict('X', 'a');
2382 if (!TAILQ_EMPTY(&wanted_branches))
2383 option_conflict('X', 'b');
2384 if (delete_refs)
2385 option_conflict('X', 'd');
2386 if (replace_tags)
2387 option_conflict('X', 't');
2388 if (!TAILQ_EMPTY(&wanted_refs))
2389 option_conflict('X', 'R');
2392 if (argc == 0) {
2393 if (delete_remote)
2394 errx(1, "-X option requires a remote name");
2395 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2396 } else if (argc == 1)
2397 remote_name = argv[0];
2398 else
2399 usage_fetch();
2401 cwd = getcwd(NULL, 0);
2402 if (cwd == NULL) {
2403 error = got_error_from_errno("getcwd");
2404 goto done;
2407 error = got_repo_pack_fds_open(&pack_fds);
2408 if (error != NULL)
2409 goto done;
2411 if (repo_path == NULL) {
2412 error = got_worktree_open(&worktree, cwd);
2413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2414 goto done;
2415 else
2416 error = NULL;
2417 if (worktree) {
2418 repo_path =
2419 strdup(got_worktree_get_repo_path(worktree));
2420 if (repo_path == NULL)
2421 error = got_error_from_errno("strdup");
2422 if (error)
2423 goto done;
2424 } else {
2425 repo_path = strdup(cwd);
2426 if (repo_path == NULL) {
2427 error = got_error_from_errno("strdup");
2428 goto done;
2433 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2434 if (error)
2435 goto done;
2437 if (delete_remote) {
2438 error = delete_refs_for_remote(repo, remote_name);
2439 goto done; /* nothing else to do */
2442 if (worktree) {
2443 worktree_conf = got_worktree_get_gotconfig(worktree);
2444 if (worktree_conf) {
2445 got_gotconfig_get_remotes(&nremotes, &remotes,
2446 worktree_conf);
2447 for (i = 0; i < nremotes; i++) {
2448 if (strcmp(remotes[i].name, remote_name) == 0) {
2449 remote = &remotes[i];
2450 break;
2455 if (remote == NULL) {
2456 repo_conf = got_repo_get_gotconfig(repo);
2457 if (repo_conf) {
2458 got_gotconfig_get_remotes(&nremotes, &remotes,
2459 repo_conf);
2460 for (i = 0; i < nremotes; i++) {
2461 if (strcmp(remotes[i].name, remote_name) == 0) {
2462 remote = &remotes[i];
2463 break;
2468 if (remote == NULL) {
2469 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2470 for (i = 0; i < nremotes; i++) {
2471 if (strcmp(remotes[i].name, remote_name) == 0) {
2472 remote = &remotes[i];
2473 break;
2477 if (remote == NULL) {
2478 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2479 goto done;
2482 if (TAILQ_EMPTY(&wanted_branches)) {
2483 if (!fetch_all_branches)
2484 fetch_all_branches = remote->fetch_all_branches;
2485 for (i = 0; i < remote->nfetch_branches; i++) {
2486 got_pathlist_append(&wanted_branches,
2487 remote->fetch_branches[i], NULL);
2490 if (TAILQ_EMPTY(&wanted_refs)) {
2491 for (i = 0; i < remote->nfetch_refs; i++) {
2492 got_pathlist_append(&wanted_refs,
2493 remote->fetch_refs[i], NULL);
2497 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2498 &repo_name, remote->fetch_url);
2499 if (error)
2500 goto done;
2502 if (strcmp(proto, "git") == 0) {
2503 #ifndef PROFILE
2504 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2505 "sendfd dns inet unveil", NULL) == -1)
2506 err(1, "pledge");
2507 #endif
2508 } else if (strcmp(proto, "git+ssh") == 0 ||
2509 strcmp(proto, "ssh") == 0) {
2510 #ifndef PROFILE
2511 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2512 "sendfd unveil", NULL) == -1)
2513 err(1, "pledge");
2514 #endif
2515 } else if (strcmp(proto, "http") == 0 ||
2516 strcmp(proto, "git+http") == 0) {
2517 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2518 goto done;
2519 } else {
2520 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2521 goto done;
2524 error = got_dial_apply_unveil(proto);
2525 if (error)
2526 goto done;
2528 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2529 if (error)
2530 goto done;
2532 if (verbosity >= 0) {
2533 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2534 remote->name, proto, host,
2535 port ? ":" : "", port ? port : "",
2536 *server_path == '/' ? "" : "/", server_path);
2539 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2540 server_path, verbosity);
2541 if (error)
2542 goto done;
2544 fpa.last_scaled_size[0] = '\0';
2545 fpa.last_p_indexed = -1;
2546 fpa.last_p_resolved = -1;
2547 fpa.verbosity = verbosity;
2548 fpa.repo = repo;
2549 fpa.create_configs = 0;
2550 fpa.configs_created = 0;
2551 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2552 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2553 remote->mirror_references, fetch_all_branches, &wanted_branches,
2554 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2555 fetch_progress, &fpa);
2556 if (error)
2557 goto done;
2559 if (list_refs_only) {
2560 error = list_remote_refs(&symrefs, &refs);
2561 goto done;
2564 if (pack_hash == NULL) {
2565 if (verbosity >= 0)
2566 printf("Already up-to-date\n");
2567 } else if (verbosity >= 0) {
2568 error = got_object_id_str(&id_str, pack_hash);
2569 if (error)
2570 goto done;
2571 printf("\nFetched %s.pack\n", id_str);
2572 free(id_str);
2573 id_str = NULL;
2576 /* Update references provided with the pack file. */
2577 TAILQ_FOREACH(pe, &refs, entry) {
2578 const char *refname = pe->path;
2579 struct got_object_id *id = pe->data;
2580 struct got_reference *ref;
2581 char *remote_refname;
2583 if (is_wanted_ref(&wanted_refs, refname) &&
2584 !remote->mirror_references) {
2585 error = update_wanted_ref(refname, id,
2586 remote->name, verbosity, repo);
2587 if (error)
2588 goto done;
2589 continue;
2592 if (remote->mirror_references ||
2593 strncmp("refs/tags/", refname, 10) == 0) {
2594 error = got_ref_open(&ref, repo, refname, 1);
2595 if (error) {
2596 if (error->code != GOT_ERR_NOT_REF)
2597 goto done;
2598 error = create_ref(refname, id, verbosity,
2599 repo);
2600 if (error)
2601 goto done;
2602 } else {
2603 error = update_ref(ref, id, replace_tags,
2604 verbosity, repo);
2605 unlock_err = got_ref_unlock(ref);
2606 if (unlock_err && error == NULL)
2607 error = unlock_err;
2608 got_ref_close(ref);
2609 if (error)
2610 goto done;
2612 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2613 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2614 remote_name, refname + 11) == -1) {
2615 error = got_error_from_errno("asprintf");
2616 goto done;
2619 error = got_ref_open(&ref, repo, remote_refname, 1);
2620 if (error) {
2621 if (error->code != GOT_ERR_NOT_REF)
2622 goto done;
2623 error = create_ref(remote_refname, id,
2624 verbosity, repo);
2625 if (error)
2626 goto done;
2627 } else {
2628 error = update_ref(ref, id, replace_tags,
2629 verbosity, repo);
2630 unlock_err = got_ref_unlock(ref);
2631 if (unlock_err && error == NULL)
2632 error = unlock_err;
2633 got_ref_close(ref);
2634 if (error)
2635 goto done;
2638 /* Also create a local branch if none exists yet. */
2639 error = got_ref_open(&ref, repo, refname, 1);
2640 if (error) {
2641 if (error->code != GOT_ERR_NOT_REF)
2642 goto done;
2643 error = create_ref(refname, id, verbosity,
2644 repo);
2645 if (error)
2646 goto done;
2647 } else {
2648 unlock_err = got_ref_unlock(ref);
2649 if (unlock_err && error == NULL)
2650 error = unlock_err;
2651 got_ref_close(ref);
2655 if (delete_refs) {
2656 error = delete_missing_refs(&refs, &symrefs, remote,
2657 verbosity, repo);
2658 if (error)
2659 goto done;
2662 if (!remote->mirror_references) {
2663 /* Update remote HEAD reference if the server provided one. */
2664 TAILQ_FOREACH(pe, &symrefs, entry) {
2665 struct got_reference *target_ref;
2666 const char *refname = pe->path;
2667 const char *target = pe->data;
2668 char *remote_refname = NULL, *remote_target = NULL;
2670 if (strcmp(refname, GOT_REF_HEAD) != 0)
2671 continue;
2673 if (strncmp("refs/heads/", target, 11) != 0)
2674 continue;
2676 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2677 remote->name, refname) == -1) {
2678 error = got_error_from_errno("asprintf");
2679 goto done;
2681 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2682 remote->name, target + 11) == -1) {
2683 error = got_error_from_errno("asprintf");
2684 free(remote_refname);
2685 goto done;
2688 error = got_ref_open(&target_ref, repo, remote_target,
2689 0);
2690 if (error) {
2691 free(remote_refname);
2692 free(remote_target);
2693 if (error->code == GOT_ERR_NOT_REF) {
2694 error = NULL;
2695 continue;
2697 goto done;
2699 error = update_symref(remote_refname, target_ref,
2700 verbosity, repo);
2701 free(remote_refname);
2702 free(remote_target);
2703 got_ref_close(target_ref);
2704 if (error)
2705 goto done;
2708 done:
2709 if (fetchpid > 0) {
2710 if (kill(fetchpid, SIGTERM) == -1)
2711 error = got_error_from_errno("kill");
2712 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2713 error = got_error_from_errno("waitpid");
2715 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2716 error = got_error_from_errno("close");
2717 if (repo) {
2718 const struct got_error *close_err = got_repo_close(repo);
2719 if (error == NULL)
2720 error = close_err;
2722 if (worktree)
2723 got_worktree_close(worktree);
2724 if (pack_fds) {
2725 const struct got_error *pack_err =
2726 got_repo_pack_fds_close(pack_fds);
2727 if (error == NULL)
2728 error = pack_err;
2730 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2731 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2732 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2733 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2734 free(id_str);
2735 free(cwd);
2736 free(repo_path);
2737 free(pack_hash);
2738 free(proto);
2739 free(host);
2740 free(port);
2741 free(server_path);
2742 free(repo_name);
2743 return error;
2747 __dead static void
2748 usage_checkout(void)
2750 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2751 "[-p path-prefix] repository-path [work-tree-path]\n",
2752 getprogname());
2753 exit(1);
2756 static void
2757 show_worktree_base_ref_warning(void)
2759 fprintf(stderr, "%s: warning: could not create a reference "
2760 "to the work tree's base commit; the commit could be "
2761 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2762 "repository writable and running 'got update' will prevent this\n",
2763 getprogname());
2766 struct got_checkout_progress_arg {
2767 const char *worktree_path;
2768 int had_base_commit_ref_error;
2769 int verbosity;
2772 static const struct got_error *
2773 checkout_progress(void *arg, unsigned char status, const char *path)
2775 struct got_checkout_progress_arg *a = arg;
2777 /* Base commit bump happens silently. */
2778 if (status == GOT_STATUS_BUMP_BASE)
2779 return NULL;
2781 if (status == GOT_STATUS_BASE_REF_ERR) {
2782 a->had_base_commit_ref_error = 1;
2783 return NULL;
2786 while (path[0] == '/')
2787 path++;
2789 if (a->verbosity >= 0)
2790 printf("%c %s/%s\n", status, a->worktree_path, path);
2792 return NULL;
2795 static const struct got_error *
2796 check_cancelled(void *arg)
2798 if (sigint_received || sigpipe_received)
2799 return got_error(GOT_ERR_CANCELLED);
2800 return NULL;
2803 static const struct got_error *
2804 check_linear_ancestry(struct got_object_id *commit_id,
2805 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2806 struct got_repository *repo)
2808 const struct got_error *err = NULL;
2809 struct got_object_id *yca_id;
2811 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2812 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2813 if (err)
2814 return err;
2816 if (yca_id == NULL)
2817 return got_error(GOT_ERR_ANCESTRY);
2820 * Require a straight line of history between the target commit
2821 * and the work tree's base commit.
2823 * Non-linear situations such as this require a rebase:
2825 * (commit) D F (base_commit)
2826 * \ /
2827 * C E
2828 * \ /
2829 * B (yca)
2830 * |
2831 * A
2833 * 'got update' only handles linear cases:
2834 * Update forwards in time: A (base/yca) - B - C - D (commit)
2835 * Update backwards in time: D (base) - C - B - A (commit/yca)
2837 if (allow_forwards_in_time_only) {
2838 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2839 return got_error(GOT_ERR_ANCESTRY);
2840 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2841 got_object_id_cmp(base_commit_id, yca_id) != 0)
2842 return got_error(GOT_ERR_ANCESTRY);
2844 free(yca_id);
2845 return NULL;
2848 static const struct got_error *
2849 check_same_branch(struct got_object_id *commit_id,
2850 struct got_reference *head_ref, struct got_object_id *yca_id,
2851 struct got_repository *repo)
2853 const struct got_error *err = NULL;
2854 struct got_commit_graph *graph = NULL;
2855 struct got_object_id *head_commit_id = NULL;
2856 int is_same_branch = 0;
2858 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2859 if (err)
2860 goto done;
2862 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2863 is_same_branch = 1;
2864 goto done;
2866 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2871 err = got_commit_graph_open(&graph, "/", 1);
2872 if (err)
2873 goto done;
2875 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2876 check_cancelled, NULL);
2877 if (err)
2878 goto done;
2880 for (;;) {
2881 struct got_object_id id;
2883 err = got_commit_graph_iter_next(&id, graph, repo,
2884 check_cancelled, NULL);
2885 if (err) {
2886 if (err->code == GOT_ERR_ITER_COMPLETED)
2887 err = NULL;
2888 break;
2891 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2892 break;
2893 if (got_object_id_cmp(&id, commit_id) == 0) {
2894 is_same_branch = 1;
2895 break;
2898 done:
2899 if (graph)
2900 got_commit_graph_close(graph);
2901 free(head_commit_id);
2902 if (!err && !is_same_branch)
2903 err = got_error(GOT_ERR_ANCESTRY);
2904 return err;
2907 static const struct got_error *
2908 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2910 static char msg[512];
2911 const char *branch_name;
2913 if (got_ref_is_symbolic(ref))
2914 branch_name = got_ref_get_symref_target(ref);
2915 else
2916 branch_name = got_ref_get_name(ref);
2918 if (strncmp("refs/heads/", branch_name, 11) == 0)
2919 branch_name += 11;
2921 snprintf(msg, sizeof(msg),
2922 "target commit is not contained in branch '%s'; "
2923 "the branch to use must be specified with -b; "
2924 "if necessary a new branch can be created for "
2925 "this commit with 'got branch -c %s BRANCH_NAME'",
2926 branch_name, commit_id_str);
2928 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2931 static const struct got_error *
2932 cmd_checkout(int argc, char *argv[])
2934 const struct got_error *error = NULL;
2935 struct got_repository *repo = NULL;
2936 struct got_reference *head_ref = NULL, *ref = NULL;
2937 struct got_worktree *worktree = NULL;
2938 char *repo_path = NULL;
2939 char *worktree_path = NULL;
2940 const char *path_prefix = "";
2941 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2942 char *commit_id_str = NULL;
2943 struct got_object_id *commit_id = NULL;
2944 char *cwd = NULL;
2945 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2946 struct got_pathlist_head paths;
2947 struct got_checkout_progress_arg cpa;
2948 int *pack_fds = NULL;
2950 TAILQ_INIT(&paths);
2952 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2953 switch (ch) {
2954 case 'b':
2955 branch_name = optarg;
2956 break;
2957 case 'c':
2958 commit_id_str = strdup(optarg);
2959 if (commit_id_str == NULL)
2960 return got_error_from_errno("strdup");
2961 break;
2962 case 'E':
2963 allow_nonempty = 1;
2964 break;
2965 case 'p':
2966 path_prefix = optarg;
2967 break;
2968 case 'q':
2969 verbosity = -1;
2970 break;
2971 default:
2972 usage_checkout();
2973 /* NOTREACHED */
2977 argc -= optind;
2978 argv += optind;
2980 #ifndef PROFILE
2981 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2982 "unveil", NULL) == -1)
2983 err(1, "pledge");
2984 #endif
2985 if (argc == 1) {
2986 char *base, *dotgit;
2987 const char *path;
2988 repo_path = realpath(argv[0], NULL);
2989 if (repo_path == NULL)
2990 return got_error_from_errno2("realpath", argv[0]);
2991 cwd = getcwd(NULL, 0);
2992 if (cwd == NULL) {
2993 error = got_error_from_errno("getcwd");
2994 goto done;
2996 if (path_prefix[0])
2997 path = path_prefix;
2998 else
2999 path = repo_path;
3000 error = got_path_basename(&base, path);
3001 if (error)
3002 goto done;
3003 dotgit = strstr(base, ".git");
3004 if (dotgit)
3005 *dotgit = '\0';
3006 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3007 error = got_error_from_errno("asprintf");
3008 free(base);
3009 goto done;
3011 free(base);
3012 } else if (argc == 2) {
3013 repo_path = realpath(argv[0], NULL);
3014 if (repo_path == NULL) {
3015 error = got_error_from_errno2("realpath", argv[0]);
3016 goto done;
3018 worktree_path = realpath(argv[1], NULL);
3019 if (worktree_path == NULL) {
3020 if (errno != ENOENT) {
3021 error = got_error_from_errno2("realpath",
3022 argv[1]);
3023 goto done;
3025 worktree_path = strdup(argv[1]);
3026 if (worktree_path == NULL) {
3027 error = got_error_from_errno("strdup");
3028 goto done;
3031 } else
3032 usage_checkout();
3034 got_path_strip_trailing_slashes(repo_path);
3035 got_path_strip_trailing_slashes(worktree_path);
3037 error = got_repo_pack_fds_open(&pack_fds);
3038 if (error != NULL)
3039 goto done;
3041 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3042 if (error != NULL)
3043 goto done;
3045 /* Pre-create work tree path for unveil(2) */
3046 error = got_path_mkdir(worktree_path);
3047 if (error) {
3048 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3049 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3050 goto done;
3051 if (!allow_nonempty &&
3052 !got_path_dir_is_empty(worktree_path)) {
3053 error = got_error_path(worktree_path,
3054 GOT_ERR_DIR_NOT_EMPTY);
3055 goto done;
3059 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3060 if (error)
3061 goto done;
3063 error = got_ref_open(&head_ref, repo, branch_name, 0);
3064 if (error != NULL)
3065 goto done;
3067 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3068 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3069 goto done;
3071 error = got_worktree_open(&worktree, worktree_path);
3072 if (error != NULL)
3073 goto done;
3075 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3076 path_prefix);
3077 if (error != NULL)
3078 goto done;
3079 if (!same_path_prefix) {
3080 error = got_error(GOT_ERR_PATH_PREFIX);
3081 goto done;
3084 if (commit_id_str) {
3085 struct got_reflist_head refs;
3086 TAILQ_INIT(&refs);
3087 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3088 NULL);
3089 if (error)
3090 goto done;
3091 error = got_repo_match_object_id(&commit_id, NULL,
3092 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3093 got_ref_list_free(&refs);
3094 if (error)
3095 goto done;
3096 error = check_linear_ancestry(commit_id,
3097 got_worktree_get_base_commit_id(worktree), 0, repo);
3098 if (error != NULL) {
3099 if (error->code == GOT_ERR_ANCESTRY) {
3100 error = checkout_ancestry_error(
3101 head_ref, commit_id_str);
3103 goto done;
3105 error = check_same_branch(commit_id, head_ref, NULL, repo);
3106 if (error) {
3107 if (error->code == GOT_ERR_ANCESTRY) {
3108 error = checkout_ancestry_error(
3109 head_ref, commit_id_str);
3111 goto done;
3113 error = got_worktree_set_base_commit_id(worktree, repo,
3114 commit_id);
3115 if (error)
3116 goto done;
3117 /* Expand potentially abbreviated commit ID string. */
3118 free(commit_id_str);
3119 error = got_object_id_str(&commit_id_str, commit_id);
3120 if (error)
3121 goto done;
3122 } else {
3123 commit_id = got_object_id_dup(
3124 got_worktree_get_base_commit_id(worktree));
3125 if (commit_id == NULL) {
3126 error = got_error_from_errno("got_object_id_dup");
3127 goto done;
3129 error = got_object_id_str(&commit_id_str, commit_id);
3130 if (error)
3131 goto done;
3134 error = got_pathlist_append(&paths, "", NULL);
3135 if (error)
3136 goto done;
3137 cpa.worktree_path = worktree_path;
3138 cpa.had_base_commit_ref_error = 0;
3139 cpa.verbosity = verbosity;
3140 error = got_worktree_checkout_files(worktree, &paths, repo,
3141 checkout_progress, &cpa, check_cancelled, NULL);
3142 if (error != NULL)
3143 goto done;
3145 if (got_ref_is_symbolic(head_ref)) {
3146 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3147 if (error)
3148 goto done;
3149 refname = got_ref_get_name(ref);
3150 } else
3151 refname = got_ref_get_name(head_ref);
3152 printf("Checked out %s: %s\n", refname, commit_id_str);
3153 printf("Now shut up and hack\n");
3154 if (cpa.had_base_commit_ref_error)
3155 show_worktree_base_ref_warning();
3156 done:
3157 if (pack_fds) {
3158 const struct got_error *pack_err =
3159 got_repo_pack_fds_close(pack_fds);
3160 if (error == NULL)
3161 error = pack_err;
3163 if (head_ref)
3164 got_ref_close(head_ref);
3165 if (ref)
3166 got_ref_close(ref);
3167 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3168 free(commit_id_str);
3169 free(commit_id);
3170 free(repo_path);
3171 free(worktree_path);
3172 free(cwd);
3173 return error;
3176 struct got_update_progress_arg {
3177 int did_something;
3178 int conflicts;
3179 int obstructed;
3180 int not_updated;
3181 int missing;
3182 int not_deleted;
3183 int unversioned;
3184 int verbosity;
3187 static void
3188 print_update_progress_stats(struct got_update_progress_arg *upa)
3190 if (!upa->did_something)
3191 return;
3193 if (upa->conflicts > 0)
3194 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3195 if (upa->obstructed > 0)
3196 printf("File paths obstructed by a non-regular file: %d\n",
3197 upa->obstructed);
3198 if (upa->not_updated > 0)
3199 printf("Files not updated because of existing merge "
3200 "conflicts: %d\n", upa->not_updated);
3204 * The meaning of some status codes differs between merge-style operations and
3205 * update operations. For example, the ! status code means "file was missing"
3206 * if changes were merged into the work tree, and "missing file was restored"
3207 * if the work tree was updated. This function should be used by any operation
3208 * which merges changes into the work tree without updating the work tree.
3210 static void
3211 print_merge_progress_stats(struct got_update_progress_arg *upa)
3213 if (!upa->did_something)
3214 return;
3216 if (upa->conflicts > 0)
3217 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3218 if (upa->obstructed > 0)
3219 printf("File paths obstructed by a non-regular file: %d\n",
3220 upa->obstructed);
3221 if (upa->missing > 0)
3222 printf("Files which had incoming changes but could not be "
3223 "found in the work tree: %d\n", upa->missing);
3224 if (upa->not_deleted > 0)
3225 printf("Files not deleted due to differences in deleted "
3226 "content: %d\n", upa->not_deleted);
3227 if (upa->unversioned > 0)
3228 printf("Files not merged because an unversioned file was "
3229 "found in the work tree: %d\n", upa->unversioned);
3232 __dead static void
3233 usage_update(void)
3235 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3236 "[path ...]\n", getprogname());
3237 exit(1);
3240 static const struct got_error *
3241 update_progress(void *arg, unsigned char status, const char *path)
3243 struct got_update_progress_arg *upa = arg;
3245 if (status == GOT_STATUS_EXISTS ||
3246 status == GOT_STATUS_BASE_REF_ERR)
3247 return NULL;
3249 upa->did_something = 1;
3251 /* Base commit bump happens silently. */
3252 if (status == GOT_STATUS_BUMP_BASE)
3253 return NULL;
3255 if (status == GOT_STATUS_CONFLICT)
3256 upa->conflicts++;
3257 if (status == GOT_STATUS_OBSTRUCTED)
3258 upa->obstructed++;
3259 if (status == GOT_STATUS_CANNOT_UPDATE)
3260 upa->not_updated++;
3261 if (status == GOT_STATUS_MISSING)
3262 upa->missing++;
3263 if (status == GOT_STATUS_CANNOT_DELETE)
3264 upa->not_deleted++;
3265 if (status == GOT_STATUS_UNVERSIONED)
3266 upa->unversioned++;
3268 while (path[0] == '/')
3269 path++;
3270 if (upa->verbosity >= 0)
3271 printf("%c %s\n", status, path);
3273 return NULL;
3276 static const struct got_error *
3277 switch_head_ref(struct got_reference *head_ref,
3278 struct got_object_id *commit_id, struct got_worktree *worktree,
3279 struct got_repository *repo)
3281 const struct got_error *err = NULL;
3282 char *base_id_str;
3283 int ref_has_moved = 0;
3285 /* Trivial case: switching between two different references. */
3286 if (strcmp(got_ref_get_name(head_ref),
3287 got_worktree_get_head_ref_name(worktree)) != 0) {
3288 printf("Switching work tree from %s to %s\n",
3289 got_worktree_get_head_ref_name(worktree),
3290 got_ref_get_name(head_ref));
3291 return got_worktree_set_head_ref(worktree, head_ref);
3294 err = check_linear_ancestry(commit_id,
3295 got_worktree_get_base_commit_id(worktree), 0, repo);
3296 if (err) {
3297 if (err->code != GOT_ERR_ANCESTRY)
3298 return err;
3299 ref_has_moved = 1;
3301 if (!ref_has_moved)
3302 return NULL;
3304 /* Switching to a rebased branch with the same reference name. */
3305 err = got_object_id_str(&base_id_str,
3306 got_worktree_get_base_commit_id(worktree));
3307 if (err)
3308 return err;
3309 printf("Reference %s now points at a different branch\n",
3310 got_worktree_get_head_ref_name(worktree));
3311 printf("Switching work tree from %s to %s\n", base_id_str,
3312 got_worktree_get_head_ref_name(worktree));
3313 return NULL;
3316 static const struct got_error *
3317 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3319 const struct got_error *err;
3320 int in_progress;
3322 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3323 if (err)
3324 return err;
3325 if (in_progress)
3326 return got_error(GOT_ERR_REBASING);
3328 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_HISTEDIT_BUSY);
3334 return NULL;
3337 static const struct got_error *
3338 check_merge_in_progress(struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err;
3342 int in_progress;
3344 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_MERGE_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3355 char *argv[], struct got_worktree *worktree)
3357 const struct got_error *err = NULL;
3358 char *path;
3359 struct got_pathlist_entry *new;
3360 int i;
3362 if (argc == 0) {
3363 path = strdup("");
3364 if (path == NULL)
3365 return got_error_from_errno("strdup");
3366 return got_pathlist_append(paths, path, NULL);
3369 for (i = 0; i < argc; i++) {
3370 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3371 if (err)
3372 break;
3373 err = got_pathlist_insert(&new, paths, path, NULL);
3374 if (err || new == NULL /* duplicate */) {
3375 free(path);
3376 if (err)
3377 break;
3381 return err;
3384 static const struct got_error *
3385 wrap_not_worktree_error(const struct got_error *orig_err,
3386 const char *cmdname, const char *path)
3388 const struct got_error *err;
3389 struct got_repository *repo;
3390 static char msg[512];
3391 int *pack_fds = NULL;
3393 err = got_repo_pack_fds_open(&pack_fds);
3394 if (err)
3395 return err;
3397 err = got_repo_open(&repo, path, NULL, pack_fds);
3398 if (err)
3399 return orig_err;
3401 snprintf(msg, sizeof(msg),
3402 "'got %s' needs a work tree in addition to a git repository\n"
3403 "Work trees can be checked out from this Git repository with "
3404 "'got checkout'.\n"
3405 "The got(1) manual page contains more information.", cmdname);
3406 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3407 got_repo_close(repo);
3408 if (pack_fds) {
3409 const struct got_error *pack_err =
3410 got_repo_pack_fds_close(pack_fds);
3411 if (err == NULL)
3412 err = pack_err;
3414 return err;
3417 static const struct got_error *
3418 cmd_update(int argc, char *argv[])
3420 const struct got_error *error = NULL;
3421 struct got_repository *repo = NULL;
3422 struct got_worktree *worktree = NULL;
3423 char *worktree_path = NULL;
3424 struct got_object_id *commit_id = NULL;
3425 char *commit_id_str = NULL;
3426 const char *branch_name = NULL;
3427 struct got_reference *head_ref = NULL;
3428 struct got_pathlist_head paths;
3429 struct got_pathlist_entry *pe;
3430 int ch, verbosity = 0;
3431 struct got_update_progress_arg upa;
3432 int *pack_fds = NULL;
3434 TAILQ_INIT(&paths);
3436 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3437 switch (ch) {
3438 case 'b':
3439 branch_name = optarg;
3440 break;
3441 case 'c':
3442 commit_id_str = strdup(optarg);
3443 if (commit_id_str == NULL)
3444 return got_error_from_errno("strdup");
3445 break;
3446 case 'q':
3447 verbosity = -1;
3448 break;
3449 default:
3450 usage_update();
3451 /* NOTREACHED */
3455 argc -= optind;
3456 argv += optind;
3458 #ifndef PROFILE
3459 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3460 "unveil", NULL) == -1)
3461 err(1, "pledge");
3462 #endif
3463 worktree_path = getcwd(NULL, 0);
3464 if (worktree_path == NULL) {
3465 error = got_error_from_errno("getcwd");
3466 goto done;
3469 error = got_repo_pack_fds_open(&pack_fds);
3470 if (error != NULL)
3471 goto done;
3473 error = got_worktree_open(&worktree, worktree_path);
3474 if (error) {
3475 if (error->code == GOT_ERR_NOT_WORKTREE)
3476 error = wrap_not_worktree_error(error, "update",
3477 worktree_path);
3478 goto done;
3481 error = check_rebase_or_histedit_in_progress(worktree);
3482 if (error)
3483 goto done;
3485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3486 NULL, pack_fds);
3487 if (error != NULL)
3488 goto done;
3490 error = apply_unveil(got_repo_get_path(repo), 0,
3491 got_worktree_get_root_path(worktree));
3492 if (error)
3493 goto done;
3495 error = check_merge_in_progress(worktree, repo);
3496 if (error)
3497 goto done;
3499 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3500 if (error)
3501 goto done;
3503 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3504 got_worktree_get_head_ref_name(worktree), 0);
3505 if (error != NULL)
3506 goto done;
3507 if (commit_id_str == NULL) {
3508 error = got_ref_resolve(&commit_id, repo, head_ref);
3509 if (error != NULL)
3510 goto done;
3511 error = got_object_id_str(&commit_id_str, commit_id);
3512 if (error != NULL)
3513 goto done;
3514 } else {
3515 struct got_reflist_head refs;
3516 TAILQ_INIT(&refs);
3517 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3518 NULL);
3519 if (error)
3520 goto done;
3521 error = got_repo_match_object_id(&commit_id, NULL,
3522 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3523 got_ref_list_free(&refs);
3524 free(commit_id_str);
3525 commit_id_str = NULL;
3526 if (error)
3527 goto done;
3528 error = got_object_id_str(&commit_id_str, commit_id);
3529 if (error)
3530 goto done;
3533 if (branch_name) {
3534 struct got_object_id *head_commit_id;
3535 TAILQ_FOREACH(pe, &paths, entry) {
3536 if (pe->path_len == 0)
3537 continue;
3538 error = got_error_msg(GOT_ERR_BAD_PATH,
3539 "switching between branches requires that "
3540 "the entire work tree gets updated");
3541 goto done;
3543 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3544 if (error)
3545 goto done;
3546 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3547 repo);
3548 free(head_commit_id);
3549 if (error != NULL)
3550 goto done;
3551 error = check_same_branch(commit_id, head_ref, NULL, repo);
3552 if (error)
3553 goto done;
3554 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3555 if (error)
3556 goto done;
3557 } else {
3558 error = check_linear_ancestry(commit_id,
3559 got_worktree_get_base_commit_id(worktree), 0, repo);
3560 if (error != NULL) {
3561 if (error->code == GOT_ERR_ANCESTRY)
3562 error = got_error(GOT_ERR_BRANCH_MOVED);
3563 goto done;
3565 error = check_same_branch(commit_id, head_ref, NULL, repo);
3566 if (error)
3567 goto done;
3570 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3571 commit_id) != 0) {
3572 error = got_worktree_set_base_commit_id(worktree, repo,
3573 commit_id);
3574 if (error)
3575 goto done;
3578 memset(&upa, 0, sizeof(upa));
3579 upa.verbosity = verbosity;
3580 error = got_worktree_checkout_files(worktree, &paths, repo,
3581 update_progress, &upa, check_cancelled, NULL);
3582 if (error != NULL)
3583 goto done;
3585 if (upa.did_something) {
3586 printf("Updated to %s: %s\n",
3587 got_worktree_get_head_ref_name(worktree), commit_id_str);
3588 } else
3589 printf("Already up-to-date\n");
3591 print_update_progress_stats(&upa);
3592 done:
3593 if (pack_fds) {
3594 const struct got_error *pack_err =
3595 got_repo_pack_fds_close(pack_fds);
3596 if (error == NULL)
3597 error = pack_err;
3599 free(worktree_path);
3600 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3601 free(commit_id);
3602 free(commit_id_str);
3603 return error;
3606 static const struct got_error *
3607 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3608 const char *path, int diff_context, int ignore_whitespace,
3609 int force_text_diff, int show_diffstat, struct got_repository *repo,
3610 FILE *outfile)
3612 const struct got_error *err = NULL;
3613 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3614 FILE *f1 = NULL, *f2 = NULL;
3615 int fd1 = -1, fd2 = -1;
3617 fd1 = got_opentempfd();
3618 if (fd1 == -1)
3619 return got_error_from_errno("got_opentempfd");
3620 fd2 = got_opentempfd();
3621 if (fd2 == -1) {
3622 err = got_error_from_errno("got_opentempfd");
3623 goto done;
3626 if (blob_id1) {
3627 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3628 fd1);
3629 if (err)
3630 goto done;
3633 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3634 if (err)
3635 goto done;
3637 f1 = got_opentemp();
3638 if (f1 == NULL) {
3639 err = got_error_from_errno("got_opentemp");
3640 goto done;
3642 f2 = got_opentemp();
3643 if (f2 == NULL) {
3644 err = got_error_from_errno("got_opentemp");
3645 goto done;
3648 while (path[0] == '/')
3649 path++;
3650 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3651 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3652 force_text_diff, show_diffstat, NULL, outfile);
3653 done:
3654 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3655 err = got_error_from_errno("close");
3656 if (blob1)
3657 got_object_blob_close(blob1);
3658 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3659 err = got_error_from_errno("close");
3660 got_object_blob_close(blob2);
3661 if (f1 && fclose(f1) == EOF && err == NULL)
3662 err = got_error_from_errno("fclose");
3663 if (f2 && fclose(f2) == EOF && err == NULL)
3664 err = got_error_from_errno("fclose");
3665 return err;
3668 static const struct got_error *
3669 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3670 const char *path, int diff_context, int ignore_whitespace,
3671 int force_text_diff, struct got_repository *repo, FILE *outfile)
3673 const struct got_error *err = NULL;
3674 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3675 struct got_diff_blob_output_unidiff_arg arg;
3676 FILE *f1 = NULL, *f2 = NULL;
3677 int fd1 = -1, fd2 = -1;
3679 if (tree_id1) {
3680 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3681 if (err)
3682 goto done;
3683 fd1 = got_opentempfd();
3684 if (fd1 == -1) {
3685 err = got_error_from_errno("got_opentempfd");
3686 goto done;
3690 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3691 if (err)
3692 goto done;
3694 f1 = got_opentemp();
3695 if (f1 == NULL) {
3696 err = got_error_from_errno("got_opentemp");
3697 goto done;
3700 f2 = got_opentemp();
3701 if (f2 == NULL) {
3702 err = got_error_from_errno("got_opentemp");
3703 goto done;
3705 fd2 = got_opentempfd();
3706 if (fd2 == -1) {
3707 err = got_error_from_errno("got_opentempfd");
3708 goto done;
3710 arg.diff_context = diff_context;
3711 arg.ignore_whitespace = ignore_whitespace;
3712 arg.force_text_diff = force_text_diff;
3713 arg.show_diffstat = 0;
3714 arg.diffstat = NULL;
3715 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3716 arg.outfile = outfile;
3717 arg.lines = NULL;
3718 arg.nlines = 0;
3719 while (path[0] == '/')
3720 path++;
3721 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3722 got_diff_blob_output_unidiff, &arg, 1);
3723 done:
3724 if (tree1)
3725 got_object_tree_close(tree1);
3726 if (tree2)
3727 got_object_tree_close(tree2);
3728 if (f1 && fclose(f1) == EOF && err == NULL)
3729 err = got_error_from_errno("fclose");
3730 if (f2 && fclose(f2) == EOF && err == NULL)
3731 err = got_error_from_errno("fclose");
3732 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3733 err = got_error_from_errno("close");
3734 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3735 err = got_error_from_errno("close");
3736 return err;
3739 static const struct got_error *
3740 get_changed_paths(struct got_pathlist_head *paths,
3741 struct got_commit_object *commit, struct got_repository *repo,
3742 struct got_diffstat_cb_arg *dsa)
3744 const struct got_error *err = NULL;
3745 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3746 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3747 struct got_object_qid *qid;
3748 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3749 FILE *f1 = NULL, *f2 = NULL;
3750 int fd1 = -1, fd2 = -1;
3752 if (dsa) {
3753 cb = got_diff_tree_compute_diffstat;
3755 f1 = got_opentemp();
3756 if (f1 == NULL) {
3757 err = got_error_from_errno("got_opentemp");
3758 goto done;
3760 f2 = got_opentemp();
3761 if (f2 == NULL) {
3762 err = got_error_from_errno("got_opentemp");
3763 goto done;
3765 fd1 = got_opentempfd();
3766 if (fd1 == -1) {
3767 err = got_error_from_errno("got_opentempfd");
3768 goto done;
3770 fd2 = got_opentempfd();
3771 if (fd2 == -1) {
3772 err = got_error_from_errno("got_opentempfd");
3773 goto done;
3777 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3778 if (qid != NULL) {
3779 struct got_commit_object *pcommit;
3780 err = got_object_open_as_commit(&pcommit, repo,
3781 &qid->id);
3782 if (err)
3783 return err;
3785 tree_id1 = got_object_id_dup(
3786 got_object_commit_get_tree_id(pcommit));
3787 if (tree_id1 == NULL) {
3788 got_object_commit_close(pcommit);
3789 return got_error_from_errno("got_object_id_dup");
3791 got_object_commit_close(pcommit);
3795 if (tree_id1) {
3796 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3797 if (err)
3798 goto done;
3801 tree_id2 = got_object_commit_get_tree_id(commit);
3802 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3803 if (err)
3804 goto done;
3806 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3807 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3808 done:
3809 if (tree1)
3810 got_object_tree_close(tree1);
3811 if (tree2)
3812 got_object_tree_close(tree2);
3813 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3814 err = got_error_from_errno("close");
3815 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3816 err = got_error_from_errno("close");
3817 if (f1 && fclose(f1) == EOF && err == NULL)
3818 err = got_error_from_errno("fclose");
3819 if (f2 && fclose(f2) == EOF && err == NULL)
3820 err = got_error_from_errno("fclose");
3821 free(tree_id1);
3822 return err;
3825 static const struct got_error *
3826 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3827 const char *path, int diff_context, struct got_repository *repo,
3828 FILE *outfile)
3830 const struct got_error *err = NULL;
3831 struct got_commit_object *pcommit = NULL;
3832 char *id_str1 = NULL, *id_str2 = NULL;
3833 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3834 struct got_object_qid *qid;
3836 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3837 if (qid != NULL) {
3838 err = got_object_open_as_commit(&pcommit, repo,
3839 &qid->id);
3840 if (err)
3841 return err;
3842 err = got_object_id_str(&id_str1, &qid->id);
3843 if (err)
3844 goto done;
3847 err = got_object_id_str(&id_str2, id);
3848 if (err)
3849 goto done;
3851 if (path && path[0] != '\0') {
3852 int obj_type;
3853 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3854 if (err)
3855 goto done;
3856 if (pcommit) {
3857 err = got_object_id_by_path(&obj_id1, repo,
3858 pcommit, path);
3859 if (err) {
3860 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3861 free(obj_id2);
3862 goto done;
3866 err = got_object_get_type(&obj_type, repo, obj_id2);
3867 if (err) {
3868 free(obj_id2);
3869 goto done;
3871 fprintf(outfile,
3872 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3873 fprintf(outfile, "commit - %s\n",
3874 id_str1 ? id_str1 : "/dev/null");
3875 fprintf(outfile, "commit + %s\n", id_str2);
3876 switch (obj_type) {
3877 case GOT_OBJ_TYPE_BLOB:
3878 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3879 0, 0, 0, repo, outfile);
3880 break;
3881 case GOT_OBJ_TYPE_TREE:
3882 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3883 0, 0, repo, outfile);
3884 break;
3885 default:
3886 err = got_error(GOT_ERR_OBJ_TYPE);
3887 break;
3889 free(obj_id1);
3890 free(obj_id2);
3891 } else {
3892 obj_id2 = got_object_commit_get_tree_id(commit);
3893 if (pcommit)
3894 obj_id1 = got_object_commit_get_tree_id(pcommit);
3895 fprintf(outfile,
3896 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3897 fprintf(outfile, "commit - %s\n",
3898 id_str1 ? id_str1 : "/dev/null");
3899 fprintf(outfile, "commit + %s\n", id_str2);
3900 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3901 repo, outfile);
3903 done:
3904 free(id_str1);
3905 free(id_str2);
3906 if (pcommit)
3907 got_object_commit_close(pcommit);
3908 return err;
3911 static char *
3912 get_datestr(time_t *time, char *datebuf)
3914 struct tm mytm, *tm;
3915 char *p, *s;
3917 tm = gmtime_r(time, &mytm);
3918 if (tm == NULL)
3919 return NULL;
3920 s = asctime_r(tm, datebuf);
3921 if (s == NULL)
3922 return NULL;
3923 p = strchr(s, '\n');
3924 if (p)
3925 *p = '\0';
3926 return s;
3929 static const struct got_error *
3930 match_commit(int *have_match, struct got_object_id *id,
3931 struct got_commit_object *commit, regex_t *regex)
3933 const struct got_error *err = NULL;
3934 regmatch_t regmatch;
3935 char *id_str = NULL, *logmsg = NULL;
3937 *have_match = 0;
3939 err = got_object_id_str(&id_str, id);
3940 if (err)
3941 return err;
3943 err = got_object_commit_get_logmsg(&logmsg, commit);
3944 if (err)
3945 goto done;
3947 if (regexec(regex, got_object_commit_get_author(commit), 1,
3948 &regmatch, 0) == 0 ||
3949 regexec(regex, got_object_commit_get_committer(commit), 1,
3950 &regmatch, 0) == 0 ||
3951 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3952 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3953 *have_match = 1;
3954 done:
3955 free(id_str);
3956 free(logmsg);
3957 return err;
3960 static void
3961 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3962 regex_t *regex)
3964 regmatch_t regmatch;
3965 struct got_pathlist_entry *pe;
3967 *have_match = 0;
3969 TAILQ_FOREACH(pe, changed_paths, entry) {
3970 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3971 *have_match = 1;
3972 break;
3977 static const struct got_error *
3978 match_patch(int *have_match, struct got_commit_object *commit,
3979 struct got_object_id *id, const char *path, int diff_context,
3980 struct got_repository *repo, regex_t *regex, FILE *f)
3982 const struct got_error *err = NULL;
3983 char *line = NULL;
3984 size_t linesize = 0;
3985 regmatch_t regmatch;
3987 *have_match = 0;
3989 err = got_opentemp_truncate(f);
3990 if (err)
3991 return err;
3993 err = print_patch(commit, id, path, diff_context, repo, f);
3994 if (err)
3995 goto done;
3997 if (fseeko(f, 0L, SEEK_SET) == -1) {
3998 err = got_error_from_errno("fseeko");
3999 goto done;
4002 while (getline(&line, &linesize, f) != -1) {
4003 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4004 *have_match = 1;
4005 break;
4008 done:
4009 free(line);
4010 return err;
4013 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4015 static const struct got_error*
4016 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4017 struct got_object_id *id, struct got_repository *repo,
4018 int local_only)
4020 static const struct got_error *err = NULL;
4021 struct got_reflist_entry *re;
4022 char *s;
4023 const char *name;
4025 *refs_str = NULL;
4027 TAILQ_FOREACH(re, refs, entry) {
4028 struct got_tag_object *tag = NULL;
4029 struct got_object_id *ref_id;
4030 int cmp;
4032 name = got_ref_get_name(re->ref);
4033 if (strcmp(name, GOT_REF_HEAD) == 0)
4034 continue;
4035 if (strncmp(name, "refs/", 5) == 0)
4036 name += 5;
4037 if (strncmp(name, "got/", 4) == 0)
4038 continue;
4039 if (strncmp(name, "heads/", 6) == 0)
4040 name += 6;
4041 if (strncmp(name, "remotes/", 8) == 0) {
4042 if (local_only)
4043 continue;
4044 name += 8;
4045 s = strstr(name, "/" GOT_REF_HEAD);
4046 if (s != NULL && s[strlen(s)] == '\0')
4047 continue;
4049 err = got_ref_resolve(&ref_id, repo, re->ref);
4050 if (err)
4051 break;
4052 if (strncmp(name, "tags/", 5) == 0) {
4053 err = got_object_open_as_tag(&tag, repo, ref_id);
4054 if (err) {
4055 if (err->code != GOT_ERR_OBJ_TYPE) {
4056 free(ref_id);
4057 break;
4059 /* Ref points at something other than a tag. */
4060 err = NULL;
4061 tag = NULL;
4064 cmp = got_object_id_cmp(tag ?
4065 got_object_tag_get_object_id(tag) : ref_id, id);
4066 free(ref_id);
4067 if (tag)
4068 got_object_tag_close(tag);
4069 if (cmp != 0)
4070 continue;
4071 s = *refs_str;
4072 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4073 s ? ", " : "", name) == -1) {
4074 err = got_error_from_errno("asprintf");
4075 free(s);
4076 *refs_str = NULL;
4077 break;
4079 free(s);
4082 return err;
4085 static const struct got_error *
4086 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4087 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4089 const struct got_error *err = NULL;
4090 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4091 char *comma, *s, *nl;
4092 struct got_reflist_head *refs;
4093 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4094 struct tm tm;
4095 time_t committer_time;
4097 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4098 if (refs) {
4099 err = build_refs_str(&ref_str, refs, id, repo, 1);
4100 if (err)
4101 return err;
4103 /* Display the first matching ref only. */
4104 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4105 *comma = '\0';
4108 if (ref_str == NULL) {
4109 err = got_object_id_str(&id_str, id);
4110 if (err)
4111 return err;
4114 committer_time = got_object_commit_get_committer_time(commit);
4115 if (gmtime_r(&committer_time, &tm) == NULL) {
4116 err = got_error_from_errno("gmtime_r");
4117 goto done;
4119 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4120 err = got_error(GOT_ERR_NO_SPACE);
4121 goto done;
4124 err = got_object_commit_get_logmsg(&logmsg0, commit);
4125 if (err)
4126 goto done;
4128 s = logmsg0;
4129 while (isspace((unsigned char)s[0]))
4130 s++;
4132 nl = strchr(s, '\n');
4133 if (nl) {
4134 *nl = '\0';
4137 if (ref_str)
4138 printf("%s%-7s %s\n", datebuf, ref_str, s);
4139 else
4140 printf("%s%.7s %s\n", datebuf, id_str, s);
4142 if (fflush(stdout) != 0 && err == NULL)
4143 err = got_error_from_errno("fflush");
4144 done:
4145 free(id_str);
4146 free(ref_str);
4147 free(logmsg0);
4148 return err;
4151 static const struct got_error *
4152 print_diffstat(struct got_diffstat_cb_arg *dsa, struct got_pathlist_head *paths,
4153 const char *header)
4155 struct got_pathlist_entry *pe;
4157 if (header != NULL)
4158 printf("%s\n", header);
4160 TAILQ_FOREACH(pe, paths, entry) {
4161 struct got_diff_changed_path *cp = pe->data;
4162 int pad = dsa->max_path_len - pe->path_len + 1;
4164 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4165 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4167 printf("\n%d file%s changed, %d insertions(+), %d deletions(-)\n\n",
4168 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins, dsa->del);
4170 if (fflush(stdout) != 0)
4171 return got_error_from_errno("fflush");
4173 return NULL;
4176 static const struct got_error *
4177 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4178 struct got_repository *repo, const char *path,
4179 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4180 int show_patch, int diff_context,
4181 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4183 const struct got_error *err = NULL;
4184 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4185 char datebuf[26];
4186 time_t committer_time;
4187 const char *author, *committer;
4188 char *refs_str = NULL;
4190 err = got_object_id_str(&id_str, id);
4191 if (err)
4192 return err;
4194 if (custom_refs_str == NULL) {
4195 struct got_reflist_head *refs;
4196 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4197 if (refs) {
4198 err = build_refs_str(&refs_str, refs, id, repo, 0);
4199 if (err)
4200 goto done;
4204 printf(GOT_COMMIT_SEP_STR);
4205 if (custom_refs_str)
4206 printf("commit %s (%s)\n", id_str, custom_refs_str);
4207 else
4208 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4209 refs_str ? refs_str : "", refs_str ? ")" : "");
4210 free(id_str);
4211 id_str = NULL;
4212 free(refs_str);
4213 refs_str = NULL;
4214 printf("from: %s\n", got_object_commit_get_author(commit));
4215 author = got_object_commit_get_author(commit);
4216 committer = got_object_commit_get_committer(commit);
4217 if (strcmp(author, committer) != 0)
4218 printf("via: %s\n", committer);
4219 committer_time = got_object_commit_get_committer_time(commit);
4220 datestr = get_datestr(&committer_time, datebuf);
4221 if (datestr)
4222 printf("date: %s UTC\n", datestr);
4223 if (got_object_commit_get_nparents(commit) > 1) {
4224 const struct got_object_id_queue *parent_ids;
4225 struct got_object_qid *qid;
4226 int n = 1;
4227 parent_ids = got_object_commit_get_parent_ids(commit);
4228 STAILQ_FOREACH(qid, parent_ids, entry) {
4229 err = got_object_id_str(&id_str, &qid->id);
4230 if (err)
4231 goto done;
4232 printf("parent %d: %s\n", n++, id_str);
4233 free(id_str);
4234 id_str = NULL;
4238 err = got_object_commit_get_logmsg(&logmsg0, commit);
4239 if (err)
4240 goto done;
4242 logmsg = logmsg0;
4243 do {
4244 line = strsep(&logmsg, "\n");
4245 if (line)
4246 printf(" %s\n", line);
4247 } while (line);
4248 free(logmsg0);
4250 if (dsa && changed_paths) {
4251 err = print_diffstat(dsa, changed_paths, NULL);
4252 if (err)
4253 goto done;
4254 } else if (changed_paths) {
4255 struct got_pathlist_entry *pe;
4257 TAILQ_FOREACH(pe, changed_paths, entry) {
4258 struct got_diff_changed_path *cp = pe->data;
4260 printf(" %c %s\n", cp->status, pe->path);
4262 printf("\n");
4264 if (show_patch) {
4265 err = print_patch(commit, id, path, diff_context, repo, stdout);
4266 if (err == 0)
4267 printf("\n");
4270 if (fflush(stdout) != 0 && err == NULL)
4271 err = got_error_from_errno("fflush");
4272 done:
4273 free(id_str);
4274 free(refs_str);
4275 return err;
4278 static const struct got_error *
4279 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4280 struct got_repository *repo, const char *path, int show_changed_paths,
4281 int show_diffstat, int show_patch, const char *search_pattern,
4282 int diff_context, int limit, int log_branches, int reverse_display_order,
4283 struct got_reflist_object_id_map *refs_idmap, int one_line,
4284 FILE *tmpfile)
4286 const struct got_error *err;
4287 struct got_commit_graph *graph;
4288 regex_t regex;
4289 int have_match;
4290 struct got_object_id_queue reversed_commits;
4291 struct got_object_qid *qid;
4292 struct got_commit_object *commit;
4293 struct got_pathlist_head changed_paths;
4295 STAILQ_INIT(&reversed_commits);
4296 TAILQ_INIT(&changed_paths);
4298 if (search_pattern && regcomp(&regex, search_pattern,
4299 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4300 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4302 err = got_commit_graph_open(&graph, path, !log_branches);
4303 if (err)
4304 return err;
4305 err = got_commit_graph_iter_start(graph, root_id, repo,
4306 check_cancelled, NULL);
4307 if (err)
4308 goto done;
4309 for (;;) {
4310 struct got_object_id id;
4311 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4312 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4314 if (sigint_received || sigpipe_received)
4315 break;
4317 err = got_commit_graph_iter_next(&id, graph, repo,
4318 check_cancelled, NULL);
4319 if (err) {
4320 if (err->code == GOT_ERR_ITER_COMPLETED)
4321 err = NULL;
4322 break;
4325 err = got_object_open_as_commit(&commit, repo, &id);
4326 if (err)
4327 break;
4329 if ((show_changed_paths || show_diffstat) &&
4330 !reverse_display_order) {
4331 err = get_changed_paths(&changed_paths, commit, repo,
4332 show_diffstat ? &dsa : NULL);
4333 if (err)
4334 break;
4337 if (search_pattern) {
4338 err = match_commit(&have_match, &id, commit, &regex);
4339 if (err) {
4340 got_object_commit_close(commit);
4341 break;
4343 if (have_match == 0 && show_changed_paths)
4344 match_changed_paths(&have_match,
4345 &changed_paths, &regex);
4346 if (have_match == 0 && show_patch) {
4347 err = match_patch(&have_match, commit, &id,
4348 path, diff_context, repo, &regex,
4349 tmpfile);
4350 if (err)
4351 break;
4353 if (have_match == 0) {
4354 got_object_commit_close(commit);
4355 got_pathlist_free(&changed_paths,
4356 GOT_PATHLIST_FREE_ALL);
4357 continue;
4361 if (reverse_display_order) {
4362 err = got_object_qid_alloc(&qid, &id);
4363 if (err)
4364 break;
4365 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4366 got_object_commit_close(commit);
4367 } else {
4368 if (one_line)
4369 err = print_commit_oneline(commit, &id,
4370 repo, refs_idmap);
4371 else
4372 err = print_commit(commit, &id, repo, path,
4373 (show_changed_paths || show_diffstat) ?
4374 &changed_paths : NULL,
4375 show_diffstat ? &dsa : NULL, show_patch,
4376 diff_context, refs_idmap, NULL);
4377 got_object_commit_close(commit);
4378 if (err)
4379 break;
4381 if ((limit && --limit == 0) ||
4382 (end_id && got_object_id_cmp(&id, end_id) == 0))
4383 break;
4385 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4387 if (reverse_display_order) {
4388 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4389 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4390 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4392 err = got_object_open_as_commit(&commit, repo,
4393 &qid->id);
4394 if (err)
4395 break;
4396 if (show_changed_paths || show_diffstat) {
4397 err = get_changed_paths(&changed_paths,
4398 commit, repo, show_diffstat ? &dsa : NULL);
4399 if (err)
4400 break;
4402 if (one_line)
4403 err = print_commit_oneline(commit, &qid->id,
4404 repo, refs_idmap);
4405 else
4406 err = print_commit(commit, &qid->id, repo, path,
4407 (show_changed_paths || show_diffstat) ?
4408 &changed_paths : NULL,
4409 show_diffstat ? &dsa : NULL, show_patch,
4410 diff_context, refs_idmap, NULL);
4411 got_object_commit_close(commit);
4412 if (err)
4413 break;
4414 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4417 done:
4418 while (!STAILQ_EMPTY(&reversed_commits)) {
4419 qid = STAILQ_FIRST(&reversed_commits);
4420 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4421 got_object_qid_free(qid);
4423 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4424 if (search_pattern)
4425 regfree(&regex);
4426 got_commit_graph_close(graph);
4427 return err;
4430 __dead static void
4431 usage_log(void)
4433 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4434 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4435 "[path]\n", getprogname());
4436 exit(1);
4439 static int
4440 get_default_log_limit(void)
4442 const char *got_default_log_limit;
4443 long long n;
4444 const char *errstr;
4446 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4447 if (got_default_log_limit == NULL)
4448 return 0;
4449 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4450 if (errstr != NULL)
4451 return 0;
4452 return n;
4455 static const struct got_error *
4456 cmd_log(int argc, char *argv[])
4458 const struct got_error *error;
4459 struct got_repository *repo = NULL;
4460 struct got_worktree *worktree = NULL;
4461 struct got_object_id *start_id = NULL, *end_id = NULL;
4462 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4463 const char *start_commit = NULL, *end_commit = NULL;
4464 const char *search_pattern = NULL;
4465 int diff_context = -1, ch;
4466 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4467 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4468 const char *errstr;
4469 struct got_reflist_head refs;
4470 struct got_reflist_object_id_map *refs_idmap = NULL;
4471 FILE *tmpfile = NULL;
4472 int *pack_fds = NULL;
4474 TAILQ_INIT(&refs);
4476 #ifndef PROFILE
4477 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4478 NULL)
4479 == -1)
4480 err(1, "pledge");
4481 #endif
4483 limit = get_default_log_limit();
4485 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4486 switch (ch) {
4487 case 'b':
4488 log_branches = 1;
4489 break;
4490 case 'C':
4491 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4492 &errstr);
4493 if (errstr != NULL)
4494 errx(1, "number of context lines is %s: %s",
4495 errstr, optarg);
4496 break;
4497 case 'c':
4498 start_commit = optarg;
4499 break;
4500 case 'd':
4501 show_diffstat = 1;
4502 break;
4503 case 'l':
4504 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4505 if (errstr != NULL)
4506 errx(1, "number of commits is %s: %s",
4507 errstr, optarg);
4508 break;
4509 case 'P':
4510 show_changed_paths = 1;
4511 break;
4512 case 'p':
4513 show_patch = 1;
4514 break;
4515 case 'R':
4516 reverse_display_order = 1;
4517 break;
4518 case 'r':
4519 repo_path = realpath(optarg, NULL);
4520 if (repo_path == NULL)
4521 return got_error_from_errno2("realpath",
4522 optarg);
4523 got_path_strip_trailing_slashes(repo_path);
4524 break;
4525 case 'S':
4526 search_pattern = optarg;
4527 break;
4528 case 's':
4529 one_line = 1;
4530 break;
4531 case 'x':
4532 end_commit = optarg;
4533 break;
4534 default:
4535 usage_log();
4536 /* NOTREACHED */
4540 argc -= optind;
4541 argv += optind;
4543 if (diff_context == -1)
4544 diff_context = 3;
4545 else if (!show_patch)
4546 errx(1, "-C requires -p");
4548 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4549 errx(1, "cannot use -s with -d, -p or -P");
4551 cwd = getcwd(NULL, 0);
4552 if (cwd == NULL) {
4553 error = got_error_from_errno("getcwd");
4554 goto done;
4557 error = got_repo_pack_fds_open(&pack_fds);
4558 if (error != NULL)
4559 goto done;
4561 if (repo_path == NULL) {
4562 error = got_worktree_open(&worktree, cwd);
4563 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4564 goto done;
4565 error = NULL;
4568 if (argc == 1) {
4569 if (worktree) {
4570 error = got_worktree_resolve_path(&path, worktree,
4571 argv[0]);
4572 if (error)
4573 goto done;
4574 } else {
4575 path = strdup(argv[0]);
4576 if (path == NULL) {
4577 error = got_error_from_errno("strdup");
4578 goto done;
4581 } else if (argc != 0)
4582 usage_log();
4584 if (repo_path == NULL) {
4585 repo_path = worktree ?
4586 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4588 if (repo_path == NULL) {
4589 error = got_error_from_errno("strdup");
4590 goto done;
4593 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4594 if (error != NULL)
4595 goto done;
4597 error = apply_unveil(got_repo_get_path(repo), 1,
4598 worktree ? got_worktree_get_root_path(worktree) : NULL);
4599 if (error)
4600 goto done;
4602 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4603 if (error)
4604 goto done;
4606 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4607 if (error)
4608 goto done;
4610 if (start_commit == NULL) {
4611 struct got_reference *head_ref;
4612 struct got_commit_object *commit = NULL;
4613 error = got_ref_open(&head_ref, repo,
4614 worktree ? got_worktree_get_head_ref_name(worktree)
4615 : GOT_REF_HEAD, 0);
4616 if (error != NULL)
4617 goto done;
4618 error = got_ref_resolve(&start_id, repo, head_ref);
4619 got_ref_close(head_ref);
4620 if (error != NULL)
4621 goto done;
4622 error = got_object_open_as_commit(&commit, repo,
4623 start_id);
4624 if (error != NULL)
4625 goto done;
4626 got_object_commit_close(commit);
4627 } else {
4628 error = got_repo_match_object_id(&start_id, NULL,
4629 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4630 if (error != NULL)
4631 goto done;
4633 if (end_commit != NULL) {
4634 error = got_repo_match_object_id(&end_id, NULL,
4635 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4636 if (error != NULL)
4637 goto done;
4640 if (worktree) {
4642 * If a path was specified on the command line it was resolved
4643 * to a path in the work tree above. Prepend the work tree's
4644 * path prefix to obtain the corresponding in-repository path.
4646 if (path) {
4647 const char *prefix;
4648 prefix = got_worktree_get_path_prefix(worktree);
4649 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4650 (path[0] != '\0') ? "/" : "", path) == -1) {
4651 error = got_error_from_errno("asprintf");
4652 goto done;
4655 } else
4656 error = got_repo_map_path(&in_repo_path, repo,
4657 path ? path : "");
4658 if (error != NULL)
4659 goto done;
4660 if (in_repo_path) {
4661 free(path);
4662 path = in_repo_path;
4665 if (worktree) {
4666 /* Release work tree lock. */
4667 got_worktree_close(worktree);
4668 worktree = NULL;
4671 if (search_pattern && show_patch) {
4672 tmpfile = got_opentemp();
4673 if (tmpfile == NULL) {
4674 error = got_error_from_errno("got_opentemp");
4675 goto done;
4679 error = print_commits(start_id, end_id, repo, path ? path : "",
4680 show_changed_paths, show_diffstat, show_patch, search_pattern,
4681 diff_context, limit, log_branches, reverse_display_order,
4682 refs_idmap, one_line, tmpfile);
4683 done:
4684 free(path);
4685 free(repo_path);
4686 free(cwd);
4687 if (worktree)
4688 got_worktree_close(worktree);
4689 if (repo) {
4690 const struct got_error *close_err = got_repo_close(repo);
4691 if (error == NULL)
4692 error = close_err;
4694 if (pack_fds) {
4695 const struct got_error *pack_err =
4696 got_repo_pack_fds_close(pack_fds);
4697 if (error == NULL)
4698 error = pack_err;
4700 if (refs_idmap)
4701 got_reflist_object_id_map_free(refs_idmap);
4702 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4703 error = got_error_from_errno("fclose");
4704 got_ref_list_free(&refs);
4705 return error;
4708 __dead static void
4709 usage_diff(void)
4711 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4712 "[-r repository-path] [object1 object2 | path ...]\n",
4713 getprogname());
4714 exit(1);
4717 struct print_diff_arg {
4718 struct got_repository *repo;
4719 struct got_worktree *worktree;
4720 struct got_diffstat_cb_arg *diffstat;
4721 int diff_context;
4722 const char *id_str;
4723 int header_shown;
4724 int diff_staged;
4725 enum got_diff_algorithm diff_algo;
4726 int ignore_whitespace;
4727 int force_text_diff;
4728 int show_diffstat;
4729 FILE *f1;
4730 FILE *f2;
4731 FILE *outfile;
4735 * Create a file which contains the target path of a symlink so we can feed
4736 * it as content to the diff engine.
4738 static const struct got_error *
4739 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4740 const char *abspath)
4742 const struct got_error *err = NULL;
4743 char target_path[PATH_MAX];
4744 ssize_t target_len, outlen;
4746 *fd = -1;
4748 if (dirfd != -1) {
4749 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4750 if (target_len == -1)
4751 return got_error_from_errno2("readlinkat", abspath);
4752 } else {
4753 target_len = readlink(abspath, target_path, PATH_MAX);
4754 if (target_len == -1)
4755 return got_error_from_errno2("readlink", abspath);
4758 *fd = got_opentempfd();
4759 if (*fd == -1)
4760 return got_error_from_errno("got_opentempfd");
4762 outlen = write(*fd, target_path, target_len);
4763 if (outlen == -1) {
4764 err = got_error_from_errno("got_opentempfd");
4765 goto done;
4768 if (lseek(*fd, 0, SEEK_SET) == -1) {
4769 err = got_error_from_errno2("lseek", abspath);
4770 goto done;
4772 done:
4773 if (err) {
4774 close(*fd);
4775 *fd = -1;
4777 return err;
4780 static const struct got_error *
4781 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4782 const char *path, struct got_object_id *blob_id,
4783 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4784 int dirfd, const char *de_name)
4786 struct print_diff_arg *a = arg;
4787 const struct got_error *err = NULL;
4788 struct got_blob_object *blob1 = NULL;
4789 int fd = -1, fd1 = -1, fd2 = -1;
4790 FILE *f2 = NULL;
4791 char *abspath = NULL, *label1 = NULL;
4792 struct stat sb;
4793 off_t size1 = 0;
4794 int f2_exists = 0;
4796 memset(&sb, 0, sizeof(sb));
4798 if (a->diff_staged) {
4799 if (staged_status != GOT_STATUS_MODIFY &&
4800 staged_status != GOT_STATUS_ADD &&
4801 staged_status != GOT_STATUS_DELETE)
4802 return NULL;
4803 } else {
4804 if (staged_status == GOT_STATUS_DELETE)
4805 return NULL;
4806 if (status == GOT_STATUS_NONEXISTENT)
4807 return got_error_set_errno(ENOENT, path);
4808 if (status != GOT_STATUS_MODIFY &&
4809 status != GOT_STATUS_ADD &&
4810 status != GOT_STATUS_DELETE &&
4811 status != GOT_STATUS_CONFLICT)
4812 return NULL;
4815 err = got_opentemp_truncate(a->f1);
4816 if (err)
4817 return got_error_from_errno("got_opentemp_truncate");
4818 err = got_opentemp_truncate(a->f2);
4819 if (err)
4820 return got_error_from_errno("got_opentemp_truncate");
4822 if (!a->header_shown) {
4823 if (fprintf(a->outfile, "diff %s%s\n",
4824 a->diff_staged ? "-s " : "",
4825 got_worktree_get_root_path(a->worktree)) < 0) {
4826 err = got_error_from_errno("fprintf");
4827 goto done;
4829 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4830 err = got_error_from_errno("fprintf");
4831 goto done;
4833 if (fprintf(a->outfile, "path + %s%s\n",
4834 got_worktree_get_root_path(a->worktree),
4835 a->diff_staged ? " (staged changes)" : "") < 0) {
4836 err = got_error_from_errno("fprintf");
4837 goto done;
4839 a->header_shown = 1;
4842 if (a->diff_staged) {
4843 const char *label1 = NULL, *label2 = NULL;
4844 switch (staged_status) {
4845 case GOT_STATUS_MODIFY:
4846 label1 = path;
4847 label2 = path;
4848 break;
4849 case GOT_STATUS_ADD:
4850 label2 = path;
4851 break;
4852 case GOT_STATUS_DELETE:
4853 label1 = path;
4854 break;
4855 default:
4856 return got_error(GOT_ERR_FILE_STATUS);
4858 fd1 = got_opentempfd();
4859 if (fd1 == -1) {
4860 err = got_error_from_errno("got_opentempfd");
4861 goto done;
4863 fd2 = got_opentempfd();
4864 if (fd2 == -1) {
4865 err = got_error_from_errno("got_opentempfd");
4866 goto done;
4868 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4869 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4870 a->diff_algo, a->diff_context, a->ignore_whitespace,
4871 a->force_text_diff, a->show_diffstat, a->diffstat, a->repo,
4872 a->outfile);
4873 goto done;
4876 fd1 = got_opentempfd();
4877 if (fd1 == -1) {
4878 err = got_error_from_errno("got_opentempfd");
4879 goto done;
4882 if (staged_status == GOT_STATUS_ADD ||
4883 staged_status == GOT_STATUS_MODIFY) {
4884 char *id_str;
4885 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4886 8192, fd1);
4887 if (err)
4888 goto done;
4889 err = got_object_id_str(&id_str, staged_blob_id);
4890 if (err)
4891 goto done;
4892 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4893 err = got_error_from_errno("asprintf");
4894 free(id_str);
4895 goto done;
4897 free(id_str);
4898 } else if (status != GOT_STATUS_ADD) {
4899 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4900 fd1);
4901 if (err)
4902 goto done;
4905 if (status != GOT_STATUS_DELETE) {
4906 if (asprintf(&abspath, "%s/%s",
4907 got_worktree_get_root_path(a->worktree), path) == -1) {
4908 err = got_error_from_errno("asprintf");
4909 goto done;
4912 if (dirfd != -1) {
4913 fd = openat(dirfd, de_name,
4914 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4915 if (fd == -1) {
4916 if (!got_err_open_nofollow_on_symlink()) {
4917 err = got_error_from_errno2("openat",
4918 abspath);
4919 goto done;
4921 err = get_symlink_target_file(&fd, dirfd,
4922 de_name, abspath);
4923 if (err)
4924 goto done;
4926 } else {
4927 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4928 if (fd == -1) {
4929 if (!got_err_open_nofollow_on_symlink()) {
4930 err = got_error_from_errno2("open",
4931 abspath);
4932 goto done;
4934 err = get_symlink_target_file(&fd, dirfd,
4935 de_name, abspath);
4936 if (err)
4937 goto done;
4940 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4941 err = got_error_from_errno2("fstatat", abspath);
4942 goto done;
4944 f2 = fdopen(fd, "r");
4945 if (f2 == NULL) {
4946 err = got_error_from_errno2("fdopen", abspath);
4947 goto done;
4949 fd = -1;
4950 f2_exists = 1;
4953 if (blob1) {
4954 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4955 a->f1, blob1);
4956 if (err)
4957 goto done;
4960 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4961 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4962 a->ignore_whitespace, a->force_text_diff, a->show_diffstat,
4963 a->diffstat, a->outfile);
4964 done:
4965 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4966 err = got_error_from_errno("close");
4967 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4968 err = got_error_from_errno("close");
4969 if (blob1)
4970 got_object_blob_close(blob1);
4971 if (fd != -1 && close(fd) == -1 && err == NULL)
4972 err = got_error_from_errno("close");
4973 if (f2 && fclose(f2) == EOF && err == NULL)
4974 err = got_error_from_errno("fclose");
4975 free(abspath);
4976 return err;
4979 static const struct got_error *
4980 printfile(FILE *f)
4982 char buf[8192];
4983 size_t r;
4985 if (fseeko(f, 0L, SEEK_SET) == -1)
4986 return got_error_from_errno("fseek");
4988 for (;;) {
4989 r = fread(buf, 1, sizeof(buf), f);
4990 if (r == 0) {
4991 if (ferror(f))
4992 return got_error_from_errno("fread");
4993 if (feof(f))
4994 break;
4996 if (fwrite(buf, 1, r, stdout) != r)
4997 return got_ferror(stdout, GOT_ERR_IO);
5000 return NULL;
5003 static const struct got_error *
5004 cmd_diff(int argc, char *argv[])
5006 const struct got_error *error;
5007 struct got_repository *repo = NULL;
5008 struct got_worktree *worktree = NULL;
5009 char *cwd = NULL, *repo_path = NULL;
5010 const char *commit_args[2] = { NULL, NULL };
5011 int ncommit_args = 0;
5012 struct got_object_id *ids[2] = { NULL, NULL };
5013 char *labels[2] = { NULL, NULL };
5014 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5015 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5016 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5017 const char *errstr;
5018 struct got_reflist_head refs;
5019 struct got_pathlist_head diffstat_paths, paths;
5020 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5021 int fd1 = -1, fd2 = -1;
5022 int *pack_fds = NULL;
5023 struct got_diffstat_cb_arg dsa;
5025 memset(&dsa, 0, sizeof(dsa));
5027 TAILQ_INIT(&refs);
5028 TAILQ_INIT(&paths);
5029 TAILQ_INIT(&diffstat_paths);
5031 #ifndef PROFILE
5032 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5033 NULL) == -1)
5034 err(1, "pledge");
5035 #endif
5037 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5038 switch (ch) {
5039 case 'a':
5040 force_text_diff = 1;
5041 break;
5042 case 'C':
5043 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5044 &errstr);
5045 if (errstr != NULL)
5046 errx(1, "number of context lines is %s: %s",
5047 errstr, optarg);
5048 break;
5049 case 'c':
5050 if (ncommit_args >= 2)
5051 errx(1, "too many -c options used");
5052 commit_args[ncommit_args++] = optarg;
5053 break;
5054 case 'd':
5055 show_diffstat = 1;
5056 break;
5057 case 'P':
5058 force_path = 1;
5059 break;
5060 case 'r':
5061 repo_path = realpath(optarg, NULL);
5062 if (repo_path == NULL)
5063 return got_error_from_errno2("realpath",
5064 optarg);
5065 got_path_strip_trailing_slashes(repo_path);
5066 rflag = 1;
5067 break;
5068 case 's':
5069 diff_staged = 1;
5070 break;
5071 case 'w':
5072 ignore_whitespace = 1;
5073 break;
5074 default:
5075 usage_diff();
5076 /* NOTREACHED */
5080 argc -= optind;
5081 argv += optind;
5083 cwd = getcwd(NULL, 0);
5084 if (cwd == NULL) {
5085 error = got_error_from_errno("getcwd");
5086 goto done;
5089 error = got_repo_pack_fds_open(&pack_fds);
5090 if (error != NULL)
5091 goto done;
5093 if (repo_path == NULL) {
5094 error = got_worktree_open(&worktree, cwd);
5095 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5096 goto done;
5097 else
5098 error = NULL;
5099 if (worktree) {
5100 repo_path =
5101 strdup(got_worktree_get_repo_path(worktree));
5102 if (repo_path == NULL) {
5103 error = got_error_from_errno("strdup");
5104 goto done;
5106 } else {
5107 repo_path = strdup(cwd);
5108 if (repo_path == NULL) {
5109 error = got_error_from_errno("strdup");
5110 goto done;
5115 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5116 free(repo_path);
5117 if (error != NULL)
5118 goto done;
5120 if (show_diffstat) {
5121 dsa.paths = &diffstat_paths;
5122 dsa.force_text = force_text_diff;
5123 dsa.ignore_ws = ignore_whitespace;
5124 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5127 if (rflag || worktree == NULL || ncommit_args > 0) {
5128 if (force_path) {
5129 error = got_error_msg(GOT_ERR_NOT_IMPL,
5130 "-P option can only be used when diffing "
5131 "a work tree");
5132 goto done;
5134 if (diff_staged) {
5135 error = got_error_msg(GOT_ERR_NOT_IMPL,
5136 "-s option can only be used when diffing "
5137 "a work tree");
5138 goto done;
5142 error = apply_unveil(got_repo_get_path(repo), 1,
5143 worktree ? got_worktree_get_root_path(worktree) : NULL);
5144 if (error)
5145 goto done;
5147 if ((!force_path && argc == 2) || ncommit_args > 0) {
5148 int obj_type = (ncommit_args > 0 ?
5149 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5150 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5151 NULL);
5152 if (error)
5153 goto done;
5154 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5155 const char *arg;
5156 if (ncommit_args > 0)
5157 arg = commit_args[i];
5158 else
5159 arg = argv[i];
5160 error = got_repo_match_object_id(&ids[i], &labels[i],
5161 arg, obj_type, &refs, repo);
5162 if (error) {
5163 if (error->code != GOT_ERR_NOT_REF &&
5164 error->code != GOT_ERR_NO_OBJ)
5165 goto done;
5166 if (ncommit_args > 0)
5167 goto done;
5168 error = NULL;
5169 break;
5174 f1 = got_opentemp();
5175 if (f1 == NULL) {
5176 error = got_error_from_errno("got_opentemp");
5177 goto done;
5180 f2 = got_opentemp();
5181 if (f2 == NULL) {
5182 error = got_error_from_errno("got_opentemp");
5183 goto done;
5186 outfile = got_opentemp();
5187 if (outfile == NULL) {
5188 error = got_error_from_errno("got_opentemp");
5189 goto done;
5192 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5193 struct print_diff_arg arg;
5194 char *id_str;
5196 if (worktree == NULL) {
5197 if (argc == 2 && ids[0] == NULL) {
5198 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5199 goto done;
5200 } else if (argc == 2 && ids[1] == NULL) {
5201 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5202 goto done;
5203 } else if (argc > 0) {
5204 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5205 "%s", "specified paths cannot be resolved");
5206 goto done;
5207 } else {
5208 error = got_error(GOT_ERR_NOT_WORKTREE);
5209 goto done;
5213 error = get_worktree_paths_from_argv(&paths, argc, argv,
5214 worktree);
5215 if (error)
5216 goto done;
5218 error = got_object_id_str(&id_str,
5219 got_worktree_get_base_commit_id(worktree));
5220 if (error)
5221 goto done;
5222 arg.repo = repo;
5223 arg.worktree = worktree;
5224 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5225 arg.diff_context = diff_context;
5226 arg.id_str = id_str;
5227 arg.header_shown = 0;
5228 arg.diff_staged = diff_staged;
5229 arg.ignore_whitespace = ignore_whitespace;
5230 arg.force_text_diff = force_text_diff;
5231 arg.show_diffstat = show_diffstat;
5232 arg.diffstat = &dsa;
5233 arg.f1 = f1;
5234 arg.f2 = f2;
5235 arg.outfile = outfile;
5237 error = got_worktree_status(worktree, &paths, repo, 0,
5238 print_diff, &arg, check_cancelled, NULL);
5239 free(id_str);
5240 if (error)
5241 goto done;
5243 if (show_diffstat && dsa.nfiles > 0) {
5244 char *header;
5246 if (asprintf(&header, "diffstat %s%s",
5247 diff_staged ? "-s " : "",
5248 got_worktree_get_root_path(worktree)) == -1)
5249 goto done;
5251 error = print_diffstat(&dsa, &diffstat_paths, header);
5252 free(header);
5253 if (error)
5254 goto done;
5257 error = printfile(outfile);
5258 goto done;
5261 if (ncommit_args == 1) {
5262 struct got_commit_object *commit;
5263 error = got_object_open_as_commit(&commit, repo, ids[0]);
5264 if (error)
5265 goto done;
5267 labels[1] = labels[0];
5268 ids[1] = ids[0];
5269 if (got_object_commit_get_nparents(commit) > 0) {
5270 const struct got_object_id_queue *pids;
5271 struct got_object_qid *pid;
5272 pids = got_object_commit_get_parent_ids(commit);
5273 pid = STAILQ_FIRST(pids);
5274 ids[0] = got_object_id_dup(&pid->id);
5275 if (ids[0] == NULL) {
5276 error = got_error_from_errno(
5277 "got_object_id_dup");
5278 got_object_commit_close(commit);
5279 goto done;
5281 error = got_object_id_str(&labels[0], ids[0]);
5282 if (error) {
5283 got_object_commit_close(commit);
5284 goto done;
5286 } else {
5287 ids[0] = NULL;
5288 labels[0] = strdup("/dev/null");
5289 if (labels[0] == NULL) {
5290 error = got_error_from_errno("strdup");
5291 got_object_commit_close(commit);
5292 goto done;
5296 got_object_commit_close(commit);
5299 if (ncommit_args == 0 && argc > 2) {
5300 error = got_error_msg(GOT_ERR_BAD_PATH,
5301 "path arguments cannot be used when diffing two objects");
5302 goto done;
5305 if (ids[0]) {
5306 error = got_object_get_type(&type1, repo, ids[0]);
5307 if (error)
5308 goto done;
5311 error = got_object_get_type(&type2, repo, ids[1]);
5312 if (error)
5313 goto done;
5314 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5315 error = got_error(GOT_ERR_OBJ_TYPE);
5316 goto done;
5318 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5319 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5320 "path arguments cannot be used when diffing blobs");
5321 goto done;
5324 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5325 char *in_repo_path;
5326 struct got_pathlist_entry *new;
5327 if (worktree) {
5328 const char *prefix;
5329 char *p;
5330 error = got_worktree_resolve_path(&p, worktree,
5331 argv[i]);
5332 if (error)
5333 goto done;
5334 prefix = got_worktree_get_path_prefix(worktree);
5335 while (prefix[0] == '/')
5336 prefix++;
5337 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5338 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5339 p) == -1) {
5340 error = got_error_from_errno("asprintf");
5341 free(p);
5342 goto done;
5344 free(p);
5345 } else {
5346 char *mapped_path, *s;
5347 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5348 if (error)
5349 goto done;
5350 s = mapped_path;
5351 while (s[0] == '/')
5352 s++;
5353 in_repo_path = strdup(s);
5354 if (in_repo_path == NULL) {
5355 error = got_error_from_errno("asprintf");
5356 free(mapped_path);
5357 goto done;
5359 free(mapped_path);
5362 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5363 if (error || new == NULL /* duplicate */)
5364 free(in_repo_path);
5365 if (error)
5366 goto done;
5369 if (worktree) {
5370 /* Release work tree lock. */
5371 got_worktree_close(worktree);
5372 worktree = NULL;
5375 fd1 = got_opentempfd();
5376 if (fd1 == -1) {
5377 error = got_error_from_errno("got_opentempfd");
5378 goto done;
5381 fd2 = got_opentempfd();
5382 if (fd2 == -1) {
5383 error = got_error_from_errno("got_opentempfd");
5384 goto done;
5387 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5388 case GOT_OBJ_TYPE_BLOB:
5389 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5390 fd1, fd2, ids[0], ids[1], NULL, NULL,
5391 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5392 ignore_whitespace, force_text_diff, show_diffstat,
5393 show_diffstat ? &dsa : NULL, repo, outfile);
5394 break;
5395 case GOT_OBJ_TYPE_TREE:
5396 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5397 ids[0], ids[1], &paths, "", "",
5398 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5399 ignore_whitespace, force_text_diff, show_diffstat,
5400 show_diffstat ? &dsa : NULL, repo, outfile);
5401 break;
5402 case GOT_OBJ_TYPE_COMMIT:
5403 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5404 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5405 fd1, fd2, ids[0], ids[1], &paths,
5406 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5407 ignore_whitespace, force_text_diff, show_diffstat,
5408 show_diffstat ? &dsa : NULL, repo, outfile);
5409 break;
5410 default:
5411 error = got_error(GOT_ERR_OBJ_TYPE);
5413 if (error)
5414 goto done;
5416 if (show_diffstat && dsa.nfiles > 0) {
5417 char *header = NULL;
5419 if (asprintf(&header, "diffstat %s %s",
5420 labels[0], labels[1]) == -1)
5421 goto done;
5423 error = print_diffstat(&dsa, &diffstat_paths, header);
5424 free(header);
5425 if (error)
5426 goto done;
5429 error = printfile(outfile);
5431 done:
5432 free(labels[0]);
5433 free(labels[1]);
5434 free(ids[0]);
5435 free(ids[1]);
5436 if (worktree)
5437 got_worktree_close(worktree);
5438 if (repo) {
5439 const struct got_error *close_err = got_repo_close(repo);
5440 if (error == NULL)
5441 error = close_err;
5443 if (pack_fds) {
5444 const struct got_error *pack_err =
5445 got_repo_pack_fds_close(pack_fds);
5446 if (error == NULL)
5447 error = pack_err;
5449 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5450 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5451 got_ref_list_free(&refs);
5452 if (outfile && fclose(outfile) == EOF && error == NULL)
5453 error = got_error_from_errno("fclose");
5454 if (f1 && fclose(f1) == EOF && error == NULL)
5455 error = got_error_from_errno("fclose");
5456 if (f2 && fclose(f2) == EOF && error == NULL)
5457 error = got_error_from_errno("fclose");
5458 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5459 error = got_error_from_errno("close");
5460 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5461 error = got_error_from_errno("close");
5462 return error;
5465 __dead static void
5466 usage_blame(void)
5468 fprintf(stderr,
5469 "usage: %s blame [-c commit] [-r repository-path] path\n",
5470 getprogname());
5471 exit(1);
5474 struct blame_line {
5475 int annotated;
5476 char *id_str;
5477 char *committer;
5478 char datebuf[11]; /* YYYY-MM-DD + NUL */
5481 struct blame_cb_args {
5482 struct blame_line *lines;
5483 int nlines;
5484 int nlines_prec;
5485 int lineno_cur;
5486 off_t *line_offsets;
5487 FILE *f;
5488 struct got_repository *repo;
5491 static const struct got_error *
5492 blame_cb(void *arg, int nlines, int lineno,
5493 struct got_commit_object *commit, struct got_object_id *id)
5495 const struct got_error *err = NULL;
5496 struct blame_cb_args *a = arg;
5497 struct blame_line *bline;
5498 char *line = NULL;
5499 size_t linesize = 0;
5500 off_t offset;
5501 struct tm tm;
5502 time_t committer_time;
5504 if (nlines != a->nlines ||
5505 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5506 return got_error(GOT_ERR_RANGE);
5508 if (sigint_received)
5509 return got_error(GOT_ERR_ITER_COMPLETED);
5511 if (lineno == -1)
5512 return NULL; /* no change in this commit */
5514 /* Annotate this line. */
5515 bline = &a->lines[lineno - 1];
5516 if (bline->annotated)
5517 return NULL;
5518 err = got_object_id_str(&bline->id_str, id);
5519 if (err)
5520 return err;
5522 bline->committer = strdup(got_object_commit_get_committer(commit));
5523 if (bline->committer == NULL) {
5524 err = got_error_from_errno("strdup");
5525 goto done;
5528 committer_time = got_object_commit_get_committer_time(commit);
5529 if (gmtime_r(&committer_time, &tm) == NULL)
5530 return got_error_from_errno("gmtime_r");
5531 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5532 &tm) == 0) {
5533 err = got_error(GOT_ERR_NO_SPACE);
5534 goto done;
5536 bline->annotated = 1;
5538 /* Print lines annotated so far. */
5539 bline = &a->lines[a->lineno_cur - 1];
5540 if (!bline->annotated)
5541 goto done;
5543 offset = a->line_offsets[a->lineno_cur - 1];
5544 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5545 err = got_error_from_errno("fseeko");
5546 goto done;
5549 while (a->lineno_cur <= a->nlines && bline->annotated) {
5550 char *smallerthan, *at, *nl, *committer;
5551 size_t len;
5553 if (getline(&line, &linesize, a->f) == -1) {
5554 if (ferror(a->f))
5555 err = got_error_from_errno("getline");
5556 break;
5559 committer = bline->committer;
5560 smallerthan = strchr(committer, '<');
5561 if (smallerthan && smallerthan[1] != '\0')
5562 committer = smallerthan + 1;
5563 at = strchr(committer, '@');
5564 if (at)
5565 *at = '\0';
5566 len = strlen(committer);
5567 if (len >= 9)
5568 committer[8] = '\0';
5570 nl = strchr(line, '\n');
5571 if (nl)
5572 *nl = '\0';
5573 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5574 bline->id_str, bline->datebuf, committer, line);
5576 a->lineno_cur++;
5577 bline = &a->lines[a->lineno_cur - 1];
5579 done:
5580 free(line);
5581 return err;
5584 static const struct got_error *
5585 cmd_blame(int argc, char *argv[])
5587 const struct got_error *error;
5588 struct got_repository *repo = NULL;
5589 struct got_worktree *worktree = NULL;
5590 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5591 char *link_target = NULL;
5592 struct got_object_id *obj_id = NULL;
5593 struct got_object_id *commit_id = NULL;
5594 struct got_commit_object *commit = NULL;
5595 struct got_blob_object *blob = NULL;
5596 char *commit_id_str = NULL;
5597 struct blame_cb_args bca;
5598 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5599 off_t filesize;
5600 int *pack_fds = NULL;
5601 FILE *f1 = NULL, *f2 = NULL;
5603 fd1 = got_opentempfd();
5604 if (fd1 == -1)
5605 return got_error_from_errno("got_opentempfd");
5607 memset(&bca, 0, sizeof(bca));
5609 #ifndef PROFILE
5610 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5611 NULL) == -1)
5612 err(1, "pledge");
5613 #endif
5615 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5616 switch (ch) {
5617 case 'c':
5618 commit_id_str = optarg;
5619 break;
5620 case 'r':
5621 repo_path = realpath(optarg, NULL);
5622 if (repo_path == NULL)
5623 return got_error_from_errno2("realpath",
5624 optarg);
5625 got_path_strip_trailing_slashes(repo_path);
5626 break;
5627 default:
5628 usage_blame();
5629 /* NOTREACHED */
5633 argc -= optind;
5634 argv += optind;
5636 if (argc == 1)
5637 path = argv[0];
5638 else
5639 usage_blame();
5641 cwd = getcwd(NULL, 0);
5642 if (cwd == NULL) {
5643 error = got_error_from_errno("getcwd");
5644 goto done;
5647 error = got_repo_pack_fds_open(&pack_fds);
5648 if (error != NULL)
5649 goto done;
5651 if (repo_path == NULL) {
5652 error = got_worktree_open(&worktree, cwd);
5653 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5654 goto done;
5655 else
5656 error = NULL;
5657 if (worktree) {
5658 repo_path =
5659 strdup(got_worktree_get_repo_path(worktree));
5660 if (repo_path == NULL) {
5661 error = got_error_from_errno("strdup");
5662 if (error)
5663 goto done;
5665 } else {
5666 repo_path = strdup(cwd);
5667 if (repo_path == NULL) {
5668 error = got_error_from_errno("strdup");
5669 goto done;
5674 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5675 if (error != NULL)
5676 goto done;
5678 if (worktree) {
5679 const char *prefix = got_worktree_get_path_prefix(worktree);
5680 char *p;
5682 error = got_worktree_resolve_path(&p, worktree, path);
5683 if (error)
5684 goto done;
5685 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5686 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5687 p) == -1) {
5688 error = got_error_from_errno("asprintf");
5689 free(p);
5690 goto done;
5692 free(p);
5693 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5694 } else {
5695 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5696 if (error)
5697 goto done;
5698 error = got_repo_map_path(&in_repo_path, repo, path);
5700 if (error)
5701 goto done;
5703 if (commit_id_str == NULL) {
5704 struct got_reference *head_ref;
5705 error = got_ref_open(&head_ref, repo, worktree ?
5706 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5707 if (error != NULL)
5708 goto done;
5709 error = got_ref_resolve(&commit_id, repo, head_ref);
5710 got_ref_close(head_ref);
5711 if (error != NULL)
5712 goto done;
5713 } else {
5714 struct got_reflist_head refs;
5715 TAILQ_INIT(&refs);
5716 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5717 NULL);
5718 if (error)
5719 goto done;
5720 error = got_repo_match_object_id(&commit_id, NULL,
5721 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5722 got_ref_list_free(&refs);
5723 if (error)
5724 goto done;
5727 if (worktree) {
5728 /* Release work tree lock. */
5729 got_worktree_close(worktree);
5730 worktree = NULL;
5733 error = got_object_open_as_commit(&commit, repo, commit_id);
5734 if (error)
5735 goto done;
5737 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5738 commit, repo);
5739 if (error)
5740 goto done;
5742 error = got_object_id_by_path(&obj_id, repo, commit,
5743 link_target ? link_target : in_repo_path);
5744 if (error)
5745 goto done;
5747 error = got_object_get_type(&obj_type, repo, obj_id);
5748 if (error)
5749 goto done;
5751 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5752 error = got_error_path(link_target ? link_target : in_repo_path,
5753 GOT_ERR_OBJ_TYPE);
5754 goto done;
5757 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5758 if (error)
5759 goto done;
5760 bca.f = got_opentemp();
5761 if (bca.f == NULL) {
5762 error = got_error_from_errno("got_opentemp");
5763 goto done;
5765 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5766 &bca.line_offsets, bca.f, blob);
5767 if (error || bca.nlines == 0)
5768 goto done;
5770 /* Don't include \n at EOF in the blame line count. */
5771 if (bca.line_offsets[bca.nlines - 1] == filesize)
5772 bca.nlines--;
5774 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5775 if (bca.lines == NULL) {
5776 error = got_error_from_errno("calloc");
5777 goto done;
5779 bca.lineno_cur = 1;
5780 bca.nlines_prec = 0;
5781 i = bca.nlines;
5782 while (i > 0) {
5783 i /= 10;
5784 bca.nlines_prec++;
5786 bca.repo = repo;
5788 fd2 = got_opentempfd();
5789 if (fd2 == -1) {
5790 error = got_error_from_errno("got_opentempfd");
5791 goto done;
5793 fd3 = got_opentempfd();
5794 if (fd3 == -1) {
5795 error = got_error_from_errno("got_opentempfd");
5796 goto done;
5798 f1 = got_opentemp();
5799 if (f1 == NULL) {
5800 error = got_error_from_errno("got_opentemp");
5801 goto done;
5803 f2 = got_opentemp();
5804 if (f2 == NULL) {
5805 error = got_error_from_errno("got_opentemp");
5806 goto done;
5808 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5809 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5810 check_cancelled, NULL, fd2, fd3, f1, f2);
5811 done:
5812 free(in_repo_path);
5813 free(link_target);
5814 free(repo_path);
5815 free(cwd);
5816 free(commit_id);
5817 free(obj_id);
5818 if (commit)
5819 got_object_commit_close(commit);
5821 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5822 error = got_error_from_errno("close");
5823 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5824 error = got_error_from_errno("close");
5825 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5826 error = got_error_from_errno("close");
5827 if (f1 && fclose(f1) == EOF && error == NULL)
5828 error = got_error_from_errno("fclose");
5829 if (f2 && fclose(f2) == EOF && error == NULL)
5830 error = got_error_from_errno("fclose");
5832 if (blob)
5833 got_object_blob_close(blob);
5834 if (worktree)
5835 got_worktree_close(worktree);
5836 if (repo) {
5837 const struct got_error *close_err = got_repo_close(repo);
5838 if (error == NULL)
5839 error = close_err;
5841 if (pack_fds) {
5842 const struct got_error *pack_err =
5843 got_repo_pack_fds_close(pack_fds);
5844 if (error == NULL)
5845 error = pack_err;
5847 if (bca.lines) {
5848 for (i = 0; i < bca.nlines; i++) {
5849 struct blame_line *bline = &bca.lines[i];
5850 free(bline->id_str);
5851 free(bline->committer);
5853 free(bca.lines);
5855 free(bca.line_offsets);
5856 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5857 error = got_error_from_errno("fclose");
5858 return error;
5861 __dead static void
5862 usage_tree(void)
5864 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5865 "[path]\n", getprogname());
5866 exit(1);
5869 static const struct got_error *
5870 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5871 const char *root_path, struct got_repository *repo)
5873 const struct got_error *err = NULL;
5874 int is_root_path = (strcmp(path, root_path) == 0);
5875 const char *modestr = "";
5876 mode_t mode = got_tree_entry_get_mode(te);
5877 char *link_target = NULL;
5879 path += strlen(root_path);
5880 while (path[0] == '/')
5881 path++;
5883 if (got_object_tree_entry_is_submodule(te))
5884 modestr = "$";
5885 else if (S_ISLNK(mode)) {
5886 int i;
5888 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5889 if (err)
5890 return err;
5891 for (i = 0; i < strlen(link_target); i++) {
5892 if (!isprint((unsigned char)link_target[i]))
5893 link_target[i] = '?';
5896 modestr = "@";
5898 else if (S_ISDIR(mode))
5899 modestr = "/";
5900 else if (mode & S_IXUSR)
5901 modestr = "*";
5903 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5904 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5905 link_target ? " -> ": "", link_target ? link_target : "");
5907 free(link_target);
5908 return NULL;
5911 static const struct got_error *
5912 print_tree(const char *path, struct got_commit_object *commit,
5913 int show_ids, int recurse, const char *root_path,
5914 struct got_repository *repo)
5916 const struct got_error *err = NULL;
5917 struct got_object_id *tree_id = NULL;
5918 struct got_tree_object *tree = NULL;
5919 int nentries, i;
5921 err = got_object_id_by_path(&tree_id, repo, commit, path);
5922 if (err)
5923 goto done;
5925 err = got_object_open_as_tree(&tree, repo, tree_id);
5926 if (err)
5927 goto done;
5928 nentries = got_object_tree_get_nentries(tree);
5929 for (i = 0; i < nentries; i++) {
5930 struct got_tree_entry *te;
5931 char *id = NULL;
5933 if (sigint_received || sigpipe_received)
5934 break;
5936 te = got_object_tree_get_entry(tree, i);
5937 if (show_ids) {
5938 char *id_str;
5939 err = got_object_id_str(&id_str,
5940 got_tree_entry_get_id(te));
5941 if (err)
5942 goto done;
5943 if (asprintf(&id, "%s ", id_str) == -1) {
5944 err = got_error_from_errno("asprintf");
5945 free(id_str);
5946 goto done;
5948 free(id_str);
5950 err = print_entry(te, id, path, root_path, repo);
5951 free(id);
5952 if (err)
5953 goto done;
5955 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5956 char *child_path;
5957 if (asprintf(&child_path, "%s%s%s", path,
5958 path[0] == '/' && path[1] == '\0' ? "" : "/",
5959 got_tree_entry_get_name(te)) == -1) {
5960 err = got_error_from_errno("asprintf");
5961 goto done;
5963 err = print_tree(child_path, commit, show_ids, 1,
5964 root_path, repo);
5965 free(child_path);
5966 if (err)
5967 goto done;
5970 done:
5971 if (tree)
5972 got_object_tree_close(tree);
5973 free(tree_id);
5974 return err;
5977 static const struct got_error *
5978 cmd_tree(int argc, char *argv[])
5980 const struct got_error *error;
5981 struct got_repository *repo = NULL;
5982 struct got_worktree *worktree = NULL;
5983 const char *path, *refname = NULL;
5984 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5985 struct got_object_id *commit_id = NULL;
5986 struct got_commit_object *commit = NULL;
5987 char *commit_id_str = NULL;
5988 int show_ids = 0, recurse = 0;
5989 int ch;
5990 int *pack_fds = NULL;
5992 #ifndef PROFILE
5993 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5994 NULL) == -1)
5995 err(1, "pledge");
5996 #endif
5998 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5999 switch (ch) {
6000 case 'c':
6001 commit_id_str = optarg;
6002 break;
6003 case 'i':
6004 show_ids = 1;
6005 break;
6006 case 'R':
6007 recurse = 1;
6008 break;
6009 case 'r':
6010 repo_path = realpath(optarg, NULL);
6011 if (repo_path == NULL)
6012 return got_error_from_errno2("realpath",
6013 optarg);
6014 got_path_strip_trailing_slashes(repo_path);
6015 break;
6016 default:
6017 usage_tree();
6018 /* NOTREACHED */
6022 argc -= optind;
6023 argv += optind;
6025 if (argc == 1)
6026 path = argv[0];
6027 else if (argc > 1)
6028 usage_tree();
6029 else
6030 path = NULL;
6032 cwd = getcwd(NULL, 0);
6033 if (cwd == NULL) {
6034 error = got_error_from_errno("getcwd");
6035 goto done;
6038 error = got_repo_pack_fds_open(&pack_fds);
6039 if (error != NULL)
6040 goto done;
6042 if (repo_path == NULL) {
6043 error = got_worktree_open(&worktree, cwd);
6044 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6045 goto done;
6046 else
6047 error = NULL;
6048 if (worktree) {
6049 repo_path =
6050 strdup(got_worktree_get_repo_path(worktree));
6051 if (repo_path == NULL)
6052 error = got_error_from_errno("strdup");
6053 if (error)
6054 goto done;
6055 } else {
6056 repo_path = strdup(cwd);
6057 if (repo_path == NULL) {
6058 error = got_error_from_errno("strdup");
6059 goto done;
6064 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6065 if (error != NULL)
6066 goto done;
6068 if (worktree) {
6069 const char *prefix = got_worktree_get_path_prefix(worktree);
6070 char *p;
6072 if (path == NULL)
6073 path = "";
6074 error = got_worktree_resolve_path(&p, worktree, path);
6075 if (error)
6076 goto done;
6077 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6078 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6079 p) == -1) {
6080 error = got_error_from_errno("asprintf");
6081 free(p);
6082 goto done;
6084 free(p);
6085 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6086 if (error)
6087 goto done;
6088 } else {
6089 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6090 if (error)
6091 goto done;
6092 if (path == NULL)
6093 path = "/";
6094 error = got_repo_map_path(&in_repo_path, repo, path);
6095 if (error != NULL)
6096 goto done;
6099 if (commit_id_str == NULL) {
6100 struct got_reference *head_ref;
6101 if (worktree)
6102 refname = got_worktree_get_head_ref_name(worktree);
6103 else
6104 refname = GOT_REF_HEAD;
6105 error = got_ref_open(&head_ref, repo, refname, 0);
6106 if (error != NULL)
6107 goto done;
6108 error = got_ref_resolve(&commit_id, repo, head_ref);
6109 got_ref_close(head_ref);
6110 if (error != NULL)
6111 goto done;
6112 } else {
6113 struct got_reflist_head refs;
6114 TAILQ_INIT(&refs);
6115 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6116 NULL);
6117 if (error)
6118 goto done;
6119 error = got_repo_match_object_id(&commit_id, NULL,
6120 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6121 got_ref_list_free(&refs);
6122 if (error)
6123 goto done;
6126 if (worktree) {
6127 /* Release work tree lock. */
6128 got_worktree_close(worktree);
6129 worktree = NULL;
6132 error = got_object_open_as_commit(&commit, repo, commit_id);
6133 if (error)
6134 goto done;
6136 error = print_tree(in_repo_path, commit, show_ids, recurse,
6137 in_repo_path, repo);
6138 done:
6139 free(in_repo_path);
6140 free(repo_path);
6141 free(cwd);
6142 free(commit_id);
6143 if (commit)
6144 got_object_commit_close(commit);
6145 if (worktree)
6146 got_worktree_close(worktree);
6147 if (repo) {
6148 const struct got_error *close_err = got_repo_close(repo);
6149 if (error == NULL)
6150 error = close_err;
6152 if (pack_fds) {
6153 const struct got_error *pack_err =
6154 got_repo_pack_fds_close(pack_fds);
6155 if (error == NULL)
6156 error = pack_err;
6158 return error;
6161 __dead static void
6162 usage_status(void)
6164 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6165 "[-s status-codes] [path ...]\n", getprogname());
6166 exit(1);
6169 struct got_status_arg {
6170 char *status_codes;
6171 int suppress;
6174 static const struct got_error *
6175 print_status(void *arg, unsigned char status, unsigned char staged_status,
6176 const char *path, struct got_object_id *blob_id,
6177 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6178 int dirfd, const char *de_name)
6180 struct got_status_arg *st = arg;
6182 if (status == staged_status && (status == GOT_STATUS_DELETE))
6183 status = GOT_STATUS_NO_CHANGE;
6184 if (st != NULL && st->status_codes) {
6185 size_t ncodes = strlen(st->status_codes);
6186 int i, j = 0;
6188 for (i = 0; i < ncodes ; i++) {
6189 if (st->suppress) {
6190 if (status == st->status_codes[i] ||
6191 staged_status == st->status_codes[i]) {
6192 j++;
6193 continue;
6195 } else {
6196 if (status == st->status_codes[i] ||
6197 staged_status == st->status_codes[i])
6198 break;
6202 if (st->suppress && j == 0)
6203 goto print;
6205 if (i == ncodes)
6206 return NULL;
6208 print:
6209 printf("%c%c %s\n", status, staged_status, path);
6210 return NULL;
6213 static const struct got_error *
6214 cmd_status(int argc, char *argv[])
6216 const struct got_error *error = NULL;
6217 struct got_repository *repo = NULL;
6218 struct got_worktree *worktree = NULL;
6219 struct got_status_arg st;
6220 char *cwd = NULL;
6221 struct got_pathlist_head paths;
6222 int ch, i, no_ignores = 0;
6223 int *pack_fds = NULL;
6225 TAILQ_INIT(&paths);
6227 memset(&st, 0, sizeof(st));
6228 st.status_codes = NULL;
6229 st.suppress = 0;
6231 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6232 switch (ch) {
6233 case 'I':
6234 no_ignores = 1;
6235 break;
6236 case 'S':
6237 if (st.status_codes != NULL && st.suppress == 0)
6238 option_conflict('S', 's');
6239 st.suppress = 1;
6240 /* fallthrough */
6241 case 's':
6242 for (i = 0; i < strlen(optarg); i++) {
6243 switch (optarg[i]) {
6244 case GOT_STATUS_MODIFY:
6245 case GOT_STATUS_ADD:
6246 case GOT_STATUS_DELETE:
6247 case GOT_STATUS_CONFLICT:
6248 case GOT_STATUS_MISSING:
6249 case GOT_STATUS_OBSTRUCTED:
6250 case GOT_STATUS_UNVERSIONED:
6251 case GOT_STATUS_MODE_CHANGE:
6252 case GOT_STATUS_NONEXISTENT:
6253 break;
6254 default:
6255 errx(1, "invalid status code '%c'",
6256 optarg[i]);
6259 if (ch == 's' && st.suppress)
6260 option_conflict('s', 'S');
6261 st.status_codes = optarg;
6262 break;
6263 default:
6264 usage_status();
6265 /* NOTREACHED */
6269 argc -= optind;
6270 argv += optind;
6272 #ifndef PROFILE
6273 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6274 NULL) == -1)
6275 err(1, "pledge");
6276 #endif
6277 cwd = getcwd(NULL, 0);
6278 if (cwd == NULL) {
6279 error = got_error_from_errno("getcwd");
6280 goto done;
6283 error = got_repo_pack_fds_open(&pack_fds);
6284 if (error != NULL)
6285 goto done;
6287 error = got_worktree_open(&worktree, cwd);
6288 if (error) {
6289 if (error->code == GOT_ERR_NOT_WORKTREE)
6290 error = wrap_not_worktree_error(error, "status", cwd);
6291 goto done;
6294 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6295 NULL, pack_fds);
6296 if (error != NULL)
6297 goto done;
6299 error = apply_unveil(got_repo_get_path(repo), 1,
6300 got_worktree_get_root_path(worktree));
6301 if (error)
6302 goto done;
6304 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6305 if (error)
6306 goto done;
6308 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6309 print_status, &st, check_cancelled, NULL);
6310 done:
6311 if (pack_fds) {
6312 const struct got_error *pack_err =
6313 got_repo_pack_fds_close(pack_fds);
6314 if (error == NULL)
6315 error = pack_err;
6318 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6319 free(cwd);
6320 return error;
6323 __dead static void
6324 usage_ref(void)
6326 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6327 "[-s reference] [name]\n", getprogname());
6328 exit(1);
6331 static const struct got_error *
6332 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6334 static const struct got_error *err = NULL;
6335 struct got_reflist_head refs;
6336 struct got_reflist_entry *re;
6338 TAILQ_INIT(&refs);
6339 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6340 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6341 repo);
6342 if (err)
6343 return err;
6345 TAILQ_FOREACH(re, &refs, entry) {
6346 char *refstr;
6347 refstr = got_ref_to_str(re->ref);
6348 if (refstr == NULL) {
6349 err = got_error_from_errno("got_ref_to_str");
6350 break;
6352 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6353 free(refstr);
6356 got_ref_list_free(&refs);
6357 return err;
6360 static const struct got_error *
6361 delete_ref_by_name(struct got_repository *repo, const char *refname)
6363 const struct got_error *err;
6364 struct got_reference *ref;
6366 err = got_ref_open(&ref, repo, refname, 0);
6367 if (err)
6368 return err;
6370 err = delete_ref(repo, ref);
6371 got_ref_close(ref);
6372 return err;
6375 static const struct got_error *
6376 add_ref(struct got_repository *repo, const char *refname, const char *target)
6378 const struct got_error *err = NULL;
6379 struct got_object_id *id = NULL;
6380 struct got_reference *ref = NULL;
6381 struct got_reflist_head refs;
6384 * Don't let the user create a reference name with a leading '-'.
6385 * While technically a valid reference name, this case is usually
6386 * an unintended typo.
6388 if (refname[0] == '-')
6389 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6391 TAILQ_INIT(&refs);
6392 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6393 if (err)
6394 goto done;
6395 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6396 &refs, repo);
6397 got_ref_list_free(&refs);
6398 if (err)
6399 goto done;
6401 err = got_ref_alloc(&ref, refname, id);
6402 if (err)
6403 goto done;
6405 err = got_ref_write(ref, repo);
6406 done:
6407 if (ref)
6408 got_ref_close(ref);
6409 free(id);
6410 return err;
6413 static const struct got_error *
6414 add_symref(struct got_repository *repo, const char *refname, const char *target)
6416 const struct got_error *err = NULL;
6417 struct got_reference *ref = NULL;
6418 struct got_reference *target_ref = NULL;
6421 * Don't let the user create a reference name with a leading '-'.
6422 * While technically a valid reference name, this case is usually
6423 * an unintended typo.
6425 if (refname[0] == '-')
6426 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6428 err = got_ref_open(&target_ref, repo, target, 0);
6429 if (err)
6430 return err;
6432 err = got_ref_alloc_symref(&ref, refname, target_ref);
6433 if (err)
6434 goto done;
6436 err = got_ref_write(ref, repo);
6437 done:
6438 if (target_ref)
6439 got_ref_close(target_ref);
6440 if (ref)
6441 got_ref_close(ref);
6442 return err;
6445 static const struct got_error *
6446 cmd_ref(int argc, char *argv[])
6448 const struct got_error *error = NULL;
6449 struct got_repository *repo = NULL;
6450 struct got_worktree *worktree = NULL;
6451 char *cwd = NULL, *repo_path = NULL;
6452 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6453 const char *obj_arg = NULL, *symref_target= NULL;
6454 char *refname = NULL;
6455 int *pack_fds = NULL;
6457 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6458 switch (ch) {
6459 case 'c':
6460 obj_arg = optarg;
6461 break;
6462 case 'd':
6463 do_delete = 1;
6464 break;
6465 case 'l':
6466 do_list = 1;
6467 break;
6468 case 'r':
6469 repo_path = realpath(optarg, NULL);
6470 if (repo_path == NULL)
6471 return got_error_from_errno2("realpath",
6472 optarg);
6473 got_path_strip_trailing_slashes(repo_path);
6474 break;
6475 case 's':
6476 symref_target = optarg;
6477 break;
6478 case 't':
6479 sort_by_time = 1;
6480 break;
6481 default:
6482 usage_ref();
6483 /* NOTREACHED */
6487 if (obj_arg && do_list)
6488 option_conflict('c', 'l');
6489 if (obj_arg && do_delete)
6490 option_conflict('c', 'd');
6491 if (obj_arg && symref_target)
6492 option_conflict('c', 's');
6493 if (symref_target && do_delete)
6494 option_conflict('s', 'd');
6495 if (symref_target && do_list)
6496 option_conflict('s', 'l');
6497 if (do_delete && do_list)
6498 option_conflict('d', 'l');
6499 if (sort_by_time && !do_list)
6500 errx(1, "-t option requires -l option");
6502 argc -= optind;
6503 argv += optind;
6505 if (do_list) {
6506 if (argc != 0 && argc != 1)
6507 usage_ref();
6508 if (argc == 1) {
6509 refname = strdup(argv[0]);
6510 if (refname == NULL) {
6511 error = got_error_from_errno("strdup");
6512 goto done;
6515 } else {
6516 if (argc != 1)
6517 usage_ref();
6518 refname = strdup(argv[0]);
6519 if (refname == NULL) {
6520 error = got_error_from_errno("strdup");
6521 goto done;
6525 if (refname)
6526 got_path_strip_trailing_slashes(refname);
6528 #ifndef PROFILE
6529 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6530 "sendfd unveil", NULL) == -1)
6531 err(1, "pledge");
6532 #endif
6533 cwd = getcwd(NULL, 0);
6534 if (cwd == NULL) {
6535 error = got_error_from_errno("getcwd");
6536 goto done;
6539 error = got_repo_pack_fds_open(&pack_fds);
6540 if (error != NULL)
6541 goto done;
6543 if (repo_path == NULL) {
6544 error = got_worktree_open(&worktree, cwd);
6545 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6546 goto done;
6547 else
6548 error = NULL;
6549 if (worktree) {
6550 repo_path =
6551 strdup(got_worktree_get_repo_path(worktree));
6552 if (repo_path == NULL)
6553 error = got_error_from_errno("strdup");
6554 if (error)
6555 goto done;
6556 } else {
6557 repo_path = strdup(cwd);
6558 if (repo_path == NULL) {
6559 error = got_error_from_errno("strdup");
6560 goto done;
6565 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6566 if (error != NULL)
6567 goto done;
6569 #ifndef PROFILE
6570 if (do_list) {
6571 /* Remove "cpath" promise. */
6572 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6573 NULL) == -1)
6574 err(1, "pledge");
6576 #endif
6578 error = apply_unveil(got_repo_get_path(repo), do_list,
6579 worktree ? got_worktree_get_root_path(worktree) : NULL);
6580 if (error)
6581 goto done;
6583 if (do_list)
6584 error = list_refs(repo, refname, sort_by_time);
6585 else if (do_delete)
6586 error = delete_ref_by_name(repo, refname);
6587 else if (symref_target)
6588 error = add_symref(repo, refname, symref_target);
6589 else {
6590 if (obj_arg == NULL)
6591 usage_ref();
6592 error = add_ref(repo, refname, obj_arg);
6594 done:
6595 free(refname);
6596 if (repo) {
6597 const struct got_error *close_err = got_repo_close(repo);
6598 if (error == NULL)
6599 error = close_err;
6601 if (worktree)
6602 got_worktree_close(worktree);
6603 if (pack_fds) {
6604 const struct got_error *pack_err =
6605 got_repo_pack_fds_close(pack_fds);
6606 if (error == NULL)
6607 error = pack_err;
6609 free(cwd);
6610 free(repo_path);
6611 return error;
6614 __dead static void
6615 usage_branch(void)
6617 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6618 "[-r repository-path] [name]\n", getprogname());
6619 exit(1);
6622 static const struct got_error *
6623 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6624 struct got_reference *ref)
6626 const struct got_error *err = NULL;
6627 const char *refname, *marker = " ";
6628 char *refstr;
6630 refname = got_ref_get_name(ref);
6631 if (worktree && strcmp(refname,
6632 got_worktree_get_head_ref_name(worktree)) == 0) {
6633 struct got_object_id *id = NULL;
6635 err = got_ref_resolve(&id, repo, ref);
6636 if (err)
6637 return err;
6638 if (got_object_id_cmp(id,
6639 got_worktree_get_base_commit_id(worktree)) == 0)
6640 marker = "* ";
6641 else
6642 marker = "~ ";
6643 free(id);
6646 if (strncmp(refname, "refs/heads/", 11) == 0)
6647 refname += 11;
6648 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6649 refname += 18;
6650 if (strncmp(refname, "refs/remotes/", 13) == 0)
6651 refname += 13;
6653 refstr = got_ref_to_str(ref);
6654 if (refstr == NULL)
6655 return got_error_from_errno("got_ref_to_str");
6657 printf("%s%s: %s\n", marker, refname, refstr);
6658 free(refstr);
6659 return NULL;
6662 static const struct got_error *
6663 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6665 const char *refname;
6667 if (worktree == NULL)
6668 return got_error(GOT_ERR_NOT_WORKTREE);
6670 refname = got_worktree_get_head_ref_name(worktree);
6672 if (strncmp(refname, "refs/heads/", 11) == 0)
6673 refname += 11;
6674 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6675 refname += 18;
6677 printf("%s\n", refname);
6679 return NULL;
6682 static const struct got_error *
6683 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6684 int sort_by_time)
6686 static const struct got_error *err = NULL;
6687 struct got_reflist_head refs;
6688 struct got_reflist_entry *re;
6689 struct got_reference *temp_ref = NULL;
6690 int rebase_in_progress, histedit_in_progress;
6692 TAILQ_INIT(&refs);
6694 if (worktree) {
6695 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6696 worktree);
6697 if (err)
6698 return err;
6700 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6701 worktree);
6702 if (err)
6703 return err;
6705 if (rebase_in_progress || histedit_in_progress) {
6706 err = got_ref_open(&temp_ref, repo,
6707 got_worktree_get_head_ref_name(worktree), 0);
6708 if (err)
6709 return err;
6710 list_branch(repo, worktree, temp_ref);
6711 got_ref_close(temp_ref);
6715 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6716 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6717 repo);
6718 if (err)
6719 return err;
6721 TAILQ_FOREACH(re, &refs, entry)
6722 list_branch(repo, worktree, re->ref);
6724 got_ref_list_free(&refs);
6726 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6727 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6728 repo);
6729 if (err)
6730 return err;
6732 TAILQ_FOREACH(re, &refs, entry)
6733 list_branch(repo, worktree, re->ref);
6735 got_ref_list_free(&refs);
6737 return NULL;
6740 static const struct got_error *
6741 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6742 const char *branch_name)
6744 const struct got_error *err = NULL;
6745 struct got_reference *ref = NULL;
6746 char *refname, *remote_refname = NULL;
6748 if (strncmp(branch_name, "refs/", 5) == 0)
6749 branch_name += 5;
6750 if (strncmp(branch_name, "heads/", 6) == 0)
6751 branch_name += 6;
6752 else if (strncmp(branch_name, "remotes/", 8) == 0)
6753 branch_name += 8;
6755 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6756 return got_error_from_errno("asprintf");
6758 if (asprintf(&remote_refname, "refs/remotes/%s",
6759 branch_name) == -1) {
6760 err = got_error_from_errno("asprintf");
6761 goto done;
6764 err = got_ref_open(&ref, repo, refname, 0);
6765 if (err) {
6766 const struct got_error *err2;
6767 if (err->code != GOT_ERR_NOT_REF)
6768 goto done;
6770 * Keep 'err' intact such that if neither branch exists
6771 * we report "refs/heads" rather than "refs/remotes" in
6772 * our error message.
6774 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6775 if (err2)
6776 goto done;
6777 err = NULL;
6780 if (worktree &&
6781 strcmp(got_worktree_get_head_ref_name(worktree),
6782 got_ref_get_name(ref)) == 0) {
6783 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6784 "will not delete this work tree's current branch");
6785 goto done;
6788 err = delete_ref(repo, ref);
6789 done:
6790 if (ref)
6791 got_ref_close(ref);
6792 free(refname);
6793 free(remote_refname);
6794 return err;
6797 static const struct got_error *
6798 add_branch(struct got_repository *repo, const char *branch_name,
6799 struct got_object_id *base_commit_id)
6801 const struct got_error *err = NULL;
6802 struct got_reference *ref = NULL;
6803 char *base_refname = NULL, *refname = NULL;
6806 * Don't let the user create a branch name with a leading '-'.
6807 * While technically a valid reference name, this case is usually
6808 * an unintended typo.
6810 if (branch_name[0] == '-')
6811 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6813 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6814 branch_name += 11;
6816 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6817 err = got_error_from_errno("asprintf");
6818 goto done;
6821 err = got_ref_open(&ref, repo, refname, 0);
6822 if (err == NULL) {
6823 err = got_error(GOT_ERR_BRANCH_EXISTS);
6824 goto done;
6825 } else if (err->code != GOT_ERR_NOT_REF)
6826 goto done;
6828 err = got_ref_alloc(&ref, refname, base_commit_id);
6829 if (err)
6830 goto done;
6832 err = got_ref_write(ref, repo);
6833 done:
6834 if (ref)
6835 got_ref_close(ref);
6836 free(base_refname);
6837 free(refname);
6838 return err;
6841 static const struct got_error *
6842 cmd_branch(int argc, char *argv[])
6844 const struct got_error *error = NULL;
6845 struct got_repository *repo = NULL;
6846 struct got_worktree *worktree = NULL;
6847 char *cwd = NULL, *repo_path = NULL;
6848 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6849 const char *delref = NULL, *commit_id_arg = NULL;
6850 struct got_reference *ref = NULL;
6851 struct got_pathlist_head paths;
6852 struct got_object_id *commit_id = NULL;
6853 char *commit_id_str = NULL;
6854 int *pack_fds = NULL;
6856 TAILQ_INIT(&paths);
6858 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6859 switch (ch) {
6860 case 'c':
6861 commit_id_arg = optarg;
6862 break;
6863 case 'd':
6864 delref = optarg;
6865 break;
6866 case 'l':
6867 do_list = 1;
6868 break;
6869 case 'n':
6870 do_update = 0;
6871 break;
6872 case 'r':
6873 repo_path = realpath(optarg, NULL);
6874 if (repo_path == NULL)
6875 return got_error_from_errno2("realpath",
6876 optarg);
6877 got_path_strip_trailing_slashes(repo_path);
6878 break;
6879 case 't':
6880 sort_by_time = 1;
6881 break;
6882 default:
6883 usage_branch();
6884 /* NOTREACHED */
6888 if (do_list && delref)
6889 option_conflict('l', 'd');
6890 if (sort_by_time && !do_list)
6891 errx(1, "-t option requires -l option");
6893 argc -= optind;
6894 argv += optind;
6896 if (!do_list && !delref && argc == 0)
6897 do_show = 1;
6899 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6900 errx(1, "-c option can only be used when creating a branch");
6902 if (do_list || delref) {
6903 if (argc > 0)
6904 usage_branch();
6905 } else if (!do_show && argc != 1)
6906 usage_branch();
6908 #ifndef PROFILE
6909 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6910 "sendfd unveil", NULL) == -1)
6911 err(1, "pledge");
6912 #endif
6913 cwd = getcwd(NULL, 0);
6914 if (cwd == NULL) {
6915 error = got_error_from_errno("getcwd");
6916 goto done;
6919 error = got_repo_pack_fds_open(&pack_fds);
6920 if (error != NULL)
6921 goto done;
6923 if (repo_path == NULL) {
6924 error = got_worktree_open(&worktree, cwd);
6925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6926 goto done;
6927 else
6928 error = NULL;
6929 if (worktree) {
6930 repo_path =
6931 strdup(got_worktree_get_repo_path(worktree));
6932 if (repo_path == NULL)
6933 error = got_error_from_errno("strdup");
6934 if (error)
6935 goto done;
6936 } else {
6937 repo_path = strdup(cwd);
6938 if (repo_path == NULL) {
6939 error = got_error_from_errno("strdup");
6940 goto done;
6945 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6946 if (error != NULL)
6947 goto done;
6949 #ifndef PROFILE
6950 if (do_list || do_show) {
6951 /* Remove "cpath" promise. */
6952 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6953 NULL) == -1)
6954 err(1, "pledge");
6956 #endif
6958 error = apply_unveil(got_repo_get_path(repo), do_list,
6959 worktree ? got_worktree_get_root_path(worktree) : NULL);
6960 if (error)
6961 goto done;
6963 if (do_show)
6964 error = show_current_branch(repo, worktree);
6965 else if (do_list)
6966 error = list_branches(repo, worktree, sort_by_time);
6967 else if (delref)
6968 error = delete_branch(repo, worktree, delref);
6969 else {
6970 struct got_reflist_head refs;
6971 TAILQ_INIT(&refs);
6972 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6973 NULL);
6974 if (error)
6975 goto done;
6976 if (commit_id_arg == NULL)
6977 commit_id_arg = worktree ?
6978 got_worktree_get_head_ref_name(worktree) :
6979 GOT_REF_HEAD;
6980 error = got_repo_match_object_id(&commit_id, NULL,
6981 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6982 got_ref_list_free(&refs);
6983 if (error)
6984 goto done;
6985 error = add_branch(repo, argv[0], commit_id);
6986 if (error)
6987 goto done;
6988 if (worktree && do_update) {
6989 struct got_update_progress_arg upa;
6990 char *branch_refname = NULL;
6992 error = got_object_id_str(&commit_id_str, commit_id);
6993 if (error)
6994 goto done;
6995 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6996 worktree);
6997 if (error)
6998 goto done;
6999 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7000 == -1) {
7001 error = got_error_from_errno("asprintf");
7002 goto done;
7004 error = got_ref_open(&ref, repo, branch_refname, 0);
7005 free(branch_refname);
7006 if (error)
7007 goto done;
7008 error = switch_head_ref(ref, commit_id, worktree,
7009 repo);
7010 if (error)
7011 goto done;
7012 error = got_worktree_set_base_commit_id(worktree, repo,
7013 commit_id);
7014 if (error)
7015 goto done;
7016 memset(&upa, 0, sizeof(upa));
7017 error = got_worktree_checkout_files(worktree, &paths,
7018 repo, update_progress, &upa, check_cancelled,
7019 NULL);
7020 if (error)
7021 goto done;
7022 if (upa.did_something) {
7023 printf("Updated to %s: %s\n",
7024 got_worktree_get_head_ref_name(worktree),
7025 commit_id_str);
7027 print_update_progress_stats(&upa);
7030 done:
7031 if (ref)
7032 got_ref_close(ref);
7033 if (repo) {
7034 const struct got_error *close_err = got_repo_close(repo);
7035 if (error == NULL)
7036 error = close_err;
7038 if (worktree)
7039 got_worktree_close(worktree);
7040 if (pack_fds) {
7041 const struct got_error *pack_err =
7042 got_repo_pack_fds_close(pack_fds);
7043 if (error == NULL)
7044 error = pack_err;
7046 free(cwd);
7047 free(repo_path);
7048 free(commit_id);
7049 free(commit_id_str);
7050 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7051 return error;
7055 __dead static void
7056 usage_tag(void)
7058 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7059 "[-r repository-path] [-s signer-id] name\n", getprogname());
7060 exit(1);
7063 #if 0
7064 static const struct got_error *
7065 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7067 const struct got_error *err = NULL;
7068 struct got_reflist_entry *re, *se, *new;
7069 struct got_object_id *re_id, *se_id;
7070 struct got_tag_object *re_tag, *se_tag;
7071 time_t re_time, se_time;
7073 STAILQ_FOREACH(re, tags, entry) {
7074 se = STAILQ_FIRST(sorted);
7075 if (se == NULL) {
7076 err = got_reflist_entry_dup(&new, re);
7077 if (err)
7078 return err;
7079 STAILQ_INSERT_HEAD(sorted, new, entry);
7080 continue;
7081 } else {
7082 err = got_ref_resolve(&re_id, repo, re->ref);
7083 if (err)
7084 break;
7085 err = got_object_open_as_tag(&re_tag, repo, re_id);
7086 free(re_id);
7087 if (err)
7088 break;
7089 re_time = got_object_tag_get_tagger_time(re_tag);
7090 got_object_tag_close(re_tag);
7093 while (se) {
7094 err = got_ref_resolve(&se_id, repo, re->ref);
7095 if (err)
7096 break;
7097 err = got_object_open_as_tag(&se_tag, repo, se_id);
7098 free(se_id);
7099 if (err)
7100 break;
7101 se_time = got_object_tag_get_tagger_time(se_tag);
7102 got_object_tag_close(se_tag);
7104 if (se_time > re_time) {
7105 err = got_reflist_entry_dup(&new, re);
7106 if (err)
7107 return err;
7108 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7109 break;
7111 se = STAILQ_NEXT(se, entry);
7112 continue;
7115 done:
7116 return err;
7118 #endif
7120 static const struct got_error *
7121 get_tag_refname(char **refname, const char *tag_name)
7123 const struct got_error *err;
7125 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7126 *refname = strdup(tag_name);
7127 if (*refname == NULL)
7128 return got_error_from_errno("strdup");
7129 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7130 err = got_error_from_errno("asprintf");
7131 *refname = NULL;
7132 return err;
7135 return NULL;
7138 static const struct got_error *
7139 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7140 const char *allowed_signers, const char *revoked_signers, int verbosity)
7142 static const struct got_error *err = NULL;
7143 struct got_reflist_head refs;
7144 struct got_reflist_entry *re;
7145 char *wanted_refname = NULL;
7146 int bad_sigs = 0;
7148 TAILQ_INIT(&refs);
7150 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7151 if (err)
7152 return err;
7154 if (tag_name) {
7155 struct got_reference *ref;
7156 err = get_tag_refname(&wanted_refname, tag_name);
7157 if (err)
7158 goto done;
7159 /* Wanted tag reference should exist. */
7160 err = got_ref_open(&ref, repo, wanted_refname, 0);
7161 if (err)
7162 goto done;
7163 got_ref_close(ref);
7166 TAILQ_FOREACH(re, &refs, entry) {
7167 const char *refname;
7168 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7169 char datebuf[26];
7170 const char *tagger, *ssh_sig = NULL;
7171 char *sig_msg = NULL;
7172 time_t tagger_time;
7173 struct got_object_id *id;
7174 struct got_tag_object *tag;
7175 struct got_commit_object *commit = NULL;
7177 refname = got_ref_get_name(re->ref);
7178 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7179 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7180 continue;
7181 refname += 10;
7182 refstr = got_ref_to_str(re->ref);
7183 if (refstr == NULL) {
7184 err = got_error_from_errno("got_ref_to_str");
7185 break;
7188 err = got_ref_resolve(&id, repo, re->ref);
7189 if (err)
7190 break;
7191 err = got_object_open_as_tag(&tag, repo, id);
7192 if (err) {
7193 if (err->code != GOT_ERR_OBJ_TYPE) {
7194 free(id);
7195 break;
7197 /* "lightweight" tag */
7198 err = got_object_open_as_commit(&commit, repo, id);
7199 if (err) {
7200 free(id);
7201 break;
7203 tagger = got_object_commit_get_committer(commit);
7204 tagger_time =
7205 got_object_commit_get_committer_time(commit);
7206 err = got_object_id_str(&id_str, id);
7207 free(id);
7208 if (err)
7209 break;
7210 } else {
7211 free(id);
7212 tagger = got_object_tag_get_tagger(tag);
7213 tagger_time = got_object_tag_get_tagger_time(tag);
7214 err = got_object_id_str(&id_str,
7215 got_object_tag_get_object_id(tag));
7216 if (err)
7217 break;
7220 if (tag && verify_tags) {
7221 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7222 got_object_tag_get_message(tag));
7223 if (ssh_sig && allowed_signers == NULL) {
7224 err = got_error_msg(
7225 GOT_ERR_VERIFY_TAG_SIGNATURE,
7226 "SSH signature verification requires "
7227 "setting allowed_signers in "
7228 "got.conf(5)");
7229 break;
7233 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7234 free(refstr);
7235 printf("from: %s\n", tagger);
7236 datestr = get_datestr(&tagger_time, datebuf);
7237 if (datestr)
7238 printf("date: %s UTC\n", datestr);
7239 if (commit)
7240 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7241 else {
7242 switch (got_object_tag_get_object_type(tag)) {
7243 case GOT_OBJ_TYPE_BLOB:
7244 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7245 id_str);
7246 break;
7247 case GOT_OBJ_TYPE_TREE:
7248 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7249 id_str);
7250 break;
7251 case GOT_OBJ_TYPE_COMMIT:
7252 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7253 id_str);
7254 break;
7255 case GOT_OBJ_TYPE_TAG:
7256 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7257 id_str);
7258 break;
7259 default:
7260 break;
7263 free(id_str);
7265 if (ssh_sig) {
7266 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7267 allowed_signers, revoked_signers, verbosity);
7268 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7269 bad_sigs = 1;
7270 else if (err)
7271 break;
7272 printf("signature: %s", sig_msg);
7273 free(sig_msg);
7274 sig_msg = NULL;
7277 if (commit) {
7278 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7279 if (err)
7280 break;
7281 got_object_commit_close(commit);
7282 } else {
7283 tagmsg0 = strdup(got_object_tag_get_message(tag));
7284 got_object_tag_close(tag);
7285 if (tagmsg0 == NULL) {
7286 err = got_error_from_errno("strdup");
7287 break;
7291 tagmsg = tagmsg0;
7292 do {
7293 line = strsep(&tagmsg, "\n");
7294 if (line)
7295 printf(" %s\n", line);
7296 } while (line);
7297 free(tagmsg0);
7299 done:
7300 got_ref_list_free(&refs);
7301 free(wanted_refname);
7303 if (err == NULL && bad_sigs)
7304 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7305 return err;
7308 static const struct got_error *
7309 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7310 const char *tag_name, const char *repo_path)
7312 const struct got_error *err = NULL;
7313 char *template = NULL, *initial_content = NULL;
7314 char *editor = NULL;
7315 int initial_content_len;
7316 int fd = -1;
7318 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7319 err = got_error_from_errno("asprintf");
7320 goto done;
7323 initial_content_len = asprintf(&initial_content,
7324 "\n# tagging commit %s as %s\n",
7325 commit_id_str, tag_name);
7326 if (initial_content_len == -1) {
7327 err = got_error_from_errno("asprintf");
7328 goto done;
7331 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7332 if (err)
7333 goto done;
7335 if (write(fd, initial_content, initial_content_len) == -1) {
7336 err = got_error_from_errno2("write", *tagmsg_path);
7337 goto done;
7340 err = get_editor(&editor);
7341 if (err)
7342 goto done;
7343 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7344 initial_content_len, 1);
7345 done:
7346 free(initial_content);
7347 free(template);
7348 free(editor);
7350 if (fd != -1 && close(fd) == -1 && err == NULL)
7351 err = got_error_from_errno2("close", *tagmsg_path);
7353 if (err) {
7354 free(*tagmsg);
7355 *tagmsg = NULL;
7357 return err;
7360 static const struct got_error *
7361 add_tag(struct got_repository *repo, const char *tagger,
7362 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7363 const char *signer_id, int verbosity)
7365 const struct got_error *err = NULL;
7366 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7367 char *label = NULL, *commit_id_str = NULL;
7368 struct got_reference *ref = NULL;
7369 char *refname = NULL, *tagmsg = NULL;
7370 char *tagmsg_path = NULL, *tag_id_str = NULL;
7371 int preserve_tagmsg = 0;
7372 struct got_reflist_head refs;
7374 TAILQ_INIT(&refs);
7377 * Don't let the user create a tag name with a leading '-'.
7378 * While technically a valid reference name, this case is usually
7379 * an unintended typo.
7381 if (tag_name[0] == '-')
7382 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7384 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7385 if (err)
7386 goto done;
7388 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7389 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7390 if (err)
7391 goto done;
7393 err = got_object_id_str(&commit_id_str, commit_id);
7394 if (err)
7395 goto done;
7397 err = get_tag_refname(&refname, tag_name);
7398 if (err)
7399 goto done;
7400 if (strncmp("refs/tags/", tag_name, 10) == 0)
7401 tag_name += 10;
7403 err = got_ref_open(&ref, repo, refname, 0);
7404 if (err == NULL) {
7405 err = got_error(GOT_ERR_TAG_EXISTS);
7406 goto done;
7407 } else if (err->code != GOT_ERR_NOT_REF)
7408 goto done;
7410 if (tagmsg_arg == NULL) {
7411 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7412 tag_name, got_repo_get_path(repo));
7413 if (err) {
7414 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7415 tagmsg_path != NULL)
7416 preserve_tagmsg = 1;
7417 goto done;
7419 /* Editor is done; we can now apply unveil(2) */
7420 err = got_sigs_apply_unveil();
7421 if (err)
7422 goto done;
7423 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7424 if (err)
7425 goto done;
7428 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7429 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7430 verbosity);
7431 if (err) {
7432 if (tagmsg_path)
7433 preserve_tagmsg = 1;
7434 goto done;
7437 err = got_ref_alloc(&ref, refname, tag_id);
7438 if (err) {
7439 if (tagmsg_path)
7440 preserve_tagmsg = 1;
7441 goto done;
7444 err = got_ref_write(ref, repo);
7445 if (err) {
7446 if (tagmsg_path)
7447 preserve_tagmsg = 1;
7448 goto done;
7451 err = got_object_id_str(&tag_id_str, tag_id);
7452 if (err) {
7453 if (tagmsg_path)
7454 preserve_tagmsg = 1;
7455 goto done;
7457 printf("Created tag %s\n", tag_id_str);
7458 done:
7459 if (preserve_tagmsg) {
7460 fprintf(stderr, "%s: tag message preserved in %s\n",
7461 getprogname(), tagmsg_path);
7462 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7463 err = got_error_from_errno2("unlink", tagmsg_path);
7464 free(tag_id_str);
7465 if (ref)
7466 got_ref_close(ref);
7467 free(commit_id);
7468 free(commit_id_str);
7469 free(refname);
7470 free(tagmsg);
7471 free(tagmsg_path);
7472 got_ref_list_free(&refs);
7473 return err;
7476 static const struct got_error *
7477 cmd_tag(int argc, char *argv[])
7479 const struct got_error *error = NULL;
7480 struct got_repository *repo = NULL;
7481 struct got_worktree *worktree = NULL;
7482 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7483 char *gitconfig_path = NULL, *tagger = NULL;
7484 char *allowed_signers = NULL, *revoked_signers = NULL;
7485 char *signer_id = NULL;
7486 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7487 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7488 int *pack_fds = NULL;
7490 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7491 switch (ch) {
7492 case 'c':
7493 commit_id_arg = optarg;
7494 break;
7495 case 'l':
7496 do_list = 1;
7497 break;
7498 case 'm':
7499 tagmsg = optarg;
7500 break;
7501 case 'r':
7502 repo_path = realpath(optarg, NULL);
7503 if (repo_path == NULL) {
7504 error = got_error_from_errno2("realpath",
7505 optarg);
7506 goto done;
7508 got_path_strip_trailing_slashes(repo_path);
7509 break;
7510 case 's':
7511 signer_id = strdup(optarg);
7512 if (signer_id == NULL) {
7513 error = got_error_from_errno("strdup");
7514 goto done;
7516 break;
7517 case 'V':
7518 verify_tags = 1;
7519 break;
7520 case 'v':
7521 if (verbosity < 0)
7522 verbosity = 0;
7523 else if (verbosity < 3)
7524 verbosity++;
7525 break;
7526 default:
7527 usage_tag();
7528 /* NOTREACHED */
7532 argc -= optind;
7533 argv += optind;
7535 if (do_list || verify_tags) {
7536 if (commit_id_arg != NULL)
7537 errx(1,
7538 "-c option can only be used when creating a tag");
7539 if (tagmsg) {
7540 if (do_list)
7541 option_conflict('l', 'm');
7542 else
7543 option_conflict('V', 'm');
7545 if (signer_id) {
7546 if (do_list)
7547 option_conflict('l', 's');
7548 else
7549 option_conflict('V', 's');
7551 if (argc > 1)
7552 usage_tag();
7553 } else if (argc != 1)
7554 usage_tag();
7556 if (argc == 1)
7557 tag_name = argv[0];
7559 #ifndef PROFILE
7560 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7561 "sendfd unveil", NULL) == -1)
7562 err(1, "pledge");
7563 #endif
7564 cwd = getcwd(NULL, 0);
7565 if (cwd == NULL) {
7566 error = got_error_from_errno("getcwd");
7567 goto done;
7570 error = got_repo_pack_fds_open(&pack_fds);
7571 if (error != NULL)
7572 goto done;
7574 if (repo_path == NULL) {
7575 error = got_worktree_open(&worktree, cwd);
7576 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7577 goto done;
7578 else
7579 error = NULL;
7580 if (worktree) {
7581 repo_path =
7582 strdup(got_worktree_get_repo_path(worktree));
7583 if (repo_path == NULL)
7584 error = got_error_from_errno("strdup");
7585 if (error)
7586 goto done;
7587 } else {
7588 repo_path = strdup(cwd);
7589 if (repo_path == NULL) {
7590 error = got_error_from_errno("strdup");
7591 goto done;
7596 if (do_list || verify_tags) {
7597 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7598 if (error != NULL)
7599 goto done;
7600 error = get_allowed_signers(&allowed_signers, repo, worktree);
7601 if (error)
7602 goto done;
7603 error = get_revoked_signers(&revoked_signers, repo, worktree);
7604 if (error)
7605 goto done;
7606 if (worktree) {
7607 /* Release work tree lock. */
7608 got_worktree_close(worktree);
7609 worktree = NULL;
7613 * Remove "cpath" promise unless needed for signature tmpfile
7614 * creation.
7616 if (verify_tags)
7617 got_sigs_apply_unveil();
7618 else {
7619 #ifndef PROFILE
7620 if (pledge("stdio rpath wpath flock proc exec sendfd "
7621 "unveil", NULL) == -1)
7622 err(1, "pledge");
7623 #endif
7625 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7626 if (error)
7627 goto done;
7628 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7629 revoked_signers, verbosity);
7630 } else {
7631 error = get_gitconfig_path(&gitconfig_path);
7632 if (error)
7633 goto done;
7634 error = got_repo_open(&repo, repo_path, gitconfig_path,
7635 pack_fds);
7636 if (error != NULL)
7637 goto done;
7639 error = get_author(&tagger, repo, worktree);
7640 if (error)
7641 goto done;
7642 if (signer_id == NULL) {
7643 error = get_signer_id(&signer_id, repo, worktree);
7644 if (error)
7645 goto done;
7648 if (tagmsg) {
7649 if (signer_id) {
7650 error = got_sigs_apply_unveil();
7651 if (error)
7652 goto done;
7654 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7655 if (error)
7656 goto done;
7659 if (commit_id_arg == NULL) {
7660 struct got_reference *head_ref;
7661 struct got_object_id *commit_id;
7662 error = got_ref_open(&head_ref, repo,
7663 worktree ? got_worktree_get_head_ref_name(worktree)
7664 : GOT_REF_HEAD, 0);
7665 if (error)
7666 goto done;
7667 error = got_ref_resolve(&commit_id, repo, head_ref);
7668 got_ref_close(head_ref);
7669 if (error)
7670 goto done;
7671 error = got_object_id_str(&commit_id_str, commit_id);
7672 free(commit_id);
7673 if (error)
7674 goto done;
7677 if (worktree) {
7678 /* Release work tree lock. */
7679 got_worktree_close(worktree);
7680 worktree = NULL;
7683 error = add_tag(repo, tagger, tag_name,
7684 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7685 signer_id, verbosity);
7687 done:
7688 if (repo) {
7689 const struct got_error *close_err = got_repo_close(repo);
7690 if (error == NULL)
7691 error = close_err;
7693 if (worktree)
7694 got_worktree_close(worktree);
7695 if (pack_fds) {
7696 const struct got_error *pack_err =
7697 got_repo_pack_fds_close(pack_fds);
7698 if (error == NULL)
7699 error = pack_err;
7701 free(cwd);
7702 free(repo_path);
7703 free(gitconfig_path);
7704 free(commit_id_str);
7705 free(tagger);
7706 free(allowed_signers);
7707 free(revoked_signers);
7708 free(signer_id);
7709 return error;
7712 __dead static void
7713 usage_add(void)
7715 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7716 exit(1);
7719 static const struct got_error *
7720 add_progress(void *arg, unsigned char status, const char *path)
7722 while (path[0] == '/')
7723 path++;
7724 printf("%c %s\n", status, path);
7725 return NULL;
7728 static const struct got_error *
7729 cmd_add(int argc, char *argv[])
7731 const struct got_error *error = NULL;
7732 struct got_repository *repo = NULL;
7733 struct got_worktree *worktree = NULL;
7734 char *cwd = NULL;
7735 struct got_pathlist_head paths;
7736 struct got_pathlist_entry *pe;
7737 int ch, can_recurse = 0, no_ignores = 0;
7738 int *pack_fds = NULL;
7740 TAILQ_INIT(&paths);
7742 while ((ch = getopt(argc, argv, "IR")) != -1) {
7743 switch (ch) {
7744 case 'I':
7745 no_ignores = 1;
7746 break;
7747 case 'R':
7748 can_recurse = 1;
7749 break;
7750 default:
7751 usage_add();
7752 /* NOTREACHED */
7756 argc -= optind;
7757 argv += optind;
7759 #ifndef PROFILE
7760 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7761 NULL) == -1)
7762 err(1, "pledge");
7763 #endif
7764 if (argc < 1)
7765 usage_add();
7767 cwd = getcwd(NULL, 0);
7768 if (cwd == NULL) {
7769 error = got_error_from_errno("getcwd");
7770 goto done;
7773 error = got_repo_pack_fds_open(&pack_fds);
7774 if (error != NULL)
7775 goto done;
7777 error = got_worktree_open(&worktree, cwd);
7778 if (error) {
7779 if (error->code == GOT_ERR_NOT_WORKTREE)
7780 error = wrap_not_worktree_error(error, "add", cwd);
7781 goto done;
7784 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7785 NULL, pack_fds);
7786 if (error != NULL)
7787 goto done;
7789 error = apply_unveil(got_repo_get_path(repo), 1,
7790 got_worktree_get_root_path(worktree));
7791 if (error)
7792 goto done;
7794 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7795 if (error)
7796 goto done;
7798 if (!can_recurse) {
7799 char *ondisk_path;
7800 struct stat sb;
7801 TAILQ_FOREACH(pe, &paths, entry) {
7802 if (asprintf(&ondisk_path, "%s/%s",
7803 got_worktree_get_root_path(worktree),
7804 pe->path) == -1) {
7805 error = got_error_from_errno("asprintf");
7806 goto done;
7808 if (lstat(ondisk_path, &sb) == -1) {
7809 if (errno == ENOENT) {
7810 free(ondisk_path);
7811 continue;
7813 error = got_error_from_errno2("lstat",
7814 ondisk_path);
7815 free(ondisk_path);
7816 goto done;
7818 free(ondisk_path);
7819 if (S_ISDIR(sb.st_mode)) {
7820 error = got_error_msg(GOT_ERR_BAD_PATH,
7821 "adding directories requires -R option");
7822 goto done;
7827 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7828 NULL, repo, no_ignores);
7829 done:
7830 if (repo) {
7831 const struct got_error *close_err = got_repo_close(repo);
7832 if (error == NULL)
7833 error = close_err;
7835 if (worktree)
7836 got_worktree_close(worktree);
7837 if (pack_fds) {
7838 const struct got_error *pack_err =
7839 got_repo_pack_fds_close(pack_fds);
7840 if (error == NULL)
7841 error = pack_err;
7843 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7844 free(cwd);
7845 return error;
7848 __dead static void
7849 usage_remove(void)
7851 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7852 getprogname());
7853 exit(1);
7856 static const struct got_error *
7857 print_remove_status(void *arg, unsigned char status,
7858 unsigned char staged_status, const char *path)
7860 while (path[0] == '/')
7861 path++;
7862 if (status == GOT_STATUS_NONEXISTENT)
7863 return NULL;
7864 if (status == staged_status && (status == GOT_STATUS_DELETE))
7865 status = GOT_STATUS_NO_CHANGE;
7866 printf("%c%c %s\n", status, staged_status, path);
7867 return NULL;
7870 static const struct got_error *
7871 cmd_remove(int argc, char *argv[])
7873 const struct got_error *error = NULL;
7874 struct got_worktree *worktree = NULL;
7875 struct got_repository *repo = NULL;
7876 const char *status_codes = NULL;
7877 char *cwd = NULL;
7878 struct got_pathlist_head paths;
7879 struct got_pathlist_entry *pe;
7880 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7881 int ignore_missing_paths = 0;
7882 int *pack_fds = NULL;
7884 TAILQ_INIT(&paths);
7886 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7887 switch (ch) {
7888 case 'f':
7889 delete_local_mods = 1;
7890 ignore_missing_paths = 1;
7891 break;
7892 case 'k':
7893 keep_on_disk = 1;
7894 break;
7895 case 'R':
7896 can_recurse = 1;
7897 break;
7898 case 's':
7899 for (i = 0; i < strlen(optarg); i++) {
7900 switch (optarg[i]) {
7901 case GOT_STATUS_MODIFY:
7902 delete_local_mods = 1;
7903 break;
7904 case GOT_STATUS_MISSING:
7905 ignore_missing_paths = 1;
7906 break;
7907 default:
7908 errx(1, "invalid status code '%c'",
7909 optarg[i]);
7912 status_codes = optarg;
7913 break;
7914 default:
7915 usage_remove();
7916 /* NOTREACHED */
7920 argc -= optind;
7921 argv += optind;
7923 #ifndef PROFILE
7924 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7925 NULL) == -1)
7926 err(1, "pledge");
7927 #endif
7928 if (argc < 1)
7929 usage_remove();
7931 cwd = getcwd(NULL, 0);
7932 if (cwd == NULL) {
7933 error = got_error_from_errno("getcwd");
7934 goto done;
7937 error = got_repo_pack_fds_open(&pack_fds);
7938 if (error != NULL)
7939 goto done;
7941 error = got_worktree_open(&worktree, cwd);
7942 if (error) {
7943 if (error->code == GOT_ERR_NOT_WORKTREE)
7944 error = wrap_not_worktree_error(error, "remove", cwd);
7945 goto done;
7948 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7949 NULL, pack_fds);
7950 if (error)
7951 goto done;
7953 error = apply_unveil(got_repo_get_path(repo), 1,
7954 got_worktree_get_root_path(worktree));
7955 if (error)
7956 goto done;
7958 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7959 if (error)
7960 goto done;
7962 if (!can_recurse) {
7963 char *ondisk_path;
7964 struct stat sb;
7965 TAILQ_FOREACH(pe, &paths, entry) {
7966 if (asprintf(&ondisk_path, "%s/%s",
7967 got_worktree_get_root_path(worktree),
7968 pe->path) == -1) {
7969 error = got_error_from_errno("asprintf");
7970 goto done;
7972 if (lstat(ondisk_path, &sb) == -1) {
7973 if (errno == ENOENT) {
7974 free(ondisk_path);
7975 continue;
7977 error = got_error_from_errno2("lstat",
7978 ondisk_path);
7979 free(ondisk_path);
7980 goto done;
7982 free(ondisk_path);
7983 if (S_ISDIR(sb.st_mode)) {
7984 error = got_error_msg(GOT_ERR_BAD_PATH,
7985 "removing directories requires -R option");
7986 goto done;
7991 error = got_worktree_schedule_delete(worktree, &paths,
7992 delete_local_mods, status_codes, print_remove_status, NULL,
7993 repo, keep_on_disk, ignore_missing_paths);
7994 done:
7995 if (repo) {
7996 const struct got_error *close_err = got_repo_close(repo);
7997 if (error == NULL)
7998 error = close_err;
8000 if (worktree)
8001 got_worktree_close(worktree);
8002 if (pack_fds) {
8003 const struct got_error *pack_err =
8004 got_repo_pack_fds_close(pack_fds);
8005 if (error == NULL)
8006 error = pack_err;
8008 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8009 free(cwd);
8010 return error;
8013 __dead static void
8014 usage_patch(void)
8016 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8017 "[patchfile]\n", getprogname());
8018 exit(1);
8021 static const struct got_error *
8022 patch_from_stdin(int *patchfd)
8024 const struct got_error *err = NULL;
8025 ssize_t r;
8026 char buf[BUFSIZ];
8027 sig_t sighup, sigint, sigquit;
8029 *patchfd = got_opentempfd();
8030 if (*patchfd == -1)
8031 return got_error_from_errno("got_opentempfd");
8033 sighup = signal(SIGHUP, SIG_DFL);
8034 sigint = signal(SIGINT, SIG_DFL);
8035 sigquit = signal(SIGQUIT, SIG_DFL);
8037 for (;;) {
8038 r = read(0, buf, sizeof(buf));
8039 if (r == -1) {
8040 err = got_error_from_errno("read");
8041 break;
8043 if (r == 0)
8044 break;
8045 if (write(*patchfd, buf, r) == -1) {
8046 err = got_error_from_errno("write");
8047 break;
8051 signal(SIGHUP, sighup);
8052 signal(SIGINT, sigint);
8053 signal(SIGQUIT, sigquit);
8055 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8056 err = got_error_from_errno("lseek");
8058 if (err != NULL) {
8059 close(*patchfd);
8060 *patchfd = -1;
8063 return err;
8066 static const struct got_error *
8067 patch_progress(void *arg, const char *old, const char *new,
8068 unsigned char status, const struct got_error *error, int old_from,
8069 int old_lines, int new_from, int new_lines, int offset,
8070 int ws_mangled, const struct got_error *hunk_err)
8072 const char *path = new == NULL ? old : new;
8074 while (*path == '/')
8075 path++;
8077 if (status != 0)
8078 printf("%c %s\n", status, path);
8080 if (error != NULL)
8081 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8083 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8084 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8085 old_lines, new_from, new_lines);
8086 if (hunk_err != NULL)
8087 printf("%s\n", hunk_err->msg);
8088 else if (offset != 0)
8089 printf("applied with offset %d\n", offset);
8090 else
8091 printf("hunk contains mangled whitespace\n");
8094 return NULL;
8097 static const struct got_error *
8098 cmd_patch(int argc, char *argv[])
8100 const struct got_error *error = NULL, *close_error = NULL;
8101 struct got_worktree *worktree = NULL;
8102 struct got_repository *repo = NULL;
8103 struct got_reflist_head refs;
8104 struct got_object_id *commit_id = NULL;
8105 const char *commit_id_str = NULL;
8106 struct stat sb;
8107 const char *errstr;
8108 char *cwd = NULL;
8109 int ch, nop = 0, strip = -1, reverse = 0;
8110 int patchfd;
8111 int *pack_fds = NULL;
8113 TAILQ_INIT(&refs);
8115 #ifndef PROFILE
8116 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8117 "unveil", NULL) == -1)
8118 err(1, "pledge");
8119 #endif
8121 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8122 switch (ch) {
8123 case 'c':
8124 commit_id_str = optarg;
8125 break;
8126 case 'n':
8127 nop = 1;
8128 break;
8129 case 'p':
8130 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8131 if (errstr != NULL)
8132 errx(1, "pathname strip count is %s: %s",
8133 errstr, optarg);
8134 break;
8135 case 'R':
8136 reverse = 1;
8137 break;
8138 default:
8139 usage_patch();
8140 /* NOTREACHED */
8144 argc -= optind;
8145 argv += optind;
8147 if (argc == 0) {
8148 error = patch_from_stdin(&patchfd);
8149 if (error)
8150 return error;
8151 } else if (argc == 1) {
8152 patchfd = open(argv[0], O_RDONLY);
8153 if (patchfd == -1) {
8154 error = got_error_from_errno2("open", argv[0]);
8155 return error;
8157 if (fstat(patchfd, &sb) == -1) {
8158 error = got_error_from_errno2("fstat", argv[0]);
8159 goto done;
8161 if (!S_ISREG(sb.st_mode)) {
8162 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8163 goto done;
8165 } else
8166 usage_patch();
8168 if ((cwd = getcwd(NULL, 0)) == NULL) {
8169 error = got_error_from_errno("getcwd");
8170 goto done;
8173 error = got_repo_pack_fds_open(&pack_fds);
8174 if (error != NULL)
8175 goto done;
8177 error = got_worktree_open(&worktree, cwd);
8178 if (error != NULL)
8179 goto done;
8181 const char *repo_path = got_worktree_get_repo_path(worktree);
8182 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8183 if (error != NULL)
8184 goto done;
8186 error = apply_unveil(got_repo_get_path(repo), 0,
8187 got_worktree_get_root_path(worktree));
8188 if (error != NULL)
8189 goto done;
8191 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8192 if (error)
8193 goto done;
8195 if (commit_id_str != NULL) {
8196 error = got_repo_match_object_id(&commit_id, NULL,
8197 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8198 if (error)
8199 goto done;
8202 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8203 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8205 done:
8206 got_ref_list_free(&refs);
8207 free(commit_id);
8208 if (repo) {
8209 close_error = got_repo_close(repo);
8210 if (error == NULL)
8211 error = close_error;
8213 if (worktree != NULL) {
8214 close_error = got_worktree_close(worktree);
8215 if (error == NULL)
8216 error = close_error;
8218 if (pack_fds) {
8219 const struct got_error *pack_err =
8220 got_repo_pack_fds_close(pack_fds);
8221 if (error == NULL)
8222 error = pack_err;
8224 free(cwd);
8225 return error;
8228 __dead static void
8229 usage_revert(void)
8231 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8232 getprogname());
8233 exit(1);
8236 static const struct got_error *
8237 revert_progress(void *arg, unsigned char status, const char *path)
8239 if (status == GOT_STATUS_UNVERSIONED)
8240 return NULL;
8242 while (path[0] == '/')
8243 path++;
8244 printf("%c %s\n", status, path);
8245 return NULL;
8248 struct choose_patch_arg {
8249 FILE *patch_script_file;
8250 const char *action;
8253 static const struct got_error *
8254 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8255 int nchanges, const char *action)
8257 const struct got_error *err;
8258 char *line = NULL;
8259 size_t linesize = 0;
8260 ssize_t linelen;
8262 switch (status) {
8263 case GOT_STATUS_ADD:
8264 printf("A %s\n%s this addition? [y/n] ", path, action);
8265 break;
8266 case GOT_STATUS_DELETE:
8267 printf("D %s\n%s this deletion? [y/n] ", path, action);
8268 break;
8269 case GOT_STATUS_MODIFY:
8270 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8271 return got_error_from_errno("fseek");
8272 printf(GOT_COMMIT_SEP_STR);
8273 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8274 printf("%s", line);
8275 if (linelen == -1 && ferror(patch_file)) {
8276 err = got_error_from_errno("getline");
8277 free(line);
8278 return err;
8280 free(line);
8281 printf(GOT_COMMIT_SEP_STR);
8282 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8283 path, n, nchanges, action);
8284 break;
8285 default:
8286 return got_error_path(path, GOT_ERR_FILE_STATUS);
8289 fflush(stdout);
8290 return NULL;
8293 static const struct got_error *
8294 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8295 FILE *patch_file, int n, int nchanges)
8297 const struct got_error *err = NULL;
8298 char *line = NULL;
8299 size_t linesize = 0;
8300 ssize_t linelen;
8301 int resp = ' ';
8302 struct choose_patch_arg *a = arg;
8304 *choice = GOT_PATCH_CHOICE_NONE;
8306 if (a->patch_script_file) {
8307 char *nl;
8308 err = show_change(status, path, patch_file, n, nchanges,
8309 a->action);
8310 if (err)
8311 return err;
8312 linelen = getline(&line, &linesize, a->patch_script_file);
8313 if (linelen == -1) {
8314 if (ferror(a->patch_script_file))
8315 return got_error_from_errno("getline");
8316 return NULL;
8318 nl = strchr(line, '\n');
8319 if (nl)
8320 *nl = '\0';
8321 if (strcmp(line, "y") == 0) {
8322 *choice = GOT_PATCH_CHOICE_YES;
8323 printf("y\n");
8324 } else if (strcmp(line, "n") == 0) {
8325 *choice = GOT_PATCH_CHOICE_NO;
8326 printf("n\n");
8327 } else if (strcmp(line, "q") == 0 &&
8328 status == GOT_STATUS_MODIFY) {
8329 *choice = GOT_PATCH_CHOICE_QUIT;
8330 printf("q\n");
8331 } else
8332 printf("invalid response '%s'\n", line);
8333 free(line);
8334 return NULL;
8337 while (resp != 'y' && resp != 'n' && resp != 'q') {
8338 err = show_change(status, path, patch_file, n, nchanges,
8339 a->action);
8340 if (err)
8341 return err;
8342 resp = getchar();
8343 if (resp == '\n')
8344 resp = getchar();
8345 if (status == GOT_STATUS_MODIFY) {
8346 if (resp != 'y' && resp != 'n' && resp != 'q') {
8347 printf("invalid response '%c'\n", resp);
8348 resp = ' ';
8350 } else if (resp != 'y' && resp != 'n') {
8351 printf("invalid response '%c'\n", resp);
8352 resp = ' ';
8356 if (resp == 'y')
8357 *choice = GOT_PATCH_CHOICE_YES;
8358 else if (resp == 'n')
8359 *choice = GOT_PATCH_CHOICE_NO;
8360 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8361 *choice = GOT_PATCH_CHOICE_QUIT;
8363 return NULL;
8366 static const struct got_error *
8367 cmd_revert(int argc, char *argv[])
8369 const struct got_error *error = NULL;
8370 struct got_worktree *worktree = NULL;
8371 struct got_repository *repo = NULL;
8372 char *cwd = NULL, *path = NULL;
8373 struct got_pathlist_head paths;
8374 struct got_pathlist_entry *pe;
8375 int ch, can_recurse = 0, pflag = 0;
8376 FILE *patch_script_file = NULL;
8377 const char *patch_script_path = NULL;
8378 struct choose_patch_arg cpa;
8379 int *pack_fds = NULL;
8381 TAILQ_INIT(&paths);
8383 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8384 switch (ch) {
8385 case 'F':
8386 patch_script_path = optarg;
8387 break;
8388 case 'p':
8389 pflag = 1;
8390 break;
8391 case 'R':
8392 can_recurse = 1;
8393 break;
8394 default:
8395 usage_revert();
8396 /* NOTREACHED */
8400 argc -= optind;
8401 argv += optind;
8403 #ifndef PROFILE
8404 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8405 "unveil", NULL) == -1)
8406 err(1, "pledge");
8407 #endif
8408 if (argc < 1)
8409 usage_revert();
8410 if (patch_script_path && !pflag)
8411 errx(1, "-F option can only be used together with -p option");
8413 cwd = getcwd(NULL, 0);
8414 if (cwd == NULL) {
8415 error = got_error_from_errno("getcwd");
8416 goto done;
8419 error = got_repo_pack_fds_open(&pack_fds);
8420 if (error != NULL)
8421 goto done;
8423 error = got_worktree_open(&worktree, cwd);
8424 if (error) {
8425 if (error->code == GOT_ERR_NOT_WORKTREE)
8426 error = wrap_not_worktree_error(error, "revert", cwd);
8427 goto done;
8430 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8431 NULL, pack_fds);
8432 if (error != NULL)
8433 goto done;
8435 if (patch_script_path) {
8436 patch_script_file = fopen(patch_script_path, "re");
8437 if (patch_script_file == NULL) {
8438 error = got_error_from_errno2("fopen",
8439 patch_script_path);
8440 goto done;
8443 error = apply_unveil(got_repo_get_path(repo), 1,
8444 got_worktree_get_root_path(worktree));
8445 if (error)
8446 goto done;
8448 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8449 if (error)
8450 goto done;
8452 if (!can_recurse) {
8453 char *ondisk_path;
8454 struct stat sb;
8455 TAILQ_FOREACH(pe, &paths, entry) {
8456 if (asprintf(&ondisk_path, "%s/%s",
8457 got_worktree_get_root_path(worktree),
8458 pe->path) == -1) {
8459 error = got_error_from_errno("asprintf");
8460 goto done;
8462 if (lstat(ondisk_path, &sb) == -1) {
8463 if (errno == ENOENT) {
8464 free(ondisk_path);
8465 continue;
8467 error = got_error_from_errno2("lstat",
8468 ondisk_path);
8469 free(ondisk_path);
8470 goto done;
8472 free(ondisk_path);
8473 if (S_ISDIR(sb.st_mode)) {
8474 error = got_error_msg(GOT_ERR_BAD_PATH,
8475 "reverting directories requires -R option");
8476 goto done;
8481 cpa.patch_script_file = patch_script_file;
8482 cpa.action = "revert";
8483 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8484 pflag ? choose_patch : NULL, &cpa, repo);
8485 done:
8486 if (patch_script_file && fclose(patch_script_file) == EOF &&
8487 error == NULL)
8488 error = got_error_from_errno2("fclose", patch_script_path);
8489 if (repo) {
8490 const struct got_error *close_err = got_repo_close(repo);
8491 if (error == NULL)
8492 error = close_err;
8494 if (worktree)
8495 got_worktree_close(worktree);
8496 if (pack_fds) {
8497 const struct got_error *pack_err =
8498 got_repo_pack_fds_close(pack_fds);
8499 if (error == NULL)
8500 error = pack_err;
8502 free(path);
8503 free(cwd);
8504 return error;
8507 __dead static void
8508 usage_commit(void)
8510 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8511 "[-m message] [path ...]\n", getprogname());
8512 exit(1);
8515 struct collect_commit_logmsg_arg {
8516 const char *cmdline_log;
8517 const char *prepared_log;
8518 int non_interactive;
8519 const char *editor;
8520 const char *worktree_path;
8521 const char *branch_name;
8522 const char *repo_path;
8523 char *logmsg_path;
8527 static const struct got_error *
8528 read_prepared_logmsg(char **logmsg, const char *path)
8530 const struct got_error *err = NULL;
8531 FILE *f = NULL;
8532 struct stat sb;
8533 size_t r;
8535 *logmsg = NULL;
8536 memset(&sb, 0, sizeof(sb));
8538 f = fopen(path, "re");
8539 if (f == NULL)
8540 return got_error_from_errno2("fopen", path);
8542 if (fstat(fileno(f), &sb) == -1) {
8543 err = got_error_from_errno2("fstat", path);
8544 goto done;
8546 if (sb.st_size == 0) {
8547 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8548 goto done;
8551 *logmsg = malloc(sb.st_size + 1);
8552 if (*logmsg == NULL) {
8553 err = got_error_from_errno("malloc");
8554 goto done;
8557 r = fread(*logmsg, 1, sb.st_size, f);
8558 if (r != sb.st_size) {
8559 if (ferror(f))
8560 err = got_error_from_errno2("fread", path);
8561 else
8562 err = got_error(GOT_ERR_IO);
8563 goto done;
8565 (*logmsg)[sb.st_size] = '\0';
8566 done:
8567 if (fclose(f) == EOF && err == NULL)
8568 err = got_error_from_errno2("fclose", path);
8569 if (err) {
8570 free(*logmsg);
8571 *logmsg = NULL;
8573 return err;
8576 static const struct got_error *
8577 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8578 const char *diff_path, char **logmsg, void *arg)
8580 char *initial_content = NULL;
8581 struct got_pathlist_entry *pe;
8582 const struct got_error *err = NULL;
8583 char *template = NULL;
8584 struct collect_commit_logmsg_arg *a = arg;
8585 int initial_content_len;
8586 int fd = -1;
8587 size_t len;
8589 /* if a message was specified on the command line, just use it */
8590 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8591 len = strlen(a->cmdline_log) + 1;
8592 *logmsg = malloc(len + 1);
8593 if (*logmsg == NULL)
8594 return got_error_from_errno("malloc");
8595 strlcpy(*logmsg, a->cmdline_log, len);
8596 return NULL;
8597 } else if (a->prepared_log != NULL && a->non_interactive)
8598 return read_prepared_logmsg(logmsg, a->prepared_log);
8600 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8601 return got_error_from_errno("asprintf");
8603 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8604 if (err)
8605 goto done;
8607 if (a->prepared_log) {
8608 char *msg;
8609 err = read_prepared_logmsg(&msg, a->prepared_log);
8610 if (err)
8611 goto done;
8612 if (write(fd, msg, strlen(msg)) == -1) {
8613 err = got_error_from_errno2("write", a->logmsg_path);
8614 free(msg);
8615 goto done;
8617 free(msg);
8620 initial_content_len = asprintf(&initial_content,
8621 "\n# changes to be committed on branch %s:\n",
8622 a->branch_name);
8623 if (initial_content_len == -1) {
8624 err = got_error_from_errno("asprintf");
8625 goto done;
8628 if (write(fd, initial_content, initial_content_len) == -1) {
8629 err = got_error_from_errno2("write", a->logmsg_path);
8630 goto done;
8633 TAILQ_FOREACH(pe, commitable_paths, entry) {
8634 struct got_commitable *ct = pe->data;
8635 dprintf(fd, "# %c %s\n",
8636 got_commitable_get_status(ct),
8637 got_commitable_get_path(ct));
8640 if (diff_path) {
8641 dprintf(fd, "# detailed changes can be viewed in %s\n",
8642 diff_path);
8645 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8646 initial_content_len, a->prepared_log ? 0 : 1);
8647 done:
8648 free(initial_content);
8649 free(template);
8651 if (fd != -1 && close(fd) == -1 && err == NULL)
8652 err = got_error_from_errno2("close", a->logmsg_path);
8654 /* Editor is done; we can now apply unveil(2) */
8655 if (err == NULL)
8656 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8657 if (err) {
8658 free(*logmsg);
8659 *logmsg = NULL;
8661 return err;
8664 static const struct got_error *
8665 cmd_commit(int argc, char *argv[])
8667 const struct got_error *error = NULL;
8668 struct got_worktree *worktree = NULL;
8669 struct got_repository *repo = NULL;
8670 char *cwd = NULL, *id_str = NULL;
8671 struct got_object_id *id = NULL;
8672 const char *logmsg = NULL;
8673 char *prepared_logmsg = NULL;
8674 struct collect_commit_logmsg_arg cl_arg;
8675 const char *author = NULL;
8676 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8677 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8678 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8679 int show_diff = 1;
8680 struct got_pathlist_head paths;
8681 int *pack_fds = NULL;
8683 TAILQ_INIT(&paths);
8684 cl_arg.logmsg_path = NULL;
8686 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8687 switch (ch) {
8688 case 'A':
8689 author = optarg;
8690 error = valid_author(author);
8691 if (error)
8692 return error;
8693 break;
8694 case 'F':
8695 if (logmsg != NULL)
8696 option_conflict('F', 'm');
8697 prepared_logmsg = realpath(optarg, NULL);
8698 if (prepared_logmsg == NULL)
8699 return got_error_from_errno2("realpath",
8700 optarg);
8701 break;
8702 case 'm':
8703 if (prepared_logmsg)
8704 option_conflict('m', 'F');
8705 logmsg = optarg;
8706 break;
8707 case 'N':
8708 non_interactive = 1;
8709 break;
8710 case 'n':
8711 show_diff = 0;
8712 break;
8713 case 'S':
8714 allow_bad_symlinks = 1;
8715 break;
8716 default:
8717 usage_commit();
8718 /* NOTREACHED */
8722 argc -= optind;
8723 argv += optind;
8725 #ifndef PROFILE
8726 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8727 "unveil", NULL) == -1)
8728 err(1, "pledge");
8729 #endif
8730 cwd = getcwd(NULL, 0);
8731 if (cwd == NULL) {
8732 error = got_error_from_errno("getcwd");
8733 goto done;
8736 error = got_repo_pack_fds_open(&pack_fds);
8737 if (error != NULL)
8738 goto done;
8740 error = got_worktree_open(&worktree, cwd);
8741 if (error) {
8742 if (error->code == GOT_ERR_NOT_WORKTREE)
8743 error = wrap_not_worktree_error(error, "commit", cwd);
8744 goto done;
8747 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8748 if (error)
8749 goto done;
8750 if (rebase_in_progress) {
8751 error = got_error(GOT_ERR_REBASING);
8752 goto done;
8755 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8756 worktree);
8757 if (error)
8758 goto done;
8760 error = get_gitconfig_path(&gitconfig_path);
8761 if (error)
8762 goto done;
8763 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8764 gitconfig_path, pack_fds);
8765 if (error != NULL)
8766 goto done;
8768 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8769 if (error)
8770 goto done;
8771 if (merge_in_progress) {
8772 error = got_error(GOT_ERR_MERGE_BUSY);
8773 goto done;
8776 error = get_author(&committer, repo, worktree);
8777 if (error)
8778 goto done;
8780 if (author != NULL && !strcmp(committer, author)) {
8781 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8782 goto done;
8785 if (author == NULL)
8786 author = committer;
8789 * unveil(2) traverses exec(2); if an editor is used we have
8790 * to apply unveil after the log message has been written.
8792 if (logmsg == NULL || strlen(logmsg) == 0)
8793 error = get_editor(&editor);
8794 else
8795 error = apply_unveil(got_repo_get_path(repo), 0,
8796 got_worktree_get_root_path(worktree));
8797 if (error)
8798 goto done;
8800 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8801 if (error)
8802 goto done;
8804 cl_arg.editor = editor;
8805 cl_arg.cmdline_log = logmsg;
8806 cl_arg.prepared_log = prepared_logmsg;
8807 cl_arg.non_interactive = non_interactive;
8808 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8809 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8810 if (!histedit_in_progress) {
8811 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8812 error = got_error(GOT_ERR_COMMIT_BRANCH);
8813 goto done;
8815 cl_arg.branch_name += 11;
8817 cl_arg.repo_path = got_repo_get_path(repo);
8818 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8819 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8820 print_status, NULL, repo);
8821 if (error) {
8822 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8823 cl_arg.logmsg_path != NULL)
8824 preserve_logmsg = 1;
8825 goto done;
8828 error = got_object_id_str(&id_str, id);
8829 if (error)
8830 goto done;
8831 printf("Created commit %s\n", id_str);
8832 done:
8833 if (preserve_logmsg) {
8834 fprintf(stderr, "%s: log message preserved in %s\n",
8835 getprogname(), cl_arg.logmsg_path);
8836 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8837 error == NULL)
8838 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8839 free(cl_arg.logmsg_path);
8840 if (repo) {
8841 const struct got_error *close_err = got_repo_close(repo);
8842 if (error == NULL)
8843 error = close_err;
8845 if (worktree)
8846 got_worktree_close(worktree);
8847 if (pack_fds) {
8848 const struct got_error *pack_err =
8849 got_repo_pack_fds_close(pack_fds);
8850 if (error == NULL)
8851 error = pack_err;
8853 free(cwd);
8854 free(id_str);
8855 free(gitconfig_path);
8856 free(editor);
8857 free(committer);
8858 free(prepared_logmsg);
8859 return error;
8862 __dead static void
8863 usage_send(void)
8865 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8866 "[-r repository-path] [-t tag] [remote-repository]\n",
8867 getprogname());
8868 exit(1);
8871 static void
8872 print_load_info(int print_colored, int print_found, int print_trees,
8873 int ncolored, int nfound, int ntrees)
8875 if (print_colored) {
8876 printf("%d commit%s colored", ncolored,
8877 ncolored == 1 ? "" : "s");
8879 if (print_found) {
8880 printf("%s%d object%s found",
8881 ncolored > 0 ? "; " : "",
8882 nfound, nfound == 1 ? "" : "s");
8884 if (print_trees) {
8885 printf("; %d tree%s scanned", ntrees,
8886 ntrees == 1 ? "" : "s");
8890 struct got_send_progress_arg {
8891 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8892 int verbosity;
8893 int last_ncolored;
8894 int last_nfound;
8895 int last_ntrees;
8896 int loading_done;
8897 int last_ncommits;
8898 int last_nobj_total;
8899 int last_p_deltify;
8900 int last_p_written;
8901 int last_p_sent;
8902 int printed_something;
8903 int sent_something;
8904 struct got_pathlist_head *delete_branches;
8907 static const struct got_error *
8908 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8909 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8910 int nobj_written, off_t bytes_sent, const char *refname,
8911 const char *errmsg, int success)
8913 struct got_send_progress_arg *a = arg;
8914 char scaled_packsize[FMT_SCALED_STRSIZE];
8915 char scaled_sent[FMT_SCALED_STRSIZE];
8916 int p_deltify = 0, p_written = 0, p_sent = 0;
8917 int print_colored = 0, print_found = 0, print_trees = 0;
8918 int print_searching = 0, print_total = 0;
8919 int print_deltify = 0, print_written = 0, print_sent = 0;
8921 if (a->verbosity < 0)
8922 return NULL;
8924 if (refname) {
8925 const char *status = success ? "accepted" : "rejected";
8927 if (success) {
8928 struct got_pathlist_entry *pe;
8929 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8930 const char *branchname = pe->path;
8931 if (got_path_cmp(branchname, refname,
8932 strlen(branchname), strlen(refname)) == 0) {
8933 status = "deleted";
8934 a->sent_something = 1;
8935 break;
8940 if (a->printed_something)
8941 putchar('\n');
8942 printf("Server has %s %s", status, refname);
8943 if (errmsg)
8944 printf(": %s", errmsg);
8945 a->printed_something = 1;
8946 return NULL;
8949 if (a->last_ncolored != ncolored) {
8950 print_colored = 1;
8951 a->last_ncolored = ncolored;
8954 if (a->last_nfound != nfound) {
8955 print_colored = 1;
8956 print_found = 1;
8957 a->last_nfound = nfound;
8960 if (a->last_ntrees != ntrees) {
8961 print_colored = 1;
8962 print_found = 1;
8963 print_trees = 1;
8964 a->last_ntrees = ntrees;
8967 if ((print_colored || print_found || print_trees) &&
8968 !a->loading_done) {
8969 printf("\r");
8970 print_load_info(print_colored, print_found, print_trees,
8971 ncolored, nfound, ntrees);
8972 a->printed_something = 1;
8973 fflush(stdout);
8974 return NULL;
8975 } else if (!a->loading_done) {
8976 printf("\r");
8977 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8978 printf("\n");
8979 a->loading_done = 1;
8982 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8983 return got_error_from_errno("fmt_scaled");
8984 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8985 return got_error_from_errno("fmt_scaled");
8987 if (a->last_ncommits != ncommits) {
8988 print_searching = 1;
8989 a->last_ncommits = ncommits;
8992 if (a->last_nobj_total != nobj_total) {
8993 print_searching = 1;
8994 print_total = 1;
8995 a->last_nobj_total = nobj_total;
8998 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8999 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9000 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9001 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9002 return got_error(GOT_ERR_NO_SPACE);
9005 if (nobj_deltify > 0 || nobj_written > 0) {
9006 if (nobj_deltify > 0) {
9007 p_deltify = (nobj_deltify * 100) / nobj_total;
9008 if (p_deltify != a->last_p_deltify) {
9009 a->last_p_deltify = p_deltify;
9010 print_searching = 1;
9011 print_total = 1;
9012 print_deltify = 1;
9015 if (nobj_written > 0) {
9016 p_written = (nobj_written * 100) / nobj_total;
9017 if (p_written != a->last_p_written) {
9018 a->last_p_written = p_written;
9019 print_searching = 1;
9020 print_total = 1;
9021 print_deltify = 1;
9022 print_written = 1;
9027 if (bytes_sent > 0) {
9028 p_sent = (bytes_sent * 100) / packfile_size;
9029 if (p_sent != a->last_p_sent) {
9030 a->last_p_sent = p_sent;
9031 print_searching = 1;
9032 print_total = 1;
9033 print_deltify = 1;
9034 print_written = 1;
9035 print_sent = 1;
9037 a->sent_something = 1;
9040 if (print_searching || print_total || print_deltify || print_written ||
9041 print_sent)
9042 printf("\r");
9043 if (print_searching)
9044 printf("packing %d reference%s", ncommits,
9045 ncommits == 1 ? "" : "s");
9046 if (print_total)
9047 printf("; %d object%s", nobj_total,
9048 nobj_total == 1 ? "" : "s");
9049 if (print_deltify)
9050 printf("; deltify: %d%%", p_deltify);
9051 if (print_sent)
9052 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9053 scaled_packsize, p_sent);
9054 else if (print_written)
9055 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9056 scaled_packsize, p_written);
9057 if (print_searching || print_total || print_deltify ||
9058 print_written || print_sent) {
9059 a->printed_something = 1;
9060 fflush(stdout);
9062 return NULL;
9065 static const struct got_error *
9066 cmd_send(int argc, char *argv[])
9068 const struct got_error *error = NULL;
9069 char *cwd = NULL, *repo_path = NULL;
9070 const char *remote_name;
9071 char *proto = NULL, *host = NULL, *port = NULL;
9072 char *repo_name = NULL, *server_path = NULL;
9073 const struct got_remote_repo *remotes, *remote = NULL;
9074 int nremotes, nbranches = 0, ndelete_branches = 0;
9075 struct got_repository *repo = NULL;
9076 struct got_worktree *worktree = NULL;
9077 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9078 struct got_pathlist_head branches;
9079 struct got_pathlist_head tags;
9080 struct got_reflist_head all_branches;
9081 struct got_reflist_head all_tags;
9082 struct got_pathlist_head delete_args;
9083 struct got_pathlist_head delete_branches;
9084 struct got_reflist_entry *re;
9085 struct got_pathlist_entry *pe;
9086 int i, ch, sendfd = -1, sendstatus;
9087 pid_t sendpid = -1;
9088 struct got_send_progress_arg spa;
9089 int verbosity = 0, overwrite_refs = 0;
9090 int send_all_branches = 0, send_all_tags = 0;
9091 struct got_reference *ref = NULL;
9092 int *pack_fds = NULL;
9094 TAILQ_INIT(&branches);
9095 TAILQ_INIT(&tags);
9096 TAILQ_INIT(&all_branches);
9097 TAILQ_INIT(&all_tags);
9098 TAILQ_INIT(&delete_args);
9099 TAILQ_INIT(&delete_branches);
9101 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9102 switch (ch) {
9103 case 'a':
9104 send_all_branches = 1;
9105 break;
9106 case 'b':
9107 error = got_pathlist_append(&branches, optarg, NULL);
9108 if (error)
9109 return error;
9110 nbranches++;
9111 break;
9112 case 'd':
9113 error = got_pathlist_append(&delete_args, optarg, NULL);
9114 if (error)
9115 return error;
9116 break;
9117 case 'f':
9118 overwrite_refs = 1;
9119 break;
9120 case 'q':
9121 verbosity = -1;
9122 break;
9123 case 'r':
9124 repo_path = realpath(optarg, NULL);
9125 if (repo_path == NULL)
9126 return got_error_from_errno2("realpath",
9127 optarg);
9128 got_path_strip_trailing_slashes(repo_path);
9129 break;
9130 case 'T':
9131 send_all_tags = 1;
9132 break;
9133 case 't':
9134 error = got_pathlist_append(&tags, optarg, NULL);
9135 if (error)
9136 return error;
9137 break;
9138 case 'v':
9139 if (verbosity < 0)
9140 verbosity = 0;
9141 else if (verbosity < 3)
9142 verbosity++;
9143 break;
9144 default:
9145 usage_send();
9146 /* NOTREACHED */
9149 argc -= optind;
9150 argv += optind;
9152 if (send_all_branches && !TAILQ_EMPTY(&branches))
9153 option_conflict('a', 'b');
9154 if (send_all_tags && !TAILQ_EMPTY(&tags))
9155 option_conflict('T', 't');
9158 if (argc == 0)
9159 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9160 else if (argc == 1)
9161 remote_name = argv[0];
9162 else
9163 usage_send();
9165 cwd = getcwd(NULL, 0);
9166 if (cwd == NULL) {
9167 error = got_error_from_errno("getcwd");
9168 goto done;
9171 error = got_repo_pack_fds_open(&pack_fds);
9172 if (error != NULL)
9173 goto done;
9175 if (repo_path == NULL) {
9176 error = got_worktree_open(&worktree, cwd);
9177 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9178 goto done;
9179 else
9180 error = NULL;
9181 if (worktree) {
9182 repo_path =
9183 strdup(got_worktree_get_repo_path(worktree));
9184 if (repo_path == NULL)
9185 error = got_error_from_errno("strdup");
9186 if (error)
9187 goto done;
9188 } else {
9189 repo_path = strdup(cwd);
9190 if (repo_path == NULL) {
9191 error = got_error_from_errno("strdup");
9192 goto done;
9197 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9198 if (error)
9199 goto done;
9201 if (worktree) {
9202 worktree_conf = got_worktree_get_gotconfig(worktree);
9203 if (worktree_conf) {
9204 got_gotconfig_get_remotes(&nremotes, &remotes,
9205 worktree_conf);
9206 for (i = 0; i < nremotes; i++) {
9207 if (strcmp(remotes[i].name, remote_name) == 0) {
9208 remote = &remotes[i];
9209 break;
9214 if (remote == NULL) {
9215 repo_conf = got_repo_get_gotconfig(repo);
9216 if (repo_conf) {
9217 got_gotconfig_get_remotes(&nremotes, &remotes,
9218 repo_conf);
9219 for (i = 0; i < nremotes; i++) {
9220 if (strcmp(remotes[i].name, remote_name) == 0) {
9221 remote = &remotes[i];
9222 break;
9227 if (remote == NULL) {
9228 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9229 for (i = 0; i < nremotes; i++) {
9230 if (strcmp(remotes[i].name, remote_name) == 0) {
9231 remote = &remotes[i];
9232 break;
9236 if (remote == NULL) {
9237 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9238 goto done;
9241 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9242 &repo_name, remote->send_url);
9243 if (error)
9244 goto done;
9246 if (strcmp(proto, "git") == 0) {
9247 #ifndef PROFILE
9248 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9249 "sendfd dns inet unveil", NULL) == -1)
9250 err(1, "pledge");
9251 #endif
9252 } else if (strcmp(proto, "git+ssh") == 0 ||
9253 strcmp(proto, "ssh") == 0) {
9254 #ifndef PROFILE
9255 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9256 "sendfd unveil", NULL) == -1)
9257 err(1, "pledge");
9258 #endif
9259 } else if (strcmp(proto, "http") == 0 ||
9260 strcmp(proto, "git+http") == 0) {
9261 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9262 goto done;
9263 } else {
9264 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9265 goto done;
9268 error = got_dial_apply_unveil(proto);
9269 if (error)
9270 goto done;
9272 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9273 if (error)
9274 goto done;
9276 if (send_all_branches) {
9277 error = got_ref_list(&all_branches, repo, "refs/heads",
9278 got_ref_cmp_by_name, NULL);
9279 if (error)
9280 goto done;
9281 TAILQ_FOREACH(re, &all_branches, entry) {
9282 const char *branchname = got_ref_get_name(re->ref);
9283 error = got_pathlist_append(&branches,
9284 branchname, NULL);
9285 if (error)
9286 goto done;
9287 nbranches++;
9289 } else if (nbranches == 0) {
9290 for (i = 0; i < remote->nsend_branches; i++) {
9291 got_pathlist_append(&branches,
9292 remote->send_branches[i], NULL);
9296 if (send_all_tags) {
9297 error = got_ref_list(&all_tags, repo, "refs/tags",
9298 got_ref_cmp_by_name, NULL);
9299 if (error)
9300 goto done;
9301 TAILQ_FOREACH(re, &all_tags, entry) {
9302 const char *tagname = got_ref_get_name(re->ref);
9303 error = got_pathlist_append(&tags,
9304 tagname, NULL);
9305 if (error)
9306 goto done;
9311 * To prevent accidents only branches in refs/heads/ can be deleted
9312 * with 'got send -d'.
9313 * Deleting anything else requires local repository access or Git.
9315 TAILQ_FOREACH(pe, &delete_args, entry) {
9316 const char *branchname = pe->path;
9317 char *s;
9318 struct got_pathlist_entry *new;
9319 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9320 s = strdup(branchname);
9321 if (s == NULL) {
9322 error = got_error_from_errno("strdup");
9323 goto done;
9325 } else {
9326 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9327 error = got_error_from_errno("asprintf");
9328 goto done;
9331 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9332 if (error || new == NULL /* duplicate */)
9333 free(s);
9334 if (error)
9335 goto done;
9336 ndelete_branches++;
9339 if (nbranches == 0 && ndelete_branches == 0) {
9340 struct got_reference *head_ref;
9341 if (worktree)
9342 error = got_ref_open(&head_ref, repo,
9343 got_worktree_get_head_ref_name(worktree), 0);
9344 else
9345 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9346 if (error)
9347 goto done;
9348 if (got_ref_is_symbolic(head_ref)) {
9349 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9350 got_ref_close(head_ref);
9351 if (error)
9352 goto done;
9353 } else
9354 ref = head_ref;
9355 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9356 NULL);
9357 if (error)
9358 goto done;
9359 nbranches++;
9362 if (verbosity >= 0) {
9363 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9364 remote->name, proto, host,
9365 port ? ":" : "", port ? port : "",
9366 *server_path == '/' ? "" : "/", server_path);
9369 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9370 server_path, verbosity);
9371 if (error)
9372 goto done;
9374 memset(&spa, 0, sizeof(spa));
9375 spa.last_scaled_packsize[0] = '\0';
9376 spa.last_p_deltify = -1;
9377 spa.last_p_written = -1;
9378 spa.verbosity = verbosity;
9379 spa.delete_branches = &delete_branches;
9380 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9381 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9382 check_cancelled, NULL);
9383 if (spa.printed_something)
9384 putchar('\n');
9385 if (error)
9386 goto done;
9387 if (!spa.sent_something && verbosity >= 0)
9388 printf("Already up-to-date\n");
9389 done:
9390 if (sendpid > 0) {
9391 if (kill(sendpid, SIGTERM) == -1)
9392 error = got_error_from_errno("kill");
9393 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9394 error = got_error_from_errno("waitpid");
9396 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9397 error = got_error_from_errno("close");
9398 if (repo) {
9399 const struct got_error *close_err = got_repo_close(repo);
9400 if (error == NULL)
9401 error = close_err;
9403 if (worktree)
9404 got_worktree_close(worktree);
9405 if (pack_fds) {
9406 const struct got_error *pack_err =
9407 got_repo_pack_fds_close(pack_fds);
9408 if (error == NULL)
9409 error = pack_err;
9411 if (ref)
9412 got_ref_close(ref);
9413 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9414 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9415 got_ref_list_free(&all_branches);
9416 got_ref_list_free(&all_tags);
9417 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9418 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9419 free(cwd);
9420 free(repo_path);
9421 free(proto);
9422 free(host);
9423 free(port);
9424 free(server_path);
9425 free(repo_name);
9426 return error;
9429 __dead static void
9430 usage_cherrypick(void)
9432 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9433 exit(1);
9436 static const struct got_error *
9437 cmd_cherrypick(int argc, char *argv[])
9439 const struct got_error *error = NULL;
9440 struct got_worktree *worktree = NULL;
9441 struct got_repository *repo = NULL;
9442 char *cwd = NULL, *commit_id_str = NULL;
9443 struct got_object_id *commit_id = NULL;
9444 struct got_commit_object *commit = NULL;
9445 struct got_object_qid *pid;
9446 int ch;
9447 struct got_update_progress_arg upa;
9448 int *pack_fds = NULL;
9450 while ((ch = getopt(argc, argv, "")) != -1) {
9451 switch (ch) {
9452 default:
9453 usage_cherrypick();
9454 /* NOTREACHED */
9458 argc -= optind;
9459 argv += optind;
9461 #ifndef PROFILE
9462 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9463 "unveil", NULL) == -1)
9464 err(1, "pledge");
9465 #endif
9466 if (argc != 1)
9467 usage_cherrypick();
9469 cwd = getcwd(NULL, 0);
9470 if (cwd == NULL) {
9471 error = got_error_from_errno("getcwd");
9472 goto done;
9475 error = got_repo_pack_fds_open(&pack_fds);
9476 if (error != NULL)
9477 goto done;
9479 error = got_worktree_open(&worktree, cwd);
9480 if (error) {
9481 if (error->code == GOT_ERR_NOT_WORKTREE)
9482 error = wrap_not_worktree_error(error, "cherrypick",
9483 cwd);
9484 goto done;
9487 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9488 NULL, pack_fds);
9489 if (error != NULL)
9490 goto done;
9492 error = apply_unveil(got_repo_get_path(repo), 0,
9493 got_worktree_get_root_path(worktree));
9494 if (error)
9495 goto done;
9497 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9498 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9499 if (error)
9500 goto done;
9501 error = got_object_id_str(&commit_id_str, commit_id);
9502 if (error)
9503 goto done;
9505 error = got_object_open_as_commit(&commit, repo, commit_id);
9506 if (error)
9507 goto done;
9508 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9509 memset(&upa, 0, sizeof(upa));
9510 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9511 commit_id, repo, update_progress, &upa, check_cancelled,
9512 NULL);
9513 if (error != NULL)
9514 goto done;
9516 if (upa.did_something)
9517 printf("Merged commit %s\n", commit_id_str);
9518 print_merge_progress_stats(&upa);
9519 done:
9520 if (commit)
9521 got_object_commit_close(commit);
9522 free(commit_id_str);
9523 if (worktree)
9524 got_worktree_close(worktree);
9525 if (repo) {
9526 const struct got_error *close_err = got_repo_close(repo);
9527 if (error == NULL)
9528 error = close_err;
9530 if (pack_fds) {
9531 const struct got_error *pack_err =
9532 got_repo_pack_fds_close(pack_fds);
9533 if (error == NULL)
9534 error = pack_err;
9537 return error;
9540 __dead static void
9541 usage_backout(void)
9543 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9544 exit(1);
9547 static const struct got_error *
9548 cmd_backout(int argc, char *argv[])
9550 const struct got_error *error = NULL;
9551 struct got_worktree *worktree = NULL;
9552 struct got_repository *repo = NULL;
9553 char *cwd = NULL, *commit_id_str = NULL;
9554 struct got_object_id *commit_id = NULL;
9555 struct got_commit_object *commit = NULL;
9556 struct got_object_qid *pid;
9557 int ch;
9558 struct got_update_progress_arg upa;
9559 int *pack_fds = NULL;
9561 while ((ch = getopt(argc, argv, "")) != -1) {
9562 switch (ch) {
9563 default:
9564 usage_backout();
9565 /* NOTREACHED */
9569 argc -= optind;
9570 argv += optind;
9572 #ifndef PROFILE
9573 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9574 "unveil", NULL) == -1)
9575 err(1, "pledge");
9576 #endif
9577 if (argc != 1)
9578 usage_backout();
9580 cwd = getcwd(NULL, 0);
9581 if (cwd == NULL) {
9582 error = got_error_from_errno("getcwd");
9583 goto done;
9586 error = got_repo_pack_fds_open(&pack_fds);
9587 if (error != NULL)
9588 goto done;
9590 error = got_worktree_open(&worktree, cwd);
9591 if (error) {
9592 if (error->code == GOT_ERR_NOT_WORKTREE)
9593 error = wrap_not_worktree_error(error, "backout", cwd);
9594 goto done;
9597 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9598 NULL, pack_fds);
9599 if (error != NULL)
9600 goto done;
9602 error = apply_unveil(got_repo_get_path(repo), 0,
9603 got_worktree_get_root_path(worktree));
9604 if (error)
9605 goto done;
9607 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9608 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9609 if (error)
9610 goto done;
9611 error = got_object_id_str(&commit_id_str, commit_id);
9612 if (error)
9613 goto done;
9615 error = got_object_open_as_commit(&commit, repo, commit_id);
9616 if (error)
9617 goto done;
9618 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9619 if (pid == NULL) {
9620 error = got_error(GOT_ERR_ROOT_COMMIT);
9621 goto done;
9624 memset(&upa, 0, sizeof(upa));
9625 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9626 repo, update_progress, &upa, check_cancelled, NULL);
9627 if (error != NULL)
9628 goto done;
9630 if (upa.did_something)
9631 printf("Backed out commit %s\n", commit_id_str);
9632 print_merge_progress_stats(&upa);
9633 done:
9634 if (commit)
9635 got_object_commit_close(commit);
9636 free(commit_id_str);
9637 if (worktree)
9638 got_worktree_close(worktree);
9639 if (repo) {
9640 const struct got_error *close_err = got_repo_close(repo);
9641 if (error == NULL)
9642 error = close_err;
9644 if (pack_fds) {
9645 const struct got_error *pack_err =
9646 got_repo_pack_fds_close(pack_fds);
9647 if (error == NULL)
9648 error = pack_err;
9650 return error;
9653 __dead static void
9654 usage_rebase(void)
9656 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9657 exit(1);
9660 static void
9661 trim_logmsg(char *logmsg, int limit)
9663 char *nl;
9664 size_t len;
9666 len = strlen(logmsg);
9667 if (len > limit)
9668 len = limit;
9669 logmsg[len] = '\0';
9670 nl = strchr(logmsg, '\n');
9671 if (nl)
9672 *nl = '\0';
9675 static const struct got_error *
9676 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9678 const struct got_error *err;
9679 char *logmsg0 = NULL;
9680 const char *s;
9682 err = got_object_commit_get_logmsg(&logmsg0, commit);
9683 if (err)
9684 return err;
9686 s = logmsg0;
9687 while (isspace((unsigned char)s[0]))
9688 s++;
9690 *logmsg = strdup(s);
9691 if (*logmsg == NULL) {
9692 err = got_error_from_errno("strdup");
9693 goto done;
9696 trim_logmsg(*logmsg, limit);
9697 done:
9698 free(logmsg0);
9699 return err;
9702 static const struct got_error *
9703 show_rebase_merge_conflict(struct got_object_id *id,
9704 struct got_repository *repo)
9706 const struct got_error *err;
9707 struct got_commit_object *commit = NULL;
9708 char *id_str = NULL, *logmsg = NULL;
9710 err = got_object_open_as_commit(&commit, repo, id);
9711 if (err)
9712 return err;
9714 err = got_object_id_str(&id_str, id);
9715 if (err)
9716 goto done;
9718 id_str[12] = '\0';
9720 err = get_short_logmsg(&logmsg, 42, commit);
9721 if (err)
9722 goto done;
9724 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9725 done:
9726 free(id_str);
9727 got_object_commit_close(commit);
9728 free(logmsg);
9729 return err;
9732 static const struct got_error *
9733 show_rebase_progress(struct got_commit_object *commit,
9734 struct got_object_id *old_id, struct got_object_id *new_id)
9736 const struct got_error *err;
9737 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9739 err = got_object_id_str(&old_id_str, old_id);
9740 if (err)
9741 goto done;
9743 if (new_id) {
9744 err = got_object_id_str(&new_id_str, new_id);
9745 if (err)
9746 goto done;
9749 old_id_str[12] = '\0';
9750 if (new_id_str)
9751 new_id_str[12] = '\0';
9753 err = get_short_logmsg(&logmsg, 42, commit);
9754 if (err)
9755 goto done;
9757 printf("%s -> %s: %s\n", old_id_str,
9758 new_id_str ? new_id_str : "no-op change", logmsg);
9759 done:
9760 free(old_id_str);
9761 free(new_id_str);
9762 free(logmsg);
9763 return err;
9766 static const struct got_error *
9767 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9768 struct got_reference *branch, struct got_reference *new_base_branch,
9769 struct got_reference *tmp_branch, struct got_repository *repo,
9770 int create_backup)
9772 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9773 return got_worktree_rebase_complete(worktree, fileindex,
9774 new_base_branch, tmp_branch, branch, repo, create_backup);
9777 static const struct got_error *
9778 rebase_commit(struct got_pathlist_head *merged_paths,
9779 struct got_worktree *worktree, struct got_fileindex *fileindex,
9780 struct got_reference *tmp_branch, const char *committer,
9781 struct got_object_id *commit_id, struct got_repository *repo)
9783 const struct got_error *error;
9784 struct got_commit_object *commit;
9785 struct got_object_id *new_commit_id;
9787 error = got_object_open_as_commit(&commit, repo, commit_id);
9788 if (error)
9789 return error;
9791 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9792 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9793 repo);
9794 if (error) {
9795 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9796 goto done;
9797 error = show_rebase_progress(commit, commit_id, NULL);
9798 } else {
9799 error = show_rebase_progress(commit, commit_id, new_commit_id);
9800 free(new_commit_id);
9802 done:
9803 got_object_commit_close(commit);
9804 return error;
9807 struct check_path_prefix_arg {
9808 const char *path_prefix;
9809 size_t len;
9810 int errcode;
9813 static const struct got_error *
9814 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9815 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9816 struct got_object_id *id1, struct got_object_id *id2,
9817 const char *path1, const char *path2,
9818 mode_t mode1, mode_t mode2, struct got_repository *repo)
9820 struct check_path_prefix_arg *a = arg;
9822 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9823 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9824 return got_error(a->errcode);
9826 return NULL;
9829 static const struct got_error *
9830 check_path_prefix(struct got_object_id *parent_id,
9831 struct got_object_id *commit_id, const char *path_prefix,
9832 int errcode, struct got_repository *repo)
9834 const struct got_error *err;
9835 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9836 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9837 struct check_path_prefix_arg cpp_arg;
9839 if (got_path_is_root_dir(path_prefix))
9840 return NULL;
9842 err = got_object_open_as_commit(&commit, repo, commit_id);
9843 if (err)
9844 goto done;
9846 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9847 if (err)
9848 goto done;
9850 err = got_object_open_as_tree(&tree1, repo,
9851 got_object_commit_get_tree_id(parent_commit));
9852 if (err)
9853 goto done;
9855 err = got_object_open_as_tree(&tree2, repo,
9856 got_object_commit_get_tree_id(commit));
9857 if (err)
9858 goto done;
9860 cpp_arg.path_prefix = path_prefix;
9861 while (cpp_arg.path_prefix[0] == '/')
9862 cpp_arg.path_prefix++;
9863 cpp_arg.len = strlen(cpp_arg.path_prefix);
9864 cpp_arg.errcode = errcode;
9865 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9866 check_path_prefix_in_diff, &cpp_arg, 0);
9867 done:
9868 if (tree1)
9869 got_object_tree_close(tree1);
9870 if (tree2)
9871 got_object_tree_close(tree2);
9872 if (commit)
9873 got_object_commit_close(commit);
9874 if (parent_commit)
9875 got_object_commit_close(parent_commit);
9876 return err;
9879 static const struct got_error *
9880 collect_commits(struct got_object_id_queue *commits,
9881 struct got_object_id *initial_commit_id,
9882 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9883 const char *path_prefix, int path_prefix_errcode,
9884 struct got_repository *repo)
9886 const struct got_error *err = NULL;
9887 struct got_commit_graph *graph = NULL;
9888 struct got_object_id parent_id, commit_id;
9889 struct got_object_qid *qid;
9891 err = got_commit_graph_open(&graph, "/", 1);
9892 if (err)
9893 return err;
9895 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9896 check_cancelled, NULL);
9897 if (err)
9898 goto done;
9900 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9901 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9902 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9903 check_cancelled, NULL);
9904 if (err) {
9905 if (err->code == GOT_ERR_ITER_COMPLETED) {
9906 err = got_error_msg(GOT_ERR_ANCESTRY,
9907 "ran out of commits to rebase before "
9908 "youngest common ancestor commit has "
9909 "been reached?!?");
9911 goto done;
9912 } else {
9913 err = check_path_prefix(&parent_id, &commit_id,
9914 path_prefix, path_prefix_errcode, repo);
9915 if (err)
9916 goto done;
9918 err = got_object_qid_alloc(&qid, &commit_id);
9919 if (err)
9920 goto done;
9921 STAILQ_INSERT_HEAD(commits, qid, entry);
9923 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9926 done:
9927 got_commit_graph_close(graph);
9928 return err;
9931 static const struct got_error *
9932 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9934 const struct got_error *err = NULL;
9935 time_t committer_time;
9936 struct tm tm;
9937 char datebuf[11]; /* YYYY-MM-DD + NUL */
9938 char *author0 = NULL, *author, *smallerthan;
9939 char *logmsg0 = NULL, *logmsg, *newline;
9941 committer_time = got_object_commit_get_committer_time(commit);
9942 if (gmtime_r(&committer_time, &tm) == NULL)
9943 return got_error_from_errno("gmtime_r");
9944 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9945 return got_error(GOT_ERR_NO_SPACE);
9947 author0 = strdup(got_object_commit_get_author(commit));
9948 if (author0 == NULL)
9949 return got_error_from_errno("strdup");
9950 author = author0;
9951 smallerthan = strchr(author, '<');
9952 if (smallerthan && smallerthan[1] != '\0')
9953 author = smallerthan + 1;
9954 author[strcspn(author, "@>")] = '\0';
9956 err = got_object_commit_get_logmsg(&logmsg0, commit);
9957 if (err)
9958 goto done;
9959 logmsg = logmsg0;
9960 while (*logmsg == '\n')
9961 logmsg++;
9962 newline = strchr(logmsg, '\n');
9963 if (newline)
9964 *newline = '\0';
9966 if (asprintf(brief_str, "%s %s %s",
9967 datebuf, author, logmsg) == -1)
9968 err = got_error_from_errno("asprintf");
9969 done:
9970 free(author0);
9971 free(logmsg0);
9972 return err;
9975 static const struct got_error *
9976 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9977 struct got_repository *repo)
9979 const struct got_error *err;
9980 char *id_str;
9982 err = got_object_id_str(&id_str, id);
9983 if (err)
9984 return err;
9986 err = got_ref_delete(ref, repo);
9987 if (err)
9988 goto done;
9990 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9991 done:
9992 free(id_str);
9993 return err;
9996 static const struct got_error *
9997 print_backup_ref(const char *branch_name, const char *new_id_str,
9998 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9999 struct got_reflist_object_id_map *refs_idmap,
10000 struct got_repository *repo)
10002 const struct got_error *err = NULL;
10003 struct got_reflist_head *refs;
10004 char *refs_str = NULL;
10005 struct got_object_id *new_commit_id = NULL;
10006 struct got_commit_object *new_commit = NULL;
10007 char *new_commit_brief_str = NULL;
10008 struct got_object_id *yca_id = NULL;
10009 struct got_commit_object *yca_commit = NULL;
10010 char *yca_id_str = NULL, *yca_brief_str = NULL;
10011 char *custom_refs_str;
10013 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10014 return got_error_from_errno("asprintf");
10016 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10017 0, 0, refs_idmap, custom_refs_str);
10018 if (err)
10019 goto done;
10021 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10022 if (err)
10023 goto done;
10025 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10026 if (refs) {
10027 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10028 if (err)
10029 goto done;
10032 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10033 if (err)
10034 goto done;
10036 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10037 if (err)
10038 goto done;
10040 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10041 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10042 if (err)
10043 goto done;
10045 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10046 refs_str ? " (" : "", refs_str ? refs_str : "",
10047 refs_str ? ")" : "", new_commit_brief_str);
10048 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10049 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10050 free(refs_str);
10051 refs_str = NULL;
10053 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10054 if (err)
10055 goto done;
10057 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10058 if (err)
10059 goto done;
10061 err = got_object_id_str(&yca_id_str, yca_id);
10062 if (err)
10063 goto done;
10065 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10066 if (refs) {
10067 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10068 if (err)
10069 goto done;
10071 printf("history forked at %s%s%s%s\n %s\n",
10072 yca_id_str,
10073 refs_str ? " (" : "", refs_str ? refs_str : "",
10074 refs_str ? ")" : "", yca_brief_str);
10076 done:
10077 free(custom_refs_str);
10078 free(new_commit_id);
10079 free(refs_str);
10080 free(yca_id);
10081 free(yca_id_str);
10082 free(yca_brief_str);
10083 if (new_commit)
10084 got_object_commit_close(new_commit);
10085 if (yca_commit)
10086 got_object_commit_close(yca_commit);
10088 return NULL;
10091 static const struct got_error *
10092 process_backup_refs(const char *backup_ref_prefix,
10093 const char *wanted_branch_name,
10094 int delete, struct got_repository *repo)
10096 const struct got_error *err;
10097 struct got_reflist_head refs, backup_refs;
10098 struct got_reflist_entry *re;
10099 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10100 struct got_object_id *old_commit_id = NULL;
10101 char *branch_name = NULL;
10102 struct got_commit_object *old_commit = NULL;
10103 struct got_reflist_object_id_map *refs_idmap = NULL;
10104 int wanted_branch_found = 0;
10106 TAILQ_INIT(&refs);
10107 TAILQ_INIT(&backup_refs);
10109 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10110 if (err)
10111 return err;
10113 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10114 if (err)
10115 goto done;
10117 if (wanted_branch_name) {
10118 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10119 wanted_branch_name += 11;
10122 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10123 got_ref_cmp_by_commit_timestamp_descending, repo);
10124 if (err)
10125 goto done;
10127 TAILQ_FOREACH(re, &backup_refs, entry) {
10128 const char *refname = got_ref_get_name(re->ref);
10129 char *slash;
10131 err = check_cancelled(NULL);
10132 if (err)
10133 break;
10135 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10136 if (err)
10137 break;
10139 err = got_object_open_as_commit(&old_commit, repo,
10140 old_commit_id);
10141 if (err)
10142 break;
10144 if (strncmp(backup_ref_prefix, refname,
10145 backup_ref_prefix_len) == 0)
10146 refname += backup_ref_prefix_len;
10148 while (refname[0] == '/')
10149 refname++;
10151 branch_name = strdup(refname);
10152 if (branch_name == NULL) {
10153 err = got_error_from_errno("strdup");
10154 break;
10156 slash = strrchr(branch_name, '/');
10157 if (slash) {
10158 *slash = '\0';
10159 refname += strlen(branch_name) + 1;
10162 if (wanted_branch_name == NULL ||
10163 strcmp(wanted_branch_name, branch_name) == 0) {
10164 wanted_branch_found = 1;
10165 if (delete) {
10166 err = delete_backup_ref(re->ref,
10167 old_commit_id, repo);
10168 } else {
10169 err = print_backup_ref(branch_name, refname,
10170 old_commit_id, old_commit, refs_idmap,
10171 repo);
10173 if (err)
10174 break;
10177 free(old_commit_id);
10178 old_commit_id = NULL;
10179 free(branch_name);
10180 branch_name = NULL;
10181 got_object_commit_close(old_commit);
10182 old_commit = NULL;
10185 if (wanted_branch_name && !wanted_branch_found) {
10186 err = got_error_fmt(GOT_ERR_NOT_REF,
10187 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10189 done:
10190 if (refs_idmap)
10191 got_reflist_object_id_map_free(refs_idmap);
10192 got_ref_list_free(&refs);
10193 got_ref_list_free(&backup_refs);
10194 free(old_commit_id);
10195 free(branch_name);
10196 if (old_commit)
10197 got_object_commit_close(old_commit);
10198 return err;
10201 static const struct got_error *
10202 abort_progress(void *arg, unsigned char status, const char *path)
10205 * Unversioned files should not clutter progress output when
10206 * an operation is aborted.
10208 if (status == GOT_STATUS_UNVERSIONED)
10209 return NULL;
10211 return update_progress(arg, status, path);
10214 static const struct got_error *
10215 cmd_rebase(int argc, char *argv[])
10217 const struct got_error *error = NULL;
10218 struct got_worktree *worktree = NULL;
10219 struct got_repository *repo = NULL;
10220 struct got_fileindex *fileindex = NULL;
10221 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10222 struct got_reference *branch = NULL;
10223 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10224 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10225 struct got_object_id *resume_commit_id = NULL;
10226 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10227 struct got_object_id *head_commit_id = NULL;
10228 struct got_reference *head_ref = NULL;
10229 struct got_commit_object *commit = NULL;
10230 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10231 int histedit_in_progress = 0, merge_in_progress = 0;
10232 int create_backup = 1, list_backups = 0, delete_backups = 0;
10233 struct got_object_id_queue commits;
10234 struct got_pathlist_head merged_paths;
10235 const struct got_object_id_queue *parent_ids;
10236 struct got_object_qid *qid, *pid;
10237 struct got_update_progress_arg upa;
10238 int *pack_fds = NULL;
10240 STAILQ_INIT(&commits);
10241 TAILQ_INIT(&merged_paths);
10242 memset(&upa, 0, sizeof(upa));
10244 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10245 switch (ch) {
10246 case 'a':
10247 abort_rebase = 1;
10248 break;
10249 case 'c':
10250 continue_rebase = 1;
10251 break;
10252 case 'l':
10253 list_backups = 1;
10254 break;
10255 case 'X':
10256 delete_backups = 1;
10257 break;
10258 default:
10259 usage_rebase();
10260 /* NOTREACHED */
10264 argc -= optind;
10265 argv += optind;
10267 #ifndef PROFILE
10268 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10269 "unveil", NULL) == -1)
10270 err(1, "pledge");
10271 #endif
10272 if (list_backups) {
10273 if (abort_rebase)
10274 option_conflict('l', 'a');
10275 if (continue_rebase)
10276 option_conflict('l', 'c');
10277 if (delete_backups)
10278 option_conflict('l', 'X');
10279 if (argc != 0 && argc != 1)
10280 usage_rebase();
10281 } else if (delete_backups) {
10282 if (abort_rebase)
10283 option_conflict('X', 'a');
10284 if (continue_rebase)
10285 option_conflict('X', 'c');
10286 if (list_backups)
10287 option_conflict('l', 'X');
10288 if (argc != 0 && argc != 1)
10289 usage_rebase();
10290 } else {
10291 if (abort_rebase && continue_rebase)
10292 usage_rebase();
10293 else if (abort_rebase || continue_rebase) {
10294 if (argc != 0)
10295 usage_rebase();
10296 } else if (argc != 1)
10297 usage_rebase();
10300 cwd = getcwd(NULL, 0);
10301 if (cwd == NULL) {
10302 error = got_error_from_errno("getcwd");
10303 goto done;
10306 error = got_repo_pack_fds_open(&pack_fds);
10307 if (error != NULL)
10308 goto done;
10310 error = got_worktree_open(&worktree, cwd);
10311 if (error) {
10312 if (list_backups || delete_backups) {
10313 if (error->code != GOT_ERR_NOT_WORKTREE)
10314 goto done;
10315 } else {
10316 if (error->code == GOT_ERR_NOT_WORKTREE)
10317 error = wrap_not_worktree_error(error,
10318 "rebase", cwd);
10319 goto done;
10323 error = get_gitconfig_path(&gitconfig_path);
10324 if (error)
10325 goto done;
10326 error = got_repo_open(&repo,
10327 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10328 gitconfig_path, pack_fds);
10329 if (error != NULL)
10330 goto done;
10332 error = get_author(&committer, repo, worktree);
10333 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10334 goto done;
10336 error = apply_unveil(got_repo_get_path(repo), 0,
10337 worktree ? got_worktree_get_root_path(worktree) : NULL);
10338 if (error)
10339 goto done;
10341 if (list_backups || delete_backups) {
10342 error = process_backup_refs(
10343 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10344 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10345 goto done; /* nothing else to do */
10348 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10349 worktree);
10350 if (error)
10351 goto done;
10352 if (histedit_in_progress) {
10353 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10354 goto done;
10357 error = got_worktree_merge_in_progress(&merge_in_progress,
10358 worktree, repo);
10359 if (error)
10360 goto done;
10361 if (merge_in_progress) {
10362 error = got_error(GOT_ERR_MERGE_BUSY);
10363 goto done;
10366 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10367 if (error)
10368 goto done;
10370 if (abort_rebase) {
10371 if (!rebase_in_progress) {
10372 error = got_error(GOT_ERR_NOT_REBASING);
10373 goto done;
10375 error = got_worktree_rebase_continue(&resume_commit_id,
10376 &new_base_branch, &tmp_branch, &branch, &fileindex,
10377 worktree, repo);
10378 if (error)
10379 goto done;
10380 printf("Switching work tree to %s\n",
10381 got_ref_get_symref_target(new_base_branch));
10382 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10383 new_base_branch, abort_progress, &upa);
10384 if (error)
10385 goto done;
10386 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10387 print_merge_progress_stats(&upa);
10388 goto done; /* nothing else to do */
10391 if (continue_rebase) {
10392 if (!rebase_in_progress) {
10393 error = got_error(GOT_ERR_NOT_REBASING);
10394 goto done;
10396 error = got_worktree_rebase_continue(&resume_commit_id,
10397 &new_base_branch, &tmp_branch, &branch, &fileindex,
10398 worktree, repo);
10399 if (error)
10400 goto done;
10402 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10403 committer, resume_commit_id, repo);
10404 if (error)
10405 goto done;
10407 yca_id = got_object_id_dup(resume_commit_id);
10408 if (yca_id == NULL) {
10409 error = got_error_from_errno("got_object_id_dup");
10410 goto done;
10412 } else {
10413 error = got_ref_open(&branch, repo, argv[0], 0);
10414 if (error != NULL)
10415 goto done;
10416 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10417 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10418 "will not rebase a branch which lives outside "
10419 "the \"refs/heads/\" reference namespace");
10420 goto done;
10424 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10425 if (error)
10426 goto done;
10428 if (!continue_rebase) {
10429 struct got_object_id *base_commit_id;
10431 error = got_ref_open(&head_ref, repo,
10432 got_worktree_get_head_ref_name(worktree), 0);
10433 if (error)
10434 goto done;
10435 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10436 if (error)
10437 goto done;
10438 base_commit_id = got_worktree_get_base_commit_id(worktree);
10439 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10440 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10441 goto done;
10444 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10445 base_commit_id, branch_head_commit_id, 1, repo,
10446 check_cancelled, NULL);
10447 if (error)
10448 goto done;
10449 if (yca_id == NULL) {
10450 error = got_error_msg(GOT_ERR_ANCESTRY,
10451 "specified branch shares no common ancestry "
10452 "with work tree's branch");
10453 goto done;
10456 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10457 if (error) {
10458 if (error->code != GOT_ERR_ANCESTRY)
10459 goto done;
10460 error = NULL;
10461 } else {
10462 struct got_pathlist_head paths;
10463 printf("%s is already based on %s\n",
10464 got_ref_get_name(branch),
10465 got_worktree_get_head_ref_name(worktree));
10466 error = switch_head_ref(branch, branch_head_commit_id,
10467 worktree, repo);
10468 if (error)
10469 goto done;
10470 error = got_worktree_set_base_commit_id(worktree, repo,
10471 branch_head_commit_id);
10472 if (error)
10473 goto done;
10474 TAILQ_INIT(&paths);
10475 error = got_pathlist_append(&paths, "", NULL);
10476 if (error)
10477 goto done;
10478 error = got_worktree_checkout_files(worktree,
10479 &paths, repo, update_progress, &upa,
10480 check_cancelled, NULL);
10481 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
10482 if (error)
10483 goto done;
10484 if (upa.did_something) {
10485 char *id_str;
10486 error = got_object_id_str(&id_str,
10487 branch_head_commit_id);
10488 if (error)
10489 goto done;
10490 printf("Updated to %s: %s\n",
10491 got_worktree_get_head_ref_name(worktree),
10492 id_str);
10493 free(id_str);
10494 } else
10495 printf("Already up-to-date\n");
10496 print_update_progress_stats(&upa);
10497 goto done;
10501 commit_id = branch_head_commit_id;
10502 error = got_object_open_as_commit(&commit, repo, commit_id);
10503 if (error)
10504 goto done;
10506 parent_ids = got_object_commit_get_parent_ids(commit);
10507 pid = STAILQ_FIRST(parent_ids);
10508 if (pid == NULL) {
10509 error = got_error(GOT_ERR_EMPTY_REBASE);
10510 goto done;
10512 error = collect_commits(&commits, commit_id, &pid->id,
10513 yca_id, got_worktree_get_path_prefix(worktree),
10514 GOT_ERR_REBASE_PATH, repo);
10515 got_object_commit_close(commit);
10516 commit = NULL;
10517 if (error)
10518 goto done;
10520 if (!continue_rebase) {
10521 error = got_worktree_rebase_prepare(&new_base_branch,
10522 &tmp_branch, &fileindex, worktree, branch, repo);
10523 if (error)
10524 goto done;
10527 if (STAILQ_EMPTY(&commits)) {
10528 if (continue_rebase) {
10529 error = rebase_complete(worktree, fileindex,
10530 branch, new_base_branch, tmp_branch, repo,
10531 create_backup);
10532 goto done;
10533 } else {
10534 /* Fast-forward the reference of the branch. */
10535 struct got_object_id *new_head_commit_id;
10536 char *id_str;
10537 error = got_ref_resolve(&new_head_commit_id, repo,
10538 new_base_branch);
10539 if (error)
10540 goto done;
10541 error = got_object_id_str(&id_str, new_head_commit_id);
10542 if (error)
10543 goto done;
10544 printf("Forwarding %s to commit %s\n",
10545 got_ref_get_name(branch), id_str);
10546 free(id_str);
10547 error = got_ref_change_ref(branch,
10548 new_head_commit_id);
10549 if (error)
10550 goto done;
10551 /* No backup needed since objects did not change. */
10552 create_backup = 0;
10556 pid = NULL;
10557 STAILQ_FOREACH(qid, &commits, entry) {
10559 commit_id = &qid->id;
10560 parent_id = pid ? &pid->id : yca_id;
10561 pid = qid;
10563 memset(&upa, 0, sizeof(upa));
10564 error = got_worktree_rebase_merge_files(&merged_paths,
10565 worktree, fileindex, parent_id, commit_id, repo,
10566 update_progress, &upa, check_cancelled, NULL);
10567 if (error)
10568 goto done;
10570 print_merge_progress_stats(&upa);
10571 if (upa.conflicts > 0 || upa.missing > 0 ||
10572 upa.not_deleted > 0 || upa.unversioned > 0) {
10573 if (upa.conflicts > 0) {
10574 error = show_rebase_merge_conflict(&qid->id,
10575 repo);
10576 if (error)
10577 goto done;
10579 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10580 break;
10583 error = rebase_commit(&merged_paths, worktree, fileindex,
10584 tmp_branch, committer, commit_id, repo);
10585 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10586 if (error)
10587 goto done;
10590 if (upa.conflicts > 0 || upa.missing > 0 ||
10591 upa.not_deleted > 0 || upa.unversioned > 0) {
10592 error = got_worktree_rebase_postpone(worktree, fileindex);
10593 if (error)
10594 goto done;
10595 if (upa.conflicts > 0 && upa.missing == 0 &&
10596 upa.not_deleted == 0 && upa.unversioned == 0) {
10597 error = got_error_msg(GOT_ERR_CONFLICTS,
10598 "conflicts must be resolved before rebasing "
10599 "can continue");
10600 } else if (upa.conflicts > 0) {
10601 error = got_error_msg(GOT_ERR_CONFLICTS,
10602 "conflicts must be resolved before rebasing "
10603 "can continue; changes destined for some "
10604 "files were not yet merged and should be "
10605 "merged manually if required before the "
10606 "rebase operation is continued");
10607 } else {
10608 error = got_error_msg(GOT_ERR_CONFLICTS,
10609 "changes destined for some files were not "
10610 "yet merged and should be merged manually "
10611 "if required before the rebase operation "
10612 "is continued");
10614 } else
10615 error = rebase_complete(worktree, fileindex, branch,
10616 new_base_branch, tmp_branch, repo, create_backup);
10617 done:
10618 free(cwd);
10619 free(committer);
10620 free(gitconfig_path);
10621 got_object_id_queue_free(&commits);
10622 free(branch_head_commit_id);
10623 free(resume_commit_id);
10624 free(head_commit_id);
10625 free(yca_id);
10626 if (commit)
10627 got_object_commit_close(commit);
10628 if (branch)
10629 got_ref_close(branch);
10630 if (new_base_branch)
10631 got_ref_close(new_base_branch);
10632 if (tmp_branch)
10633 got_ref_close(tmp_branch);
10634 if (head_ref)
10635 got_ref_close(head_ref);
10636 if (worktree)
10637 got_worktree_close(worktree);
10638 if (repo) {
10639 const struct got_error *close_err = got_repo_close(repo);
10640 if (error == NULL)
10641 error = close_err;
10643 if (pack_fds) {
10644 const struct got_error *pack_err =
10645 got_repo_pack_fds_close(pack_fds);
10646 if (error == NULL)
10647 error = pack_err;
10649 return error;
10652 __dead static void
10653 usage_histedit(void)
10655 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10656 "[branch]\n", getprogname());
10657 exit(1);
10660 #define GOT_HISTEDIT_PICK 'p'
10661 #define GOT_HISTEDIT_EDIT 'e'
10662 #define GOT_HISTEDIT_FOLD 'f'
10663 #define GOT_HISTEDIT_DROP 'd'
10664 #define GOT_HISTEDIT_MESG 'm'
10666 static const struct got_histedit_cmd {
10667 unsigned char code;
10668 const char *name;
10669 const char *desc;
10670 } got_histedit_cmds[] = {
10671 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10672 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10673 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10674 "be used" },
10675 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10676 { GOT_HISTEDIT_MESG, "mesg",
10677 "single-line log message for commit above (open editor if empty)" },
10680 struct got_histedit_list_entry {
10681 TAILQ_ENTRY(got_histedit_list_entry) entry;
10682 struct got_object_id *commit_id;
10683 const struct got_histedit_cmd *cmd;
10684 char *logmsg;
10686 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10688 static const struct got_error *
10689 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10690 FILE *f, struct got_repository *repo)
10692 const struct got_error *err = NULL;
10693 char *logmsg = NULL, *id_str = NULL;
10694 struct got_commit_object *commit = NULL;
10695 int n;
10697 err = got_object_open_as_commit(&commit, repo, commit_id);
10698 if (err)
10699 goto done;
10701 err = get_short_logmsg(&logmsg, 34, commit);
10702 if (err)
10703 goto done;
10705 err = got_object_id_str(&id_str, commit_id);
10706 if (err)
10707 goto done;
10709 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10710 if (n < 0)
10711 err = got_ferror(f, GOT_ERR_IO);
10712 done:
10713 if (commit)
10714 got_object_commit_close(commit);
10715 free(id_str);
10716 free(logmsg);
10717 return err;
10720 static const struct got_error *
10721 histedit_write_commit_list(struct got_object_id_queue *commits,
10722 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10723 struct got_repository *repo)
10725 const struct got_error *err = NULL;
10726 struct got_object_qid *qid;
10727 const char *histedit_cmd = NULL;
10729 if (STAILQ_EMPTY(commits))
10730 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10732 STAILQ_FOREACH(qid, commits, entry) {
10733 histedit_cmd = got_histedit_cmds[0].name;
10734 if (edit_only)
10735 histedit_cmd = "edit";
10736 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10737 histedit_cmd = "fold";
10738 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10739 if (err)
10740 break;
10741 if (edit_logmsg_only) {
10742 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10743 if (n < 0) {
10744 err = got_ferror(f, GOT_ERR_IO);
10745 break;
10750 return err;
10753 static const struct got_error *
10754 write_cmd_list(FILE *f, const char *branch_name,
10755 struct got_object_id_queue *commits)
10757 const struct got_error *err = NULL;
10758 size_t i;
10759 int n;
10760 char *id_str;
10761 struct got_object_qid *qid;
10763 qid = STAILQ_FIRST(commits);
10764 err = got_object_id_str(&id_str, &qid->id);
10765 if (err)
10766 return err;
10768 n = fprintf(f,
10769 "# Editing the history of branch '%s' starting at\n"
10770 "# commit %s\n"
10771 "# Commits will be processed in order from top to "
10772 "bottom of this file.\n", branch_name, id_str);
10773 if (n < 0) {
10774 err = got_ferror(f, GOT_ERR_IO);
10775 goto done;
10778 n = fprintf(f, "# Available histedit commands:\n");
10779 if (n < 0) {
10780 err = got_ferror(f, GOT_ERR_IO);
10781 goto done;
10784 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10785 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10786 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10787 cmd->desc);
10788 if (n < 0) {
10789 err = got_ferror(f, GOT_ERR_IO);
10790 break;
10793 done:
10794 free(id_str);
10795 return err;
10798 static const struct got_error *
10799 histedit_syntax_error(int lineno)
10801 static char msg[42];
10802 int ret;
10804 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10805 lineno);
10806 if (ret < 0 || (size_t)ret >= sizeof(msg))
10807 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10809 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10812 static const struct got_error *
10813 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10814 char *logmsg, struct got_repository *repo)
10816 const struct got_error *err;
10817 struct got_commit_object *folded_commit = NULL;
10818 char *id_str, *folded_logmsg = NULL;
10820 err = got_object_id_str(&id_str, hle->commit_id);
10821 if (err)
10822 return err;
10824 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10825 if (err)
10826 goto done;
10828 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10829 if (err)
10830 goto done;
10831 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10832 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10833 folded_logmsg) == -1) {
10834 err = got_error_from_errno("asprintf");
10836 done:
10837 if (folded_commit)
10838 got_object_commit_close(folded_commit);
10839 free(id_str);
10840 free(folded_logmsg);
10841 return err;
10844 static struct got_histedit_list_entry *
10845 get_folded_commits(struct got_histedit_list_entry *hle)
10847 struct got_histedit_list_entry *prev, *folded = NULL;
10849 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10850 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10851 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10852 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10853 folded = prev;
10854 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10857 return folded;
10860 static const struct got_error *
10861 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10862 struct got_repository *repo)
10864 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10865 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10866 const struct got_error *err = NULL;
10867 struct got_commit_object *commit = NULL;
10868 int logmsg_len;
10869 int fd;
10870 struct got_histedit_list_entry *folded = NULL;
10872 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10873 if (err)
10874 return err;
10876 folded = get_folded_commits(hle);
10877 if (folded) {
10878 while (folded != hle) {
10879 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10880 folded = TAILQ_NEXT(folded, entry);
10881 continue;
10883 err = append_folded_commit_msg(&new_msg, folded,
10884 logmsg, repo);
10885 if (err)
10886 goto done;
10887 free(logmsg);
10888 logmsg = new_msg;
10889 folded = TAILQ_NEXT(folded, entry);
10893 err = got_object_id_str(&id_str, hle->commit_id);
10894 if (err)
10895 goto done;
10896 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10897 if (err)
10898 goto done;
10899 logmsg_len = asprintf(&new_msg,
10900 "%s\n# original log message of commit %s: %s",
10901 logmsg ? logmsg : "", id_str, orig_logmsg);
10902 if (logmsg_len == -1) {
10903 err = got_error_from_errno("asprintf");
10904 goto done;
10906 free(logmsg);
10907 logmsg = new_msg;
10909 err = got_object_id_str(&id_str, hle->commit_id);
10910 if (err)
10911 goto done;
10913 err = got_opentemp_named_fd(&logmsg_path, &fd,
10914 GOT_TMPDIR_STR "/got-logmsg", "");
10915 if (err)
10916 goto done;
10918 write(fd, logmsg, logmsg_len);
10919 close(fd);
10921 err = get_editor(&editor);
10922 if (err)
10923 goto done;
10925 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10926 logmsg_len, 0);
10927 if (err) {
10928 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10929 goto done;
10930 err = NULL;
10931 hle->logmsg = strdup(new_msg);
10932 if (hle->logmsg == NULL)
10933 err = got_error_from_errno("strdup");
10935 done:
10936 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10937 err = got_error_from_errno2("unlink", logmsg_path);
10938 free(logmsg_path);
10939 free(logmsg);
10940 free(orig_logmsg);
10941 free(editor);
10942 if (commit)
10943 got_object_commit_close(commit);
10944 return err;
10947 static const struct got_error *
10948 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10949 FILE *f, struct got_repository *repo)
10951 const struct got_error *err = NULL;
10952 char *line = NULL, *p, *end;
10953 size_t i, size;
10954 ssize_t len;
10955 int lineno = 0, lastcmd = -1;
10956 const struct got_histedit_cmd *cmd;
10957 struct got_object_id *commit_id = NULL;
10958 struct got_histedit_list_entry *hle = NULL;
10960 for (;;) {
10961 len = getline(&line, &size, f);
10962 if (len == -1) {
10963 const struct got_error *getline_err;
10964 if (feof(f))
10965 break;
10966 getline_err = got_error_from_errno("getline");
10967 err = got_ferror(f, getline_err->code);
10968 break;
10970 lineno++;
10971 p = line;
10972 while (isspace((unsigned char)p[0]))
10973 p++;
10974 if (p[0] == '#' || p[0] == '\0') {
10975 free(line);
10976 line = NULL;
10977 continue;
10979 cmd = NULL;
10980 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10981 cmd = &got_histedit_cmds[i];
10982 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10983 isspace((unsigned char)p[strlen(cmd->name)])) {
10984 p += strlen(cmd->name);
10985 break;
10987 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10988 p++;
10989 break;
10992 if (i == nitems(got_histedit_cmds)) {
10993 err = histedit_syntax_error(lineno);
10994 break;
10996 while (isspace((unsigned char)p[0]))
10997 p++;
10998 if (cmd->code == GOT_HISTEDIT_MESG) {
10999 if (lastcmd != GOT_HISTEDIT_PICK &&
11000 lastcmd != GOT_HISTEDIT_EDIT) {
11001 err = got_error(GOT_ERR_HISTEDIT_CMD);
11002 break;
11004 if (p[0] == '\0') {
11005 err = histedit_edit_logmsg(hle, repo);
11006 if (err)
11007 break;
11008 } else {
11009 hle->logmsg = strdup(p);
11010 if (hle->logmsg == NULL) {
11011 err = got_error_from_errno("strdup");
11012 break;
11015 free(line);
11016 line = NULL;
11017 lastcmd = cmd->code;
11018 continue;
11019 } else {
11020 end = p;
11021 while (end[0] && !isspace((unsigned char)end[0]))
11022 end++;
11023 *end = '\0';
11025 err = got_object_resolve_id_str(&commit_id, repo, p);
11026 if (err) {
11027 /* override error code */
11028 err = histedit_syntax_error(lineno);
11029 break;
11032 hle = malloc(sizeof(*hle));
11033 if (hle == NULL) {
11034 err = got_error_from_errno("malloc");
11035 break;
11037 hle->cmd = cmd;
11038 hle->commit_id = commit_id;
11039 hle->logmsg = NULL;
11040 commit_id = NULL;
11041 free(line);
11042 line = NULL;
11043 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11044 lastcmd = cmd->code;
11047 free(line);
11048 free(commit_id);
11049 return err;
11052 static const struct got_error *
11053 histedit_check_script(struct got_histedit_list *histedit_cmds,
11054 struct got_object_id_queue *commits, struct got_repository *repo)
11056 const struct got_error *err = NULL;
11057 struct got_object_qid *qid;
11058 struct got_histedit_list_entry *hle;
11059 static char msg[92];
11060 char *id_str;
11062 if (TAILQ_EMPTY(histedit_cmds))
11063 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11064 "histedit script contains no commands");
11065 if (STAILQ_EMPTY(commits))
11066 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11068 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11069 struct got_histedit_list_entry *hle2;
11070 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11071 if (hle == hle2)
11072 continue;
11073 if (got_object_id_cmp(hle->commit_id,
11074 hle2->commit_id) != 0)
11075 continue;
11076 err = got_object_id_str(&id_str, hle->commit_id);
11077 if (err)
11078 return err;
11079 snprintf(msg, sizeof(msg), "commit %s is listed "
11080 "more than once in histedit script", id_str);
11081 free(id_str);
11082 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11086 STAILQ_FOREACH(qid, commits, entry) {
11087 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11088 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11089 break;
11091 if (hle == NULL) {
11092 err = got_object_id_str(&id_str, &qid->id);
11093 if (err)
11094 return err;
11095 snprintf(msg, sizeof(msg),
11096 "commit %s missing from histedit script", id_str);
11097 free(id_str);
11098 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11102 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11103 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11104 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11105 "last commit in histedit script cannot be folded");
11107 return NULL;
11110 static const struct got_error *
11111 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11112 const char *path, struct got_object_id_queue *commits,
11113 struct got_repository *repo)
11115 const struct got_error *err = NULL;
11116 char *editor;
11117 FILE *f = NULL;
11119 err = get_editor(&editor);
11120 if (err)
11121 return err;
11123 if (spawn_editor(editor, path) == -1) {
11124 err = got_error_from_errno("failed spawning editor");
11125 goto done;
11128 f = fopen(path, "re");
11129 if (f == NULL) {
11130 err = got_error_from_errno("fopen");
11131 goto done;
11133 err = histedit_parse_list(histedit_cmds, f, repo);
11134 if (err)
11135 goto done;
11137 err = histedit_check_script(histedit_cmds, commits, repo);
11138 done:
11139 if (f && fclose(f) == EOF && err == NULL)
11140 err = got_error_from_errno("fclose");
11141 free(editor);
11142 return err;
11145 static const struct got_error *
11146 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11147 struct got_object_id_queue *, const char *, const char *,
11148 struct got_repository *);
11150 static const struct got_error *
11151 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11152 struct got_object_id_queue *commits, const char *branch_name,
11153 int edit_logmsg_only, int fold_only, int edit_only,
11154 struct got_repository *repo)
11156 const struct got_error *err;
11157 FILE *f = NULL;
11158 char *path = NULL;
11160 err = got_opentemp_named(&path, &f, "got-histedit", "");
11161 if (err)
11162 return err;
11164 err = write_cmd_list(f, branch_name, commits);
11165 if (err)
11166 goto done;
11168 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11169 fold_only, edit_only, repo);
11170 if (err)
11171 goto done;
11173 if (edit_logmsg_only || fold_only || edit_only) {
11174 rewind(f);
11175 err = histedit_parse_list(histedit_cmds, f, repo);
11176 } else {
11177 if (fclose(f) == EOF) {
11178 err = got_error_from_errno("fclose");
11179 goto done;
11181 f = NULL;
11182 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11183 if (err) {
11184 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11185 err->code != GOT_ERR_HISTEDIT_CMD)
11186 goto done;
11187 err = histedit_edit_list_retry(histedit_cmds, err,
11188 commits, path, branch_name, repo);
11191 done:
11192 if (f && fclose(f) == EOF && err == NULL)
11193 err = got_error_from_errno("fclose");
11194 if (path && unlink(path) != 0 && err == NULL)
11195 err = got_error_from_errno2("unlink", path);
11196 free(path);
11197 return err;
11200 static const struct got_error *
11201 histedit_save_list(struct got_histedit_list *histedit_cmds,
11202 struct got_worktree *worktree, struct got_repository *repo)
11204 const struct got_error *err = NULL;
11205 char *path = NULL;
11206 FILE *f = NULL;
11207 struct got_histedit_list_entry *hle;
11208 struct got_commit_object *commit = NULL;
11210 err = got_worktree_get_histedit_script_path(&path, worktree);
11211 if (err)
11212 return err;
11214 f = fopen(path, "we");
11215 if (f == NULL) {
11216 err = got_error_from_errno2("fopen", path);
11217 goto done;
11219 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11220 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11221 repo);
11222 if (err)
11223 break;
11225 if (hle->logmsg) {
11226 int n = fprintf(f, "%c %s\n",
11227 GOT_HISTEDIT_MESG, hle->logmsg);
11228 if (n < 0) {
11229 err = got_ferror(f, GOT_ERR_IO);
11230 break;
11234 done:
11235 if (f && fclose(f) == EOF && err == NULL)
11236 err = got_error_from_errno("fclose");
11237 free(path);
11238 if (commit)
11239 got_object_commit_close(commit);
11240 return err;
11243 static void
11244 histedit_free_list(struct got_histedit_list *histedit_cmds)
11246 struct got_histedit_list_entry *hle;
11248 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11249 TAILQ_REMOVE(histedit_cmds, hle, entry);
11250 free(hle);
11254 static const struct got_error *
11255 histedit_load_list(struct got_histedit_list *histedit_cmds,
11256 const char *path, struct got_repository *repo)
11258 const struct got_error *err = NULL;
11259 FILE *f = NULL;
11261 f = fopen(path, "re");
11262 if (f == NULL) {
11263 err = got_error_from_errno2("fopen", path);
11264 goto done;
11267 err = histedit_parse_list(histedit_cmds, f, repo);
11268 done:
11269 if (f && fclose(f) == EOF && err == NULL)
11270 err = got_error_from_errno("fclose");
11271 return err;
11274 static const struct got_error *
11275 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11276 const struct got_error *edit_err, struct got_object_id_queue *commits,
11277 const char *path, const char *branch_name, struct got_repository *repo)
11279 const struct got_error *err = NULL, *prev_err = edit_err;
11280 int resp = ' ';
11282 while (resp != 'c' && resp != 'r' && resp != 'a') {
11283 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11284 "or (a)bort: ", getprogname(), prev_err->msg);
11285 resp = getchar();
11286 if (resp == '\n')
11287 resp = getchar();
11288 if (resp == 'c') {
11289 histedit_free_list(histedit_cmds);
11290 err = histedit_run_editor(histedit_cmds, path, commits,
11291 repo);
11292 if (err) {
11293 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11294 err->code != GOT_ERR_HISTEDIT_CMD)
11295 break;
11296 prev_err = err;
11297 resp = ' ';
11298 continue;
11300 break;
11301 } else if (resp == 'r') {
11302 histedit_free_list(histedit_cmds);
11303 err = histedit_edit_script(histedit_cmds,
11304 commits, branch_name, 0, 0, 0, repo);
11305 if (err) {
11306 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11307 err->code != GOT_ERR_HISTEDIT_CMD)
11308 break;
11309 prev_err = err;
11310 resp = ' ';
11311 continue;
11313 break;
11314 } else if (resp == 'a') {
11315 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11316 break;
11317 } else
11318 printf("invalid response '%c'\n", resp);
11321 return err;
11324 static const struct got_error *
11325 histedit_complete(struct got_worktree *worktree,
11326 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11327 struct got_reference *branch, struct got_repository *repo)
11329 printf("Switching work tree to %s\n",
11330 got_ref_get_symref_target(branch));
11331 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11332 branch, repo);
11335 static const struct got_error *
11336 show_histedit_progress(struct got_commit_object *commit,
11337 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11339 const struct got_error *err;
11340 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11342 err = got_object_id_str(&old_id_str, hle->commit_id);
11343 if (err)
11344 goto done;
11346 if (new_id) {
11347 err = got_object_id_str(&new_id_str, new_id);
11348 if (err)
11349 goto done;
11352 old_id_str[12] = '\0';
11353 if (new_id_str)
11354 new_id_str[12] = '\0';
11356 if (hle->logmsg) {
11357 logmsg = strdup(hle->logmsg);
11358 if (logmsg == NULL) {
11359 err = got_error_from_errno("strdup");
11360 goto done;
11362 trim_logmsg(logmsg, 42);
11363 } else {
11364 err = get_short_logmsg(&logmsg, 42, commit);
11365 if (err)
11366 goto done;
11369 switch (hle->cmd->code) {
11370 case GOT_HISTEDIT_PICK:
11371 case GOT_HISTEDIT_EDIT:
11372 printf("%s -> %s: %s\n", old_id_str,
11373 new_id_str ? new_id_str : "no-op change", logmsg);
11374 break;
11375 case GOT_HISTEDIT_DROP:
11376 case GOT_HISTEDIT_FOLD:
11377 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11378 logmsg);
11379 break;
11380 default:
11381 break;
11383 done:
11384 free(old_id_str);
11385 free(new_id_str);
11386 return err;
11389 static const struct got_error *
11390 histedit_commit(struct got_pathlist_head *merged_paths,
11391 struct got_worktree *worktree, struct got_fileindex *fileindex,
11392 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11393 const char *committer, struct got_repository *repo)
11395 const struct got_error *err;
11396 struct got_commit_object *commit;
11397 struct got_object_id *new_commit_id;
11399 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11400 && hle->logmsg == NULL) {
11401 err = histedit_edit_logmsg(hle, repo);
11402 if (err)
11403 return err;
11406 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11407 if (err)
11408 return err;
11410 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11411 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11412 hle->logmsg, repo);
11413 if (err) {
11414 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11415 goto done;
11416 err = show_histedit_progress(commit, hle, NULL);
11417 } else {
11418 err = show_histedit_progress(commit, hle, new_commit_id);
11419 free(new_commit_id);
11421 done:
11422 got_object_commit_close(commit);
11423 return err;
11426 static const struct got_error *
11427 histedit_skip_commit(struct got_histedit_list_entry *hle,
11428 struct got_worktree *worktree, struct got_repository *repo)
11430 const struct got_error *error;
11431 struct got_commit_object *commit;
11433 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11434 repo);
11435 if (error)
11436 return error;
11438 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11439 if (error)
11440 return error;
11442 error = show_histedit_progress(commit, hle, NULL);
11443 got_object_commit_close(commit);
11444 return error;
11447 static const struct got_error *
11448 check_local_changes(void *arg, unsigned char status,
11449 unsigned char staged_status, const char *path,
11450 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11451 struct got_object_id *commit_id, int dirfd, const char *de_name)
11453 int *have_local_changes = arg;
11455 switch (status) {
11456 case GOT_STATUS_ADD:
11457 case GOT_STATUS_DELETE:
11458 case GOT_STATUS_MODIFY:
11459 case GOT_STATUS_CONFLICT:
11460 *have_local_changes = 1;
11461 return got_error(GOT_ERR_CANCELLED);
11462 default:
11463 break;
11466 switch (staged_status) {
11467 case GOT_STATUS_ADD:
11468 case GOT_STATUS_DELETE:
11469 case GOT_STATUS_MODIFY:
11470 *have_local_changes = 1;
11471 return got_error(GOT_ERR_CANCELLED);
11472 default:
11473 break;
11476 return NULL;
11479 static const struct got_error *
11480 cmd_histedit(int argc, char *argv[])
11482 const struct got_error *error = NULL;
11483 struct got_worktree *worktree = NULL;
11484 struct got_fileindex *fileindex = NULL;
11485 struct got_repository *repo = NULL;
11486 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11487 struct got_reference *branch = NULL;
11488 struct got_reference *tmp_branch = NULL;
11489 struct got_object_id *resume_commit_id = NULL;
11490 struct got_object_id *base_commit_id = NULL;
11491 struct got_object_id *head_commit_id = NULL;
11492 struct got_commit_object *commit = NULL;
11493 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11494 struct got_update_progress_arg upa;
11495 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11496 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11497 int list_backups = 0, delete_backups = 0;
11498 const char *edit_script_path = NULL;
11499 struct got_object_id_queue commits;
11500 struct got_pathlist_head merged_paths;
11501 const struct got_object_id_queue *parent_ids;
11502 struct got_object_qid *pid;
11503 struct got_histedit_list histedit_cmds;
11504 struct got_histedit_list_entry *hle;
11505 int *pack_fds = NULL;
11507 STAILQ_INIT(&commits);
11508 TAILQ_INIT(&histedit_cmds);
11509 TAILQ_INIT(&merged_paths);
11510 memset(&upa, 0, sizeof(upa));
11512 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11513 switch (ch) {
11514 case 'a':
11515 abort_edit = 1;
11516 break;
11517 case 'c':
11518 continue_edit = 1;
11519 break;
11520 case 'e':
11521 edit_only = 1;
11522 break;
11523 case 'F':
11524 edit_script_path = optarg;
11525 break;
11526 case 'f':
11527 fold_only = 1;
11528 break;
11529 case 'l':
11530 list_backups = 1;
11531 break;
11532 case 'm':
11533 edit_logmsg_only = 1;
11534 break;
11535 case 'X':
11536 delete_backups = 1;
11537 break;
11538 default:
11539 usage_histedit();
11540 /* NOTREACHED */
11544 argc -= optind;
11545 argv += optind;
11547 #ifndef PROFILE
11548 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11549 "unveil", NULL) == -1)
11550 err(1, "pledge");
11551 #endif
11552 if (abort_edit && continue_edit)
11553 option_conflict('a', 'c');
11554 if (edit_script_path && edit_logmsg_only)
11555 option_conflict('F', 'm');
11556 if (abort_edit && edit_logmsg_only)
11557 option_conflict('a', 'm');
11558 if (continue_edit && edit_logmsg_only)
11559 option_conflict('c', 'm');
11560 if (abort_edit && fold_only)
11561 option_conflict('a', 'f');
11562 if (continue_edit && fold_only)
11563 option_conflict('c', 'f');
11564 if (fold_only && edit_logmsg_only)
11565 option_conflict('f', 'm');
11566 if (edit_script_path && fold_only)
11567 option_conflict('F', 'f');
11568 if (abort_edit && edit_only)
11569 option_conflict('a', 'e');
11570 if (continue_edit && edit_only)
11571 option_conflict('c', 'e');
11572 if (edit_only && edit_logmsg_only)
11573 option_conflict('e', 'm');
11574 if (edit_script_path && edit_only)
11575 option_conflict('F', 'e');
11576 if (list_backups) {
11577 if (abort_edit)
11578 option_conflict('l', 'a');
11579 if (continue_edit)
11580 option_conflict('l', 'c');
11581 if (edit_script_path)
11582 option_conflict('l', 'F');
11583 if (edit_logmsg_only)
11584 option_conflict('l', 'm');
11585 if (fold_only)
11586 option_conflict('l', 'f');
11587 if (edit_only)
11588 option_conflict('l', 'e');
11589 if (delete_backups)
11590 option_conflict('l', 'X');
11591 if (argc != 0 && argc != 1)
11592 usage_histedit();
11593 } else if (delete_backups) {
11594 if (abort_edit)
11595 option_conflict('X', 'a');
11596 if (continue_edit)
11597 option_conflict('X', 'c');
11598 if (edit_script_path)
11599 option_conflict('X', 'F');
11600 if (edit_logmsg_only)
11601 option_conflict('X', 'm');
11602 if (fold_only)
11603 option_conflict('X', 'f');
11604 if (edit_only)
11605 option_conflict('X', 'e');
11606 if (list_backups)
11607 option_conflict('X', 'l');
11608 if (argc != 0 && argc != 1)
11609 usage_histedit();
11610 } else if (argc != 0)
11611 usage_histedit();
11614 * This command cannot apply unveil(2) in all cases because the
11615 * user may choose to run an editor to edit the histedit script
11616 * and to edit individual commit log messages.
11617 * unveil(2) traverses exec(2); if an editor is used we have to
11618 * apply unveil after edit script and log messages have been written.
11619 * XXX TODO: Make use of unveil(2) where possible.
11622 cwd = getcwd(NULL, 0);
11623 if (cwd == NULL) {
11624 error = got_error_from_errno("getcwd");
11625 goto done;
11628 error = got_repo_pack_fds_open(&pack_fds);
11629 if (error != NULL)
11630 goto done;
11632 error = got_worktree_open(&worktree, cwd);
11633 if (error) {
11634 if (list_backups || delete_backups) {
11635 if (error->code != GOT_ERR_NOT_WORKTREE)
11636 goto done;
11637 } else {
11638 if (error->code == GOT_ERR_NOT_WORKTREE)
11639 error = wrap_not_worktree_error(error,
11640 "histedit", cwd);
11641 goto done;
11645 if (list_backups || delete_backups) {
11646 error = got_repo_open(&repo,
11647 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11648 NULL, pack_fds);
11649 if (error != NULL)
11650 goto done;
11651 error = apply_unveil(got_repo_get_path(repo), 0,
11652 worktree ? got_worktree_get_root_path(worktree) : NULL);
11653 if (error)
11654 goto done;
11655 error = process_backup_refs(
11656 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11657 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11658 goto done; /* nothing else to do */
11661 error = get_gitconfig_path(&gitconfig_path);
11662 if (error)
11663 goto done;
11664 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11665 gitconfig_path, pack_fds);
11666 if (error != NULL)
11667 goto done;
11669 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11670 if (error)
11671 goto done;
11672 if (rebase_in_progress) {
11673 error = got_error(GOT_ERR_REBASING);
11674 goto done;
11677 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11678 repo);
11679 if (error)
11680 goto done;
11681 if (merge_in_progress) {
11682 error = got_error(GOT_ERR_MERGE_BUSY);
11683 goto done;
11686 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11687 if (error)
11688 goto done;
11690 if (edit_in_progress && edit_logmsg_only) {
11691 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11692 "histedit operation is in progress in this "
11693 "work tree and must be continued or aborted "
11694 "before the -m option can be used");
11695 goto done;
11697 if (edit_in_progress && fold_only) {
11698 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11699 "histedit operation is in progress in this "
11700 "work tree and must be continued or aborted "
11701 "before the -f option can be used");
11702 goto done;
11704 if (edit_in_progress && edit_only) {
11705 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11706 "histedit operation is in progress in this "
11707 "work tree and must be continued or aborted "
11708 "before the -e option can be used");
11709 goto done;
11712 if (edit_in_progress && abort_edit) {
11713 error = got_worktree_histedit_continue(&resume_commit_id,
11714 &tmp_branch, &branch, &base_commit_id, &fileindex,
11715 worktree, repo);
11716 if (error)
11717 goto done;
11718 printf("Switching work tree to %s\n",
11719 got_ref_get_symref_target(branch));
11720 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11721 branch, base_commit_id, abort_progress, &upa);
11722 if (error)
11723 goto done;
11724 printf("Histedit of %s aborted\n",
11725 got_ref_get_symref_target(branch));
11726 print_merge_progress_stats(&upa);
11727 goto done; /* nothing else to do */
11728 } else if (abort_edit) {
11729 error = got_error(GOT_ERR_NOT_HISTEDIT);
11730 goto done;
11733 error = get_author(&committer, repo, worktree);
11734 if (error)
11735 goto done;
11737 if (continue_edit) {
11738 char *path;
11740 if (!edit_in_progress) {
11741 error = got_error(GOT_ERR_NOT_HISTEDIT);
11742 goto done;
11745 error = got_worktree_get_histedit_script_path(&path, worktree);
11746 if (error)
11747 goto done;
11749 error = histedit_load_list(&histedit_cmds, path, repo);
11750 free(path);
11751 if (error)
11752 goto done;
11754 error = got_worktree_histedit_continue(&resume_commit_id,
11755 &tmp_branch, &branch, &base_commit_id, &fileindex,
11756 worktree, repo);
11757 if (error)
11758 goto done;
11760 error = got_ref_resolve(&head_commit_id, repo, branch);
11761 if (error)
11762 goto done;
11764 error = got_object_open_as_commit(&commit, repo,
11765 head_commit_id);
11766 if (error)
11767 goto done;
11768 parent_ids = got_object_commit_get_parent_ids(commit);
11769 pid = STAILQ_FIRST(parent_ids);
11770 if (pid == NULL) {
11771 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11772 goto done;
11774 error = collect_commits(&commits, head_commit_id, &pid->id,
11775 base_commit_id, got_worktree_get_path_prefix(worktree),
11776 GOT_ERR_HISTEDIT_PATH, repo);
11777 got_object_commit_close(commit);
11778 commit = NULL;
11779 if (error)
11780 goto done;
11781 } else {
11782 if (edit_in_progress) {
11783 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11784 goto done;
11787 error = got_ref_open(&branch, repo,
11788 got_worktree_get_head_ref_name(worktree), 0);
11789 if (error != NULL)
11790 goto done;
11792 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11793 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11794 "will not edit commit history of a branch outside "
11795 "the \"refs/heads/\" reference namespace");
11796 goto done;
11799 error = got_ref_resolve(&head_commit_id, repo, branch);
11800 got_ref_close(branch);
11801 branch = NULL;
11802 if (error)
11803 goto done;
11805 error = got_object_open_as_commit(&commit, repo,
11806 head_commit_id);
11807 if (error)
11808 goto done;
11809 parent_ids = got_object_commit_get_parent_ids(commit);
11810 pid = STAILQ_FIRST(parent_ids);
11811 if (pid == NULL) {
11812 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11813 goto done;
11815 error = collect_commits(&commits, head_commit_id, &pid->id,
11816 got_worktree_get_base_commit_id(worktree),
11817 got_worktree_get_path_prefix(worktree),
11818 GOT_ERR_HISTEDIT_PATH, repo);
11819 got_object_commit_close(commit);
11820 commit = NULL;
11821 if (error)
11822 goto done;
11824 if (STAILQ_EMPTY(&commits)) {
11825 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11826 goto done;
11829 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11830 &base_commit_id, &fileindex, worktree, repo);
11831 if (error)
11832 goto done;
11834 if (edit_script_path) {
11835 error = histedit_load_list(&histedit_cmds,
11836 edit_script_path, repo);
11837 if (error) {
11838 got_worktree_histedit_abort(worktree, fileindex,
11839 repo, branch, base_commit_id,
11840 abort_progress, &upa);
11841 print_merge_progress_stats(&upa);
11842 goto done;
11844 } else {
11845 const char *branch_name;
11846 branch_name = got_ref_get_symref_target(branch);
11847 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11848 branch_name += 11;
11849 error = histedit_edit_script(&histedit_cmds, &commits,
11850 branch_name, edit_logmsg_only, fold_only,
11851 edit_only, repo);
11852 if (error) {
11853 got_worktree_histedit_abort(worktree, fileindex,
11854 repo, branch, base_commit_id,
11855 abort_progress, &upa);
11856 print_merge_progress_stats(&upa);
11857 goto done;
11862 error = histedit_save_list(&histedit_cmds, worktree,
11863 repo);
11864 if (error) {
11865 got_worktree_histedit_abort(worktree, fileindex,
11866 repo, branch, base_commit_id,
11867 abort_progress, &upa);
11868 print_merge_progress_stats(&upa);
11869 goto done;
11874 error = histedit_check_script(&histedit_cmds, &commits, repo);
11875 if (error)
11876 goto done;
11878 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11879 if (resume_commit_id) {
11880 if (got_object_id_cmp(hle->commit_id,
11881 resume_commit_id) != 0)
11882 continue;
11884 resume_commit_id = NULL;
11885 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11886 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11887 error = histedit_skip_commit(hle, worktree,
11888 repo);
11889 if (error)
11890 goto done;
11891 } else {
11892 struct got_pathlist_head paths;
11893 int have_changes = 0;
11895 TAILQ_INIT(&paths);
11896 error = got_pathlist_append(&paths, "", NULL);
11897 if (error)
11898 goto done;
11899 error = got_worktree_status(worktree, &paths,
11900 repo, 0, check_local_changes, &have_changes,
11901 check_cancelled, NULL);
11902 got_pathlist_free(&paths,
11903 GOT_PATHLIST_FREE_NONE);
11904 if (error) {
11905 if (error->code != GOT_ERR_CANCELLED)
11906 goto done;
11907 if (sigint_received || sigpipe_received)
11908 goto done;
11910 if (have_changes) {
11911 error = histedit_commit(NULL, worktree,
11912 fileindex, tmp_branch, hle,
11913 committer, repo);
11914 if (error)
11915 goto done;
11916 } else {
11917 error = got_object_open_as_commit(
11918 &commit, repo, hle->commit_id);
11919 if (error)
11920 goto done;
11921 error = show_histedit_progress(commit,
11922 hle, NULL);
11923 got_object_commit_close(commit);
11924 commit = NULL;
11925 if (error)
11926 goto done;
11929 continue;
11932 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11933 error = histedit_skip_commit(hle, worktree, repo);
11934 if (error)
11935 goto done;
11936 continue;
11939 error = got_object_open_as_commit(&commit, repo,
11940 hle->commit_id);
11941 if (error)
11942 goto done;
11943 parent_ids = got_object_commit_get_parent_ids(commit);
11944 pid = STAILQ_FIRST(parent_ids);
11946 error = got_worktree_histedit_merge_files(&merged_paths,
11947 worktree, fileindex, &pid->id, hle->commit_id, repo,
11948 update_progress, &upa, check_cancelled, NULL);
11949 if (error)
11950 goto done;
11951 got_object_commit_close(commit);
11952 commit = NULL;
11954 print_merge_progress_stats(&upa);
11955 if (upa.conflicts > 0 || upa.missing > 0 ||
11956 upa.not_deleted > 0 || upa.unversioned > 0) {
11957 if (upa.conflicts > 0) {
11958 error = show_rebase_merge_conflict(
11959 hle->commit_id, repo);
11960 if (error)
11961 goto done;
11963 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11964 break;
11967 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11968 char *id_str;
11969 error = got_object_id_str(&id_str, hle->commit_id);
11970 if (error)
11971 goto done;
11972 printf("Stopping histedit for amending commit %s\n",
11973 id_str);
11974 free(id_str);
11975 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11976 error = got_worktree_histedit_postpone(worktree,
11977 fileindex);
11978 goto done;
11981 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11982 error = histedit_skip_commit(hle, worktree, repo);
11983 if (error)
11984 goto done;
11985 continue;
11988 error = histedit_commit(&merged_paths, worktree, fileindex,
11989 tmp_branch, hle, committer, repo);
11990 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11991 if (error)
11992 goto done;
11995 if (upa.conflicts > 0 || upa.missing > 0 ||
11996 upa.not_deleted > 0 || upa.unversioned > 0) {
11997 error = got_worktree_histedit_postpone(worktree, fileindex);
11998 if (error)
11999 goto done;
12000 if (upa.conflicts > 0 && upa.missing == 0 &&
12001 upa.not_deleted == 0 && upa.unversioned == 0) {
12002 error = got_error_msg(GOT_ERR_CONFLICTS,
12003 "conflicts must be resolved before histedit "
12004 "can continue");
12005 } else if (upa.conflicts > 0) {
12006 error = got_error_msg(GOT_ERR_CONFLICTS,
12007 "conflicts must be resolved before histedit "
12008 "can continue; changes destined for some "
12009 "files were not yet merged and should be "
12010 "merged manually if required before the "
12011 "histedit operation is continued");
12012 } else {
12013 error = got_error_msg(GOT_ERR_CONFLICTS,
12014 "changes destined for some files were not "
12015 "yet merged and should be merged manually "
12016 "if required before the histedit operation "
12017 "is continued");
12019 } else
12020 error = histedit_complete(worktree, fileindex, tmp_branch,
12021 branch, repo);
12022 done:
12023 free(cwd);
12024 free(committer);
12025 free(gitconfig_path);
12026 got_object_id_queue_free(&commits);
12027 histedit_free_list(&histedit_cmds);
12028 free(head_commit_id);
12029 free(base_commit_id);
12030 free(resume_commit_id);
12031 if (commit)
12032 got_object_commit_close(commit);
12033 if (branch)
12034 got_ref_close(branch);
12035 if (tmp_branch)
12036 got_ref_close(tmp_branch);
12037 if (worktree)
12038 got_worktree_close(worktree);
12039 if (repo) {
12040 const struct got_error *close_err = got_repo_close(repo);
12041 if (error == NULL)
12042 error = close_err;
12044 if (pack_fds) {
12045 const struct got_error *pack_err =
12046 got_repo_pack_fds_close(pack_fds);
12047 if (error == NULL)
12048 error = pack_err;
12050 return error;
12053 __dead static void
12054 usage_integrate(void)
12056 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12057 exit(1);
12060 static const struct got_error *
12061 cmd_integrate(int argc, char *argv[])
12063 const struct got_error *error = NULL;
12064 struct got_repository *repo = NULL;
12065 struct got_worktree *worktree = NULL;
12066 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12067 const char *branch_arg = NULL;
12068 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12069 struct got_fileindex *fileindex = NULL;
12070 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12071 int ch;
12072 struct got_update_progress_arg upa;
12073 int *pack_fds = NULL;
12075 while ((ch = getopt(argc, argv, "")) != -1) {
12076 switch (ch) {
12077 default:
12078 usage_integrate();
12079 /* NOTREACHED */
12083 argc -= optind;
12084 argv += optind;
12086 if (argc != 1)
12087 usage_integrate();
12088 branch_arg = argv[0];
12089 #ifndef PROFILE
12090 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12091 "unveil", NULL) == -1)
12092 err(1, "pledge");
12093 #endif
12094 cwd = getcwd(NULL, 0);
12095 if (cwd == NULL) {
12096 error = got_error_from_errno("getcwd");
12097 goto done;
12100 error = got_repo_pack_fds_open(&pack_fds);
12101 if (error != NULL)
12102 goto done;
12104 error = got_worktree_open(&worktree, cwd);
12105 if (error) {
12106 if (error->code == GOT_ERR_NOT_WORKTREE)
12107 error = wrap_not_worktree_error(error, "integrate",
12108 cwd);
12109 goto done;
12112 error = check_rebase_or_histedit_in_progress(worktree);
12113 if (error)
12114 goto done;
12116 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12117 NULL, pack_fds);
12118 if (error != NULL)
12119 goto done;
12121 error = apply_unveil(got_repo_get_path(repo), 0,
12122 got_worktree_get_root_path(worktree));
12123 if (error)
12124 goto done;
12126 error = check_merge_in_progress(worktree, repo);
12127 if (error)
12128 goto done;
12130 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12131 error = got_error_from_errno("asprintf");
12132 goto done;
12135 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12136 &base_branch_ref, worktree, refname, repo);
12137 if (error)
12138 goto done;
12140 refname = strdup(got_ref_get_name(branch_ref));
12141 if (refname == NULL) {
12142 error = got_error_from_errno("strdup");
12143 got_worktree_integrate_abort(worktree, fileindex, repo,
12144 branch_ref, base_branch_ref);
12145 goto done;
12147 base_refname = strdup(got_ref_get_name(base_branch_ref));
12148 if (base_refname == NULL) {
12149 error = got_error_from_errno("strdup");
12150 got_worktree_integrate_abort(worktree, fileindex, repo,
12151 branch_ref, base_branch_ref);
12152 goto done;
12154 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12155 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12156 got_worktree_integrate_abort(worktree, fileindex, repo,
12157 branch_ref, base_branch_ref);
12158 goto done;
12161 error = got_ref_resolve(&commit_id, repo, branch_ref);
12162 if (error)
12163 goto done;
12165 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12166 if (error)
12167 goto done;
12169 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12170 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12171 "specified branch has already been integrated");
12172 got_worktree_integrate_abort(worktree, fileindex, repo,
12173 branch_ref, base_branch_ref);
12174 goto done;
12177 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12178 if (error) {
12179 if (error->code == GOT_ERR_ANCESTRY)
12180 error = got_error(GOT_ERR_REBASE_REQUIRED);
12181 got_worktree_integrate_abort(worktree, fileindex, repo,
12182 branch_ref, base_branch_ref);
12183 goto done;
12186 memset(&upa, 0, sizeof(upa));
12187 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12188 branch_ref, base_branch_ref, update_progress, &upa,
12189 check_cancelled, NULL);
12190 if (error)
12191 goto done;
12193 printf("Integrated %s into %s\n", refname, base_refname);
12194 print_update_progress_stats(&upa);
12195 done:
12196 if (repo) {
12197 const struct got_error *close_err = got_repo_close(repo);
12198 if (error == NULL)
12199 error = close_err;
12201 if (worktree)
12202 got_worktree_close(worktree);
12203 if (pack_fds) {
12204 const struct got_error *pack_err =
12205 got_repo_pack_fds_close(pack_fds);
12206 if (error == NULL)
12207 error = pack_err;
12209 free(cwd);
12210 free(base_commit_id);
12211 free(commit_id);
12212 free(refname);
12213 free(base_refname);
12214 return error;
12217 __dead static void
12218 usage_merge(void)
12220 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12221 exit(1);
12224 static const struct got_error *
12225 cmd_merge(int argc, char *argv[])
12227 const struct got_error *error = NULL;
12228 struct got_worktree *worktree = NULL;
12229 struct got_repository *repo = NULL;
12230 struct got_fileindex *fileindex = NULL;
12231 char *cwd = NULL, *id_str = NULL, *author = NULL;
12232 struct got_reference *branch = NULL, *wt_branch = NULL;
12233 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12234 struct got_object_id *wt_branch_tip = NULL;
12235 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12236 int interrupt_merge = 0;
12237 struct got_update_progress_arg upa;
12238 struct got_object_id *merge_commit_id = NULL;
12239 char *branch_name = NULL;
12240 int *pack_fds = NULL;
12242 memset(&upa, 0, sizeof(upa));
12244 while ((ch = getopt(argc, argv, "acn")) != -1) {
12245 switch (ch) {
12246 case 'a':
12247 abort_merge = 1;
12248 break;
12249 case 'c':
12250 continue_merge = 1;
12251 break;
12252 case 'n':
12253 interrupt_merge = 1;
12254 break;
12255 default:
12256 usage_rebase();
12257 /* NOTREACHED */
12261 argc -= optind;
12262 argv += optind;
12264 #ifndef PROFILE
12265 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12266 "unveil", NULL) == -1)
12267 err(1, "pledge");
12268 #endif
12270 if (abort_merge && continue_merge)
12271 option_conflict('a', 'c');
12272 if (abort_merge || continue_merge) {
12273 if (argc != 0)
12274 usage_merge();
12275 } else if (argc != 1)
12276 usage_merge();
12278 cwd = getcwd(NULL, 0);
12279 if (cwd == NULL) {
12280 error = got_error_from_errno("getcwd");
12281 goto done;
12284 error = got_repo_pack_fds_open(&pack_fds);
12285 if (error != NULL)
12286 goto done;
12288 error = got_worktree_open(&worktree, cwd);
12289 if (error) {
12290 if (error->code == GOT_ERR_NOT_WORKTREE)
12291 error = wrap_not_worktree_error(error,
12292 "merge", cwd);
12293 goto done;
12296 error = got_repo_open(&repo,
12297 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12298 pack_fds);
12299 if (error != NULL)
12300 goto done;
12302 error = apply_unveil(got_repo_get_path(repo), 0,
12303 worktree ? got_worktree_get_root_path(worktree) : NULL);
12304 if (error)
12305 goto done;
12307 error = check_rebase_or_histedit_in_progress(worktree);
12308 if (error)
12309 goto done;
12311 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12312 repo);
12313 if (error)
12314 goto done;
12316 if (abort_merge) {
12317 if (!merge_in_progress) {
12318 error = got_error(GOT_ERR_NOT_MERGING);
12319 goto done;
12321 error = got_worktree_merge_continue(&branch_name,
12322 &branch_tip, &fileindex, worktree, repo);
12323 if (error)
12324 goto done;
12325 error = got_worktree_merge_abort(worktree, fileindex, repo,
12326 abort_progress, &upa);
12327 if (error)
12328 goto done;
12329 printf("Merge of %s aborted\n", branch_name);
12330 goto done; /* nothing else to do */
12333 error = get_author(&author, repo, worktree);
12334 if (error)
12335 goto done;
12337 if (continue_merge) {
12338 if (!merge_in_progress) {
12339 error = got_error(GOT_ERR_NOT_MERGING);
12340 goto done;
12342 error = got_worktree_merge_continue(&branch_name,
12343 &branch_tip, &fileindex, worktree, repo);
12344 if (error)
12345 goto done;
12346 } else {
12347 error = got_ref_open(&branch, repo, argv[0], 0);
12348 if (error != NULL)
12349 goto done;
12350 branch_name = strdup(got_ref_get_name(branch));
12351 if (branch_name == NULL) {
12352 error = got_error_from_errno("strdup");
12353 goto done;
12355 error = got_ref_resolve(&branch_tip, repo, branch);
12356 if (error)
12357 goto done;
12360 error = got_ref_open(&wt_branch, repo,
12361 got_worktree_get_head_ref_name(worktree), 0);
12362 if (error)
12363 goto done;
12364 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12365 if (error)
12366 goto done;
12367 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12368 wt_branch_tip, branch_tip, 0, repo,
12369 check_cancelled, NULL);
12370 if (error && error->code != GOT_ERR_ANCESTRY)
12371 goto done;
12373 if (!continue_merge) {
12374 error = check_path_prefix(wt_branch_tip, branch_tip,
12375 got_worktree_get_path_prefix(worktree),
12376 GOT_ERR_MERGE_PATH, repo);
12377 if (error)
12378 goto done;
12379 if (yca_id) {
12380 error = check_same_branch(wt_branch_tip, branch,
12381 yca_id, repo);
12382 if (error) {
12383 if (error->code != GOT_ERR_ANCESTRY)
12384 goto done;
12385 error = NULL;
12386 } else {
12387 static char msg[512];
12388 snprintf(msg, sizeof(msg),
12389 "cannot create a merge commit because "
12390 "%s is based on %s; %s can be integrated "
12391 "with 'got integrate' instead", branch_name,
12392 got_worktree_get_head_ref_name(worktree),
12393 branch_name);
12394 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12395 goto done;
12398 error = got_worktree_merge_prepare(&fileindex, worktree,
12399 branch, repo);
12400 if (error)
12401 goto done;
12403 error = got_worktree_merge_branch(worktree, fileindex,
12404 yca_id, branch_tip, repo, update_progress, &upa,
12405 check_cancelled, NULL);
12406 if (error)
12407 goto done;
12408 print_merge_progress_stats(&upa);
12409 if (!upa.did_something) {
12410 error = got_worktree_merge_abort(worktree, fileindex,
12411 repo, abort_progress, &upa);
12412 if (error)
12413 goto done;
12414 printf("Already up-to-date\n");
12415 goto done;
12419 if (interrupt_merge) {
12420 error = got_worktree_merge_postpone(worktree, fileindex);
12421 if (error)
12422 goto done;
12423 printf("Merge of %s interrupted on request\n", branch_name);
12424 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12425 upa.not_deleted > 0 || upa.unversioned > 0) {
12426 error = got_worktree_merge_postpone(worktree, fileindex);
12427 if (error)
12428 goto done;
12429 if (upa.conflicts > 0 && upa.missing == 0 &&
12430 upa.not_deleted == 0 && upa.unversioned == 0) {
12431 error = got_error_msg(GOT_ERR_CONFLICTS,
12432 "conflicts must be resolved before merging "
12433 "can continue");
12434 } else if (upa.conflicts > 0) {
12435 error = got_error_msg(GOT_ERR_CONFLICTS,
12436 "conflicts must be resolved before merging "
12437 "can continue; changes destined for some "
12438 "files were not yet merged and "
12439 "should be merged manually if required before the "
12440 "merge operation is continued");
12441 } else {
12442 error = got_error_msg(GOT_ERR_CONFLICTS,
12443 "changes destined for some "
12444 "files were not yet merged and should be "
12445 "merged manually if required before the "
12446 "merge operation is continued");
12448 goto done;
12449 } else {
12450 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12451 fileindex, author, NULL, 1, branch_tip, branch_name,
12452 repo, continue_merge ? print_status : NULL, NULL);
12453 if (error)
12454 goto done;
12455 error = got_worktree_merge_complete(worktree, fileindex, repo);
12456 if (error)
12457 goto done;
12458 error = got_object_id_str(&id_str, merge_commit_id);
12459 if (error)
12460 goto done;
12461 printf("Merged %s into %s: %s\n", branch_name,
12462 got_worktree_get_head_ref_name(worktree),
12463 id_str);
12466 done:
12467 free(id_str);
12468 free(merge_commit_id);
12469 free(author);
12470 free(branch_tip);
12471 free(branch_name);
12472 free(yca_id);
12473 if (branch)
12474 got_ref_close(branch);
12475 if (wt_branch)
12476 got_ref_close(wt_branch);
12477 if (worktree)
12478 got_worktree_close(worktree);
12479 if (repo) {
12480 const struct got_error *close_err = got_repo_close(repo);
12481 if (error == NULL)
12482 error = close_err;
12484 if (pack_fds) {
12485 const struct got_error *pack_err =
12486 got_repo_pack_fds_close(pack_fds);
12487 if (error == NULL)
12488 error = pack_err;
12490 return error;
12493 __dead static void
12494 usage_stage(void)
12496 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12497 "[path ...]\n", getprogname());
12498 exit(1);
12501 static const struct got_error *
12502 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12503 const char *path, struct got_object_id *blob_id,
12504 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12505 int dirfd, const char *de_name)
12507 const struct got_error *err = NULL;
12508 char *id_str = NULL;
12510 if (staged_status != GOT_STATUS_ADD &&
12511 staged_status != GOT_STATUS_MODIFY &&
12512 staged_status != GOT_STATUS_DELETE)
12513 return NULL;
12515 if (staged_status == GOT_STATUS_ADD ||
12516 staged_status == GOT_STATUS_MODIFY)
12517 err = got_object_id_str(&id_str, staged_blob_id);
12518 else
12519 err = got_object_id_str(&id_str, blob_id);
12520 if (err)
12521 return err;
12523 printf("%s %c %s\n", id_str, staged_status, path);
12524 free(id_str);
12525 return NULL;
12528 static const struct got_error *
12529 cmd_stage(int argc, char *argv[])
12531 const struct got_error *error = NULL;
12532 struct got_repository *repo = NULL;
12533 struct got_worktree *worktree = NULL;
12534 char *cwd = NULL;
12535 struct got_pathlist_head paths;
12536 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12537 FILE *patch_script_file = NULL;
12538 const char *patch_script_path = NULL;
12539 struct choose_patch_arg cpa;
12540 int *pack_fds = NULL;
12542 TAILQ_INIT(&paths);
12544 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12545 switch (ch) {
12546 case 'F':
12547 patch_script_path = optarg;
12548 break;
12549 case 'l':
12550 list_stage = 1;
12551 break;
12552 case 'p':
12553 pflag = 1;
12554 break;
12555 case 'S':
12556 allow_bad_symlinks = 1;
12557 break;
12558 default:
12559 usage_stage();
12560 /* NOTREACHED */
12564 argc -= optind;
12565 argv += optind;
12567 #ifndef PROFILE
12568 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12569 "unveil", NULL) == -1)
12570 err(1, "pledge");
12571 #endif
12572 if (list_stage && (pflag || patch_script_path))
12573 errx(1, "-l option cannot be used with other options");
12574 if (patch_script_path && !pflag)
12575 errx(1, "-F option can only be used together with -p option");
12577 cwd = getcwd(NULL, 0);
12578 if (cwd == NULL) {
12579 error = got_error_from_errno("getcwd");
12580 goto done;
12583 error = got_repo_pack_fds_open(&pack_fds);
12584 if (error != NULL)
12585 goto done;
12587 error = got_worktree_open(&worktree, cwd);
12588 if (error) {
12589 if (error->code == GOT_ERR_NOT_WORKTREE)
12590 error = wrap_not_worktree_error(error, "stage", cwd);
12591 goto done;
12594 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12595 NULL, pack_fds);
12596 if (error != NULL)
12597 goto done;
12599 if (patch_script_path) {
12600 patch_script_file = fopen(patch_script_path, "re");
12601 if (patch_script_file == NULL) {
12602 error = got_error_from_errno2("fopen",
12603 patch_script_path);
12604 goto done;
12607 error = apply_unveil(got_repo_get_path(repo), 0,
12608 got_worktree_get_root_path(worktree));
12609 if (error)
12610 goto done;
12612 error = check_merge_in_progress(worktree, repo);
12613 if (error)
12614 goto done;
12616 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12617 if (error)
12618 goto done;
12620 if (list_stage)
12621 error = got_worktree_status(worktree, &paths, repo, 0,
12622 print_stage, NULL, check_cancelled, NULL);
12623 else {
12624 cpa.patch_script_file = patch_script_file;
12625 cpa.action = "stage";
12626 error = got_worktree_stage(worktree, &paths,
12627 pflag ? NULL : print_status, NULL,
12628 pflag ? choose_patch : NULL, &cpa,
12629 allow_bad_symlinks, repo);
12631 done:
12632 if (patch_script_file && fclose(patch_script_file) == EOF &&
12633 error == NULL)
12634 error = got_error_from_errno2("fclose", patch_script_path);
12635 if (repo) {
12636 const struct got_error *close_err = got_repo_close(repo);
12637 if (error == NULL)
12638 error = close_err;
12640 if (worktree)
12641 got_worktree_close(worktree);
12642 if (pack_fds) {
12643 const struct got_error *pack_err =
12644 got_repo_pack_fds_close(pack_fds);
12645 if (error == NULL)
12646 error = pack_err;
12648 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12649 free(cwd);
12650 return error;
12653 __dead static void
12654 usage_unstage(void)
12656 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12657 "[path ...]\n", getprogname());
12658 exit(1);
12662 static const struct got_error *
12663 cmd_unstage(int argc, char *argv[])
12665 const struct got_error *error = NULL;
12666 struct got_repository *repo = NULL;
12667 struct got_worktree *worktree = NULL;
12668 char *cwd = NULL;
12669 struct got_pathlist_head paths;
12670 int ch, pflag = 0;
12671 struct got_update_progress_arg upa;
12672 FILE *patch_script_file = NULL;
12673 const char *patch_script_path = NULL;
12674 struct choose_patch_arg cpa;
12675 int *pack_fds = NULL;
12677 TAILQ_INIT(&paths);
12679 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12680 switch (ch) {
12681 case 'F':
12682 patch_script_path = optarg;
12683 break;
12684 case 'p':
12685 pflag = 1;
12686 break;
12687 default:
12688 usage_unstage();
12689 /* NOTREACHED */
12693 argc -= optind;
12694 argv += optind;
12696 #ifndef PROFILE
12697 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12698 "unveil", NULL) == -1)
12699 err(1, "pledge");
12700 #endif
12701 if (patch_script_path && !pflag)
12702 errx(1, "-F option can only be used together with -p option");
12704 cwd = getcwd(NULL, 0);
12705 if (cwd == NULL) {
12706 error = got_error_from_errno("getcwd");
12707 goto done;
12710 error = got_repo_pack_fds_open(&pack_fds);
12711 if (error != NULL)
12712 goto done;
12714 error = got_worktree_open(&worktree, cwd);
12715 if (error) {
12716 if (error->code == GOT_ERR_NOT_WORKTREE)
12717 error = wrap_not_worktree_error(error, "unstage", cwd);
12718 goto done;
12721 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12722 NULL, pack_fds);
12723 if (error != NULL)
12724 goto done;
12726 if (patch_script_path) {
12727 patch_script_file = fopen(patch_script_path, "re");
12728 if (patch_script_file == NULL) {
12729 error = got_error_from_errno2("fopen",
12730 patch_script_path);
12731 goto done;
12735 error = apply_unveil(got_repo_get_path(repo), 0,
12736 got_worktree_get_root_path(worktree));
12737 if (error)
12738 goto done;
12740 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12741 if (error)
12742 goto done;
12744 cpa.patch_script_file = patch_script_file;
12745 cpa.action = "unstage";
12746 memset(&upa, 0, sizeof(upa));
12747 error = got_worktree_unstage(worktree, &paths, update_progress,
12748 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12749 if (!error)
12750 print_merge_progress_stats(&upa);
12751 done:
12752 if (patch_script_file && fclose(patch_script_file) == EOF &&
12753 error == NULL)
12754 error = got_error_from_errno2("fclose", patch_script_path);
12755 if (repo) {
12756 const struct got_error *close_err = got_repo_close(repo);
12757 if (error == NULL)
12758 error = close_err;
12760 if (worktree)
12761 got_worktree_close(worktree);
12762 if (pack_fds) {
12763 const struct got_error *pack_err =
12764 got_repo_pack_fds_close(pack_fds);
12765 if (error == NULL)
12766 error = pack_err;
12768 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12769 free(cwd);
12770 return error;
12773 __dead static void
12774 usage_cat(void)
12776 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12777 "arg ...\n", getprogname());
12778 exit(1);
12781 static const struct got_error *
12782 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12784 const struct got_error *err;
12785 struct got_blob_object *blob;
12786 int fd = -1;
12788 fd = got_opentempfd();
12789 if (fd == -1)
12790 return got_error_from_errno("got_opentempfd");
12792 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12793 if (err)
12794 goto done;
12796 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12797 done:
12798 if (fd != -1 && close(fd) == -1 && err == NULL)
12799 err = got_error_from_errno("close");
12800 if (blob)
12801 got_object_blob_close(blob);
12802 return err;
12805 static const struct got_error *
12806 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12808 const struct got_error *err;
12809 struct got_tree_object *tree;
12810 int nentries, i;
12812 err = got_object_open_as_tree(&tree, repo, id);
12813 if (err)
12814 return err;
12816 nentries = got_object_tree_get_nentries(tree);
12817 for (i = 0; i < nentries; i++) {
12818 struct got_tree_entry *te;
12819 char *id_str;
12820 if (sigint_received || sigpipe_received)
12821 break;
12822 te = got_object_tree_get_entry(tree, i);
12823 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12824 if (err)
12825 break;
12826 fprintf(outfile, "%s %.7o %s\n", id_str,
12827 got_tree_entry_get_mode(te),
12828 got_tree_entry_get_name(te));
12829 free(id_str);
12832 got_object_tree_close(tree);
12833 return err;
12836 static const struct got_error *
12837 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12839 const struct got_error *err;
12840 struct got_commit_object *commit;
12841 const struct got_object_id_queue *parent_ids;
12842 struct got_object_qid *pid;
12843 char *id_str = NULL;
12844 const char *logmsg = NULL;
12845 char gmtoff[6];
12847 err = got_object_open_as_commit(&commit, repo, id);
12848 if (err)
12849 return err;
12851 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12852 if (err)
12853 goto done;
12855 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12856 parent_ids = got_object_commit_get_parent_ids(commit);
12857 fprintf(outfile, "numparents %d\n",
12858 got_object_commit_get_nparents(commit));
12859 STAILQ_FOREACH(pid, parent_ids, entry) {
12860 char *pid_str;
12861 err = got_object_id_str(&pid_str, &pid->id);
12862 if (err)
12863 goto done;
12864 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12865 free(pid_str);
12867 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12868 got_object_commit_get_author_gmtoff(commit));
12869 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12870 got_object_commit_get_author(commit),
12871 (long long)got_object_commit_get_author_time(commit),
12872 gmtoff);
12874 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12875 got_object_commit_get_committer_gmtoff(commit));
12876 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12877 got_object_commit_get_committer(commit),
12878 (long long)got_object_commit_get_committer_time(commit),
12879 gmtoff);
12881 logmsg = got_object_commit_get_logmsg_raw(commit);
12882 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12883 fprintf(outfile, "%s", logmsg);
12884 done:
12885 free(id_str);
12886 got_object_commit_close(commit);
12887 return err;
12890 static const struct got_error *
12891 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12893 const struct got_error *err;
12894 struct got_tag_object *tag;
12895 char *id_str = NULL;
12896 const char *tagmsg = NULL;
12897 char gmtoff[6];
12899 err = got_object_open_as_tag(&tag, repo, id);
12900 if (err)
12901 return err;
12903 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12904 if (err)
12905 goto done;
12907 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12909 switch (got_object_tag_get_object_type(tag)) {
12910 case GOT_OBJ_TYPE_BLOB:
12911 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12912 GOT_OBJ_LABEL_BLOB);
12913 break;
12914 case GOT_OBJ_TYPE_TREE:
12915 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12916 GOT_OBJ_LABEL_TREE);
12917 break;
12918 case GOT_OBJ_TYPE_COMMIT:
12919 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12920 GOT_OBJ_LABEL_COMMIT);
12921 break;
12922 case GOT_OBJ_TYPE_TAG:
12923 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12924 GOT_OBJ_LABEL_TAG);
12925 break;
12926 default:
12927 break;
12930 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12931 got_object_tag_get_name(tag));
12933 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12934 got_object_tag_get_tagger_gmtoff(tag));
12935 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12936 got_object_tag_get_tagger(tag),
12937 (long long)got_object_tag_get_tagger_time(tag),
12938 gmtoff);
12940 tagmsg = got_object_tag_get_message(tag);
12941 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12942 fprintf(outfile, "%s", tagmsg);
12943 done:
12944 free(id_str);
12945 got_object_tag_close(tag);
12946 return err;
12949 static const struct got_error *
12950 cmd_cat(int argc, char *argv[])
12952 const struct got_error *error;
12953 struct got_repository *repo = NULL;
12954 struct got_worktree *worktree = NULL;
12955 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12956 const char *commit_id_str = NULL;
12957 struct got_object_id *id = NULL, *commit_id = NULL;
12958 struct got_commit_object *commit = NULL;
12959 int ch, obj_type, i, force_path = 0;
12960 struct got_reflist_head refs;
12961 int *pack_fds = NULL;
12963 TAILQ_INIT(&refs);
12965 #ifndef PROFILE
12966 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12967 NULL) == -1)
12968 err(1, "pledge");
12969 #endif
12971 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12972 switch (ch) {
12973 case 'c':
12974 commit_id_str = optarg;
12975 break;
12976 case 'P':
12977 force_path = 1;
12978 break;
12979 case 'r':
12980 repo_path = realpath(optarg, NULL);
12981 if (repo_path == NULL)
12982 return got_error_from_errno2("realpath",
12983 optarg);
12984 got_path_strip_trailing_slashes(repo_path);
12985 break;
12986 default:
12987 usage_cat();
12988 /* NOTREACHED */
12992 argc -= optind;
12993 argv += optind;
12995 cwd = getcwd(NULL, 0);
12996 if (cwd == NULL) {
12997 error = got_error_from_errno("getcwd");
12998 goto done;
13001 error = got_repo_pack_fds_open(&pack_fds);
13002 if (error != NULL)
13003 goto done;
13005 if (repo_path == NULL) {
13006 error = got_worktree_open(&worktree, cwd);
13007 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13008 goto done;
13009 if (worktree) {
13010 repo_path = strdup(
13011 got_worktree_get_repo_path(worktree));
13012 if (repo_path == NULL) {
13013 error = got_error_from_errno("strdup");
13014 goto done;
13017 /* Release work tree lock. */
13018 got_worktree_close(worktree);
13019 worktree = NULL;
13023 if (repo_path == NULL) {
13024 repo_path = strdup(cwd);
13025 if (repo_path == NULL)
13026 return got_error_from_errno("strdup");
13029 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13030 free(repo_path);
13031 if (error != NULL)
13032 goto done;
13034 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13035 if (error)
13036 goto done;
13038 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13039 if (error)
13040 goto done;
13042 if (commit_id_str == NULL)
13043 commit_id_str = GOT_REF_HEAD;
13044 error = got_repo_match_object_id(&commit_id, NULL,
13045 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13046 if (error)
13047 goto done;
13049 error = got_object_open_as_commit(&commit, repo, commit_id);
13050 if (error)
13051 goto done;
13053 for (i = 0; i < argc; i++) {
13054 if (force_path) {
13055 error = got_object_id_by_path(&id, repo, commit,
13056 argv[i]);
13057 if (error)
13058 break;
13059 } else {
13060 error = got_repo_match_object_id(&id, &label, argv[i],
13061 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13062 repo);
13063 if (error) {
13064 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13065 error->code != GOT_ERR_NOT_REF)
13066 break;
13067 error = got_object_id_by_path(&id, repo,
13068 commit, argv[i]);
13069 if (error)
13070 break;
13074 error = got_object_get_type(&obj_type, repo, id);
13075 if (error)
13076 break;
13078 switch (obj_type) {
13079 case GOT_OBJ_TYPE_BLOB:
13080 error = cat_blob(id, repo, stdout);
13081 break;
13082 case GOT_OBJ_TYPE_TREE:
13083 error = cat_tree(id, repo, stdout);
13084 break;
13085 case GOT_OBJ_TYPE_COMMIT:
13086 error = cat_commit(id, repo, stdout);
13087 break;
13088 case GOT_OBJ_TYPE_TAG:
13089 error = cat_tag(id, repo, stdout);
13090 break;
13091 default:
13092 error = got_error(GOT_ERR_OBJ_TYPE);
13093 break;
13095 if (error)
13096 break;
13097 free(label);
13098 label = NULL;
13099 free(id);
13100 id = NULL;
13102 done:
13103 free(label);
13104 free(id);
13105 free(commit_id);
13106 if (commit)
13107 got_object_commit_close(commit);
13108 if (worktree)
13109 got_worktree_close(worktree);
13110 if (repo) {
13111 const struct got_error *close_err = got_repo_close(repo);
13112 if (error == NULL)
13113 error = close_err;
13115 if (pack_fds) {
13116 const struct got_error *pack_err =
13117 got_repo_pack_fds_close(pack_fds);
13118 if (error == NULL)
13119 error = pack_err;
13122 got_ref_list_free(&refs);
13123 return error;
13126 __dead static void
13127 usage_info(void)
13129 fprintf(stderr, "usage: %s info [path ...]\n",
13130 getprogname());
13131 exit(1);
13134 static const struct got_error *
13135 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13136 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13137 struct got_object_id *commit_id)
13139 const struct got_error *err = NULL;
13140 char *id_str = NULL;
13141 char datebuf[128];
13142 struct tm mytm, *tm;
13143 struct got_pathlist_head *paths = arg;
13144 struct got_pathlist_entry *pe;
13147 * Clear error indication from any of the path arguments which
13148 * would cause this file index entry to be displayed.
13150 TAILQ_FOREACH(pe, paths, entry) {
13151 if (got_path_cmp(path, pe->path, strlen(path),
13152 pe->path_len) == 0 ||
13153 got_path_is_child(path, pe->path, pe->path_len))
13154 pe->data = NULL; /* no error */
13157 printf(GOT_COMMIT_SEP_STR);
13158 if (S_ISLNK(mode))
13159 printf("symlink: %s\n", path);
13160 else if (S_ISREG(mode)) {
13161 printf("file: %s\n", path);
13162 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13163 } else if (S_ISDIR(mode))
13164 printf("directory: %s\n", path);
13165 else
13166 printf("something: %s\n", path);
13168 tm = localtime_r(&mtime, &mytm);
13169 if (tm == NULL)
13170 return NULL;
13171 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13172 return got_error(GOT_ERR_NO_SPACE);
13173 printf("timestamp: %s\n", datebuf);
13175 if (blob_id) {
13176 err = got_object_id_str(&id_str, blob_id);
13177 if (err)
13178 return err;
13179 printf("based on blob: %s\n", id_str);
13180 free(id_str);
13183 if (staged_blob_id) {
13184 err = got_object_id_str(&id_str, staged_blob_id);
13185 if (err)
13186 return err;
13187 printf("based on staged blob: %s\n", id_str);
13188 free(id_str);
13191 if (commit_id) {
13192 err = got_object_id_str(&id_str, commit_id);
13193 if (err)
13194 return err;
13195 printf("based on commit: %s\n", id_str);
13196 free(id_str);
13199 return NULL;
13202 static const struct got_error *
13203 cmd_info(int argc, char *argv[])
13205 const struct got_error *error = NULL;
13206 struct got_worktree *worktree = NULL;
13207 char *cwd = NULL, *id_str = NULL;
13208 struct got_pathlist_head paths;
13209 char *uuidstr = NULL;
13210 int ch, show_files = 0;
13212 TAILQ_INIT(&paths);
13214 while ((ch = getopt(argc, argv, "")) != -1) {
13215 switch (ch) {
13216 default:
13217 usage_info();
13218 /* NOTREACHED */
13222 argc -= optind;
13223 argv += optind;
13225 #ifndef PROFILE
13226 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13227 NULL) == -1)
13228 err(1, "pledge");
13229 #endif
13230 cwd = getcwd(NULL, 0);
13231 if (cwd == NULL) {
13232 error = got_error_from_errno("getcwd");
13233 goto done;
13236 error = got_worktree_open(&worktree, cwd);
13237 if (error) {
13238 if (error->code == GOT_ERR_NOT_WORKTREE)
13239 error = wrap_not_worktree_error(error, "info", cwd);
13240 goto done;
13243 #ifndef PROFILE
13244 /* Remove "wpath cpath proc exec sendfd" promises. */
13245 if (pledge("stdio rpath flock unveil", NULL) == -1)
13246 err(1, "pledge");
13247 #endif
13248 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13249 if (error)
13250 goto done;
13252 if (argc >= 1) {
13253 error = get_worktree_paths_from_argv(&paths, argc, argv,
13254 worktree);
13255 if (error)
13256 goto done;
13257 show_files = 1;
13260 error = got_object_id_str(&id_str,
13261 got_worktree_get_base_commit_id(worktree));
13262 if (error)
13263 goto done;
13265 error = got_worktree_get_uuid(&uuidstr, worktree);
13266 if (error)
13267 goto done;
13269 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13270 printf("work tree base commit: %s\n", id_str);
13271 printf("work tree path prefix: %s\n",
13272 got_worktree_get_path_prefix(worktree));
13273 printf("work tree branch reference: %s\n",
13274 got_worktree_get_head_ref_name(worktree));
13275 printf("work tree UUID: %s\n", uuidstr);
13276 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13278 if (show_files) {
13279 struct got_pathlist_entry *pe;
13280 TAILQ_FOREACH(pe, &paths, entry) {
13281 if (pe->path_len == 0)
13282 continue;
13284 * Assume this path will fail. This will be corrected
13285 * in print_path_info() in case the path does suceeed.
13287 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13289 error = got_worktree_path_info(worktree, &paths,
13290 print_path_info, &paths, check_cancelled, NULL);
13291 if (error)
13292 goto done;
13293 TAILQ_FOREACH(pe, &paths, entry) {
13294 if (pe->data != NULL) {
13295 const struct got_error *perr;
13297 perr = pe->data;
13298 error = got_error_fmt(perr->code, "%s",
13299 pe->path);
13300 break;
13304 done:
13305 if (worktree)
13306 got_worktree_close(worktree);
13307 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13308 free(cwd);
13309 free(id_str);
13310 free(uuidstr);
13311 return error;