Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.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 error = got_pathlist_append(&wanted_branches,
2487 remote->fetch_branches[i], NULL);
2488 if (error)
2489 goto done;
2492 if (TAILQ_EMPTY(&wanted_refs)) {
2493 for (i = 0; i < remote->nfetch_refs; i++) {
2494 error = got_pathlist_append(&wanted_refs,
2495 remote->fetch_refs[i], NULL);
2496 if (error)
2497 goto done;
2501 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2502 &repo_name, remote->fetch_url);
2503 if (error)
2504 goto done;
2506 if (strcmp(proto, "git") == 0) {
2507 #ifndef PROFILE
2508 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2509 "sendfd dns inet unveil", NULL) == -1)
2510 err(1, "pledge");
2511 #endif
2512 } else if (strcmp(proto, "git+ssh") == 0 ||
2513 strcmp(proto, "ssh") == 0) {
2514 #ifndef PROFILE
2515 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2516 "sendfd unveil", NULL) == -1)
2517 err(1, "pledge");
2518 #endif
2519 } else if (strcmp(proto, "http") == 0 ||
2520 strcmp(proto, "git+http") == 0) {
2521 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2522 goto done;
2523 } else {
2524 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2525 goto done;
2528 error = got_dial_apply_unveil(proto);
2529 if (error)
2530 goto done;
2532 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2533 if (error)
2534 goto done;
2536 if (verbosity >= 0) {
2537 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2538 remote->name, proto, host,
2539 port ? ":" : "", port ? port : "",
2540 *server_path == '/' ? "" : "/", server_path);
2543 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2544 server_path, verbosity);
2545 if (error)
2546 goto done;
2548 fpa.last_scaled_size[0] = '\0';
2549 fpa.last_p_indexed = -1;
2550 fpa.last_p_resolved = -1;
2551 fpa.verbosity = verbosity;
2552 fpa.repo = repo;
2553 fpa.create_configs = 0;
2554 fpa.configs_created = 0;
2555 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2556 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2557 remote->mirror_references, fetch_all_branches, &wanted_branches,
2558 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2559 fetch_progress, &fpa);
2560 if (error)
2561 goto done;
2563 if (list_refs_only) {
2564 error = list_remote_refs(&symrefs, &refs);
2565 goto done;
2568 if (pack_hash == NULL) {
2569 if (verbosity >= 0)
2570 printf("Already up-to-date\n");
2571 } else if (verbosity >= 0) {
2572 error = got_object_id_str(&id_str, pack_hash);
2573 if (error)
2574 goto done;
2575 printf("\nFetched %s.pack\n", id_str);
2576 free(id_str);
2577 id_str = NULL;
2580 /* Update references provided with the pack file. */
2581 TAILQ_FOREACH(pe, &refs, entry) {
2582 const char *refname = pe->path;
2583 struct got_object_id *id = pe->data;
2584 struct got_reference *ref;
2585 char *remote_refname;
2587 if (is_wanted_ref(&wanted_refs, refname) &&
2588 !remote->mirror_references) {
2589 error = update_wanted_ref(refname, id,
2590 remote->name, verbosity, repo);
2591 if (error)
2592 goto done;
2593 continue;
2596 if (remote->mirror_references ||
2597 strncmp("refs/tags/", refname, 10) == 0) {
2598 error = got_ref_open(&ref, repo, refname, 1);
2599 if (error) {
2600 if (error->code != GOT_ERR_NOT_REF)
2601 goto done;
2602 error = create_ref(refname, id, verbosity,
2603 repo);
2604 if (error)
2605 goto done;
2606 } else {
2607 error = update_ref(ref, id, replace_tags,
2608 verbosity, repo);
2609 unlock_err = got_ref_unlock(ref);
2610 if (unlock_err && error == NULL)
2611 error = unlock_err;
2612 got_ref_close(ref);
2613 if (error)
2614 goto done;
2616 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2617 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2618 remote_name, refname + 11) == -1) {
2619 error = got_error_from_errno("asprintf");
2620 goto done;
2623 error = got_ref_open(&ref, repo, remote_refname, 1);
2624 if (error) {
2625 if (error->code != GOT_ERR_NOT_REF)
2626 goto done;
2627 error = create_ref(remote_refname, id,
2628 verbosity, repo);
2629 if (error)
2630 goto done;
2631 } else {
2632 error = update_ref(ref, id, replace_tags,
2633 verbosity, repo);
2634 unlock_err = got_ref_unlock(ref);
2635 if (unlock_err && error == NULL)
2636 error = unlock_err;
2637 got_ref_close(ref);
2638 if (error)
2639 goto done;
2642 /* Also create a local branch if none exists yet. */
2643 error = got_ref_open(&ref, repo, refname, 1);
2644 if (error) {
2645 if (error->code != GOT_ERR_NOT_REF)
2646 goto done;
2647 error = create_ref(refname, id, verbosity,
2648 repo);
2649 if (error)
2650 goto done;
2651 } else {
2652 unlock_err = got_ref_unlock(ref);
2653 if (unlock_err && error == NULL)
2654 error = unlock_err;
2655 got_ref_close(ref);
2659 if (delete_refs) {
2660 error = delete_missing_refs(&refs, &symrefs, remote,
2661 verbosity, repo);
2662 if (error)
2663 goto done;
2666 if (!remote->mirror_references) {
2667 /* Update remote HEAD reference if the server provided one. */
2668 TAILQ_FOREACH(pe, &symrefs, entry) {
2669 struct got_reference *target_ref;
2670 const char *refname = pe->path;
2671 const char *target = pe->data;
2672 char *remote_refname = NULL, *remote_target = NULL;
2674 if (strcmp(refname, GOT_REF_HEAD) != 0)
2675 continue;
2677 if (strncmp("refs/heads/", target, 11) != 0)
2678 continue;
2680 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2681 remote->name, refname) == -1) {
2682 error = got_error_from_errno("asprintf");
2683 goto done;
2685 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2686 remote->name, target + 11) == -1) {
2687 error = got_error_from_errno("asprintf");
2688 free(remote_refname);
2689 goto done;
2692 error = got_ref_open(&target_ref, repo, remote_target,
2693 0);
2694 if (error) {
2695 free(remote_refname);
2696 free(remote_target);
2697 if (error->code == GOT_ERR_NOT_REF) {
2698 error = NULL;
2699 continue;
2701 goto done;
2703 error = update_symref(remote_refname, target_ref,
2704 verbosity, repo);
2705 free(remote_refname);
2706 free(remote_target);
2707 got_ref_close(target_ref);
2708 if (error)
2709 goto done;
2712 done:
2713 if (fetchpid > 0) {
2714 if (kill(fetchpid, SIGTERM) == -1)
2715 error = got_error_from_errno("kill");
2716 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2717 error = got_error_from_errno("waitpid");
2719 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2720 error = got_error_from_errno("close");
2721 if (repo) {
2722 const struct got_error *close_err = got_repo_close(repo);
2723 if (error == NULL)
2724 error = close_err;
2726 if (worktree)
2727 got_worktree_close(worktree);
2728 if (pack_fds) {
2729 const struct got_error *pack_err =
2730 got_repo_pack_fds_close(pack_fds);
2731 if (error == NULL)
2732 error = pack_err;
2734 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2735 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2736 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2737 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2738 free(id_str);
2739 free(cwd);
2740 free(repo_path);
2741 free(pack_hash);
2742 free(proto);
2743 free(host);
2744 free(port);
2745 free(server_path);
2746 free(repo_name);
2747 return error;
2751 __dead static void
2752 usage_checkout(void)
2754 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2755 "[-p path-prefix] repository-path [work-tree-path]\n",
2756 getprogname());
2757 exit(1);
2760 static void
2761 show_worktree_base_ref_warning(void)
2763 fprintf(stderr, "%s: warning: could not create a reference "
2764 "to the work tree's base commit; the commit could be "
2765 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2766 "repository writable and running 'got update' will prevent this\n",
2767 getprogname());
2770 struct got_checkout_progress_arg {
2771 const char *worktree_path;
2772 int had_base_commit_ref_error;
2773 int verbosity;
2776 static const struct got_error *
2777 checkout_progress(void *arg, unsigned char status, const char *path)
2779 struct got_checkout_progress_arg *a = arg;
2781 /* Base commit bump happens silently. */
2782 if (status == GOT_STATUS_BUMP_BASE)
2783 return NULL;
2785 if (status == GOT_STATUS_BASE_REF_ERR) {
2786 a->had_base_commit_ref_error = 1;
2787 return NULL;
2790 while (path[0] == '/')
2791 path++;
2793 if (a->verbosity >= 0)
2794 printf("%c %s/%s\n", status, a->worktree_path, path);
2796 return NULL;
2799 static const struct got_error *
2800 check_cancelled(void *arg)
2802 if (sigint_received || sigpipe_received)
2803 return got_error(GOT_ERR_CANCELLED);
2804 return NULL;
2807 static const struct got_error *
2808 check_linear_ancestry(struct got_object_id *commit_id,
2809 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2810 struct got_repository *repo)
2812 const struct got_error *err = NULL;
2813 struct got_object_id *yca_id;
2815 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2816 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2817 if (err)
2818 return err;
2820 if (yca_id == NULL)
2821 return got_error(GOT_ERR_ANCESTRY);
2824 * Require a straight line of history between the target commit
2825 * and the work tree's base commit.
2827 * Non-linear situations such as this require a rebase:
2829 * (commit) D F (base_commit)
2830 * \ /
2831 * C E
2832 * \ /
2833 * B (yca)
2834 * |
2835 * A
2837 * 'got update' only handles linear cases:
2838 * Update forwards in time: A (base/yca) - B - C - D (commit)
2839 * Update backwards in time: D (base) - C - B - A (commit/yca)
2841 if (allow_forwards_in_time_only) {
2842 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2843 return got_error(GOT_ERR_ANCESTRY);
2844 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2845 got_object_id_cmp(base_commit_id, yca_id) != 0)
2846 return got_error(GOT_ERR_ANCESTRY);
2848 free(yca_id);
2849 return NULL;
2852 static const struct got_error *
2853 check_same_branch(struct got_object_id *commit_id,
2854 struct got_reference *head_ref, struct got_object_id *yca_id,
2855 struct got_repository *repo)
2857 const struct got_error *err = NULL;
2858 struct got_commit_graph *graph = NULL;
2859 struct got_object_id *head_commit_id = NULL;
2860 int is_same_branch = 0;
2862 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2863 if (err)
2864 goto done;
2866 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2870 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2871 is_same_branch = 1;
2872 goto done;
2875 err = got_commit_graph_open(&graph, "/", 1);
2876 if (err)
2877 goto done;
2879 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2880 check_cancelled, NULL);
2881 if (err)
2882 goto done;
2884 for (;;) {
2885 struct got_object_id id;
2887 err = got_commit_graph_iter_next(&id, graph, repo,
2888 check_cancelled, NULL);
2889 if (err) {
2890 if (err->code == GOT_ERR_ITER_COMPLETED)
2891 err = NULL;
2892 break;
2895 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2896 break;
2897 if (got_object_id_cmp(&id, commit_id) == 0) {
2898 is_same_branch = 1;
2899 break;
2902 done:
2903 if (graph)
2904 got_commit_graph_close(graph);
2905 free(head_commit_id);
2906 if (!err && !is_same_branch)
2907 err = got_error(GOT_ERR_ANCESTRY);
2908 return err;
2911 static const struct got_error *
2912 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2914 static char msg[512];
2915 const char *branch_name;
2917 if (got_ref_is_symbolic(ref))
2918 branch_name = got_ref_get_symref_target(ref);
2919 else
2920 branch_name = got_ref_get_name(ref);
2922 if (strncmp("refs/heads/", branch_name, 11) == 0)
2923 branch_name += 11;
2925 snprintf(msg, sizeof(msg),
2926 "target commit is not contained in branch '%s'; "
2927 "the branch to use must be specified with -b; "
2928 "if necessary a new branch can be created for "
2929 "this commit with 'got branch -c %s BRANCH_NAME'",
2930 branch_name, commit_id_str);
2932 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2935 static const struct got_error *
2936 cmd_checkout(int argc, char *argv[])
2938 const struct got_error *error = NULL;
2939 struct got_repository *repo = NULL;
2940 struct got_reference *head_ref = NULL, *ref = NULL;
2941 struct got_worktree *worktree = NULL;
2942 char *repo_path = NULL;
2943 char *worktree_path = NULL;
2944 const char *path_prefix = "";
2945 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2946 char *commit_id_str = NULL;
2947 struct got_object_id *commit_id = NULL;
2948 char *cwd = NULL;
2949 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2950 struct got_pathlist_head paths;
2951 struct got_checkout_progress_arg cpa;
2952 int *pack_fds = NULL;
2954 TAILQ_INIT(&paths);
2956 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2957 switch (ch) {
2958 case 'b':
2959 branch_name = optarg;
2960 break;
2961 case 'c':
2962 commit_id_str = strdup(optarg);
2963 if (commit_id_str == NULL)
2964 return got_error_from_errno("strdup");
2965 break;
2966 case 'E':
2967 allow_nonempty = 1;
2968 break;
2969 case 'p':
2970 path_prefix = optarg;
2971 break;
2972 case 'q':
2973 verbosity = -1;
2974 break;
2975 default:
2976 usage_checkout();
2977 /* NOTREACHED */
2981 argc -= optind;
2982 argv += optind;
2984 #ifndef PROFILE
2985 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2986 "unveil", NULL) == -1)
2987 err(1, "pledge");
2988 #endif
2989 if (argc == 1) {
2990 char *base, *dotgit;
2991 const char *path;
2992 repo_path = realpath(argv[0], NULL);
2993 if (repo_path == NULL)
2994 return got_error_from_errno2("realpath", argv[0]);
2995 cwd = getcwd(NULL, 0);
2996 if (cwd == NULL) {
2997 error = got_error_from_errno("getcwd");
2998 goto done;
3000 if (path_prefix[0])
3001 path = path_prefix;
3002 else
3003 path = repo_path;
3004 error = got_path_basename(&base, path);
3005 if (error)
3006 goto done;
3007 dotgit = strstr(base, ".git");
3008 if (dotgit)
3009 *dotgit = '\0';
3010 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3011 error = got_error_from_errno("asprintf");
3012 free(base);
3013 goto done;
3015 free(base);
3016 } else if (argc == 2) {
3017 repo_path = realpath(argv[0], NULL);
3018 if (repo_path == NULL) {
3019 error = got_error_from_errno2("realpath", argv[0]);
3020 goto done;
3022 worktree_path = realpath(argv[1], NULL);
3023 if (worktree_path == NULL) {
3024 if (errno != ENOENT) {
3025 error = got_error_from_errno2("realpath",
3026 argv[1]);
3027 goto done;
3029 worktree_path = strdup(argv[1]);
3030 if (worktree_path == NULL) {
3031 error = got_error_from_errno("strdup");
3032 goto done;
3035 } else
3036 usage_checkout();
3038 got_path_strip_trailing_slashes(repo_path);
3039 got_path_strip_trailing_slashes(worktree_path);
3041 error = got_repo_pack_fds_open(&pack_fds);
3042 if (error != NULL)
3043 goto done;
3045 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3046 if (error != NULL)
3047 goto done;
3049 /* Pre-create work tree path for unveil(2) */
3050 error = got_path_mkdir(worktree_path);
3051 if (error) {
3052 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3053 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3054 goto done;
3055 if (!allow_nonempty &&
3056 !got_path_dir_is_empty(worktree_path)) {
3057 error = got_error_path(worktree_path,
3058 GOT_ERR_DIR_NOT_EMPTY);
3059 goto done;
3063 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3064 if (error)
3065 goto done;
3067 error = got_ref_open(&head_ref, repo, branch_name, 0);
3068 if (error != NULL)
3069 goto done;
3071 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3072 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3073 goto done;
3075 error = got_worktree_open(&worktree, worktree_path);
3076 if (error != NULL)
3077 goto done;
3079 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3080 path_prefix);
3081 if (error != NULL)
3082 goto done;
3083 if (!same_path_prefix) {
3084 error = got_error(GOT_ERR_PATH_PREFIX);
3085 goto done;
3088 if (commit_id_str) {
3089 struct got_reflist_head refs;
3090 TAILQ_INIT(&refs);
3091 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3092 NULL);
3093 if (error)
3094 goto done;
3095 error = got_repo_match_object_id(&commit_id, NULL,
3096 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3097 got_ref_list_free(&refs);
3098 if (error)
3099 goto done;
3100 error = check_linear_ancestry(commit_id,
3101 got_worktree_get_base_commit_id(worktree), 0, repo);
3102 if (error != NULL) {
3103 if (error->code == GOT_ERR_ANCESTRY) {
3104 error = checkout_ancestry_error(
3105 head_ref, commit_id_str);
3107 goto done;
3109 error = check_same_branch(commit_id, head_ref, NULL, repo);
3110 if (error) {
3111 if (error->code == GOT_ERR_ANCESTRY) {
3112 error = checkout_ancestry_error(
3113 head_ref, commit_id_str);
3115 goto done;
3117 error = got_worktree_set_base_commit_id(worktree, repo,
3118 commit_id);
3119 if (error)
3120 goto done;
3121 /* Expand potentially abbreviated commit ID string. */
3122 free(commit_id_str);
3123 error = got_object_id_str(&commit_id_str, commit_id);
3124 if (error)
3125 goto done;
3126 } else {
3127 commit_id = got_object_id_dup(
3128 got_worktree_get_base_commit_id(worktree));
3129 if (commit_id == NULL) {
3130 error = got_error_from_errno("got_object_id_dup");
3131 goto done;
3133 error = got_object_id_str(&commit_id_str, commit_id);
3134 if (error)
3135 goto done;
3138 error = got_pathlist_append(&paths, "", NULL);
3139 if (error)
3140 goto done;
3141 cpa.worktree_path = worktree_path;
3142 cpa.had_base_commit_ref_error = 0;
3143 cpa.verbosity = verbosity;
3144 error = got_worktree_checkout_files(worktree, &paths, repo,
3145 checkout_progress, &cpa, check_cancelled, NULL);
3146 if (error != NULL)
3147 goto done;
3149 if (got_ref_is_symbolic(head_ref)) {
3150 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3151 if (error)
3152 goto done;
3153 refname = got_ref_get_name(ref);
3154 } else
3155 refname = got_ref_get_name(head_ref);
3156 printf("Checked out %s: %s\n", refname, commit_id_str);
3157 printf("Now shut up and hack\n");
3158 if (cpa.had_base_commit_ref_error)
3159 show_worktree_base_ref_warning();
3160 done:
3161 if (pack_fds) {
3162 const struct got_error *pack_err =
3163 got_repo_pack_fds_close(pack_fds);
3164 if (error == NULL)
3165 error = pack_err;
3167 if (head_ref)
3168 got_ref_close(head_ref);
3169 if (ref)
3170 got_ref_close(ref);
3171 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3172 free(commit_id_str);
3173 free(commit_id);
3174 free(repo_path);
3175 free(worktree_path);
3176 free(cwd);
3177 return error;
3180 struct got_update_progress_arg {
3181 int did_something;
3182 int conflicts;
3183 int obstructed;
3184 int not_updated;
3185 int missing;
3186 int not_deleted;
3187 int unversioned;
3188 int verbosity;
3191 static void
3192 print_update_progress_stats(struct got_update_progress_arg *upa)
3194 if (!upa->did_something)
3195 return;
3197 if (upa->conflicts > 0)
3198 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3199 if (upa->obstructed > 0)
3200 printf("File paths obstructed by a non-regular file: %d\n",
3201 upa->obstructed);
3202 if (upa->not_updated > 0)
3203 printf("Files not updated because of existing merge "
3204 "conflicts: %d\n", upa->not_updated);
3208 * The meaning of some status codes differs between merge-style operations and
3209 * update operations. For example, the ! status code means "file was missing"
3210 * if changes were merged into the work tree, and "missing file was restored"
3211 * if the work tree was updated. This function should be used by any operation
3212 * which merges changes into the work tree without updating the work tree.
3214 static void
3215 print_merge_progress_stats(struct got_update_progress_arg *upa)
3217 if (!upa->did_something)
3218 return;
3220 if (upa->conflicts > 0)
3221 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3222 if (upa->obstructed > 0)
3223 printf("File paths obstructed by a non-regular file: %d\n",
3224 upa->obstructed);
3225 if (upa->missing > 0)
3226 printf("Files which had incoming changes but could not be "
3227 "found in the work tree: %d\n", upa->missing);
3228 if (upa->not_deleted > 0)
3229 printf("Files not deleted due to differences in deleted "
3230 "content: %d\n", upa->not_deleted);
3231 if (upa->unversioned > 0)
3232 printf("Files not merged because an unversioned file was "
3233 "found in the work tree: %d\n", upa->unversioned);
3236 __dead static void
3237 usage_update(void)
3239 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3240 "[path ...]\n", getprogname());
3241 exit(1);
3244 static const struct got_error *
3245 update_progress(void *arg, unsigned char status, const char *path)
3247 struct got_update_progress_arg *upa = arg;
3249 if (status == GOT_STATUS_EXISTS ||
3250 status == GOT_STATUS_BASE_REF_ERR)
3251 return NULL;
3253 upa->did_something = 1;
3255 /* Base commit bump happens silently. */
3256 if (status == GOT_STATUS_BUMP_BASE)
3257 return NULL;
3259 if (status == GOT_STATUS_CONFLICT)
3260 upa->conflicts++;
3261 if (status == GOT_STATUS_OBSTRUCTED)
3262 upa->obstructed++;
3263 if (status == GOT_STATUS_CANNOT_UPDATE)
3264 upa->not_updated++;
3265 if (status == GOT_STATUS_MISSING)
3266 upa->missing++;
3267 if (status == GOT_STATUS_CANNOT_DELETE)
3268 upa->not_deleted++;
3269 if (status == GOT_STATUS_UNVERSIONED)
3270 upa->unversioned++;
3272 while (path[0] == '/')
3273 path++;
3274 if (upa->verbosity >= 0)
3275 printf("%c %s\n", status, path);
3277 return NULL;
3280 static const struct got_error *
3281 switch_head_ref(struct got_reference *head_ref,
3282 struct got_object_id *commit_id, struct got_worktree *worktree,
3283 struct got_repository *repo)
3285 const struct got_error *err = NULL;
3286 char *base_id_str;
3287 int ref_has_moved = 0;
3289 /* Trivial case: switching between two different references. */
3290 if (strcmp(got_ref_get_name(head_ref),
3291 got_worktree_get_head_ref_name(worktree)) != 0) {
3292 printf("Switching work tree from %s to %s\n",
3293 got_worktree_get_head_ref_name(worktree),
3294 got_ref_get_name(head_ref));
3295 return got_worktree_set_head_ref(worktree, head_ref);
3298 err = check_linear_ancestry(commit_id,
3299 got_worktree_get_base_commit_id(worktree), 0, repo);
3300 if (err) {
3301 if (err->code != GOT_ERR_ANCESTRY)
3302 return err;
3303 ref_has_moved = 1;
3305 if (!ref_has_moved)
3306 return NULL;
3308 /* Switching to a rebased branch with the same reference name. */
3309 err = got_object_id_str(&base_id_str,
3310 got_worktree_get_base_commit_id(worktree));
3311 if (err)
3312 return err;
3313 printf("Reference %s now points at a different branch\n",
3314 got_worktree_get_head_ref_name(worktree));
3315 printf("Switching work tree from %s to %s\n", base_id_str,
3316 got_worktree_get_head_ref_name(worktree));
3317 return NULL;
3320 static const struct got_error *
3321 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3323 const struct got_error *err;
3324 int in_progress;
3326 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3327 if (err)
3328 return err;
3329 if (in_progress)
3330 return got_error(GOT_ERR_REBASING);
3332 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3333 if (err)
3334 return err;
3335 if (in_progress)
3336 return got_error(GOT_ERR_HISTEDIT_BUSY);
3338 return NULL;
3341 static const struct got_error *
3342 check_merge_in_progress(struct got_worktree *worktree,
3343 struct got_repository *repo)
3345 const struct got_error *err;
3346 int in_progress;
3348 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3349 if (err)
3350 return err;
3351 if (in_progress)
3352 return got_error(GOT_ERR_MERGE_BUSY);
3354 return NULL;
3357 static const struct got_error *
3358 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3359 char *argv[], struct got_worktree *worktree)
3361 const struct got_error *err = NULL;
3362 char *path;
3363 struct got_pathlist_entry *new;
3364 int i;
3366 if (argc == 0) {
3367 path = strdup("");
3368 if (path == NULL)
3369 return got_error_from_errno("strdup");
3370 return got_pathlist_append(paths, path, NULL);
3373 for (i = 0; i < argc; i++) {
3374 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3375 if (err)
3376 break;
3377 err = got_pathlist_insert(&new, paths, path, NULL);
3378 if (err || new == NULL /* duplicate */) {
3379 free(path);
3380 if (err)
3381 break;
3385 return err;
3388 static const struct got_error *
3389 wrap_not_worktree_error(const struct got_error *orig_err,
3390 const char *cmdname, const char *path)
3392 const struct got_error *err;
3393 struct got_repository *repo;
3394 static char msg[512];
3395 int *pack_fds = NULL;
3397 err = got_repo_pack_fds_open(&pack_fds);
3398 if (err)
3399 return err;
3401 err = got_repo_open(&repo, path, NULL, pack_fds);
3402 if (err)
3403 return orig_err;
3405 snprintf(msg, sizeof(msg),
3406 "'got %s' needs a work tree in addition to a git repository\n"
3407 "Work trees can be checked out from this Git repository with "
3408 "'got checkout'.\n"
3409 "The got(1) manual page contains more information.", cmdname);
3410 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3411 got_repo_close(repo);
3412 if (pack_fds) {
3413 const struct got_error *pack_err =
3414 got_repo_pack_fds_close(pack_fds);
3415 if (err == NULL)
3416 err = pack_err;
3418 return err;
3421 static const struct got_error *
3422 cmd_update(int argc, char *argv[])
3424 const struct got_error *error = NULL;
3425 struct got_repository *repo = NULL;
3426 struct got_worktree *worktree = NULL;
3427 char *worktree_path = NULL;
3428 struct got_object_id *commit_id = NULL;
3429 char *commit_id_str = NULL;
3430 const char *branch_name = NULL;
3431 struct got_reference *head_ref = NULL;
3432 struct got_pathlist_head paths;
3433 struct got_pathlist_entry *pe;
3434 int ch, verbosity = 0;
3435 struct got_update_progress_arg upa;
3436 int *pack_fds = NULL;
3438 TAILQ_INIT(&paths);
3440 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3441 switch (ch) {
3442 case 'b':
3443 branch_name = optarg;
3444 break;
3445 case 'c':
3446 commit_id_str = strdup(optarg);
3447 if (commit_id_str == NULL)
3448 return got_error_from_errno("strdup");
3449 break;
3450 case 'q':
3451 verbosity = -1;
3452 break;
3453 default:
3454 usage_update();
3455 /* NOTREACHED */
3459 argc -= optind;
3460 argv += optind;
3462 #ifndef PROFILE
3463 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3464 "unveil", NULL) == -1)
3465 err(1, "pledge");
3466 #endif
3467 worktree_path = getcwd(NULL, 0);
3468 if (worktree_path == NULL) {
3469 error = got_error_from_errno("getcwd");
3470 goto done;
3473 error = got_repo_pack_fds_open(&pack_fds);
3474 if (error != NULL)
3475 goto done;
3477 error = got_worktree_open(&worktree, worktree_path);
3478 if (error) {
3479 if (error->code == GOT_ERR_NOT_WORKTREE)
3480 error = wrap_not_worktree_error(error, "update",
3481 worktree_path);
3482 goto done;
3485 error = check_rebase_or_histedit_in_progress(worktree);
3486 if (error)
3487 goto done;
3489 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3490 NULL, pack_fds);
3491 if (error != NULL)
3492 goto done;
3494 error = apply_unveil(got_repo_get_path(repo), 0,
3495 got_worktree_get_root_path(worktree));
3496 if (error)
3497 goto done;
3499 error = check_merge_in_progress(worktree, repo);
3500 if (error)
3501 goto done;
3503 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3504 if (error)
3505 goto done;
3507 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3508 got_worktree_get_head_ref_name(worktree), 0);
3509 if (error != NULL)
3510 goto done;
3511 if (commit_id_str == NULL) {
3512 error = got_ref_resolve(&commit_id, repo, head_ref);
3513 if (error != NULL)
3514 goto done;
3515 error = got_object_id_str(&commit_id_str, commit_id);
3516 if (error != NULL)
3517 goto done;
3518 } else {
3519 struct got_reflist_head refs;
3520 TAILQ_INIT(&refs);
3521 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3522 NULL);
3523 if (error)
3524 goto done;
3525 error = got_repo_match_object_id(&commit_id, NULL,
3526 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3527 got_ref_list_free(&refs);
3528 free(commit_id_str);
3529 commit_id_str = NULL;
3530 if (error)
3531 goto done;
3532 error = got_object_id_str(&commit_id_str, commit_id);
3533 if (error)
3534 goto done;
3537 if (branch_name) {
3538 struct got_object_id *head_commit_id;
3539 TAILQ_FOREACH(pe, &paths, entry) {
3540 if (pe->path_len == 0)
3541 continue;
3542 error = got_error_msg(GOT_ERR_BAD_PATH,
3543 "switching between branches requires that "
3544 "the entire work tree gets updated");
3545 goto done;
3547 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3548 if (error)
3549 goto done;
3550 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3551 repo);
3552 free(head_commit_id);
3553 if (error != NULL)
3554 goto done;
3555 error = check_same_branch(commit_id, head_ref, NULL, repo);
3556 if (error)
3557 goto done;
3558 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3559 if (error)
3560 goto done;
3561 } else {
3562 error = check_linear_ancestry(commit_id,
3563 got_worktree_get_base_commit_id(worktree), 0, repo);
3564 if (error != NULL) {
3565 if (error->code == GOT_ERR_ANCESTRY)
3566 error = got_error(GOT_ERR_BRANCH_MOVED);
3567 goto done;
3569 error = check_same_branch(commit_id, head_ref, NULL, repo);
3570 if (error)
3571 goto done;
3574 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3575 commit_id) != 0) {
3576 error = got_worktree_set_base_commit_id(worktree, repo,
3577 commit_id);
3578 if (error)
3579 goto done;
3582 memset(&upa, 0, sizeof(upa));
3583 upa.verbosity = verbosity;
3584 error = got_worktree_checkout_files(worktree, &paths, repo,
3585 update_progress, &upa, check_cancelled, NULL);
3586 if (error != NULL)
3587 goto done;
3589 if (upa.did_something) {
3590 printf("Updated to %s: %s\n",
3591 got_worktree_get_head_ref_name(worktree), commit_id_str);
3592 } else
3593 printf("Already up-to-date\n");
3595 print_update_progress_stats(&upa);
3596 done:
3597 if (pack_fds) {
3598 const struct got_error *pack_err =
3599 got_repo_pack_fds_close(pack_fds);
3600 if (error == NULL)
3601 error = pack_err;
3603 free(worktree_path);
3604 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3605 free(commit_id);
3606 free(commit_id_str);
3607 return error;
3610 static const struct got_error *
3611 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3612 const char *path, int diff_context, int ignore_whitespace,
3613 int force_text_diff, int show_diffstat, struct got_repository *repo,
3614 FILE *outfile)
3616 const struct got_error *err = NULL;
3617 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3618 FILE *f1 = NULL, *f2 = NULL;
3619 int fd1 = -1, fd2 = -1;
3621 fd1 = got_opentempfd();
3622 if (fd1 == -1)
3623 return got_error_from_errno("got_opentempfd");
3624 fd2 = got_opentempfd();
3625 if (fd2 == -1) {
3626 err = got_error_from_errno("got_opentempfd");
3627 goto done;
3630 if (blob_id1) {
3631 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3632 fd1);
3633 if (err)
3634 goto done;
3637 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3638 if (err)
3639 goto done;
3641 f1 = got_opentemp();
3642 if (f1 == NULL) {
3643 err = got_error_from_errno("got_opentemp");
3644 goto done;
3646 f2 = got_opentemp();
3647 if (f2 == NULL) {
3648 err = got_error_from_errno("got_opentemp");
3649 goto done;
3652 while (path[0] == '/')
3653 path++;
3654 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3655 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3656 force_text_diff, show_diffstat, NULL, outfile);
3657 done:
3658 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3659 err = got_error_from_errno("close");
3660 if (blob1)
3661 got_object_blob_close(blob1);
3662 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3663 err = got_error_from_errno("close");
3664 got_object_blob_close(blob2);
3665 if (f1 && fclose(f1) == EOF && err == NULL)
3666 err = got_error_from_errno("fclose");
3667 if (f2 && fclose(f2) == EOF && err == NULL)
3668 err = got_error_from_errno("fclose");
3669 return err;
3672 static const struct got_error *
3673 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3674 const char *path, int diff_context, int ignore_whitespace,
3675 int force_text_diff, struct got_repository *repo, FILE *outfile)
3677 const struct got_error *err = NULL;
3678 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3679 struct got_diff_blob_output_unidiff_arg arg;
3680 FILE *f1 = NULL, *f2 = NULL;
3681 int fd1 = -1, fd2 = -1;
3683 if (tree_id1) {
3684 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3685 if (err)
3686 goto done;
3687 fd1 = got_opentempfd();
3688 if (fd1 == -1) {
3689 err = got_error_from_errno("got_opentempfd");
3690 goto done;
3694 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3695 if (err)
3696 goto done;
3698 f1 = got_opentemp();
3699 if (f1 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3704 f2 = got_opentemp();
3705 if (f2 == NULL) {
3706 err = got_error_from_errno("got_opentemp");
3707 goto done;
3709 fd2 = got_opentempfd();
3710 if (fd2 == -1) {
3711 err = got_error_from_errno("got_opentempfd");
3712 goto done;
3714 arg.diff_context = diff_context;
3715 arg.ignore_whitespace = ignore_whitespace;
3716 arg.force_text_diff = force_text_diff;
3717 arg.show_diffstat = 0;
3718 arg.diffstat = NULL;
3719 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3720 arg.outfile = outfile;
3721 arg.lines = NULL;
3722 arg.nlines = 0;
3723 while (path[0] == '/')
3724 path++;
3725 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3726 got_diff_blob_output_unidiff, &arg, 1);
3727 done:
3728 if (tree1)
3729 got_object_tree_close(tree1);
3730 if (tree2)
3731 got_object_tree_close(tree2);
3732 if (f1 && fclose(f1) == EOF && err == NULL)
3733 err = got_error_from_errno("fclose");
3734 if (f2 && fclose(f2) == EOF && err == NULL)
3735 err = got_error_from_errno("fclose");
3736 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3737 err = got_error_from_errno("close");
3738 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3739 err = got_error_from_errno("close");
3740 return err;
3743 static const struct got_error *
3744 get_changed_paths(struct got_pathlist_head *paths,
3745 struct got_commit_object *commit, struct got_repository *repo,
3746 struct got_diffstat_cb_arg *dsa)
3748 const struct got_error *err = NULL;
3749 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3750 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3751 struct got_object_qid *qid;
3752 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3753 FILE *f1 = NULL, *f2 = NULL;
3754 int fd1 = -1, fd2 = -1;
3756 if (dsa) {
3757 cb = got_diff_tree_compute_diffstat;
3759 f1 = got_opentemp();
3760 if (f1 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3764 f2 = got_opentemp();
3765 if (f2 == NULL) {
3766 err = got_error_from_errno("got_opentemp");
3767 goto done;
3769 fd1 = got_opentempfd();
3770 if (fd1 == -1) {
3771 err = got_error_from_errno("got_opentempfd");
3772 goto done;
3774 fd2 = got_opentempfd();
3775 if (fd2 == -1) {
3776 err = got_error_from_errno("got_opentempfd");
3777 goto done;
3781 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3782 if (qid != NULL) {
3783 struct got_commit_object *pcommit;
3784 err = got_object_open_as_commit(&pcommit, repo,
3785 &qid->id);
3786 if (err)
3787 return err;
3789 tree_id1 = got_object_id_dup(
3790 got_object_commit_get_tree_id(pcommit));
3791 if (tree_id1 == NULL) {
3792 got_object_commit_close(pcommit);
3793 return got_error_from_errno("got_object_id_dup");
3795 got_object_commit_close(pcommit);
3799 if (tree_id1) {
3800 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3801 if (err)
3802 goto done;
3805 tree_id2 = got_object_commit_get_tree_id(commit);
3806 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3807 if (err)
3808 goto done;
3810 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3811 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3812 done:
3813 if (tree1)
3814 got_object_tree_close(tree1);
3815 if (tree2)
3816 got_object_tree_close(tree2);
3817 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3818 err = got_error_from_errno("close");
3819 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3820 err = got_error_from_errno("close");
3821 if (f1 && fclose(f1) == EOF && err == NULL)
3822 err = got_error_from_errno("fclose");
3823 if (f2 && fclose(f2) == EOF && err == NULL)
3824 err = got_error_from_errno("fclose");
3825 free(tree_id1);
3826 return err;
3829 static const struct got_error *
3830 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3831 const char *path, int diff_context, struct got_repository *repo,
3832 FILE *outfile)
3834 const struct got_error *err = NULL;
3835 struct got_commit_object *pcommit = NULL;
3836 char *id_str1 = NULL, *id_str2 = NULL;
3837 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3838 struct got_object_qid *qid;
3840 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3841 if (qid != NULL) {
3842 err = got_object_open_as_commit(&pcommit, repo,
3843 &qid->id);
3844 if (err)
3845 return err;
3846 err = got_object_id_str(&id_str1, &qid->id);
3847 if (err)
3848 goto done;
3851 err = got_object_id_str(&id_str2, id);
3852 if (err)
3853 goto done;
3855 if (path && path[0] != '\0') {
3856 int obj_type;
3857 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3858 if (err)
3859 goto done;
3860 if (pcommit) {
3861 err = got_object_id_by_path(&obj_id1, repo,
3862 pcommit, path);
3863 if (err) {
3864 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3865 free(obj_id2);
3866 goto done;
3870 err = got_object_get_type(&obj_type, repo, obj_id2);
3871 if (err) {
3872 free(obj_id2);
3873 goto done;
3875 fprintf(outfile,
3876 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3877 fprintf(outfile, "commit - %s\n",
3878 id_str1 ? id_str1 : "/dev/null");
3879 fprintf(outfile, "commit + %s\n", id_str2);
3880 switch (obj_type) {
3881 case GOT_OBJ_TYPE_BLOB:
3882 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3883 0, 0, 0, repo, outfile);
3884 break;
3885 case GOT_OBJ_TYPE_TREE:
3886 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3887 0, 0, repo, outfile);
3888 break;
3889 default:
3890 err = got_error(GOT_ERR_OBJ_TYPE);
3891 break;
3893 free(obj_id1);
3894 free(obj_id2);
3895 } else {
3896 obj_id2 = got_object_commit_get_tree_id(commit);
3897 if (pcommit)
3898 obj_id1 = got_object_commit_get_tree_id(pcommit);
3899 fprintf(outfile,
3900 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3901 fprintf(outfile, "commit - %s\n",
3902 id_str1 ? id_str1 : "/dev/null");
3903 fprintf(outfile, "commit + %s\n", id_str2);
3904 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3905 repo, outfile);
3907 done:
3908 free(id_str1);
3909 free(id_str2);
3910 if (pcommit)
3911 got_object_commit_close(pcommit);
3912 return err;
3915 static char *
3916 get_datestr(time_t *time, char *datebuf)
3918 struct tm mytm, *tm;
3919 char *p, *s;
3921 tm = gmtime_r(time, &mytm);
3922 if (tm == NULL)
3923 return NULL;
3924 s = asctime_r(tm, datebuf);
3925 if (s == NULL)
3926 return NULL;
3927 p = strchr(s, '\n');
3928 if (p)
3929 *p = '\0';
3930 return s;
3933 static const struct got_error *
3934 match_commit(int *have_match, struct got_object_id *id,
3935 struct got_commit_object *commit, regex_t *regex)
3937 const struct got_error *err = NULL;
3938 regmatch_t regmatch;
3939 char *id_str = NULL, *logmsg = NULL;
3941 *have_match = 0;
3943 err = got_object_id_str(&id_str, id);
3944 if (err)
3945 return err;
3947 err = got_object_commit_get_logmsg(&logmsg, commit);
3948 if (err)
3949 goto done;
3951 if (regexec(regex, got_object_commit_get_author(commit), 1,
3952 &regmatch, 0) == 0 ||
3953 regexec(regex, got_object_commit_get_committer(commit), 1,
3954 &regmatch, 0) == 0 ||
3955 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3956 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3957 *have_match = 1;
3958 done:
3959 free(id_str);
3960 free(logmsg);
3961 return err;
3964 static void
3965 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3966 regex_t *regex)
3968 regmatch_t regmatch;
3969 struct got_pathlist_entry *pe;
3971 *have_match = 0;
3973 TAILQ_FOREACH(pe, changed_paths, entry) {
3974 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3975 *have_match = 1;
3976 break;
3981 static const struct got_error *
3982 match_patch(int *have_match, struct got_commit_object *commit,
3983 struct got_object_id *id, const char *path, int diff_context,
3984 struct got_repository *repo, regex_t *regex, FILE *f)
3986 const struct got_error *err = NULL;
3987 char *line = NULL;
3988 size_t linesize = 0;
3989 regmatch_t regmatch;
3991 *have_match = 0;
3993 err = got_opentemp_truncate(f);
3994 if (err)
3995 return err;
3997 err = print_patch(commit, id, path, diff_context, repo, f);
3998 if (err)
3999 goto done;
4001 if (fseeko(f, 0L, SEEK_SET) == -1) {
4002 err = got_error_from_errno("fseeko");
4003 goto done;
4006 while (getline(&line, &linesize, f) != -1) {
4007 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4008 *have_match = 1;
4009 break;
4012 done:
4013 free(line);
4014 return err;
4017 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4019 static const struct got_error*
4020 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4021 struct got_object_id *id, struct got_repository *repo,
4022 int local_only)
4024 static const struct got_error *err = NULL;
4025 struct got_reflist_entry *re;
4026 char *s;
4027 const char *name;
4029 *refs_str = NULL;
4031 TAILQ_FOREACH(re, refs, entry) {
4032 struct got_tag_object *tag = NULL;
4033 struct got_object_id *ref_id;
4034 int cmp;
4036 name = got_ref_get_name(re->ref);
4037 if (strcmp(name, GOT_REF_HEAD) == 0)
4038 continue;
4039 if (strncmp(name, "refs/", 5) == 0)
4040 name += 5;
4041 if (strncmp(name, "got/", 4) == 0)
4042 continue;
4043 if (strncmp(name, "heads/", 6) == 0)
4044 name += 6;
4045 if (strncmp(name, "remotes/", 8) == 0) {
4046 if (local_only)
4047 continue;
4048 name += 8;
4049 s = strstr(name, "/" GOT_REF_HEAD);
4050 if (s != NULL && s[strlen(s)] == '\0')
4051 continue;
4053 err = got_ref_resolve(&ref_id, repo, re->ref);
4054 if (err)
4055 break;
4056 if (strncmp(name, "tags/", 5) == 0) {
4057 err = got_object_open_as_tag(&tag, repo, ref_id);
4058 if (err) {
4059 if (err->code != GOT_ERR_OBJ_TYPE) {
4060 free(ref_id);
4061 break;
4063 /* Ref points at something other than a tag. */
4064 err = NULL;
4065 tag = NULL;
4068 cmp = got_object_id_cmp(tag ?
4069 got_object_tag_get_object_id(tag) : ref_id, id);
4070 free(ref_id);
4071 if (tag)
4072 got_object_tag_close(tag);
4073 if (cmp != 0)
4074 continue;
4075 s = *refs_str;
4076 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4077 s ? ", " : "", name) == -1) {
4078 err = got_error_from_errno("asprintf");
4079 free(s);
4080 *refs_str = NULL;
4081 break;
4083 free(s);
4086 return err;
4089 static const struct got_error *
4090 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4091 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4093 const struct got_error *err = NULL;
4094 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4095 char *comma, *s, *nl;
4096 struct got_reflist_head *refs;
4097 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4098 struct tm tm;
4099 time_t committer_time;
4101 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4102 if (refs) {
4103 err = build_refs_str(&ref_str, refs, id, repo, 1);
4104 if (err)
4105 return err;
4107 /* Display the first matching ref only. */
4108 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4109 *comma = '\0';
4112 if (ref_str == NULL) {
4113 err = got_object_id_str(&id_str, id);
4114 if (err)
4115 return err;
4118 committer_time = got_object_commit_get_committer_time(commit);
4119 if (gmtime_r(&committer_time, &tm) == NULL) {
4120 err = got_error_from_errno("gmtime_r");
4121 goto done;
4123 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4124 err = got_error(GOT_ERR_NO_SPACE);
4125 goto done;
4128 err = got_object_commit_get_logmsg(&logmsg0, commit);
4129 if (err)
4130 goto done;
4132 s = logmsg0;
4133 while (isspace((unsigned char)s[0]))
4134 s++;
4136 nl = strchr(s, '\n');
4137 if (nl) {
4138 *nl = '\0';
4141 if (ref_str)
4142 printf("%s%-7s %s\n", datebuf, ref_str, s);
4143 else
4144 printf("%s%.7s %s\n", datebuf, id_str, s);
4146 if (fflush(stdout) != 0 && err == NULL)
4147 err = got_error_from_errno("fflush");
4148 done:
4149 free(id_str);
4150 free(ref_str);
4151 free(logmsg0);
4152 return err;
4155 static const struct got_error *
4156 print_diffstat(struct got_diffstat_cb_arg *dsa, struct got_pathlist_head *paths,
4157 const char *header)
4159 struct got_pathlist_entry *pe;
4161 if (header != NULL)
4162 printf("%s\n", header);
4164 TAILQ_FOREACH(pe, paths, entry) {
4165 struct got_diff_changed_path *cp = pe->data;
4166 int pad = dsa->max_path_len - pe->path_len + 1;
4168 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4169 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4171 printf("\n%d file%s changed, %d insertions(+), %d deletions(-)\n\n",
4172 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins, dsa->del);
4174 if (fflush(stdout) != 0)
4175 return got_error_from_errno("fflush");
4177 return NULL;
4180 static const struct got_error *
4181 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4182 struct got_repository *repo, const char *path,
4183 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4184 int show_patch, int diff_context,
4185 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4187 const struct got_error *err = NULL;
4188 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4189 char datebuf[26];
4190 time_t committer_time;
4191 const char *author, *committer;
4192 char *refs_str = NULL;
4194 err = got_object_id_str(&id_str, id);
4195 if (err)
4196 return err;
4198 if (custom_refs_str == NULL) {
4199 struct got_reflist_head *refs;
4200 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4201 if (refs) {
4202 err = build_refs_str(&refs_str, refs, id, repo, 0);
4203 if (err)
4204 goto done;
4208 printf(GOT_COMMIT_SEP_STR);
4209 if (custom_refs_str)
4210 printf("commit %s (%s)\n", id_str, custom_refs_str);
4211 else
4212 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4213 refs_str ? refs_str : "", refs_str ? ")" : "");
4214 free(id_str);
4215 id_str = NULL;
4216 free(refs_str);
4217 refs_str = NULL;
4218 printf("from: %s\n", got_object_commit_get_author(commit));
4219 author = got_object_commit_get_author(commit);
4220 committer = got_object_commit_get_committer(commit);
4221 if (strcmp(author, committer) != 0)
4222 printf("via: %s\n", committer);
4223 committer_time = got_object_commit_get_committer_time(commit);
4224 datestr = get_datestr(&committer_time, datebuf);
4225 if (datestr)
4226 printf("date: %s UTC\n", datestr);
4227 if (got_object_commit_get_nparents(commit) > 1) {
4228 const struct got_object_id_queue *parent_ids;
4229 struct got_object_qid *qid;
4230 int n = 1;
4231 parent_ids = got_object_commit_get_parent_ids(commit);
4232 STAILQ_FOREACH(qid, parent_ids, entry) {
4233 err = got_object_id_str(&id_str, &qid->id);
4234 if (err)
4235 goto done;
4236 printf("parent %d: %s\n", n++, id_str);
4237 free(id_str);
4238 id_str = NULL;
4242 err = got_object_commit_get_logmsg(&logmsg0, commit);
4243 if (err)
4244 goto done;
4246 logmsg = logmsg0;
4247 do {
4248 line = strsep(&logmsg, "\n");
4249 if (line)
4250 printf(" %s\n", line);
4251 } while (line);
4252 free(logmsg0);
4254 if (dsa && changed_paths) {
4255 err = print_diffstat(dsa, changed_paths, NULL);
4256 if (err)
4257 goto done;
4258 } else if (changed_paths) {
4259 struct got_pathlist_entry *pe;
4261 TAILQ_FOREACH(pe, changed_paths, entry) {
4262 struct got_diff_changed_path *cp = pe->data;
4264 printf(" %c %s\n", cp->status, pe->path);
4266 printf("\n");
4268 if (show_patch) {
4269 err = print_patch(commit, id, path, diff_context, repo, stdout);
4270 if (err == 0)
4271 printf("\n");
4274 if (fflush(stdout) != 0 && err == NULL)
4275 err = got_error_from_errno("fflush");
4276 done:
4277 free(id_str);
4278 free(refs_str);
4279 return err;
4282 static const struct got_error *
4283 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4284 struct got_repository *repo, const char *path, int show_changed_paths,
4285 int show_diffstat, int show_patch, const char *search_pattern,
4286 int diff_context, int limit, int log_branches, int reverse_display_order,
4287 struct got_reflist_object_id_map *refs_idmap, int one_line,
4288 FILE *tmpfile)
4290 const struct got_error *err;
4291 struct got_commit_graph *graph;
4292 regex_t regex;
4293 int have_match;
4294 struct got_object_id_queue reversed_commits;
4295 struct got_object_qid *qid;
4296 struct got_commit_object *commit;
4297 struct got_pathlist_head changed_paths;
4299 STAILQ_INIT(&reversed_commits);
4300 TAILQ_INIT(&changed_paths);
4302 if (search_pattern && regcomp(&regex, search_pattern,
4303 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4304 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4306 err = got_commit_graph_open(&graph, path, !log_branches);
4307 if (err)
4308 return err;
4309 err = got_commit_graph_iter_start(graph, root_id, repo,
4310 check_cancelled, NULL);
4311 if (err)
4312 goto done;
4313 for (;;) {
4314 struct got_object_id id;
4315 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4316 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4318 if (sigint_received || sigpipe_received)
4319 break;
4321 err = got_commit_graph_iter_next(&id, graph, repo,
4322 check_cancelled, NULL);
4323 if (err) {
4324 if (err->code == GOT_ERR_ITER_COMPLETED)
4325 err = NULL;
4326 break;
4329 err = got_object_open_as_commit(&commit, repo, &id);
4330 if (err)
4331 break;
4333 if ((show_changed_paths || show_diffstat) &&
4334 !reverse_display_order) {
4335 err = get_changed_paths(&changed_paths, commit, repo,
4336 show_diffstat ? &dsa : NULL);
4337 if (err)
4338 break;
4341 if (search_pattern) {
4342 err = match_commit(&have_match, &id, commit, &regex);
4343 if (err) {
4344 got_object_commit_close(commit);
4345 break;
4347 if (have_match == 0 && show_changed_paths)
4348 match_changed_paths(&have_match,
4349 &changed_paths, &regex);
4350 if (have_match == 0 && show_patch) {
4351 err = match_patch(&have_match, commit, &id,
4352 path, diff_context, repo, &regex,
4353 tmpfile);
4354 if (err)
4355 break;
4357 if (have_match == 0) {
4358 got_object_commit_close(commit);
4359 got_pathlist_free(&changed_paths,
4360 GOT_PATHLIST_FREE_ALL);
4361 continue;
4365 if (reverse_display_order) {
4366 err = got_object_qid_alloc(&qid, &id);
4367 if (err)
4368 break;
4369 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4370 got_object_commit_close(commit);
4371 } else {
4372 if (one_line)
4373 err = print_commit_oneline(commit, &id,
4374 repo, refs_idmap);
4375 else
4376 err = print_commit(commit, &id, repo, path,
4377 (show_changed_paths || show_diffstat) ?
4378 &changed_paths : NULL,
4379 show_diffstat ? &dsa : NULL, show_patch,
4380 diff_context, refs_idmap, NULL);
4381 got_object_commit_close(commit);
4382 if (err)
4383 break;
4385 if ((limit && --limit == 0) ||
4386 (end_id && got_object_id_cmp(&id, end_id) == 0))
4387 break;
4389 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4391 if (reverse_display_order) {
4392 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4393 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4394 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4396 err = got_object_open_as_commit(&commit, repo,
4397 &qid->id);
4398 if (err)
4399 break;
4400 if (show_changed_paths || show_diffstat) {
4401 err = get_changed_paths(&changed_paths,
4402 commit, repo, show_diffstat ? &dsa : NULL);
4403 if (err)
4404 break;
4406 if (one_line)
4407 err = print_commit_oneline(commit, &qid->id,
4408 repo, refs_idmap);
4409 else
4410 err = print_commit(commit, &qid->id, repo, path,
4411 (show_changed_paths || show_diffstat) ?
4412 &changed_paths : NULL,
4413 show_diffstat ? &dsa : NULL, show_patch,
4414 diff_context, refs_idmap, NULL);
4415 got_object_commit_close(commit);
4416 if (err)
4417 break;
4418 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4421 done:
4422 while (!STAILQ_EMPTY(&reversed_commits)) {
4423 qid = STAILQ_FIRST(&reversed_commits);
4424 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4425 got_object_qid_free(qid);
4427 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4428 if (search_pattern)
4429 regfree(&regex);
4430 got_commit_graph_close(graph);
4431 return err;
4434 __dead static void
4435 usage_log(void)
4437 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4438 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4439 "[path]\n", getprogname());
4440 exit(1);
4443 static int
4444 get_default_log_limit(void)
4446 const char *got_default_log_limit;
4447 long long n;
4448 const char *errstr;
4450 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4451 if (got_default_log_limit == NULL)
4452 return 0;
4453 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4454 if (errstr != NULL)
4455 return 0;
4456 return n;
4459 static const struct got_error *
4460 cmd_log(int argc, char *argv[])
4462 const struct got_error *error;
4463 struct got_repository *repo = NULL;
4464 struct got_worktree *worktree = NULL;
4465 struct got_object_id *start_id = NULL, *end_id = NULL;
4466 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4467 const char *start_commit = NULL, *end_commit = NULL;
4468 const char *search_pattern = NULL;
4469 int diff_context = -1, ch;
4470 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4471 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4472 const char *errstr;
4473 struct got_reflist_head refs;
4474 struct got_reflist_object_id_map *refs_idmap = NULL;
4475 FILE *tmpfile = NULL;
4476 int *pack_fds = NULL;
4478 TAILQ_INIT(&refs);
4480 #ifndef PROFILE
4481 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4482 NULL)
4483 == -1)
4484 err(1, "pledge");
4485 #endif
4487 limit = get_default_log_limit();
4489 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4490 switch (ch) {
4491 case 'b':
4492 log_branches = 1;
4493 break;
4494 case 'C':
4495 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4496 &errstr);
4497 if (errstr != NULL)
4498 errx(1, "number of context lines is %s: %s",
4499 errstr, optarg);
4500 break;
4501 case 'c':
4502 start_commit = optarg;
4503 break;
4504 case 'd':
4505 show_diffstat = 1;
4506 break;
4507 case 'l':
4508 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4509 if (errstr != NULL)
4510 errx(1, "number of commits is %s: %s",
4511 errstr, optarg);
4512 break;
4513 case 'P':
4514 show_changed_paths = 1;
4515 break;
4516 case 'p':
4517 show_patch = 1;
4518 break;
4519 case 'R':
4520 reverse_display_order = 1;
4521 break;
4522 case 'r':
4523 repo_path = realpath(optarg, NULL);
4524 if (repo_path == NULL)
4525 return got_error_from_errno2("realpath",
4526 optarg);
4527 got_path_strip_trailing_slashes(repo_path);
4528 break;
4529 case 'S':
4530 search_pattern = optarg;
4531 break;
4532 case 's':
4533 one_line = 1;
4534 break;
4535 case 'x':
4536 end_commit = optarg;
4537 break;
4538 default:
4539 usage_log();
4540 /* NOTREACHED */
4544 argc -= optind;
4545 argv += optind;
4547 if (diff_context == -1)
4548 diff_context = 3;
4549 else if (!show_patch)
4550 errx(1, "-C requires -p");
4552 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4553 errx(1, "cannot use -s with -d, -p or -P");
4555 cwd = getcwd(NULL, 0);
4556 if (cwd == NULL) {
4557 error = got_error_from_errno("getcwd");
4558 goto done;
4561 error = got_repo_pack_fds_open(&pack_fds);
4562 if (error != NULL)
4563 goto done;
4565 if (repo_path == NULL) {
4566 error = got_worktree_open(&worktree, cwd);
4567 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4568 goto done;
4569 error = NULL;
4572 if (argc == 1) {
4573 if (worktree) {
4574 error = got_worktree_resolve_path(&path, worktree,
4575 argv[0]);
4576 if (error)
4577 goto done;
4578 } else {
4579 path = strdup(argv[0]);
4580 if (path == NULL) {
4581 error = got_error_from_errno("strdup");
4582 goto done;
4585 } else if (argc != 0)
4586 usage_log();
4588 if (repo_path == NULL) {
4589 repo_path = worktree ?
4590 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4592 if (repo_path == NULL) {
4593 error = got_error_from_errno("strdup");
4594 goto done;
4597 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4598 if (error != NULL)
4599 goto done;
4601 error = apply_unveil(got_repo_get_path(repo), 1,
4602 worktree ? got_worktree_get_root_path(worktree) : NULL);
4603 if (error)
4604 goto done;
4606 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4607 if (error)
4608 goto done;
4610 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4611 if (error)
4612 goto done;
4614 if (start_commit == NULL) {
4615 struct got_reference *head_ref;
4616 struct got_commit_object *commit = NULL;
4617 error = got_ref_open(&head_ref, repo,
4618 worktree ? got_worktree_get_head_ref_name(worktree)
4619 : GOT_REF_HEAD, 0);
4620 if (error != NULL)
4621 goto done;
4622 error = got_ref_resolve(&start_id, repo, head_ref);
4623 got_ref_close(head_ref);
4624 if (error != NULL)
4625 goto done;
4626 error = got_object_open_as_commit(&commit, repo,
4627 start_id);
4628 if (error != NULL)
4629 goto done;
4630 got_object_commit_close(commit);
4631 } else {
4632 error = got_repo_match_object_id(&start_id, NULL,
4633 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4634 if (error != NULL)
4635 goto done;
4637 if (end_commit != NULL) {
4638 error = got_repo_match_object_id(&end_id, NULL,
4639 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4640 if (error != NULL)
4641 goto done;
4644 if (worktree) {
4646 * If a path was specified on the command line it was resolved
4647 * to a path in the work tree above. Prepend the work tree's
4648 * path prefix to obtain the corresponding in-repository path.
4650 if (path) {
4651 const char *prefix;
4652 prefix = got_worktree_get_path_prefix(worktree);
4653 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4654 (path[0] != '\0') ? "/" : "", path) == -1) {
4655 error = got_error_from_errno("asprintf");
4656 goto done;
4659 } else
4660 error = got_repo_map_path(&in_repo_path, repo,
4661 path ? path : "");
4662 if (error != NULL)
4663 goto done;
4664 if (in_repo_path) {
4665 free(path);
4666 path = in_repo_path;
4669 if (worktree) {
4670 /* Release work tree lock. */
4671 got_worktree_close(worktree);
4672 worktree = NULL;
4675 if (search_pattern && show_patch) {
4676 tmpfile = got_opentemp();
4677 if (tmpfile == NULL) {
4678 error = got_error_from_errno("got_opentemp");
4679 goto done;
4683 error = print_commits(start_id, end_id, repo, path ? path : "",
4684 show_changed_paths, show_diffstat, show_patch, search_pattern,
4685 diff_context, limit, log_branches, reverse_display_order,
4686 refs_idmap, one_line, tmpfile);
4687 done:
4688 free(path);
4689 free(repo_path);
4690 free(cwd);
4691 if (worktree)
4692 got_worktree_close(worktree);
4693 if (repo) {
4694 const struct got_error *close_err = got_repo_close(repo);
4695 if (error == NULL)
4696 error = close_err;
4698 if (pack_fds) {
4699 const struct got_error *pack_err =
4700 got_repo_pack_fds_close(pack_fds);
4701 if (error == NULL)
4702 error = pack_err;
4704 if (refs_idmap)
4705 got_reflist_object_id_map_free(refs_idmap);
4706 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4707 error = got_error_from_errno("fclose");
4708 got_ref_list_free(&refs);
4709 return error;
4712 __dead static void
4713 usage_diff(void)
4715 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4716 "[-r repository-path] [object1 object2 | path ...]\n",
4717 getprogname());
4718 exit(1);
4721 struct print_diff_arg {
4722 struct got_repository *repo;
4723 struct got_worktree *worktree;
4724 struct got_diffstat_cb_arg *diffstat;
4725 int diff_context;
4726 const char *id_str;
4727 int header_shown;
4728 int diff_staged;
4729 enum got_diff_algorithm diff_algo;
4730 int ignore_whitespace;
4731 int force_text_diff;
4732 int show_diffstat;
4733 FILE *f1;
4734 FILE *f2;
4735 FILE *outfile;
4739 * Create a file which contains the target path of a symlink so we can feed
4740 * it as content to the diff engine.
4742 static const struct got_error *
4743 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4744 const char *abspath)
4746 const struct got_error *err = NULL;
4747 char target_path[PATH_MAX];
4748 ssize_t target_len, outlen;
4750 *fd = -1;
4752 if (dirfd != -1) {
4753 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4754 if (target_len == -1)
4755 return got_error_from_errno2("readlinkat", abspath);
4756 } else {
4757 target_len = readlink(abspath, target_path, PATH_MAX);
4758 if (target_len == -1)
4759 return got_error_from_errno2("readlink", abspath);
4762 *fd = got_opentempfd();
4763 if (*fd == -1)
4764 return got_error_from_errno("got_opentempfd");
4766 outlen = write(*fd, target_path, target_len);
4767 if (outlen == -1) {
4768 err = got_error_from_errno("got_opentempfd");
4769 goto done;
4772 if (lseek(*fd, 0, SEEK_SET) == -1) {
4773 err = got_error_from_errno2("lseek", abspath);
4774 goto done;
4776 done:
4777 if (err) {
4778 close(*fd);
4779 *fd = -1;
4781 return err;
4784 static const struct got_error *
4785 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4786 const char *path, struct got_object_id *blob_id,
4787 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4788 int dirfd, const char *de_name)
4790 struct print_diff_arg *a = arg;
4791 const struct got_error *err = NULL;
4792 struct got_blob_object *blob1 = NULL;
4793 int fd = -1, fd1 = -1, fd2 = -1;
4794 FILE *f2 = NULL;
4795 char *abspath = NULL, *label1 = NULL;
4796 struct stat sb;
4797 off_t size1 = 0;
4798 int f2_exists = 0;
4800 memset(&sb, 0, sizeof(sb));
4802 if (a->diff_staged) {
4803 if (staged_status != GOT_STATUS_MODIFY &&
4804 staged_status != GOT_STATUS_ADD &&
4805 staged_status != GOT_STATUS_DELETE)
4806 return NULL;
4807 } else {
4808 if (staged_status == GOT_STATUS_DELETE)
4809 return NULL;
4810 if (status == GOT_STATUS_NONEXISTENT)
4811 return got_error_set_errno(ENOENT, path);
4812 if (status != GOT_STATUS_MODIFY &&
4813 status != GOT_STATUS_ADD &&
4814 status != GOT_STATUS_DELETE &&
4815 status != GOT_STATUS_CONFLICT)
4816 return NULL;
4819 err = got_opentemp_truncate(a->f1);
4820 if (err)
4821 return got_error_from_errno("got_opentemp_truncate");
4822 err = got_opentemp_truncate(a->f2);
4823 if (err)
4824 return got_error_from_errno("got_opentemp_truncate");
4826 if (!a->header_shown) {
4827 if (fprintf(a->outfile, "diff %s%s\n",
4828 a->diff_staged ? "-s " : "",
4829 got_worktree_get_root_path(a->worktree)) < 0) {
4830 err = got_error_from_errno("fprintf");
4831 goto done;
4833 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4834 err = got_error_from_errno("fprintf");
4835 goto done;
4837 if (fprintf(a->outfile, "path + %s%s\n",
4838 got_worktree_get_root_path(a->worktree),
4839 a->diff_staged ? " (staged changes)" : "") < 0) {
4840 err = got_error_from_errno("fprintf");
4841 goto done;
4843 a->header_shown = 1;
4846 if (a->diff_staged) {
4847 const char *label1 = NULL, *label2 = NULL;
4848 switch (staged_status) {
4849 case GOT_STATUS_MODIFY:
4850 label1 = path;
4851 label2 = path;
4852 break;
4853 case GOT_STATUS_ADD:
4854 label2 = path;
4855 break;
4856 case GOT_STATUS_DELETE:
4857 label1 = path;
4858 break;
4859 default:
4860 return got_error(GOT_ERR_FILE_STATUS);
4862 fd1 = got_opentempfd();
4863 if (fd1 == -1) {
4864 err = got_error_from_errno("got_opentempfd");
4865 goto done;
4867 fd2 = got_opentempfd();
4868 if (fd2 == -1) {
4869 err = got_error_from_errno("got_opentempfd");
4870 goto done;
4872 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4873 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4874 a->diff_algo, a->diff_context, a->ignore_whitespace,
4875 a->force_text_diff, a->show_diffstat, a->diffstat, a->repo,
4876 a->outfile);
4877 goto done;
4880 fd1 = got_opentempfd();
4881 if (fd1 == -1) {
4882 err = got_error_from_errno("got_opentempfd");
4883 goto done;
4886 if (staged_status == GOT_STATUS_ADD ||
4887 staged_status == GOT_STATUS_MODIFY) {
4888 char *id_str;
4889 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4890 8192, fd1);
4891 if (err)
4892 goto done;
4893 err = got_object_id_str(&id_str, staged_blob_id);
4894 if (err)
4895 goto done;
4896 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4897 err = got_error_from_errno("asprintf");
4898 free(id_str);
4899 goto done;
4901 free(id_str);
4902 } else if (status != GOT_STATUS_ADD) {
4903 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4904 fd1);
4905 if (err)
4906 goto done;
4909 if (status != GOT_STATUS_DELETE) {
4910 if (asprintf(&abspath, "%s/%s",
4911 got_worktree_get_root_path(a->worktree), path) == -1) {
4912 err = got_error_from_errno("asprintf");
4913 goto done;
4916 if (dirfd != -1) {
4917 fd = openat(dirfd, de_name,
4918 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4919 if (fd == -1) {
4920 if (!got_err_open_nofollow_on_symlink()) {
4921 err = got_error_from_errno2("openat",
4922 abspath);
4923 goto done;
4925 err = get_symlink_target_file(&fd, dirfd,
4926 de_name, abspath);
4927 if (err)
4928 goto done;
4930 } else {
4931 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4932 if (fd == -1) {
4933 if (!got_err_open_nofollow_on_symlink()) {
4934 err = got_error_from_errno2("open",
4935 abspath);
4936 goto done;
4938 err = get_symlink_target_file(&fd, dirfd,
4939 de_name, abspath);
4940 if (err)
4941 goto done;
4944 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4945 err = got_error_from_errno2("fstatat", abspath);
4946 goto done;
4948 f2 = fdopen(fd, "r");
4949 if (f2 == NULL) {
4950 err = got_error_from_errno2("fdopen", abspath);
4951 goto done;
4953 fd = -1;
4954 f2_exists = 1;
4957 if (blob1) {
4958 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4959 a->f1, blob1);
4960 if (err)
4961 goto done;
4964 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4965 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4966 a->ignore_whitespace, a->force_text_diff, a->show_diffstat,
4967 a->diffstat, a->outfile);
4968 done:
4969 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4970 err = got_error_from_errno("close");
4971 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4972 err = got_error_from_errno("close");
4973 if (blob1)
4974 got_object_blob_close(blob1);
4975 if (fd != -1 && close(fd) == -1 && err == NULL)
4976 err = got_error_from_errno("close");
4977 if (f2 && fclose(f2) == EOF && err == NULL)
4978 err = got_error_from_errno("fclose");
4979 free(abspath);
4980 return err;
4983 static const struct got_error *
4984 printfile(FILE *f)
4986 char buf[8192];
4987 size_t r;
4989 if (fseeko(f, 0L, SEEK_SET) == -1)
4990 return got_error_from_errno("fseek");
4992 for (;;) {
4993 r = fread(buf, 1, sizeof(buf), f);
4994 if (r == 0) {
4995 if (ferror(f))
4996 return got_error_from_errno("fread");
4997 if (feof(f))
4998 break;
5000 if (fwrite(buf, 1, r, stdout) != r)
5001 return got_ferror(stdout, GOT_ERR_IO);
5004 return NULL;
5007 static const struct got_error *
5008 cmd_diff(int argc, char *argv[])
5010 const struct got_error *error;
5011 struct got_repository *repo = NULL;
5012 struct got_worktree *worktree = NULL;
5013 char *cwd = NULL, *repo_path = NULL;
5014 const char *commit_args[2] = { NULL, NULL };
5015 int ncommit_args = 0;
5016 struct got_object_id *ids[2] = { NULL, NULL };
5017 char *labels[2] = { NULL, NULL };
5018 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5019 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5020 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5021 const char *errstr;
5022 struct got_reflist_head refs;
5023 struct got_pathlist_head diffstat_paths, paths;
5024 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5025 int fd1 = -1, fd2 = -1;
5026 int *pack_fds = NULL;
5027 struct got_diffstat_cb_arg dsa;
5029 memset(&dsa, 0, sizeof(dsa));
5031 TAILQ_INIT(&refs);
5032 TAILQ_INIT(&paths);
5033 TAILQ_INIT(&diffstat_paths);
5035 #ifndef PROFILE
5036 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5037 NULL) == -1)
5038 err(1, "pledge");
5039 #endif
5041 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5042 switch (ch) {
5043 case 'a':
5044 force_text_diff = 1;
5045 break;
5046 case 'C':
5047 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5048 &errstr);
5049 if (errstr != NULL)
5050 errx(1, "number of context lines is %s: %s",
5051 errstr, optarg);
5052 break;
5053 case 'c':
5054 if (ncommit_args >= 2)
5055 errx(1, "too many -c options used");
5056 commit_args[ncommit_args++] = optarg;
5057 break;
5058 case 'd':
5059 show_diffstat = 1;
5060 break;
5061 case 'P':
5062 force_path = 1;
5063 break;
5064 case 'r':
5065 repo_path = realpath(optarg, NULL);
5066 if (repo_path == NULL)
5067 return got_error_from_errno2("realpath",
5068 optarg);
5069 got_path_strip_trailing_slashes(repo_path);
5070 rflag = 1;
5071 break;
5072 case 's':
5073 diff_staged = 1;
5074 break;
5075 case 'w':
5076 ignore_whitespace = 1;
5077 break;
5078 default:
5079 usage_diff();
5080 /* NOTREACHED */
5084 argc -= optind;
5085 argv += optind;
5087 cwd = getcwd(NULL, 0);
5088 if (cwd == NULL) {
5089 error = got_error_from_errno("getcwd");
5090 goto done;
5093 error = got_repo_pack_fds_open(&pack_fds);
5094 if (error != NULL)
5095 goto done;
5097 if (repo_path == NULL) {
5098 error = got_worktree_open(&worktree, cwd);
5099 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5100 goto done;
5101 else
5102 error = NULL;
5103 if (worktree) {
5104 repo_path =
5105 strdup(got_worktree_get_repo_path(worktree));
5106 if (repo_path == NULL) {
5107 error = got_error_from_errno("strdup");
5108 goto done;
5110 } else {
5111 repo_path = strdup(cwd);
5112 if (repo_path == NULL) {
5113 error = got_error_from_errno("strdup");
5114 goto done;
5119 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5120 free(repo_path);
5121 if (error != NULL)
5122 goto done;
5124 if (show_diffstat) {
5125 dsa.paths = &diffstat_paths;
5126 dsa.force_text = force_text_diff;
5127 dsa.ignore_ws = ignore_whitespace;
5128 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5131 if (rflag || worktree == NULL || ncommit_args > 0) {
5132 if (force_path) {
5133 error = got_error_msg(GOT_ERR_NOT_IMPL,
5134 "-P option can only be used when diffing "
5135 "a work tree");
5136 goto done;
5138 if (diff_staged) {
5139 error = got_error_msg(GOT_ERR_NOT_IMPL,
5140 "-s option can only be used when diffing "
5141 "a work tree");
5142 goto done;
5146 error = apply_unveil(got_repo_get_path(repo), 1,
5147 worktree ? got_worktree_get_root_path(worktree) : NULL);
5148 if (error)
5149 goto done;
5151 if ((!force_path && argc == 2) || ncommit_args > 0) {
5152 int obj_type = (ncommit_args > 0 ?
5153 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5154 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5155 NULL);
5156 if (error)
5157 goto done;
5158 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5159 const char *arg;
5160 if (ncommit_args > 0)
5161 arg = commit_args[i];
5162 else
5163 arg = argv[i];
5164 error = got_repo_match_object_id(&ids[i], &labels[i],
5165 arg, obj_type, &refs, repo);
5166 if (error) {
5167 if (error->code != GOT_ERR_NOT_REF &&
5168 error->code != GOT_ERR_NO_OBJ)
5169 goto done;
5170 if (ncommit_args > 0)
5171 goto done;
5172 error = NULL;
5173 break;
5178 f1 = got_opentemp();
5179 if (f1 == NULL) {
5180 error = got_error_from_errno("got_opentemp");
5181 goto done;
5184 f2 = got_opentemp();
5185 if (f2 == NULL) {
5186 error = got_error_from_errno("got_opentemp");
5187 goto done;
5190 outfile = got_opentemp();
5191 if (outfile == NULL) {
5192 error = got_error_from_errno("got_opentemp");
5193 goto done;
5196 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5197 struct print_diff_arg arg;
5198 char *id_str;
5200 if (worktree == NULL) {
5201 if (argc == 2 && ids[0] == NULL) {
5202 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5203 goto done;
5204 } else if (argc == 2 && ids[1] == NULL) {
5205 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5206 goto done;
5207 } else if (argc > 0) {
5208 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5209 "%s", "specified paths cannot be resolved");
5210 goto done;
5211 } else {
5212 error = got_error(GOT_ERR_NOT_WORKTREE);
5213 goto done;
5217 error = get_worktree_paths_from_argv(&paths, argc, argv,
5218 worktree);
5219 if (error)
5220 goto done;
5222 error = got_object_id_str(&id_str,
5223 got_worktree_get_base_commit_id(worktree));
5224 if (error)
5225 goto done;
5226 arg.repo = repo;
5227 arg.worktree = worktree;
5228 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5229 arg.diff_context = diff_context;
5230 arg.id_str = id_str;
5231 arg.header_shown = 0;
5232 arg.diff_staged = diff_staged;
5233 arg.ignore_whitespace = ignore_whitespace;
5234 arg.force_text_diff = force_text_diff;
5235 arg.show_diffstat = show_diffstat;
5236 arg.diffstat = &dsa;
5237 arg.f1 = f1;
5238 arg.f2 = f2;
5239 arg.outfile = outfile;
5241 error = got_worktree_status(worktree, &paths, repo, 0,
5242 print_diff, &arg, check_cancelled, NULL);
5243 free(id_str);
5244 if (error)
5245 goto done;
5247 if (show_diffstat && dsa.nfiles > 0) {
5248 char *header;
5250 if (asprintf(&header, "diffstat %s%s",
5251 diff_staged ? "-s " : "",
5252 got_worktree_get_root_path(worktree)) == -1) {
5253 error = got_error_from_errno("asprintf");
5254 goto done;
5257 error = print_diffstat(&dsa, &diffstat_paths, header);
5258 free(header);
5259 if (error)
5260 goto done;
5263 error = printfile(outfile);
5264 goto done;
5267 if (ncommit_args == 1) {
5268 struct got_commit_object *commit;
5269 error = got_object_open_as_commit(&commit, repo, ids[0]);
5270 if (error)
5271 goto done;
5273 labels[1] = labels[0];
5274 ids[1] = ids[0];
5275 if (got_object_commit_get_nparents(commit) > 0) {
5276 const struct got_object_id_queue *pids;
5277 struct got_object_qid *pid;
5278 pids = got_object_commit_get_parent_ids(commit);
5279 pid = STAILQ_FIRST(pids);
5280 ids[0] = got_object_id_dup(&pid->id);
5281 if (ids[0] == NULL) {
5282 error = got_error_from_errno(
5283 "got_object_id_dup");
5284 got_object_commit_close(commit);
5285 goto done;
5287 error = got_object_id_str(&labels[0], ids[0]);
5288 if (error) {
5289 got_object_commit_close(commit);
5290 goto done;
5292 } else {
5293 ids[0] = NULL;
5294 labels[0] = strdup("/dev/null");
5295 if (labels[0] == NULL) {
5296 error = got_error_from_errno("strdup");
5297 got_object_commit_close(commit);
5298 goto done;
5302 got_object_commit_close(commit);
5305 if (ncommit_args == 0 && argc > 2) {
5306 error = got_error_msg(GOT_ERR_BAD_PATH,
5307 "path arguments cannot be used when diffing two objects");
5308 goto done;
5311 if (ids[0]) {
5312 error = got_object_get_type(&type1, repo, ids[0]);
5313 if (error)
5314 goto done;
5317 error = got_object_get_type(&type2, repo, ids[1]);
5318 if (error)
5319 goto done;
5320 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5321 error = got_error(GOT_ERR_OBJ_TYPE);
5322 goto done;
5324 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5325 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5326 "path arguments cannot be used when diffing blobs");
5327 goto done;
5330 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5331 char *in_repo_path;
5332 struct got_pathlist_entry *new;
5333 if (worktree) {
5334 const char *prefix;
5335 char *p;
5336 error = got_worktree_resolve_path(&p, worktree,
5337 argv[i]);
5338 if (error)
5339 goto done;
5340 prefix = got_worktree_get_path_prefix(worktree);
5341 while (prefix[0] == '/')
5342 prefix++;
5343 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5344 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5345 p) == -1) {
5346 error = got_error_from_errno("asprintf");
5347 free(p);
5348 goto done;
5350 free(p);
5351 } else {
5352 char *mapped_path, *s;
5353 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5354 if (error)
5355 goto done;
5356 s = mapped_path;
5357 while (s[0] == '/')
5358 s++;
5359 in_repo_path = strdup(s);
5360 if (in_repo_path == NULL) {
5361 error = got_error_from_errno("asprintf");
5362 free(mapped_path);
5363 goto done;
5365 free(mapped_path);
5368 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5369 if (error || new == NULL /* duplicate */)
5370 free(in_repo_path);
5371 if (error)
5372 goto done;
5375 if (worktree) {
5376 /* Release work tree lock. */
5377 got_worktree_close(worktree);
5378 worktree = NULL;
5381 fd1 = got_opentempfd();
5382 if (fd1 == -1) {
5383 error = got_error_from_errno("got_opentempfd");
5384 goto done;
5387 fd2 = got_opentempfd();
5388 if (fd2 == -1) {
5389 error = got_error_from_errno("got_opentempfd");
5390 goto done;
5393 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5394 case GOT_OBJ_TYPE_BLOB:
5395 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5396 fd1, fd2, ids[0], ids[1], NULL, NULL,
5397 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5398 ignore_whitespace, force_text_diff, show_diffstat,
5399 show_diffstat ? &dsa : NULL, repo, outfile);
5400 break;
5401 case GOT_OBJ_TYPE_TREE:
5402 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5403 ids[0], ids[1], &paths, "", "",
5404 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5405 ignore_whitespace, force_text_diff, show_diffstat,
5406 show_diffstat ? &dsa : NULL, repo, outfile);
5407 break;
5408 case GOT_OBJ_TYPE_COMMIT:
5409 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5410 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5411 fd1, fd2, ids[0], ids[1], &paths,
5412 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5413 ignore_whitespace, force_text_diff, show_diffstat,
5414 show_diffstat ? &dsa : NULL, repo, outfile);
5415 break;
5416 default:
5417 error = got_error(GOT_ERR_OBJ_TYPE);
5419 if (error)
5420 goto done;
5422 if (show_diffstat && dsa.nfiles > 0) {
5423 char *header = NULL;
5425 if (asprintf(&header, "diffstat %s %s",
5426 labels[0], labels[1]) == -1) {
5427 error = got_error_from_errno("asprintf");
5428 goto done;
5431 error = print_diffstat(&dsa, &diffstat_paths, header);
5432 free(header);
5433 if (error)
5434 goto done;
5437 error = printfile(outfile);
5439 done:
5440 free(labels[0]);
5441 free(labels[1]);
5442 free(ids[0]);
5443 free(ids[1]);
5444 if (worktree)
5445 got_worktree_close(worktree);
5446 if (repo) {
5447 const struct got_error *close_err = got_repo_close(repo);
5448 if (error == NULL)
5449 error = close_err;
5451 if (pack_fds) {
5452 const struct got_error *pack_err =
5453 got_repo_pack_fds_close(pack_fds);
5454 if (error == NULL)
5455 error = pack_err;
5457 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5458 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5459 got_ref_list_free(&refs);
5460 if (outfile && fclose(outfile) == EOF && error == NULL)
5461 error = got_error_from_errno("fclose");
5462 if (f1 && fclose(f1) == EOF && error == NULL)
5463 error = got_error_from_errno("fclose");
5464 if (f2 && fclose(f2) == EOF && error == NULL)
5465 error = got_error_from_errno("fclose");
5466 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5467 error = got_error_from_errno("close");
5468 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5469 error = got_error_from_errno("close");
5470 return error;
5473 __dead static void
5474 usage_blame(void)
5476 fprintf(stderr,
5477 "usage: %s blame [-c commit] [-r repository-path] path\n",
5478 getprogname());
5479 exit(1);
5482 struct blame_line {
5483 int annotated;
5484 char *id_str;
5485 char *committer;
5486 char datebuf[11]; /* YYYY-MM-DD + NUL */
5489 struct blame_cb_args {
5490 struct blame_line *lines;
5491 int nlines;
5492 int nlines_prec;
5493 int lineno_cur;
5494 off_t *line_offsets;
5495 FILE *f;
5496 struct got_repository *repo;
5499 static const struct got_error *
5500 blame_cb(void *arg, int nlines, int lineno,
5501 struct got_commit_object *commit, struct got_object_id *id)
5503 const struct got_error *err = NULL;
5504 struct blame_cb_args *a = arg;
5505 struct blame_line *bline;
5506 char *line = NULL;
5507 size_t linesize = 0;
5508 off_t offset;
5509 struct tm tm;
5510 time_t committer_time;
5512 if (nlines != a->nlines ||
5513 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5514 return got_error(GOT_ERR_RANGE);
5516 if (sigint_received)
5517 return got_error(GOT_ERR_ITER_COMPLETED);
5519 if (lineno == -1)
5520 return NULL; /* no change in this commit */
5522 /* Annotate this line. */
5523 bline = &a->lines[lineno - 1];
5524 if (bline->annotated)
5525 return NULL;
5526 err = got_object_id_str(&bline->id_str, id);
5527 if (err)
5528 return err;
5530 bline->committer = strdup(got_object_commit_get_committer(commit));
5531 if (bline->committer == NULL) {
5532 err = got_error_from_errno("strdup");
5533 goto done;
5536 committer_time = got_object_commit_get_committer_time(commit);
5537 if (gmtime_r(&committer_time, &tm) == NULL)
5538 return got_error_from_errno("gmtime_r");
5539 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5540 &tm) == 0) {
5541 err = got_error(GOT_ERR_NO_SPACE);
5542 goto done;
5544 bline->annotated = 1;
5546 /* Print lines annotated so far. */
5547 bline = &a->lines[a->lineno_cur - 1];
5548 if (!bline->annotated)
5549 goto done;
5551 offset = a->line_offsets[a->lineno_cur - 1];
5552 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5553 err = got_error_from_errno("fseeko");
5554 goto done;
5557 while (a->lineno_cur <= a->nlines && bline->annotated) {
5558 char *smallerthan, *at, *nl, *committer;
5559 size_t len;
5561 if (getline(&line, &linesize, a->f) == -1) {
5562 if (ferror(a->f))
5563 err = got_error_from_errno("getline");
5564 break;
5567 committer = bline->committer;
5568 smallerthan = strchr(committer, '<');
5569 if (smallerthan && smallerthan[1] != '\0')
5570 committer = smallerthan + 1;
5571 at = strchr(committer, '@');
5572 if (at)
5573 *at = '\0';
5574 len = strlen(committer);
5575 if (len >= 9)
5576 committer[8] = '\0';
5578 nl = strchr(line, '\n');
5579 if (nl)
5580 *nl = '\0';
5581 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5582 bline->id_str, bline->datebuf, committer, line);
5584 a->lineno_cur++;
5585 bline = &a->lines[a->lineno_cur - 1];
5587 done:
5588 free(line);
5589 return err;
5592 static const struct got_error *
5593 cmd_blame(int argc, char *argv[])
5595 const struct got_error *error;
5596 struct got_repository *repo = NULL;
5597 struct got_worktree *worktree = NULL;
5598 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5599 char *link_target = NULL;
5600 struct got_object_id *obj_id = NULL;
5601 struct got_object_id *commit_id = NULL;
5602 struct got_commit_object *commit = NULL;
5603 struct got_blob_object *blob = NULL;
5604 char *commit_id_str = NULL;
5605 struct blame_cb_args bca;
5606 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5607 off_t filesize;
5608 int *pack_fds = NULL;
5609 FILE *f1 = NULL, *f2 = NULL;
5611 fd1 = got_opentempfd();
5612 if (fd1 == -1)
5613 return got_error_from_errno("got_opentempfd");
5615 memset(&bca, 0, sizeof(bca));
5617 #ifndef PROFILE
5618 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5619 NULL) == -1)
5620 err(1, "pledge");
5621 #endif
5623 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5624 switch (ch) {
5625 case 'c':
5626 commit_id_str = optarg;
5627 break;
5628 case 'r':
5629 repo_path = realpath(optarg, NULL);
5630 if (repo_path == NULL)
5631 return got_error_from_errno2("realpath",
5632 optarg);
5633 got_path_strip_trailing_slashes(repo_path);
5634 break;
5635 default:
5636 usage_blame();
5637 /* NOTREACHED */
5641 argc -= optind;
5642 argv += optind;
5644 if (argc == 1)
5645 path = argv[0];
5646 else
5647 usage_blame();
5649 cwd = getcwd(NULL, 0);
5650 if (cwd == NULL) {
5651 error = got_error_from_errno("getcwd");
5652 goto done;
5655 error = got_repo_pack_fds_open(&pack_fds);
5656 if (error != NULL)
5657 goto done;
5659 if (repo_path == NULL) {
5660 error = got_worktree_open(&worktree, cwd);
5661 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5662 goto done;
5663 else
5664 error = NULL;
5665 if (worktree) {
5666 repo_path =
5667 strdup(got_worktree_get_repo_path(worktree));
5668 if (repo_path == NULL) {
5669 error = got_error_from_errno("strdup");
5670 if (error)
5671 goto done;
5673 } else {
5674 repo_path = strdup(cwd);
5675 if (repo_path == NULL) {
5676 error = got_error_from_errno("strdup");
5677 goto done;
5682 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5683 if (error != NULL)
5684 goto done;
5686 if (worktree) {
5687 const char *prefix = got_worktree_get_path_prefix(worktree);
5688 char *p;
5690 error = got_worktree_resolve_path(&p, worktree, path);
5691 if (error)
5692 goto done;
5693 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5694 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5695 p) == -1) {
5696 error = got_error_from_errno("asprintf");
5697 free(p);
5698 goto done;
5700 free(p);
5701 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5702 } else {
5703 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5704 if (error)
5705 goto done;
5706 error = got_repo_map_path(&in_repo_path, repo, path);
5708 if (error)
5709 goto done;
5711 if (commit_id_str == NULL) {
5712 struct got_reference *head_ref;
5713 error = got_ref_open(&head_ref, repo, worktree ?
5714 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5715 if (error != NULL)
5716 goto done;
5717 error = got_ref_resolve(&commit_id, repo, head_ref);
5718 got_ref_close(head_ref);
5719 if (error != NULL)
5720 goto done;
5721 } else {
5722 struct got_reflist_head refs;
5723 TAILQ_INIT(&refs);
5724 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5725 NULL);
5726 if (error)
5727 goto done;
5728 error = got_repo_match_object_id(&commit_id, NULL,
5729 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5730 got_ref_list_free(&refs);
5731 if (error)
5732 goto done;
5735 if (worktree) {
5736 /* Release work tree lock. */
5737 got_worktree_close(worktree);
5738 worktree = NULL;
5741 error = got_object_open_as_commit(&commit, repo, commit_id);
5742 if (error)
5743 goto done;
5745 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5746 commit, repo);
5747 if (error)
5748 goto done;
5750 error = got_object_id_by_path(&obj_id, repo, commit,
5751 link_target ? link_target : in_repo_path);
5752 if (error)
5753 goto done;
5755 error = got_object_get_type(&obj_type, repo, obj_id);
5756 if (error)
5757 goto done;
5759 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5760 error = got_error_path(link_target ? link_target : in_repo_path,
5761 GOT_ERR_OBJ_TYPE);
5762 goto done;
5765 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5766 if (error)
5767 goto done;
5768 bca.f = got_opentemp();
5769 if (bca.f == NULL) {
5770 error = got_error_from_errno("got_opentemp");
5771 goto done;
5773 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5774 &bca.line_offsets, bca.f, blob);
5775 if (error || bca.nlines == 0)
5776 goto done;
5778 /* Don't include \n at EOF in the blame line count. */
5779 if (bca.line_offsets[bca.nlines - 1] == filesize)
5780 bca.nlines--;
5782 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5783 if (bca.lines == NULL) {
5784 error = got_error_from_errno("calloc");
5785 goto done;
5787 bca.lineno_cur = 1;
5788 bca.nlines_prec = 0;
5789 i = bca.nlines;
5790 while (i > 0) {
5791 i /= 10;
5792 bca.nlines_prec++;
5794 bca.repo = repo;
5796 fd2 = got_opentempfd();
5797 if (fd2 == -1) {
5798 error = got_error_from_errno("got_opentempfd");
5799 goto done;
5801 fd3 = got_opentempfd();
5802 if (fd3 == -1) {
5803 error = got_error_from_errno("got_opentempfd");
5804 goto done;
5806 f1 = got_opentemp();
5807 if (f1 == NULL) {
5808 error = got_error_from_errno("got_opentemp");
5809 goto done;
5811 f2 = got_opentemp();
5812 if (f2 == NULL) {
5813 error = got_error_from_errno("got_opentemp");
5814 goto done;
5816 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5817 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5818 check_cancelled, NULL, fd2, fd3, f1, f2);
5819 done:
5820 free(in_repo_path);
5821 free(link_target);
5822 free(repo_path);
5823 free(cwd);
5824 free(commit_id);
5825 free(obj_id);
5826 if (commit)
5827 got_object_commit_close(commit);
5829 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5830 error = got_error_from_errno("close");
5831 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5832 error = got_error_from_errno("close");
5833 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5834 error = got_error_from_errno("close");
5835 if (f1 && fclose(f1) == EOF && error == NULL)
5836 error = got_error_from_errno("fclose");
5837 if (f2 && fclose(f2) == EOF && error == NULL)
5838 error = got_error_from_errno("fclose");
5840 if (blob)
5841 got_object_blob_close(blob);
5842 if (worktree)
5843 got_worktree_close(worktree);
5844 if (repo) {
5845 const struct got_error *close_err = got_repo_close(repo);
5846 if (error == NULL)
5847 error = close_err;
5849 if (pack_fds) {
5850 const struct got_error *pack_err =
5851 got_repo_pack_fds_close(pack_fds);
5852 if (error == NULL)
5853 error = pack_err;
5855 if (bca.lines) {
5856 for (i = 0; i < bca.nlines; i++) {
5857 struct blame_line *bline = &bca.lines[i];
5858 free(bline->id_str);
5859 free(bline->committer);
5861 free(bca.lines);
5863 free(bca.line_offsets);
5864 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5865 error = got_error_from_errno("fclose");
5866 return error;
5869 __dead static void
5870 usage_tree(void)
5872 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5873 "[path]\n", getprogname());
5874 exit(1);
5877 static const struct got_error *
5878 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5879 const char *root_path, struct got_repository *repo)
5881 const struct got_error *err = NULL;
5882 int is_root_path = (strcmp(path, root_path) == 0);
5883 const char *modestr = "";
5884 mode_t mode = got_tree_entry_get_mode(te);
5885 char *link_target = NULL;
5887 path += strlen(root_path);
5888 while (path[0] == '/')
5889 path++;
5891 if (got_object_tree_entry_is_submodule(te))
5892 modestr = "$";
5893 else if (S_ISLNK(mode)) {
5894 int i;
5896 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5897 if (err)
5898 return err;
5899 for (i = 0; i < strlen(link_target); i++) {
5900 if (!isprint((unsigned char)link_target[i]))
5901 link_target[i] = '?';
5904 modestr = "@";
5906 else if (S_ISDIR(mode))
5907 modestr = "/";
5908 else if (mode & S_IXUSR)
5909 modestr = "*";
5911 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5912 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5913 link_target ? " -> ": "", link_target ? link_target : "");
5915 free(link_target);
5916 return NULL;
5919 static const struct got_error *
5920 print_tree(const char *path, struct got_commit_object *commit,
5921 int show_ids, int recurse, const char *root_path,
5922 struct got_repository *repo)
5924 const struct got_error *err = NULL;
5925 struct got_object_id *tree_id = NULL;
5926 struct got_tree_object *tree = NULL;
5927 int nentries, i;
5929 err = got_object_id_by_path(&tree_id, repo, commit, path);
5930 if (err)
5931 goto done;
5933 err = got_object_open_as_tree(&tree, repo, tree_id);
5934 if (err)
5935 goto done;
5936 nentries = got_object_tree_get_nentries(tree);
5937 for (i = 0; i < nentries; i++) {
5938 struct got_tree_entry *te;
5939 char *id = NULL;
5941 if (sigint_received || sigpipe_received)
5942 break;
5944 te = got_object_tree_get_entry(tree, i);
5945 if (show_ids) {
5946 char *id_str;
5947 err = got_object_id_str(&id_str,
5948 got_tree_entry_get_id(te));
5949 if (err)
5950 goto done;
5951 if (asprintf(&id, "%s ", id_str) == -1) {
5952 err = got_error_from_errno("asprintf");
5953 free(id_str);
5954 goto done;
5956 free(id_str);
5958 err = print_entry(te, id, path, root_path, repo);
5959 free(id);
5960 if (err)
5961 goto done;
5963 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5964 char *child_path;
5965 if (asprintf(&child_path, "%s%s%s", path,
5966 path[0] == '/' && path[1] == '\0' ? "" : "/",
5967 got_tree_entry_get_name(te)) == -1) {
5968 err = got_error_from_errno("asprintf");
5969 goto done;
5971 err = print_tree(child_path, commit, show_ids, 1,
5972 root_path, repo);
5973 free(child_path);
5974 if (err)
5975 goto done;
5978 done:
5979 if (tree)
5980 got_object_tree_close(tree);
5981 free(tree_id);
5982 return err;
5985 static const struct got_error *
5986 cmd_tree(int argc, char *argv[])
5988 const struct got_error *error;
5989 struct got_repository *repo = NULL;
5990 struct got_worktree *worktree = NULL;
5991 const char *path, *refname = NULL;
5992 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5993 struct got_object_id *commit_id = NULL;
5994 struct got_commit_object *commit = NULL;
5995 char *commit_id_str = NULL;
5996 int show_ids = 0, recurse = 0;
5997 int ch;
5998 int *pack_fds = NULL;
6000 #ifndef PROFILE
6001 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6002 NULL) == -1)
6003 err(1, "pledge");
6004 #endif
6006 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6007 switch (ch) {
6008 case 'c':
6009 commit_id_str = optarg;
6010 break;
6011 case 'i':
6012 show_ids = 1;
6013 break;
6014 case 'R':
6015 recurse = 1;
6016 break;
6017 case 'r':
6018 repo_path = realpath(optarg, NULL);
6019 if (repo_path == NULL)
6020 return got_error_from_errno2("realpath",
6021 optarg);
6022 got_path_strip_trailing_slashes(repo_path);
6023 break;
6024 default:
6025 usage_tree();
6026 /* NOTREACHED */
6030 argc -= optind;
6031 argv += optind;
6033 if (argc == 1)
6034 path = argv[0];
6035 else if (argc > 1)
6036 usage_tree();
6037 else
6038 path = NULL;
6040 cwd = getcwd(NULL, 0);
6041 if (cwd == NULL) {
6042 error = got_error_from_errno("getcwd");
6043 goto done;
6046 error = got_repo_pack_fds_open(&pack_fds);
6047 if (error != NULL)
6048 goto done;
6050 if (repo_path == NULL) {
6051 error = got_worktree_open(&worktree, cwd);
6052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6053 goto done;
6054 else
6055 error = NULL;
6056 if (worktree) {
6057 repo_path =
6058 strdup(got_worktree_get_repo_path(worktree));
6059 if (repo_path == NULL)
6060 error = got_error_from_errno("strdup");
6061 if (error)
6062 goto done;
6063 } else {
6064 repo_path = strdup(cwd);
6065 if (repo_path == NULL) {
6066 error = got_error_from_errno("strdup");
6067 goto done;
6072 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6073 if (error != NULL)
6074 goto done;
6076 if (worktree) {
6077 const char *prefix = got_worktree_get_path_prefix(worktree);
6078 char *p;
6080 if (path == NULL)
6081 path = "";
6082 error = got_worktree_resolve_path(&p, worktree, path);
6083 if (error)
6084 goto done;
6085 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6086 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6087 p) == -1) {
6088 error = got_error_from_errno("asprintf");
6089 free(p);
6090 goto done;
6092 free(p);
6093 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6094 if (error)
6095 goto done;
6096 } else {
6097 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6098 if (error)
6099 goto done;
6100 if (path == NULL)
6101 path = "/";
6102 error = got_repo_map_path(&in_repo_path, repo, path);
6103 if (error != NULL)
6104 goto done;
6107 if (commit_id_str == NULL) {
6108 struct got_reference *head_ref;
6109 if (worktree)
6110 refname = got_worktree_get_head_ref_name(worktree);
6111 else
6112 refname = GOT_REF_HEAD;
6113 error = got_ref_open(&head_ref, repo, refname, 0);
6114 if (error != NULL)
6115 goto done;
6116 error = got_ref_resolve(&commit_id, repo, head_ref);
6117 got_ref_close(head_ref);
6118 if (error != NULL)
6119 goto done;
6120 } else {
6121 struct got_reflist_head refs;
6122 TAILQ_INIT(&refs);
6123 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6124 NULL);
6125 if (error)
6126 goto done;
6127 error = got_repo_match_object_id(&commit_id, NULL,
6128 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6129 got_ref_list_free(&refs);
6130 if (error)
6131 goto done;
6134 if (worktree) {
6135 /* Release work tree lock. */
6136 got_worktree_close(worktree);
6137 worktree = NULL;
6140 error = got_object_open_as_commit(&commit, repo, commit_id);
6141 if (error)
6142 goto done;
6144 error = print_tree(in_repo_path, commit, show_ids, recurse,
6145 in_repo_path, repo);
6146 done:
6147 free(in_repo_path);
6148 free(repo_path);
6149 free(cwd);
6150 free(commit_id);
6151 if (commit)
6152 got_object_commit_close(commit);
6153 if (worktree)
6154 got_worktree_close(worktree);
6155 if (repo) {
6156 const struct got_error *close_err = got_repo_close(repo);
6157 if (error == NULL)
6158 error = close_err;
6160 if (pack_fds) {
6161 const struct got_error *pack_err =
6162 got_repo_pack_fds_close(pack_fds);
6163 if (error == NULL)
6164 error = pack_err;
6166 return error;
6169 __dead static void
6170 usage_status(void)
6172 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6173 "[-s status-codes] [path ...]\n", getprogname());
6174 exit(1);
6177 struct got_status_arg {
6178 char *status_codes;
6179 int suppress;
6182 static const struct got_error *
6183 print_status(void *arg, unsigned char status, unsigned char staged_status,
6184 const char *path, struct got_object_id *blob_id,
6185 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6186 int dirfd, const char *de_name)
6188 struct got_status_arg *st = arg;
6190 if (status == staged_status && (status == GOT_STATUS_DELETE))
6191 status = GOT_STATUS_NO_CHANGE;
6192 if (st != NULL && st->status_codes) {
6193 size_t ncodes = strlen(st->status_codes);
6194 int i, j = 0;
6196 for (i = 0; i < ncodes ; i++) {
6197 if (st->suppress) {
6198 if (status == st->status_codes[i] ||
6199 staged_status == st->status_codes[i]) {
6200 j++;
6201 continue;
6203 } else {
6204 if (status == st->status_codes[i] ||
6205 staged_status == st->status_codes[i])
6206 break;
6210 if (st->suppress && j == 0)
6211 goto print;
6213 if (i == ncodes)
6214 return NULL;
6216 print:
6217 printf("%c%c %s\n", status, staged_status, path);
6218 return NULL;
6221 static const struct got_error *
6222 cmd_status(int argc, char *argv[])
6224 const struct got_error *error = NULL;
6225 struct got_repository *repo = NULL;
6226 struct got_worktree *worktree = NULL;
6227 struct got_status_arg st;
6228 char *cwd = NULL;
6229 struct got_pathlist_head paths;
6230 int ch, i, no_ignores = 0;
6231 int *pack_fds = NULL;
6233 TAILQ_INIT(&paths);
6235 memset(&st, 0, sizeof(st));
6236 st.status_codes = NULL;
6237 st.suppress = 0;
6239 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6240 switch (ch) {
6241 case 'I':
6242 no_ignores = 1;
6243 break;
6244 case 'S':
6245 if (st.status_codes != NULL && st.suppress == 0)
6246 option_conflict('S', 's');
6247 st.suppress = 1;
6248 /* fallthrough */
6249 case 's':
6250 for (i = 0; i < strlen(optarg); i++) {
6251 switch (optarg[i]) {
6252 case GOT_STATUS_MODIFY:
6253 case GOT_STATUS_ADD:
6254 case GOT_STATUS_DELETE:
6255 case GOT_STATUS_CONFLICT:
6256 case GOT_STATUS_MISSING:
6257 case GOT_STATUS_OBSTRUCTED:
6258 case GOT_STATUS_UNVERSIONED:
6259 case GOT_STATUS_MODE_CHANGE:
6260 case GOT_STATUS_NONEXISTENT:
6261 break;
6262 default:
6263 errx(1, "invalid status code '%c'",
6264 optarg[i]);
6267 if (ch == 's' && st.suppress)
6268 option_conflict('s', 'S');
6269 st.status_codes = optarg;
6270 break;
6271 default:
6272 usage_status();
6273 /* NOTREACHED */
6277 argc -= optind;
6278 argv += optind;
6280 #ifndef PROFILE
6281 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6282 NULL) == -1)
6283 err(1, "pledge");
6284 #endif
6285 cwd = getcwd(NULL, 0);
6286 if (cwd == NULL) {
6287 error = got_error_from_errno("getcwd");
6288 goto done;
6291 error = got_repo_pack_fds_open(&pack_fds);
6292 if (error != NULL)
6293 goto done;
6295 error = got_worktree_open(&worktree, cwd);
6296 if (error) {
6297 if (error->code == GOT_ERR_NOT_WORKTREE)
6298 error = wrap_not_worktree_error(error, "status", cwd);
6299 goto done;
6302 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6303 NULL, pack_fds);
6304 if (error != NULL)
6305 goto done;
6307 error = apply_unveil(got_repo_get_path(repo), 1,
6308 got_worktree_get_root_path(worktree));
6309 if (error)
6310 goto done;
6312 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6313 if (error)
6314 goto done;
6316 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6317 print_status, &st, check_cancelled, NULL);
6318 done:
6319 if (pack_fds) {
6320 const struct got_error *pack_err =
6321 got_repo_pack_fds_close(pack_fds);
6322 if (error == NULL)
6323 error = pack_err;
6326 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6327 free(cwd);
6328 return error;
6331 __dead static void
6332 usage_ref(void)
6334 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6335 "[-s reference] [name]\n", getprogname());
6336 exit(1);
6339 static const struct got_error *
6340 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6342 static const struct got_error *err = NULL;
6343 struct got_reflist_head refs;
6344 struct got_reflist_entry *re;
6346 TAILQ_INIT(&refs);
6347 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6348 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6349 repo);
6350 if (err)
6351 return err;
6353 TAILQ_FOREACH(re, &refs, entry) {
6354 char *refstr;
6355 refstr = got_ref_to_str(re->ref);
6356 if (refstr == NULL) {
6357 err = got_error_from_errno("got_ref_to_str");
6358 break;
6360 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6361 free(refstr);
6364 got_ref_list_free(&refs);
6365 return err;
6368 static const struct got_error *
6369 delete_ref_by_name(struct got_repository *repo, const char *refname)
6371 const struct got_error *err;
6372 struct got_reference *ref;
6374 err = got_ref_open(&ref, repo, refname, 0);
6375 if (err)
6376 return err;
6378 err = delete_ref(repo, ref);
6379 got_ref_close(ref);
6380 return err;
6383 static const struct got_error *
6384 add_ref(struct got_repository *repo, const char *refname, const char *target)
6386 const struct got_error *err = NULL;
6387 struct got_object_id *id = NULL;
6388 struct got_reference *ref = NULL;
6389 struct got_reflist_head refs;
6392 * Don't let the user create a reference name with a leading '-'.
6393 * While technically a valid reference name, this case is usually
6394 * an unintended typo.
6396 if (refname[0] == '-')
6397 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6399 TAILQ_INIT(&refs);
6400 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6401 if (err)
6402 goto done;
6403 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6404 &refs, repo);
6405 got_ref_list_free(&refs);
6406 if (err)
6407 goto done;
6409 err = got_ref_alloc(&ref, refname, id);
6410 if (err)
6411 goto done;
6413 err = got_ref_write(ref, repo);
6414 done:
6415 if (ref)
6416 got_ref_close(ref);
6417 free(id);
6418 return err;
6421 static const struct got_error *
6422 add_symref(struct got_repository *repo, const char *refname, const char *target)
6424 const struct got_error *err = NULL;
6425 struct got_reference *ref = NULL;
6426 struct got_reference *target_ref = NULL;
6429 * Don't let the user create a reference name with a leading '-'.
6430 * While technically a valid reference name, this case is usually
6431 * an unintended typo.
6433 if (refname[0] == '-')
6434 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6436 err = got_ref_open(&target_ref, repo, target, 0);
6437 if (err)
6438 return err;
6440 err = got_ref_alloc_symref(&ref, refname, target_ref);
6441 if (err)
6442 goto done;
6444 err = got_ref_write(ref, repo);
6445 done:
6446 if (target_ref)
6447 got_ref_close(target_ref);
6448 if (ref)
6449 got_ref_close(ref);
6450 return err;
6453 static const struct got_error *
6454 cmd_ref(int argc, char *argv[])
6456 const struct got_error *error = NULL;
6457 struct got_repository *repo = NULL;
6458 struct got_worktree *worktree = NULL;
6459 char *cwd = NULL, *repo_path = NULL;
6460 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6461 const char *obj_arg = NULL, *symref_target= NULL;
6462 char *refname = NULL;
6463 int *pack_fds = NULL;
6465 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6466 switch (ch) {
6467 case 'c':
6468 obj_arg = optarg;
6469 break;
6470 case 'd':
6471 do_delete = 1;
6472 break;
6473 case 'l':
6474 do_list = 1;
6475 break;
6476 case 'r':
6477 repo_path = realpath(optarg, NULL);
6478 if (repo_path == NULL)
6479 return got_error_from_errno2("realpath",
6480 optarg);
6481 got_path_strip_trailing_slashes(repo_path);
6482 break;
6483 case 's':
6484 symref_target = optarg;
6485 break;
6486 case 't':
6487 sort_by_time = 1;
6488 break;
6489 default:
6490 usage_ref();
6491 /* NOTREACHED */
6495 if (obj_arg && do_list)
6496 option_conflict('c', 'l');
6497 if (obj_arg && do_delete)
6498 option_conflict('c', 'd');
6499 if (obj_arg && symref_target)
6500 option_conflict('c', 's');
6501 if (symref_target && do_delete)
6502 option_conflict('s', 'd');
6503 if (symref_target && do_list)
6504 option_conflict('s', 'l');
6505 if (do_delete && do_list)
6506 option_conflict('d', 'l');
6507 if (sort_by_time && !do_list)
6508 errx(1, "-t option requires -l option");
6510 argc -= optind;
6511 argv += optind;
6513 if (do_list) {
6514 if (argc != 0 && argc != 1)
6515 usage_ref();
6516 if (argc == 1) {
6517 refname = strdup(argv[0]);
6518 if (refname == NULL) {
6519 error = got_error_from_errno("strdup");
6520 goto done;
6523 } else {
6524 if (argc != 1)
6525 usage_ref();
6526 refname = strdup(argv[0]);
6527 if (refname == NULL) {
6528 error = got_error_from_errno("strdup");
6529 goto done;
6533 if (refname)
6534 got_path_strip_trailing_slashes(refname);
6536 #ifndef PROFILE
6537 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6538 "sendfd unveil", NULL) == -1)
6539 err(1, "pledge");
6540 #endif
6541 cwd = getcwd(NULL, 0);
6542 if (cwd == NULL) {
6543 error = got_error_from_errno("getcwd");
6544 goto done;
6547 error = got_repo_pack_fds_open(&pack_fds);
6548 if (error != NULL)
6549 goto done;
6551 if (repo_path == NULL) {
6552 error = got_worktree_open(&worktree, cwd);
6553 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6554 goto done;
6555 else
6556 error = NULL;
6557 if (worktree) {
6558 repo_path =
6559 strdup(got_worktree_get_repo_path(worktree));
6560 if (repo_path == NULL)
6561 error = got_error_from_errno("strdup");
6562 if (error)
6563 goto done;
6564 } else {
6565 repo_path = strdup(cwd);
6566 if (repo_path == NULL) {
6567 error = got_error_from_errno("strdup");
6568 goto done;
6573 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6574 if (error != NULL)
6575 goto done;
6577 #ifndef PROFILE
6578 if (do_list) {
6579 /* Remove "cpath" promise. */
6580 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6581 NULL) == -1)
6582 err(1, "pledge");
6584 #endif
6586 error = apply_unveil(got_repo_get_path(repo), do_list,
6587 worktree ? got_worktree_get_root_path(worktree) : NULL);
6588 if (error)
6589 goto done;
6591 if (do_list)
6592 error = list_refs(repo, refname, sort_by_time);
6593 else if (do_delete)
6594 error = delete_ref_by_name(repo, refname);
6595 else if (symref_target)
6596 error = add_symref(repo, refname, symref_target);
6597 else {
6598 if (obj_arg == NULL)
6599 usage_ref();
6600 error = add_ref(repo, refname, obj_arg);
6602 done:
6603 free(refname);
6604 if (repo) {
6605 const struct got_error *close_err = got_repo_close(repo);
6606 if (error == NULL)
6607 error = close_err;
6609 if (worktree)
6610 got_worktree_close(worktree);
6611 if (pack_fds) {
6612 const struct got_error *pack_err =
6613 got_repo_pack_fds_close(pack_fds);
6614 if (error == NULL)
6615 error = pack_err;
6617 free(cwd);
6618 free(repo_path);
6619 return error;
6622 __dead static void
6623 usage_branch(void)
6625 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6626 "[-r repository-path] [name]\n", getprogname());
6627 exit(1);
6630 static const struct got_error *
6631 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6632 struct got_reference *ref)
6634 const struct got_error *err = NULL;
6635 const char *refname, *marker = " ";
6636 char *refstr;
6638 refname = got_ref_get_name(ref);
6639 if (worktree && strcmp(refname,
6640 got_worktree_get_head_ref_name(worktree)) == 0) {
6641 struct got_object_id *id = NULL;
6643 err = got_ref_resolve(&id, repo, ref);
6644 if (err)
6645 return err;
6646 if (got_object_id_cmp(id,
6647 got_worktree_get_base_commit_id(worktree)) == 0)
6648 marker = "* ";
6649 else
6650 marker = "~ ";
6651 free(id);
6654 if (strncmp(refname, "refs/heads/", 11) == 0)
6655 refname += 11;
6656 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6657 refname += 18;
6658 if (strncmp(refname, "refs/remotes/", 13) == 0)
6659 refname += 13;
6661 refstr = got_ref_to_str(ref);
6662 if (refstr == NULL)
6663 return got_error_from_errno("got_ref_to_str");
6665 printf("%s%s: %s\n", marker, refname, refstr);
6666 free(refstr);
6667 return NULL;
6670 static const struct got_error *
6671 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6673 const char *refname;
6675 if (worktree == NULL)
6676 return got_error(GOT_ERR_NOT_WORKTREE);
6678 refname = got_worktree_get_head_ref_name(worktree);
6680 if (strncmp(refname, "refs/heads/", 11) == 0)
6681 refname += 11;
6682 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6683 refname += 18;
6685 printf("%s\n", refname);
6687 return NULL;
6690 static const struct got_error *
6691 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6692 int sort_by_time)
6694 static const struct got_error *err = NULL;
6695 struct got_reflist_head refs;
6696 struct got_reflist_entry *re;
6697 struct got_reference *temp_ref = NULL;
6698 int rebase_in_progress, histedit_in_progress;
6700 TAILQ_INIT(&refs);
6702 if (worktree) {
6703 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6704 worktree);
6705 if (err)
6706 return err;
6708 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6709 worktree);
6710 if (err)
6711 return err;
6713 if (rebase_in_progress || histedit_in_progress) {
6714 err = got_ref_open(&temp_ref, repo,
6715 got_worktree_get_head_ref_name(worktree), 0);
6716 if (err)
6717 return err;
6718 list_branch(repo, worktree, temp_ref);
6719 got_ref_close(temp_ref);
6723 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6724 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6725 repo);
6726 if (err)
6727 return err;
6729 TAILQ_FOREACH(re, &refs, entry)
6730 list_branch(repo, worktree, re->ref);
6732 got_ref_list_free(&refs);
6734 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6735 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6736 repo);
6737 if (err)
6738 return err;
6740 TAILQ_FOREACH(re, &refs, entry)
6741 list_branch(repo, worktree, re->ref);
6743 got_ref_list_free(&refs);
6745 return NULL;
6748 static const struct got_error *
6749 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6750 const char *branch_name)
6752 const struct got_error *err = NULL;
6753 struct got_reference *ref = NULL;
6754 char *refname, *remote_refname = NULL;
6756 if (strncmp(branch_name, "refs/", 5) == 0)
6757 branch_name += 5;
6758 if (strncmp(branch_name, "heads/", 6) == 0)
6759 branch_name += 6;
6760 else if (strncmp(branch_name, "remotes/", 8) == 0)
6761 branch_name += 8;
6763 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6764 return got_error_from_errno("asprintf");
6766 if (asprintf(&remote_refname, "refs/remotes/%s",
6767 branch_name) == -1) {
6768 err = got_error_from_errno("asprintf");
6769 goto done;
6772 err = got_ref_open(&ref, repo, refname, 0);
6773 if (err) {
6774 const struct got_error *err2;
6775 if (err->code != GOT_ERR_NOT_REF)
6776 goto done;
6778 * Keep 'err' intact such that if neither branch exists
6779 * we report "refs/heads" rather than "refs/remotes" in
6780 * our error message.
6782 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6783 if (err2)
6784 goto done;
6785 err = NULL;
6788 if (worktree &&
6789 strcmp(got_worktree_get_head_ref_name(worktree),
6790 got_ref_get_name(ref)) == 0) {
6791 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6792 "will not delete this work tree's current branch");
6793 goto done;
6796 err = delete_ref(repo, ref);
6797 done:
6798 if (ref)
6799 got_ref_close(ref);
6800 free(refname);
6801 free(remote_refname);
6802 return err;
6805 static const struct got_error *
6806 add_branch(struct got_repository *repo, const char *branch_name,
6807 struct got_object_id *base_commit_id)
6809 const struct got_error *err = NULL;
6810 struct got_reference *ref = NULL;
6811 char *refname = NULL;
6814 * Don't let the user create a branch name with a leading '-'.
6815 * While technically a valid reference name, this case is usually
6816 * an unintended typo.
6818 if (branch_name[0] == '-')
6819 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6821 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6822 branch_name += 11;
6824 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6825 err = got_error_from_errno("asprintf");
6826 goto done;
6829 err = got_ref_open(&ref, repo, refname, 0);
6830 if (err == NULL) {
6831 err = got_error(GOT_ERR_BRANCH_EXISTS);
6832 goto done;
6833 } else if (err->code != GOT_ERR_NOT_REF)
6834 goto done;
6836 err = got_ref_alloc(&ref, refname, base_commit_id);
6837 if (err)
6838 goto done;
6840 err = got_ref_write(ref, repo);
6841 done:
6842 if (ref)
6843 got_ref_close(ref);
6844 free(refname);
6845 return err;
6848 static const struct got_error *
6849 cmd_branch(int argc, char *argv[])
6851 const struct got_error *error = NULL;
6852 struct got_repository *repo = NULL;
6853 struct got_worktree *worktree = NULL;
6854 char *cwd = NULL, *repo_path = NULL;
6855 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6856 const char *delref = NULL, *commit_id_arg = NULL;
6857 struct got_reference *ref = NULL;
6858 struct got_pathlist_head paths;
6859 struct got_object_id *commit_id = NULL;
6860 char *commit_id_str = NULL;
6861 int *pack_fds = NULL;
6863 TAILQ_INIT(&paths);
6865 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6866 switch (ch) {
6867 case 'c':
6868 commit_id_arg = optarg;
6869 break;
6870 case 'd':
6871 delref = optarg;
6872 break;
6873 case 'l':
6874 do_list = 1;
6875 break;
6876 case 'n':
6877 do_update = 0;
6878 break;
6879 case 'r':
6880 repo_path = realpath(optarg, NULL);
6881 if (repo_path == NULL)
6882 return got_error_from_errno2("realpath",
6883 optarg);
6884 got_path_strip_trailing_slashes(repo_path);
6885 break;
6886 case 't':
6887 sort_by_time = 1;
6888 break;
6889 default:
6890 usage_branch();
6891 /* NOTREACHED */
6895 if (do_list && delref)
6896 option_conflict('l', 'd');
6897 if (sort_by_time && !do_list)
6898 errx(1, "-t option requires -l option");
6900 argc -= optind;
6901 argv += optind;
6903 if (!do_list && !delref && argc == 0)
6904 do_show = 1;
6906 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6907 errx(1, "-c option can only be used when creating a branch");
6909 if (do_list || delref) {
6910 if (argc > 0)
6911 usage_branch();
6912 } else if (!do_show && argc != 1)
6913 usage_branch();
6915 #ifndef PROFILE
6916 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6917 "sendfd unveil", NULL) == -1)
6918 err(1, "pledge");
6919 #endif
6920 cwd = getcwd(NULL, 0);
6921 if (cwd == NULL) {
6922 error = got_error_from_errno("getcwd");
6923 goto done;
6926 error = got_repo_pack_fds_open(&pack_fds);
6927 if (error != NULL)
6928 goto done;
6930 if (repo_path == NULL) {
6931 error = got_worktree_open(&worktree, cwd);
6932 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6933 goto done;
6934 else
6935 error = NULL;
6936 if (worktree) {
6937 repo_path =
6938 strdup(got_worktree_get_repo_path(worktree));
6939 if (repo_path == NULL)
6940 error = got_error_from_errno("strdup");
6941 if (error)
6942 goto done;
6943 } else {
6944 repo_path = strdup(cwd);
6945 if (repo_path == NULL) {
6946 error = got_error_from_errno("strdup");
6947 goto done;
6952 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6953 if (error != NULL)
6954 goto done;
6956 #ifndef PROFILE
6957 if (do_list || do_show) {
6958 /* Remove "cpath" promise. */
6959 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6960 NULL) == -1)
6961 err(1, "pledge");
6963 #endif
6965 error = apply_unveil(got_repo_get_path(repo), do_list,
6966 worktree ? got_worktree_get_root_path(worktree) : NULL);
6967 if (error)
6968 goto done;
6970 if (do_show)
6971 error = show_current_branch(repo, worktree);
6972 else if (do_list)
6973 error = list_branches(repo, worktree, sort_by_time);
6974 else if (delref)
6975 error = delete_branch(repo, worktree, delref);
6976 else {
6977 struct got_reflist_head refs;
6978 TAILQ_INIT(&refs);
6979 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6980 NULL);
6981 if (error)
6982 goto done;
6983 if (commit_id_arg == NULL)
6984 commit_id_arg = worktree ?
6985 got_worktree_get_head_ref_name(worktree) :
6986 GOT_REF_HEAD;
6987 error = got_repo_match_object_id(&commit_id, NULL,
6988 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6989 got_ref_list_free(&refs);
6990 if (error)
6991 goto done;
6992 error = add_branch(repo, argv[0], commit_id);
6993 if (error)
6994 goto done;
6995 if (worktree && do_update) {
6996 struct got_update_progress_arg upa;
6997 char *branch_refname = NULL;
6999 error = got_object_id_str(&commit_id_str, commit_id);
7000 if (error)
7001 goto done;
7002 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7003 worktree);
7004 if (error)
7005 goto done;
7006 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7007 == -1) {
7008 error = got_error_from_errno("asprintf");
7009 goto done;
7011 error = got_ref_open(&ref, repo, branch_refname, 0);
7012 free(branch_refname);
7013 if (error)
7014 goto done;
7015 error = switch_head_ref(ref, commit_id, worktree,
7016 repo);
7017 if (error)
7018 goto done;
7019 error = got_worktree_set_base_commit_id(worktree, repo,
7020 commit_id);
7021 if (error)
7022 goto done;
7023 memset(&upa, 0, sizeof(upa));
7024 error = got_worktree_checkout_files(worktree, &paths,
7025 repo, update_progress, &upa, check_cancelled,
7026 NULL);
7027 if (error)
7028 goto done;
7029 if (upa.did_something) {
7030 printf("Updated to %s: %s\n",
7031 got_worktree_get_head_ref_name(worktree),
7032 commit_id_str);
7034 print_update_progress_stats(&upa);
7037 done:
7038 if (ref)
7039 got_ref_close(ref);
7040 if (repo) {
7041 const struct got_error *close_err = got_repo_close(repo);
7042 if (error == NULL)
7043 error = close_err;
7045 if (worktree)
7046 got_worktree_close(worktree);
7047 if (pack_fds) {
7048 const struct got_error *pack_err =
7049 got_repo_pack_fds_close(pack_fds);
7050 if (error == NULL)
7051 error = pack_err;
7053 free(cwd);
7054 free(repo_path);
7055 free(commit_id);
7056 free(commit_id_str);
7057 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7058 return error;
7062 __dead static void
7063 usage_tag(void)
7065 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7066 "[-r repository-path] [-s signer-id] name\n", getprogname());
7067 exit(1);
7070 #if 0
7071 static const struct got_error *
7072 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7074 const struct got_error *err = NULL;
7075 struct got_reflist_entry *re, *se, *new;
7076 struct got_object_id *re_id, *se_id;
7077 struct got_tag_object *re_tag, *se_tag;
7078 time_t re_time, se_time;
7080 STAILQ_FOREACH(re, tags, entry) {
7081 se = STAILQ_FIRST(sorted);
7082 if (se == NULL) {
7083 err = got_reflist_entry_dup(&new, re);
7084 if (err)
7085 return err;
7086 STAILQ_INSERT_HEAD(sorted, new, entry);
7087 continue;
7088 } else {
7089 err = got_ref_resolve(&re_id, repo, re->ref);
7090 if (err)
7091 break;
7092 err = got_object_open_as_tag(&re_tag, repo, re_id);
7093 free(re_id);
7094 if (err)
7095 break;
7096 re_time = got_object_tag_get_tagger_time(re_tag);
7097 got_object_tag_close(re_tag);
7100 while (se) {
7101 err = got_ref_resolve(&se_id, repo, re->ref);
7102 if (err)
7103 break;
7104 err = got_object_open_as_tag(&se_tag, repo, se_id);
7105 free(se_id);
7106 if (err)
7107 break;
7108 se_time = got_object_tag_get_tagger_time(se_tag);
7109 got_object_tag_close(se_tag);
7111 if (se_time > re_time) {
7112 err = got_reflist_entry_dup(&new, re);
7113 if (err)
7114 return err;
7115 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7116 break;
7118 se = STAILQ_NEXT(se, entry);
7119 continue;
7122 done:
7123 return err;
7125 #endif
7127 static const struct got_error *
7128 get_tag_refname(char **refname, const char *tag_name)
7130 const struct got_error *err;
7132 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7133 *refname = strdup(tag_name);
7134 if (*refname == NULL)
7135 return got_error_from_errno("strdup");
7136 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7137 err = got_error_from_errno("asprintf");
7138 *refname = NULL;
7139 return err;
7142 return NULL;
7145 static const struct got_error *
7146 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7147 const char *allowed_signers, const char *revoked_signers, int verbosity)
7149 static const struct got_error *err = NULL;
7150 struct got_reflist_head refs;
7151 struct got_reflist_entry *re;
7152 char *wanted_refname = NULL;
7153 int bad_sigs = 0;
7155 TAILQ_INIT(&refs);
7157 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7158 if (err)
7159 return err;
7161 if (tag_name) {
7162 struct got_reference *ref;
7163 err = get_tag_refname(&wanted_refname, tag_name);
7164 if (err)
7165 goto done;
7166 /* Wanted tag reference should exist. */
7167 err = got_ref_open(&ref, repo, wanted_refname, 0);
7168 if (err)
7169 goto done;
7170 got_ref_close(ref);
7173 TAILQ_FOREACH(re, &refs, entry) {
7174 const char *refname;
7175 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7176 char datebuf[26];
7177 const char *tagger, *ssh_sig = NULL;
7178 char *sig_msg = NULL;
7179 time_t tagger_time;
7180 struct got_object_id *id;
7181 struct got_tag_object *tag;
7182 struct got_commit_object *commit = NULL;
7184 refname = got_ref_get_name(re->ref);
7185 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7186 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7187 continue;
7188 refname += 10;
7189 refstr = got_ref_to_str(re->ref);
7190 if (refstr == NULL) {
7191 err = got_error_from_errno("got_ref_to_str");
7192 break;
7195 err = got_ref_resolve(&id, repo, re->ref);
7196 if (err)
7197 break;
7198 err = got_object_open_as_tag(&tag, repo, id);
7199 if (err) {
7200 if (err->code != GOT_ERR_OBJ_TYPE) {
7201 free(id);
7202 break;
7204 /* "lightweight" tag */
7205 err = got_object_open_as_commit(&commit, repo, id);
7206 if (err) {
7207 free(id);
7208 break;
7210 tagger = got_object_commit_get_committer(commit);
7211 tagger_time =
7212 got_object_commit_get_committer_time(commit);
7213 err = got_object_id_str(&id_str, id);
7214 free(id);
7215 if (err)
7216 break;
7217 } else {
7218 free(id);
7219 tagger = got_object_tag_get_tagger(tag);
7220 tagger_time = got_object_tag_get_tagger_time(tag);
7221 err = got_object_id_str(&id_str,
7222 got_object_tag_get_object_id(tag));
7223 if (err)
7224 break;
7227 if (tag && verify_tags) {
7228 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7229 got_object_tag_get_message(tag));
7230 if (ssh_sig && allowed_signers == NULL) {
7231 err = got_error_msg(
7232 GOT_ERR_VERIFY_TAG_SIGNATURE,
7233 "SSH signature verification requires "
7234 "setting allowed_signers in "
7235 "got.conf(5)");
7236 break;
7240 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7241 free(refstr);
7242 printf("from: %s\n", tagger);
7243 datestr = get_datestr(&tagger_time, datebuf);
7244 if (datestr)
7245 printf("date: %s UTC\n", datestr);
7246 if (commit)
7247 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7248 else {
7249 switch (got_object_tag_get_object_type(tag)) {
7250 case GOT_OBJ_TYPE_BLOB:
7251 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7252 id_str);
7253 break;
7254 case GOT_OBJ_TYPE_TREE:
7255 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7256 id_str);
7257 break;
7258 case GOT_OBJ_TYPE_COMMIT:
7259 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7260 id_str);
7261 break;
7262 case GOT_OBJ_TYPE_TAG:
7263 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7264 id_str);
7265 break;
7266 default:
7267 break;
7270 free(id_str);
7272 if (ssh_sig) {
7273 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7274 allowed_signers, revoked_signers, verbosity);
7275 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7276 bad_sigs = 1;
7277 else if (err)
7278 break;
7279 printf("signature: %s", sig_msg);
7280 free(sig_msg);
7281 sig_msg = NULL;
7284 if (commit) {
7285 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7286 if (err)
7287 break;
7288 got_object_commit_close(commit);
7289 } else {
7290 tagmsg0 = strdup(got_object_tag_get_message(tag));
7291 got_object_tag_close(tag);
7292 if (tagmsg0 == NULL) {
7293 err = got_error_from_errno("strdup");
7294 break;
7298 tagmsg = tagmsg0;
7299 do {
7300 line = strsep(&tagmsg, "\n");
7301 if (line)
7302 printf(" %s\n", line);
7303 } while (line);
7304 free(tagmsg0);
7306 done:
7307 got_ref_list_free(&refs);
7308 free(wanted_refname);
7310 if (err == NULL && bad_sigs)
7311 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7312 return err;
7315 static const struct got_error *
7316 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7317 const char *tag_name, const char *repo_path)
7319 const struct got_error *err = NULL;
7320 char *template = NULL, *initial_content = NULL;
7321 char *editor = NULL;
7322 int initial_content_len;
7323 int fd = -1;
7325 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7326 err = got_error_from_errno("asprintf");
7327 goto done;
7330 initial_content_len = asprintf(&initial_content,
7331 "\n# tagging commit %s as %s\n",
7332 commit_id_str, tag_name);
7333 if (initial_content_len == -1) {
7334 err = got_error_from_errno("asprintf");
7335 goto done;
7338 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7339 if (err)
7340 goto done;
7342 if (write(fd, initial_content, initial_content_len) == -1) {
7343 err = got_error_from_errno2("write", *tagmsg_path);
7344 goto done;
7347 err = get_editor(&editor);
7348 if (err)
7349 goto done;
7350 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7351 initial_content_len, 1);
7352 done:
7353 free(initial_content);
7354 free(template);
7355 free(editor);
7357 if (fd != -1 && close(fd) == -1 && err == NULL)
7358 err = got_error_from_errno2("close", *tagmsg_path);
7360 if (err) {
7361 free(*tagmsg);
7362 *tagmsg = NULL;
7364 return err;
7367 static const struct got_error *
7368 add_tag(struct got_repository *repo, const char *tagger,
7369 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7370 const char *signer_id, int verbosity)
7372 const struct got_error *err = NULL;
7373 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7374 char *label = NULL, *commit_id_str = NULL;
7375 struct got_reference *ref = NULL;
7376 char *refname = NULL, *tagmsg = NULL;
7377 char *tagmsg_path = NULL, *tag_id_str = NULL;
7378 int preserve_tagmsg = 0;
7379 struct got_reflist_head refs;
7381 TAILQ_INIT(&refs);
7384 * Don't let the user create a tag name with a leading '-'.
7385 * While technically a valid reference name, this case is usually
7386 * an unintended typo.
7388 if (tag_name[0] == '-')
7389 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7391 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7392 if (err)
7393 goto done;
7395 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7396 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7397 if (err)
7398 goto done;
7400 err = got_object_id_str(&commit_id_str, commit_id);
7401 if (err)
7402 goto done;
7404 err = get_tag_refname(&refname, tag_name);
7405 if (err)
7406 goto done;
7407 if (strncmp("refs/tags/", tag_name, 10) == 0)
7408 tag_name += 10;
7410 err = got_ref_open(&ref, repo, refname, 0);
7411 if (err == NULL) {
7412 err = got_error(GOT_ERR_TAG_EXISTS);
7413 goto done;
7414 } else if (err->code != GOT_ERR_NOT_REF)
7415 goto done;
7417 if (tagmsg_arg == NULL) {
7418 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7419 tag_name, got_repo_get_path(repo));
7420 if (err) {
7421 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7422 tagmsg_path != NULL)
7423 preserve_tagmsg = 1;
7424 goto done;
7426 /* Editor is done; we can now apply unveil(2) */
7427 err = got_sigs_apply_unveil();
7428 if (err)
7429 goto done;
7430 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7431 if (err)
7432 goto done;
7435 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7436 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7437 verbosity);
7438 if (err) {
7439 if (tagmsg_path)
7440 preserve_tagmsg = 1;
7441 goto done;
7444 err = got_ref_alloc(&ref, refname, tag_id);
7445 if (err) {
7446 if (tagmsg_path)
7447 preserve_tagmsg = 1;
7448 goto done;
7451 err = got_ref_write(ref, repo);
7452 if (err) {
7453 if (tagmsg_path)
7454 preserve_tagmsg = 1;
7455 goto done;
7458 err = got_object_id_str(&tag_id_str, tag_id);
7459 if (err) {
7460 if (tagmsg_path)
7461 preserve_tagmsg = 1;
7462 goto done;
7464 printf("Created tag %s\n", tag_id_str);
7465 done:
7466 if (preserve_tagmsg) {
7467 fprintf(stderr, "%s: tag message preserved in %s\n",
7468 getprogname(), tagmsg_path);
7469 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7470 err = got_error_from_errno2("unlink", tagmsg_path);
7471 free(tag_id_str);
7472 if (ref)
7473 got_ref_close(ref);
7474 free(commit_id);
7475 free(commit_id_str);
7476 free(refname);
7477 free(tagmsg);
7478 free(tagmsg_path);
7479 got_ref_list_free(&refs);
7480 return err;
7483 static const struct got_error *
7484 cmd_tag(int argc, char *argv[])
7486 const struct got_error *error = NULL;
7487 struct got_repository *repo = NULL;
7488 struct got_worktree *worktree = NULL;
7489 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7490 char *gitconfig_path = NULL, *tagger = NULL;
7491 char *allowed_signers = NULL, *revoked_signers = NULL;
7492 char *signer_id = NULL;
7493 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7494 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7495 int *pack_fds = NULL;
7497 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7498 switch (ch) {
7499 case 'c':
7500 commit_id_arg = optarg;
7501 break;
7502 case 'l':
7503 do_list = 1;
7504 break;
7505 case 'm':
7506 tagmsg = optarg;
7507 break;
7508 case 'r':
7509 repo_path = realpath(optarg, NULL);
7510 if (repo_path == NULL) {
7511 error = got_error_from_errno2("realpath",
7512 optarg);
7513 goto done;
7515 got_path_strip_trailing_slashes(repo_path);
7516 break;
7517 case 's':
7518 signer_id = strdup(optarg);
7519 if (signer_id == NULL) {
7520 error = got_error_from_errno("strdup");
7521 goto done;
7523 break;
7524 case 'V':
7525 verify_tags = 1;
7526 break;
7527 case 'v':
7528 if (verbosity < 0)
7529 verbosity = 0;
7530 else if (verbosity < 3)
7531 verbosity++;
7532 break;
7533 default:
7534 usage_tag();
7535 /* NOTREACHED */
7539 argc -= optind;
7540 argv += optind;
7542 if (do_list || verify_tags) {
7543 if (commit_id_arg != NULL)
7544 errx(1,
7545 "-c option can only be used when creating a tag");
7546 if (tagmsg) {
7547 if (do_list)
7548 option_conflict('l', 'm');
7549 else
7550 option_conflict('V', 'm');
7552 if (signer_id) {
7553 if (do_list)
7554 option_conflict('l', 's');
7555 else
7556 option_conflict('V', 's');
7558 if (argc > 1)
7559 usage_tag();
7560 } else if (argc != 1)
7561 usage_tag();
7563 if (argc == 1)
7564 tag_name = argv[0];
7566 #ifndef PROFILE
7567 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7568 "sendfd unveil", NULL) == -1)
7569 err(1, "pledge");
7570 #endif
7571 cwd = getcwd(NULL, 0);
7572 if (cwd == NULL) {
7573 error = got_error_from_errno("getcwd");
7574 goto done;
7577 error = got_repo_pack_fds_open(&pack_fds);
7578 if (error != NULL)
7579 goto done;
7581 if (repo_path == NULL) {
7582 error = got_worktree_open(&worktree, cwd);
7583 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7584 goto done;
7585 else
7586 error = NULL;
7587 if (worktree) {
7588 repo_path =
7589 strdup(got_worktree_get_repo_path(worktree));
7590 if (repo_path == NULL)
7591 error = got_error_from_errno("strdup");
7592 if (error)
7593 goto done;
7594 } else {
7595 repo_path = strdup(cwd);
7596 if (repo_path == NULL) {
7597 error = got_error_from_errno("strdup");
7598 goto done;
7603 if (do_list || verify_tags) {
7604 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7605 if (error != NULL)
7606 goto done;
7607 error = get_allowed_signers(&allowed_signers, repo, worktree);
7608 if (error)
7609 goto done;
7610 error = get_revoked_signers(&revoked_signers, repo, worktree);
7611 if (error)
7612 goto done;
7613 if (worktree) {
7614 /* Release work tree lock. */
7615 got_worktree_close(worktree);
7616 worktree = NULL;
7620 * Remove "cpath" promise unless needed for signature tmpfile
7621 * creation.
7623 if (verify_tags)
7624 got_sigs_apply_unveil();
7625 else {
7626 #ifndef PROFILE
7627 if (pledge("stdio rpath wpath flock proc exec sendfd "
7628 "unveil", NULL) == -1)
7629 err(1, "pledge");
7630 #endif
7632 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7633 if (error)
7634 goto done;
7635 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7636 revoked_signers, verbosity);
7637 } else {
7638 error = get_gitconfig_path(&gitconfig_path);
7639 if (error)
7640 goto done;
7641 error = got_repo_open(&repo, repo_path, gitconfig_path,
7642 pack_fds);
7643 if (error != NULL)
7644 goto done;
7646 error = get_author(&tagger, repo, worktree);
7647 if (error)
7648 goto done;
7649 if (signer_id == NULL) {
7650 error = get_signer_id(&signer_id, repo, worktree);
7651 if (error)
7652 goto done;
7655 if (tagmsg) {
7656 if (signer_id) {
7657 error = got_sigs_apply_unveil();
7658 if (error)
7659 goto done;
7661 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7662 if (error)
7663 goto done;
7666 if (commit_id_arg == NULL) {
7667 struct got_reference *head_ref;
7668 struct got_object_id *commit_id;
7669 error = got_ref_open(&head_ref, repo,
7670 worktree ? got_worktree_get_head_ref_name(worktree)
7671 : GOT_REF_HEAD, 0);
7672 if (error)
7673 goto done;
7674 error = got_ref_resolve(&commit_id, repo, head_ref);
7675 got_ref_close(head_ref);
7676 if (error)
7677 goto done;
7678 error = got_object_id_str(&commit_id_str, commit_id);
7679 free(commit_id);
7680 if (error)
7681 goto done;
7684 if (worktree) {
7685 /* Release work tree lock. */
7686 got_worktree_close(worktree);
7687 worktree = NULL;
7690 error = add_tag(repo, tagger, tag_name,
7691 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7692 signer_id, verbosity);
7694 done:
7695 if (repo) {
7696 const struct got_error *close_err = got_repo_close(repo);
7697 if (error == NULL)
7698 error = close_err;
7700 if (worktree)
7701 got_worktree_close(worktree);
7702 if (pack_fds) {
7703 const struct got_error *pack_err =
7704 got_repo_pack_fds_close(pack_fds);
7705 if (error == NULL)
7706 error = pack_err;
7708 free(cwd);
7709 free(repo_path);
7710 free(gitconfig_path);
7711 free(commit_id_str);
7712 free(tagger);
7713 free(allowed_signers);
7714 free(revoked_signers);
7715 free(signer_id);
7716 return error;
7719 __dead static void
7720 usage_add(void)
7722 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7723 exit(1);
7726 static const struct got_error *
7727 add_progress(void *arg, unsigned char status, const char *path)
7729 while (path[0] == '/')
7730 path++;
7731 printf("%c %s\n", status, path);
7732 return NULL;
7735 static const struct got_error *
7736 cmd_add(int argc, char *argv[])
7738 const struct got_error *error = NULL;
7739 struct got_repository *repo = NULL;
7740 struct got_worktree *worktree = NULL;
7741 char *cwd = NULL;
7742 struct got_pathlist_head paths;
7743 struct got_pathlist_entry *pe;
7744 int ch, can_recurse = 0, no_ignores = 0;
7745 int *pack_fds = NULL;
7747 TAILQ_INIT(&paths);
7749 while ((ch = getopt(argc, argv, "IR")) != -1) {
7750 switch (ch) {
7751 case 'I':
7752 no_ignores = 1;
7753 break;
7754 case 'R':
7755 can_recurse = 1;
7756 break;
7757 default:
7758 usage_add();
7759 /* NOTREACHED */
7763 argc -= optind;
7764 argv += optind;
7766 #ifndef PROFILE
7767 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7768 NULL) == -1)
7769 err(1, "pledge");
7770 #endif
7771 if (argc < 1)
7772 usage_add();
7774 cwd = getcwd(NULL, 0);
7775 if (cwd == NULL) {
7776 error = got_error_from_errno("getcwd");
7777 goto done;
7780 error = got_repo_pack_fds_open(&pack_fds);
7781 if (error != NULL)
7782 goto done;
7784 error = got_worktree_open(&worktree, cwd);
7785 if (error) {
7786 if (error->code == GOT_ERR_NOT_WORKTREE)
7787 error = wrap_not_worktree_error(error, "add", cwd);
7788 goto done;
7791 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7792 NULL, pack_fds);
7793 if (error != NULL)
7794 goto done;
7796 error = apply_unveil(got_repo_get_path(repo), 1,
7797 got_worktree_get_root_path(worktree));
7798 if (error)
7799 goto done;
7801 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7802 if (error)
7803 goto done;
7805 if (!can_recurse) {
7806 char *ondisk_path;
7807 struct stat sb;
7808 TAILQ_FOREACH(pe, &paths, entry) {
7809 if (asprintf(&ondisk_path, "%s/%s",
7810 got_worktree_get_root_path(worktree),
7811 pe->path) == -1) {
7812 error = got_error_from_errno("asprintf");
7813 goto done;
7815 if (lstat(ondisk_path, &sb) == -1) {
7816 if (errno == ENOENT) {
7817 free(ondisk_path);
7818 continue;
7820 error = got_error_from_errno2("lstat",
7821 ondisk_path);
7822 free(ondisk_path);
7823 goto done;
7825 free(ondisk_path);
7826 if (S_ISDIR(sb.st_mode)) {
7827 error = got_error_msg(GOT_ERR_BAD_PATH,
7828 "adding directories requires -R option");
7829 goto done;
7834 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7835 NULL, repo, no_ignores);
7836 done:
7837 if (repo) {
7838 const struct got_error *close_err = got_repo_close(repo);
7839 if (error == NULL)
7840 error = close_err;
7842 if (worktree)
7843 got_worktree_close(worktree);
7844 if (pack_fds) {
7845 const struct got_error *pack_err =
7846 got_repo_pack_fds_close(pack_fds);
7847 if (error == NULL)
7848 error = pack_err;
7850 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7851 free(cwd);
7852 return error;
7855 __dead static void
7856 usage_remove(void)
7858 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7859 getprogname());
7860 exit(1);
7863 static const struct got_error *
7864 print_remove_status(void *arg, unsigned char status,
7865 unsigned char staged_status, const char *path)
7867 while (path[0] == '/')
7868 path++;
7869 if (status == GOT_STATUS_NONEXISTENT)
7870 return NULL;
7871 if (status == staged_status && (status == GOT_STATUS_DELETE))
7872 status = GOT_STATUS_NO_CHANGE;
7873 printf("%c%c %s\n", status, staged_status, path);
7874 return NULL;
7877 static const struct got_error *
7878 cmd_remove(int argc, char *argv[])
7880 const struct got_error *error = NULL;
7881 struct got_worktree *worktree = NULL;
7882 struct got_repository *repo = NULL;
7883 const char *status_codes = NULL;
7884 char *cwd = NULL;
7885 struct got_pathlist_head paths;
7886 struct got_pathlist_entry *pe;
7887 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7888 int ignore_missing_paths = 0;
7889 int *pack_fds = NULL;
7891 TAILQ_INIT(&paths);
7893 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7894 switch (ch) {
7895 case 'f':
7896 delete_local_mods = 1;
7897 ignore_missing_paths = 1;
7898 break;
7899 case 'k':
7900 keep_on_disk = 1;
7901 break;
7902 case 'R':
7903 can_recurse = 1;
7904 break;
7905 case 's':
7906 for (i = 0; i < strlen(optarg); i++) {
7907 switch (optarg[i]) {
7908 case GOT_STATUS_MODIFY:
7909 delete_local_mods = 1;
7910 break;
7911 case GOT_STATUS_MISSING:
7912 ignore_missing_paths = 1;
7913 break;
7914 default:
7915 errx(1, "invalid status code '%c'",
7916 optarg[i]);
7919 status_codes = optarg;
7920 break;
7921 default:
7922 usage_remove();
7923 /* NOTREACHED */
7927 argc -= optind;
7928 argv += optind;
7930 #ifndef PROFILE
7931 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7932 NULL) == -1)
7933 err(1, "pledge");
7934 #endif
7935 if (argc < 1)
7936 usage_remove();
7938 cwd = getcwd(NULL, 0);
7939 if (cwd == NULL) {
7940 error = got_error_from_errno("getcwd");
7941 goto done;
7944 error = got_repo_pack_fds_open(&pack_fds);
7945 if (error != NULL)
7946 goto done;
7948 error = got_worktree_open(&worktree, cwd);
7949 if (error) {
7950 if (error->code == GOT_ERR_NOT_WORKTREE)
7951 error = wrap_not_worktree_error(error, "remove", cwd);
7952 goto done;
7955 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7956 NULL, pack_fds);
7957 if (error)
7958 goto done;
7960 error = apply_unveil(got_repo_get_path(repo), 1,
7961 got_worktree_get_root_path(worktree));
7962 if (error)
7963 goto done;
7965 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7966 if (error)
7967 goto done;
7969 if (!can_recurse) {
7970 char *ondisk_path;
7971 struct stat sb;
7972 TAILQ_FOREACH(pe, &paths, entry) {
7973 if (asprintf(&ondisk_path, "%s/%s",
7974 got_worktree_get_root_path(worktree),
7975 pe->path) == -1) {
7976 error = got_error_from_errno("asprintf");
7977 goto done;
7979 if (lstat(ondisk_path, &sb) == -1) {
7980 if (errno == ENOENT) {
7981 free(ondisk_path);
7982 continue;
7984 error = got_error_from_errno2("lstat",
7985 ondisk_path);
7986 free(ondisk_path);
7987 goto done;
7989 free(ondisk_path);
7990 if (S_ISDIR(sb.st_mode)) {
7991 error = got_error_msg(GOT_ERR_BAD_PATH,
7992 "removing directories requires -R option");
7993 goto done;
7998 error = got_worktree_schedule_delete(worktree, &paths,
7999 delete_local_mods, status_codes, print_remove_status, NULL,
8000 repo, keep_on_disk, ignore_missing_paths);
8001 done:
8002 if (repo) {
8003 const struct got_error *close_err = got_repo_close(repo);
8004 if (error == NULL)
8005 error = close_err;
8007 if (worktree)
8008 got_worktree_close(worktree);
8009 if (pack_fds) {
8010 const struct got_error *pack_err =
8011 got_repo_pack_fds_close(pack_fds);
8012 if (error == NULL)
8013 error = pack_err;
8015 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8016 free(cwd);
8017 return error;
8020 __dead static void
8021 usage_patch(void)
8023 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8024 "[patchfile]\n", getprogname());
8025 exit(1);
8028 static const struct got_error *
8029 patch_from_stdin(int *patchfd)
8031 const struct got_error *err = NULL;
8032 ssize_t r;
8033 char buf[BUFSIZ];
8034 sig_t sighup, sigint, sigquit;
8036 *patchfd = got_opentempfd();
8037 if (*patchfd == -1)
8038 return got_error_from_errno("got_opentempfd");
8040 sighup = signal(SIGHUP, SIG_DFL);
8041 sigint = signal(SIGINT, SIG_DFL);
8042 sigquit = signal(SIGQUIT, SIG_DFL);
8044 for (;;) {
8045 r = read(0, buf, sizeof(buf));
8046 if (r == -1) {
8047 err = got_error_from_errno("read");
8048 break;
8050 if (r == 0)
8051 break;
8052 if (write(*patchfd, buf, r) == -1) {
8053 err = got_error_from_errno("write");
8054 break;
8058 signal(SIGHUP, sighup);
8059 signal(SIGINT, sigint);
8060 signal(SIGQUIT, sigquit);
8062 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8063 err = got_error_from_errno("lseek");
8065 if (err != NULL) {
8066 close(*patchfd);
8067 *patchfd = -1;
8070 return err;
8073 static const struct got_error *
8074 patch_progress(void *arg, const char *old, const char *new,
8075 unsigned char status, const struct got_error *error, int old_from,
8076 int old_lines, int new_from, int new_lines, int offset,
8077 int ws_mangled, const struct got_error *hunk_err)
8079 const char *path = new == NULL ? old : new;
8081 while (*path == '/')
8082 path++;
8084 if (status != 0)
8085 printf("%c %s\n", status, path);
8087 if (error != NULL)
8088 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8090 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8091 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8092 old_lines, new_from, new_lines);
8093 if (hunk_err != NULL)
8094 printf("%s\n", hunk_err->msg);
8095 else if (offset != 0)
8096 printf("applied with offset %d\n", offset);
8097 else
8098 printf("hunk contains mangled whitespace\n");
8101 return NULL;
8104 static const struct got_error *
8105 cmd_patch(int argc, char *argv[])
8107 const struct got_error *error = NULL, *close_error = NULL;
8108 struct got_worktree *worktree = NULL;
8109 struct got_repository *repo = NULL;
8110 struct got_reflist_head refs;
8111 struct got_object_id *commit_id = NULL;
8112 const char *commit_id_str = NULL;
8113 struct stat sb;
8114 const char *errstr;
8115 char *cwd = NULL;
8116 int ch, nop = 0, strip = -1, reverse = 0;
8117 int patchfd;
8118 int *pack_fds = NULL;
8120 TAILQ_INIT(&refs);
8122 #ifndef PROFILE
8123 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8124 "unveil", NULL) == -1)
8125 err(1, "pledge");
8126 #endif
8128 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8129 switch (ch) {
8130 case 'c':
8131 commit_id_str = optarg;
8132 break;
8133 case 'n':
8134 nop = 1;
8135 break;
8136 case 'p':
8137 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8138 if (errstr != NULL)
8139 errx(1, "pathname strip count is %s: %s",
8140 errstr, optarg);
8141 break;
8142 case 'R':
8143 reverse = 1;
8144 break;
8145 default:
8146 usage_patch();
8147 /* NOTREACHED */
8151 argc -= optind;
8152 argv += optind;
8154 if (argc == 0) {
8155 error = patch_from_stdin(&patchfd);
8156 if (error)
8157 return error;
8158 } else if (argc == 1) {
8159 patchfd = open(argv[0], O_RDONLY);
8160 if (patchfd == -1) {
8161 error = got_error_from_errno2("open", argv[0]);
8162 return error;
8164 if (fstat(patchfd, &sb) == -1) {
8165 error = got_error_from_errno2("fstat", argv[0]);
8166 goto done;
8168 if (!S_ISREG(sb.st_mode)) {
8169 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8170 goto done;
8172 } else
8173 usage_patch();
8175 if ((cwd = getcwd(NULL, 0)) == NULL) {
8176 error = got_error_from_errno("getcwd");
8177 goto done;
8180 error = got_repo_pack_fds_open(&pack_fds);
8181 if (error != NULL)
8182 goto done;
8184 error = got_worktree_open(&worktree, cwd);
8185 if (error != NULL)
8186 goto done;
8188 const char *repo_path = got_worktree_get_repo_path(worktree);
8189 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8190 if (error != NULL)
8191 goto done;
8193 error = apply_unveil(got_repo_get_path(repo), 0,
8194 got_worktree_get_root_path(worktree));
8195 if (error != NULL)
8196 goto done;
8198 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8199 if (error)
8200 goto done;
8202 if (commit_id_str != NULL) {
8203 error = got_repo_match_object_id(&commit_id, NULL,
8204 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8205 if (error)
8206 goto done;
8209 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8210 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8212 done:
8213 got_ref_list_free(&refs);
8214 free(commit_id);
8215 if (repo) {
8216 close_error = got_repo_close(repo);
8217 if (error == NULL)
8218 error = close_error;
8220 if (worktree != NULL) {
8221 close_error = got_worktree_close(worktree);
8222 if (error == NULL)
8223 error = close_error;
8225 if (pack_fds) {
8226 const struct got_error *pack_err =
8227 got_repo_pack_fds_close(pack_fds);
8228 if (error == NULL)
8229 error = pack_err;
8231 free(cwd);
8232 return error;
8235 __dead static void
8236 usage_revert(void)
8238 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8239 getprogname());
8240 exit(1);
8243 static const struct got_error *
8244 revert_progress(void *arg, unsigned char status, const char *path)
8246 if (status == GOT_STATUS_UNVERSIONED)
8247 return NULL;
8249 while (path[0] == '/')
8250 path++;
8251 printf("%c %s\n", status, path);
8252 return NULL;
8255 struct choose_patch_arg {
8256 FILE *patch_script_file;
8257 const char *action;
8260 static const struct got_error *
8261 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8262 int nchanges, const char *action)
8264 const struct got_error *err;
8265 char *line = NULL;
8266 size_t linesize = 0;
8267 ssize_t linelen;
8269 switch (status) {
8270 case GOT_STATUS_ADD:
8271 printf("A %s\n%s this addition? [y/n] ", path, action);
8272 break;
8273 case GOT_STATUS_DELETE:
8274 printf("D %s\n%s this deletion? [y/n] ", path, action);
8275 break;
8276 case GOT_STATUS_MODIFY:
8277 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8278 return got_error_from_errno("fseek");
8279 printf(GOT_COMMIT_SEP_STR);
8280 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8281 printf("%s", line);
8282 if (linelen == -1 && ferror(patch_file)) {
8283 err = got_error_from_errno("getline");
8284 free(line);
8285 return err;
8287 free(line);
8288 printf(GOT_COMMIT_SEP_STR);
8289 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8290 path, n, nchanges, action);
8291 break;
8292 default:
8293 return got_error_path(path, GOT_ERR_FILE_STATUS);
8296 fflush(stdout);
8297 return NULL;
8300 static const struct got_error *
8301 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8302 FILE *patch_file, int n, int nchanges)
8304 const struct got_error *err = NULL;
8305 char *line = NULL;
8306 size_t linesize = 0;
8307 ssize_t linelen;
8308 int resp = ' ';
8309 struct choose_patch_arg *a = arg;
8311 *choice = GOT_PATCH_CHOICE_NONE;
8313 if (a->patch_script_file) {
8314 char *nl;
8315 err = show_change(status, path, patch_file, n, nchanges,
8316 a->action);
8317 if (err)
8318 return err;
8319 linelen = getline(&line, &linesize, a->patch_script_file);
8320 if (linelen == -1) {
8321 if (ferror(a->patch_script_file))
8322 return got_error_from_errno("getline");
8323 return NULL;
8325 nl = strchr(line, '\n');
8326 if (nl)
8327 *nl = '\0';
8328 if (strcmp(line, "y") == 0) {
8329 *choice = GOT_PATCH_CHOICE_YES;
8330 printf("y\n");
8331 } else if (strcmp(line, "n") == 0) {
8332 *choice = GOT_PATCH_CHOICE_NO;
8333 printf("n\n");
8334 } else if (strcmp(line, "q") == 0 &&
8335 status == GOT_STATUS_MODIFY) {
8336 *choice = GOT_PATCH_CHOICE_QUIT;
8337 printf("q\n");
8338 } else
8339 printf("invalid response '%s'\n", line);
8340 free(line);
8341 return NULL;
8344 while (resp != 'y' && resp != 'n' && resp != 'q') {
8345 err = show_change(status, path, patch_file, n, nchanges,
8346 a->action);
8347 if (err)
8348 return err;
8349 resp = getchar();
8350 if (resp == '\n')
8351 resp = getchar();
8352 if (status == GOT_STATUS_MODIFY) {
8353 if (resp != 'y' && resp != 'n' && resp != 'q') {
8354 printf("invalid response '%c'\n", resp);
8355 resp = ' ';
8357 } else if (resp != 'y' && resp != 'n') {
8358 printf("invalid response '%c'\n", resp);
8359 resp = ' ';
8363 if (resp == 'y')
8364 *choice = GOT_PATCH_CHOICE_YES;
8365 else if (resp == 'n')
8366 *choice = GOT_PATCH_CHOICE_NO;
8367 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8368 *choice = GOT_PATCH_CHOICE_QUIT;
8370 return NULL;
8373 static const struct got_error *
8374 cmd_revert(int argc, char *argv[])
8376 const struct got_error *error = NULL;
8377 struct got_worktree *worktree = NULL;
8378 struct got_repository *repo = NULL;
8379 char *cwd = NULL, *path = NULL;
8380 struct got_pathlist_head paths;
8381 struct got_pathlist_entry *pe;
8382 int ch, can_recurse = 0, pflag = 0;
8383 FILE *patch_script_file = NULL;
8384 const char *patch_script_path = NULL;
8385 struct choose_patch_arg cpa;
8386 int *pack_fds = NULL;
8388 TAILQ_INIT(&paths);
8390 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8391 switch (ch) {
8392 case 'F':
8393 patch_script_path = optarg;
8394 break;
8395 case 'p':
8396 pflag = 1;
8397 break;
8398 case 'R':
8399 can_recurse = 1;
8400 break;
8401 default:
8402 usage_revert();
8403 /* NOTREACHED */
8407 argc -= optind;
8408 argv += optind;
8410 #ifndef PROFILE
8411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8412 "unveil", NULL) == -1)
8413 err(1, "pledge");
8414 #endif
8415 if (argc < 1)
8416 usage_revert();
8417 if (patch_script_path && !pflag)
8418 errx(1, "-F option can only be used together with -p option");
8420 cwd = getcwd(NULL, 0);
8421 if (cwd == NULL) {
8422 error = got_error_from_errno("getcwd");
8423 goto done;
8426 error = got_repo_pack_fds_open(&pack_fds);
8427 if (error != NULL)
8428 goto done;
8430 error = got_worktree_open(&worktree, cwd);
8431 if (error) {
8432 if (error->code == GOT_ERR_NOT_WORKTREE)
8433 error = wrap_not_worktree_error(error, "revert", cwd);
8434 goto done;
8437 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8438 NULL, pack_fds);
8439 if (error != NULL)
8440 goto done;
8442 if (patch_script_path) {
8443 patch_script_file = fopen(patch_script_path, "re");
8444 if (patch_script_file == NULL) {
8445 error = got_error_from_errno2("fopen",
8446 patch_script_path);
8447 goto done;
8450 error = apply_unveil(got_repo_get_path(repo), 1,
8451 got_worktree_get_root_path(worktree));
8452 if (error)
8453 goto done;
8455 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8456 if (error)
8457 goto done;
8459 if (!can_recurse) {
8460 char *ondisk_path;
8461 struct stat sb;
8462 TAILQ_FOREACH(pe, &paths, entry) {
8463 if (asprintf(&ondisk_path, "%s/%s",
8464 got_worktree_get_root_path(worktree),
8465 pe->path) == -1) {
8466 error = got_error_from_errno("asprintf");
8467 goto done;
8469 if (lstat(ondisk_path, &sb) == -1) {
8470 if (errno == ENOENT) {
8471 free(ondisk_path);
8472 continue;
8474 error = got_error_from_errno2("lstat",
8475 ondisk_path);
8476 free(ondisk_path);
8477 goto done;
8479 free(ondisk_path);
8480 if (S_ISDIR(sb.st_mode)) {
8481 error = got_error_msg(GOT_ERR_BAD_PATH,
8482 "reverting directories requires -R option");
8483 goto done;
8488 cpa.patch_script_file = patch_script_file;
8489 cpa.action = "revert";
8490 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8491 pflag ? choose_patch : NULL, &cpa, repo);
8492 done:
8493 if (patch_script_file && fclose(patch_script_file) == EOF &&
8494 error == NULL)
8495 error = got_error_from_errno2("fclose", patch_script_path);
8496 if (repo) {
8497 const struct got_error *close_err = got_repo_close(repo);
8498 if (error == NULL)
8499 error = close_err;
8501 if (worktree)
8502 got_worktree_close(worktree);
8503 if (pack_fds) {
8504 const struct got_error *pack_err =
8505 got_repo_pack_fds_close(pack_fds);
8506 if (error == NULL)
8507 error = pack_err;
8509 free(path);
8510 free(cwd);
8511 return error;
8514 __dead static void
8515 usage_commit(void)
8517 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8518 "[-m message] [path ...]\n", getprogname());
8519 exit(1);
8522 struct collect_commit_logmsg_arg {
8523 const char *cmdline_log;
8524 const char *prepared_log;
8525 int non_interactive;
8526 const char *editor;
8527 const char *worktree_path;
8528 const char *branch_name;
8529 const char *repo_path;
8530 char *logmsg_path;
8534 static const struct got_error *
8535 read_prepared_logmsg(char **logmsg, const char *path)
8537 const struct got_error *err = NULL;
8538 FILE *f = NULL;
8539 struct stat sb;
8540 size_t r;
8542 *logmsg = NULL;
8543 memset(&sb, 0, sizeof(sb));
8545 f = fopen(path, "re");
8546 if (f == NULL)
8547 return got_error_from_errno2("fopen", path);
8549 if (fstat(fileno(f), &sb) == -1) {
8550 err = got_error_from_errno2("fstat", path);
8551 goto done;
8553 if (sb.st_size == 0) {
8554 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8555 goto done;
8558 *logmsg = malloc(sb.st_size + 1);
8559 if (*logmsg == NULL) {
8560 err = got_error_from_errno("malloc");
8561 goto done;
8564 r = fread(*logmsg, 1, sb.st_size, f);
8565 if (r != sb.st_size) {
8566 if (ferror(f))
8567 err = got_error_from_errno2("fread", path);
8568 else
8569 err = got_error(GOT_ERR_IO);
8570 goto done;
8572 (*logmsg)[sb.st_size] = '\0';
8573 done:
8574 if (fclose(f) == EOF && err == NULL)
8575 err = got_error_from_errno2("fclose", path);
8576 if (err) {
8577 free(*logmsg);
8578 *logmsg = NULL;
8580 return err;
8583 static const struct got_error *
8584 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8585 const char *diff_path, char **logmsg, void *arg)
8587 char *initial_content = NULL;
8588 struct got_pathlist_entry *pe;
8589 const struct got_error *err = NULL;
8590 char *template = NULL;
8591 struct collect_commit_logmsg_arg *a = arg;
8592 int initial_content_len;
8593 int fd = -1;
8594 size_t len;
8596 /* if a message was specified on the command line, just use it */
8597 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8598 len = strlen(a->cmdline_log) + 1;
8599 *logmsg = malloc(len + 1);
8600 if (*logmsg == NULL)
8601 return got_error_from_errno("malloc");
8602 strlcpy(*logmsg, a->cmdline_log, len);
8603 return NULL;
8604 } else if (a->prepared_log != NULL && a->non_interactive)
8605 return read_prepared_logmsg(logmsg, a->prepared_log);
8607 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8608 return got_error_from_errno("asprintf");
8610 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8611 if (err)
8612 goto done;
8614 if (a->prepared_log) {
8615 char *msg;
8616 err = read_prepared_logmsg(&msg, a->prepared_log);
8617 if (err)
8618 goto done;
8619 if (write(fd, msg, strlen(msg)) == -1) {
8620 err = got_error_from_errno2("write", a->logmsg_path);
8621 free(msg);
8622 goto done;
8624 free(msg);
8627 initial_content_len = asprintf(&initial_content,
8628 "\n# changes to be committed on branch %s:\n",
8629 a->branch_name);
8630 if (initial_content_len == -1) {
8631 err = got_error_from_errno("asprintf");
8632 goto done;
8635 if (write(fd, initial_content, initial_content_len) == -1) {
8636 err = got_error_from_errno2("write", a->logmsg_path);
8637 goto done;
8640 TAILQ_FOREACH(pe, commitable_paths, entry) {
8641 struct got_commitable *ct = pe->data;
8642 dprintf(fd, "# %c %s\n",
8643 got_commitable_get_status(ct),
8644 got_commitable_get_path(ct));
8647 if (diff_path) {
8648 dprintf(fd, "# detailed changes can be viewed in %s\n",
8649 diff_path);
8652 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8653 initial_content_len, a->prepared_log ? 0 : 1);
8654 done:
8655 free(initial_content);
8656 free(template);
8658 if (fd != -1 && close(fd) == -1 && err == NULL)
8659 err = got_error_from_errno2("close", a->logmsg_path);
8661 /* Editor is done; we can now apply unveil(2) */
8662 if (err == NULL)
8663 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8664 if (err) {
8665 free(*logmsg);
8666 *logmsg = NULL;
8668 return err;
8671 static const struct got_error *
8672 cmd_commit(int argc, char *argv[])
8674 const struct got_error *error = NULL;
8675 struct got_worktree *worktree = NULL;
8676 struct got_repository *repo = NULL;
8677 char *cwd = NULL, *id_str = NULL;
8678 struct got_object_id *id = NULL;
8679 const char *logmsg = NULL;
8680 char *prepared_logmsg = NULL;
8681 struct collect_commit_logmsg_arg cl_arg;
8682 const char *author = NULL;
8683 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8684 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8685 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8686 int show_diff = 1;
8687 struct got_pathlist_head paths;
8688 int *pack_fds = NULL;
8690 TAILQ_INIT(&paths);
8691 cl_arg.logmsg_path = NULL;
8693 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8694 switch (ch) {
8695 case 'A':
8696 author = optarg;
8697 error = valid_author(author);
8698 if (error)
8699 return error;
8700 break;
8701 case 'F':
8702 if (logmsg != NULL)
8703 option_conflict('F', 'm');
8704 prepared_logmsg = realpath(optarg, NULL);
8705 if (prepared_logmsg == NULL)
8706 return got_error_from_errno2("realpath",
8707 optarg);
8708 break;
8709 case 'm':
8710 if (prepared_logmsg)
8711 option_conflict('m', 'F');
8712 logmsg = optarg;
8713 break;
8714 case 'N':
8715 non_interactive = 1;
8716 break;
8717 case 'n':
8718 show_diff = 0;
8719 break;
8720 case 'S':
8721 allow_bad_symlinks = 1;
8722 break;
8723 default:
8724 usage_commit();
8725 /* NOTREACHED */
8729 argc -= optind;
8730 argv += optind;
8732 #ifndef PROFILE
8733 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8734 "unveil", NULL) == -1)
8735 err(1, "pledge");
8736 #endif
8737 cwd = getcwd(NULL, 0);
8738 if (cwd == NULL) {
8739 error = got_error_from_errno("getcwd");
8740 goto done;
8743 error = got_repo_pack_fds_open(&pack_fds);
8744 if (error != NULL)
8745 goto done;
8747 error = got_worktree_open(&worktree, cwd);
8748 if (error) {
8749 if (error->code == GOT_ERR_NOT_WORKTREE)
8750 error = wrap_not_worktree_error(error, "commit", cwd);
8751 goto done;
8754 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8755 if (error)
8756 goto done;
8757 if (rebase_in_progress) {
8758 error = got_error(GOT_ERR_REBASING);
8759 goto done;
8762 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8763 worktree);
8764 if (error)
8765 goto done;
8767 error = get_gitconfig_path(&gitconfig_path);
8768 if (error)
8769 goto done;
8770 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8771 gitconfig_path, pack_fds);
8772 if (error != NULL)
8773 goto done;
8775 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8776 if (error)
8777 goto done;
8778 if (merge_in_progress) {
8779 error = got_error(GOT_ERR_MERGE_BUSY);
8780 goto done;
8783 error = get_author(&committer, repo, worktree);
8784 if (error)
8785 goto done;
8787 if (author != NULL && !strcmp(committer, author)) {
8788 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8789 goto done;
8792 if (author == NULL)
8793 author = committer;
8796 * unveil(2) traverses exec(2); if an editor is used we have
8797 * to apply unveil after the log message has been written.
8799 if (logmsg == NULL || strlen(logmsg) == 0)
8800 error = get_editor(&editor);
8801 else
8802 error = apply_unveil(got_repo_get_path(repo), 0,
8803 got_worktree_get_root_path(worktree));
8804 if (error)
8805 goto done;
8807 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8808 if (error)
8809 goto done;
8811 cl_arg.editor = editor;
8812 cl_arg.cmdline_log = logmsg;
8813 cl_arg.prepared_log = prepared_logmsg;
8814 cl_arg.non_interactive = non_interactive;
8815 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8816 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8817 if (!histedit_in_progress) {
8818 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8819 error = got_error(GOT_ERR_COMMIT_BRANCH);
8820 goto done;
8822 cl_arg.branch_name += 11;
8824 cl_arg.repo_path = got_repo_get_path(repo);
8825 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8826 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8827 print_status, NULL, repo);
8828 if (error) {
8829 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8830 cl_arg.logmsg_path != NULL)
8831 preserve_logmsg = 1;
8832 goto done;
8835 error = got_object_id_str(&id_str, id);
8836 if (error)
8837 goto done;
8838 printf("Created commit %s\n", id_str);
8839 done:
8840 if (preserve_logmsg) {
8841 fprintf(stderr, "%s: log message preserved in %s\n",
8842 getprogname(), cl_arg.logmsg_path);
8843 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8844 error == NULL)
8845 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8846 free(cl_arg.logmsg_path);
8847 if (repo) {
8848 const struct got_error *close_err = got_repo_close(repo);
8849 if (error == NULL)
8850 error = close_err;
8852 if (worktree)
8853 got_worktree_close(worktree);
8854 if (pack_fds) {
8855 const struct got_error *pack_err =
8856 got_repo_pack_fds_close(pack_fds);
8857 if (error == NULL)
8858 error = pack_err;
8860 free(cwd);
8861 free(id_str);
8862 free(gitconfig_path);
8863 free(editor);
8864 free(committer);
8865 free(prepared_logmsg);
8866 return error;
8869 __dead static void
8870 usage_send(void)
8872 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8873 "[-r repository-path] [-t tag] [remote-repository]\n",
8874 getprogname());
8875 exit(1);
8878 static void
8879 print_load_info(int print_colored, int print_found, int print_trees,
8880 int ncolored, int nfound, int ntrees)
8882 if (print_colored) {
8883 printf("%d commit%s colored", ncolored,
8884 ncolored == 1 ? "" : "s");
8886 if (print_found) {
8887 printf("%s%d object%s found",
8888 ncolored > 0 ? "; " : "",
8889 nfound, nfound == 1 ? "" : "s");
8891 if (print_trees) {
8892 printf("; %d tree%s scanned", ntrees,
8893 ntrees == 1 ? "" : "s");
8897 struct got_send_progress_arg {
8898 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8899 int verbosity;
8900 int last_ncolored;
8901 int last_nfound;
8902 int last_ntrees;
8903 int loading_done;
8904 int last_ncommits;
8905 int last_nobj_total;
8906 int last_p_deltify;
8907 int last_p_written;
8908 int last_p_sent;
8909 int printed_something;
8910 int sent_something;
8911 struct got_pathlist_head *delete_branches;
8914 static const struct got_error *
8915 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8916 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8917 int nobj_written, off_t bytes_sent, const char *refname,
8918 const char *errmsg, int success)
8920 struct got_send_progress_arg *a = arg;
8921 char scaled_packsize[FMT_SCALED_STRSIZE];
8922 char scaled_sent[FMT_SCALED_STRSIZE];
8923 int p_deltify = 0, p_written = 0, p_sent = 0;
8924 int print_colored = 0, print_found = 0, print_trees = 0;
8925 int print_searching = 0, print_total = 0;
8926 int print_deltify = 0, print_written = 0, print_sent = 0;
8928 if (a->verbosity < 0)
8929 return NULL;
8931 if (refname) {
8932 const char *status = success ? "accepted" : "rejected";
8934 if (success) {
8935 struct got_pathlist_entry *pe;
8936 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8937 const char *branchname = pe->path;
8938 if (got_path_cmp(branchname, refname,
8939 strlen(branchname), strlen(refname)) == 0) {
8940 status = "deleted";
8941 a->sent_something = 1;
8942 break;
8947 if (a->printed_something)
8948 putchar('\n');
8949 printf("Server has %s %s", status, refname);
8950 if (errmsg)
8951 printf(": %s", errmsg);
8952 a->printed_something = 1;
8953 return NULL;
8956 if (a->last_ncolored != ncolored) {
8957 print_colored = 1;
8958 a->last_ncolored = ncolored;
8961 if (a->last_nfound != nfound) {
8962 print_colored = 1;
8963 print_found = 1;
8964 a->last_nfound = nfound;
8967 if (a->last_ntrees != ntrees) {
8968 print_colored = 1;
8969 print_found = 1;
8970 print_trees = 1;
8971 a->last_ntrees = ntrees;
8974 if ((print_colored || print_found || print_trees) &&
8975 !a->loading_done) {
8976 printf("\r");
8977 print_load_info(print_colored, print_found, print_trees,
8978 ncolored, nfound, ntrees);
8979 a->printed_something = 1;
8980 fflush(stdout);
8981 return NULL;
8982 } else if (!a->loading_done) {
8983 printf("\r");
8984 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8985 printf("\n");
8986 a->loading_done = 1;
8989 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8990 return got_error_from_errno("fmt_scaled");
8991 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8992 return got_error_from_errno("fmt_scaled");
8994 if (a->last_ncommits != ncommits) {
8995 print_searching = 1;
8996 a->last_ncommits = ncommits;
8999 if (a->last_nobj_total != nobj_total) {
9000 print_searching = 1;
9001 print_total = 1;
9002 a->last_nobj_total = nobj_total;
9005 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9006 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9007 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9008 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9009 return got_error(GOT_ERR_NO_SPACE);
9012 if (nobj_deltify > 0 || nobj_written > 0) {
9013 if (nobj_deltify > 0) {
9014 p_deltify = (nobj_deltify * 100) / nobj_total;
9015 if (p_deltify != a->last_p_deltify) {
9016 a->last_p_deltify = p_deltify;
9017 print_searching = 1;
9018 print_total = 1;
9019 print_deltify = 1;
9022 if (nobj_written > 0) {
9023 p_written = (nobj_written * 100) / nobj_total;
9024 if (p_written != a->last_p_written) {
9025 a->last_p_written = p_written;
9026 print_searching = 1;
9027 print_total = 1;
9028 print_deltify = 1;
9029 print_written = 1;
9034 if (bytes_sent > 0) {
9035 p_sent = (bytes_sent * 100) / packfile_size;
9036 if (p_sent != a->last_p_sent) {
9037 a->last_p_sent = p_sent;
9038 print_searching = 1;
9039 print_total = 1;
9040 print_deltify = 1;
9041 print_written = 1;
9042 print_sent = 1;
9044 a->sent_something = 1;
9047 if (print_searching || print_total || print_deltify || print_written ||
9048 print_sent)
9049 printf("\r");
9050 if (print_searching)
9051 printf("packing %d reference%s", ncommits,
9052 ncommits == 1 ? "" : "s");
9053 if (print_total)
9054 printf("; %d object%s", nobj_total,
9055 nobj_total == 1 ? "" : "s");
9056 if (print_deltify)
9057 printf("; deltify: %d%%", p_deltify);
9058 if (print_sent)
9059 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9060 scaled_packsize, p_sent);
9061 else if (print_written)
9062 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9063 scaled_packsize, p_written);
9064 if (print_searching || print_total || print_deltify ||
9065 print_written || print_sent) {
9066 a->printed_something = 1;
9067 fflush(stdout);
9069 return NULL;
9072 static const struct got_error *
9073 cmd_send(int argc, char *argv[])
9075 const struct got_error *error = NULL;
9076 char *cwd = NULL, *repo_path = NULL;
9077 const char *remote_name;
9078 char *proto = NULL, *host = NULL, *port = NULL;
9079 char *repo_name = NULL, *server_path = NULL;
9080 const struct got_remote_repo *remotes, *remote = NULL;
9081 int nremotes, nbranches = 0, ndelete_branches = 0;
9082 struct got_repository *repo = NULL;
9083 struct got_worktree *worktree = NULL;
9084 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9085 struct got_pathlist_head branches;
9086 struct got_pathlist_head tags;
9087 struct got_reflist_head all_branches;
9088 struct got_reflist_head all_tags;
9089 struct got_pathlist_head delete_args;
9090 struct got_pathlist_head delete_branches;
9091 struct got_reflist_entry *re;
9092 struct got_pathlist_entry *pe;
9093 int i, ch, sendfd = -1, sendstatus;
9094 pid_t sendpid = -1;
9095 struct got_send_progress_arg spa;
9096 int verbosity = 0, overwrite_refs = 0;
9097 int send_all_branches = 0, send_all_tags = 0;
9098 struct got_reference *ref = NULL;
9099 int *pack_fds = NULL;
9101 TAILQ_INIT(&branches);
9102 TAILQ_INIT(&tags);
9103 TAILQ_INIT(&all_branches);
9104 TAILQ_INIT(&all_tags);
9105 TAILQ_INIT(&delete_args);
9106 TAILQ_INIT(&delete_branches);
9108 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9109 switch (ch) {
9110 case 'a':
9111 send_all_branches = 1;
9112 break;
9113 case 'b':
9114 error = got_pathlist_append(&branches, optarg, NULL);
9115 if (error)
9116 return error;
9117 nbranches++;
9118 break;
9119 case 'd':
9120 error = got_pathlist_append(&delete_args, optarg, NULL);
9121 if (error)
9122 return error;
9123 break;
9124 case 'f':
9125 overwrite_refs = 1;
9126 break;
9127 case 'q':
9128 verbosity = -1;
9129 break;
9130 case 'r':
9131 repo_path = realpath(optarg, NULL);
9132 if (repo_path == NULL)
9133 return got_error_from_errno2("realpath",
9134 optarg);
9135 got_path_strip_trailing_slashes(repo_path);
9136 break;
9137 case 'T':
9138 send_all_tags = 1;
9139 break;
9140 case 't':
9141 error = got_pathlist_append(&tags, optarg, NULL);
9142 if (error)
9143 return error;
9144 break;
9145 case 'v':
9146 if (verbosity < 0)
9147 verbosity = 0;
9148 else if (verbosity < 3)
9149 verbosity++;
9150 break;
9151 default:
9152 usage_send();
9153 /* NOTREACHED */
9156 argc -= optind;
9157 argv += optind;
9159 if (send_all_branches && !TAILQ_EMPTY(&branches))
9160 option_conflict('a', 'b');
9161 if (send_all_tags && !TAILQ_EMPTY(&tags))
9162 option_conflict('T', 't');
9165 if (argc == 0)
9166 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9167 else if (argc == 1)
9168 remote_name = argv[0];
9169 else
9170 usage_send();
9172 cwd = getcwd(NULL, 0);
9173 if (cwd == NULL) {
9174 error = got_error_from_errno("getcwd");
9175 goto done;
9178 error = got_repo_pack_fds_open(&pack_fds);
9179 if (error != NULL)
9180 goto done;
9182 if (repo_path == NULL) {
9183 error = got_worktree_open(&worktree, cwd);
9184 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9185 goto done;
9186 else
9187 error = NULL;
9188 if (worktree) {
9189 repo_path =
9190 strdup(got_worktree_get_repo_path(worktree));
9191 if (repo_path == NULL)
9192 error = got_error_from_errno("strdup");
9193 if (error)
9194 goto done;
9195 } else {
9196 repo_path = strdup(cwd);
9197 if (repo_path == NULL) {
9198 error = got_error_from_errno("strdup");
9199 goto done;
9204 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9205 if (error)
9206 goto done;
9208 if (worktree) {
9209 worktree_conf = got_worktree_get_gotconfig(worktree);
9210 if (worktree_conf) {
9211 got_gotconfig_get_remotes(&nremotes, &remotes,
9212 worktree_conf);
9213 for (i = 0; i < nremotes; i++) {
9214 if (strcmp(remotes[i].name, remote_name) == 0) {
9215 remote = &remotes[i];
9216 break;
9221 if (remote == NULL) {
9222 repo_conf = got_repo_get_gotconfig(repo);
9223 if (repo_conf) {
9224 got_gotconfig_get_remotes(&nremotes, &remotes,
9225 repo_conf);
9226 for (i = 0; i < nremotes; i++) {
9227 if (strcmp(remotes[i].name, remote_name) == 0) {
9228 remote = &remotes[i];
9229 break;
9234 if (remote == NULL) {
9235 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9236 for (i = 0; i < nremotes; i++) {
9237 if (strcmp(remotes[i].name, remote_name) == 0) {
9238 remote = &remotes[i];
9239 break;
9243 if (remote == NULL) {
9244 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9245 goto done;
9248 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9249 &repo_name, remote->send_url);
9250 if (error)
9251 goto done;
9253 if (strcmp(proto, "git") == 0) {
9254 #ifndef PROFILE
9255 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9256 "sendfd dns inet unveil", NULL) == -1)
9257 err(1, "pledge");
9258 #endif
9259 } else if (strcmp(proto, "git+ssh") == 0 ||
9260 strcmp(proto, "ssh") == 0) {
9261 #ifndef PROFILE
9262 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9263 "sendfd unveil", NULL) == -1)
9264 err(1, "pledge");
9265 #endif
9266 } else if (strcmp(proto, "http") == 0 ||
9267 strcmp(proto, "git+http") == 0) {
9268 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9269 goto done;
9270 } else {
9271 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9272 goto done;
9275 error = got_dial_apply_unveil(proto);
9276 if (error)
9277 goto done;
9279 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9280 if (error)
9281 goto done;
9283 if (send_all_branches) {
9284 error = got_ref_list(&all_branches, repo, "refs/heads",
9285 got_ref_cmp_by_name, NULL);
9286 if (error)
9287 goto done;
9288 TAILQ_FOREACH(re, &all_branches, entry) {
9289 const char *branchname = got_ref_get_name(re->ref);
9290 error = got_pathlist_append(&branches,
9291 branchname, NULL);
9292 if (error)
9293 goto done;
9294 nbranches++;
9296 } else if (nbranches == 0) {
9297 for (i = 0; i < remote->nsend_branches; i++) {
9298 error = got_pathlist_append(&branches,
9299 remote->send_branches[i], NULL);
9300 if (error)
9301 goto done;
9305 if (send_all_tags) {
9306 error = got_ref_list(&all_tags, repo, "refs/tags",
9307 got_ref_cmp_by_name, NULL);
9308 if (error)
9309 goto done;
9310 TAILQ_FOREACH(re, &all_tags, entry) {
9311 const char *tagname = got_ref_get_name(re->ref);
9312 error = got_pathlist_append(&tags,
9313 tagname, NULL);
9314 if (error)
9315 goto done;
9320 * To prevent accidents only branches in refs/heads/ can be deleted
9321 * with 'got send -d'.
9322 * Deleting anything else requires local repository access or Git.
9324 TAILQ_FOREACH(pe, &delete_args, entry) {
9325 const char *branchname = pe->path;
9326 char *s;
9327 struct got_pathlist_entry *new;
9328 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9329 s = strdup(branchname);
9330 if (s == NULL) {
9331 error = got_error_from_errno("strdup");
9332 goto done;
9334 } else {
9335 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9336 error = got_error_from_errno("asprintf");
9337 goto done;
9340 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9341 if (error || new == NULL /* duplicate */)
9342 free(s);
9343 if (error)
9344 goto done;
9345 ndelete_branches++;
9348 if (nbranches == 0 && ndelete_branches == 0) {
9349 struct got_reference *head_ref;
9350 if (worktree)
9351 error = got_ref_open(&head_ref, repo,
9352 got_worktree_get_head_ref_name(worktree), 0);
9353 else
9354 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9355 if (error)
9356 goto done;
9357 if (got_ref_is_symbolic(head_ref)) {
9358 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9359 got_ref_close(head_ref);
9360 if (error)
9361 goto done;
9362 } else
9363 ref = head_ref;
9364 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9365 NULL);
9366 if (error)
9367 goto done;
9368 nbranches++;
9371 if (verbosity >= 0) {
9372 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9373 remote->name, proto, host,
9374 port ? ":" : "", port ? port : "",
9375 *server_path == '/' ? "" : "/", server_path);
9378 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9379 server_path, verbosity);
9380 if (error)
9381 goto done;
9383 memset(&spa, 0, sizeof(spa));
9384 spa.last_scaled_packsize[0] = '\0';
9385 spa.last_p_deltify = -1;
9386 spa.last_p_written = -1;
9387 spa.verbosity = verbosity;
9388 spa.delete_branches = &delete_branches;
9389 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9390 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9391 check_cancelled, NULL);
9392 if (spa.printed_something)
9393 putchar('\n');
9394 if (error)
9395 goto done;
9396 if (!spa.sent_something && verbosity >= 0)
9397 printf("Already up-to-date\n");
9398 done:
9399 if (sendpid > 0) {
9400 if (kill(sendpid, SIGTERM) == -1)
9401 error = got_error_from_errno("kill");
9402 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9403 error = got_error_from_errno("waitpid");
9405 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9406 error = got_error_from_errno("close");
9407 if (repo) {
9408 const struct got_error *close_err = got_repo_close(repo);
9409 if (error == NULL)
9410 error = close_err;
9412 if (worktree)
9413 got_worktree_close(worktree);
9414 if (pack_fds) {
9415 const struct got_error *pack_err =
9416 got_repo_pack_fds_close(pack_fds);
9417 if (error == NULL)
9418 error = pack_err;
9420 if (ref)
9421 got_ref_close(ref);
9422 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9423 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9424 got_ref_list_free(&all_branches);
9425 got_ref_list_free(&all_tags);
9426 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9427 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9428 free(cwd);
9429 free(repo_path);
9430 free(proto);
9431 free(host);
9432 free(port);
9433 free(server_path);
9434 free(repo_name);
9435 return error;
9438 __dead static void
9439 usage_cherrypick(void)
9441 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9442 exit(1);
9445 static const struct got_error *
9446 cmd_cherrypick(int argc, char *argv[])
9448 const struct got_error *error = NULL;
9449 struct got_worktree *worktree = NULL;
9450 struct got_repository *repo = NULL;
9451 char *cwd = NULL, *commit_id_str = NULL;
9452 struct got_object_id *commit_id = NULL;
9453 struct got_commit_object *commit = NULL;
9454 struct got_object_qid *pid;
9455 int ch;
9456 struct got_update_progress_arg upa;
9457 int *pack_fds = NULL;
9459 while ((ch = getopt(argc, argv, "")) != -1) {
9460 switch (ch) {
9461 default:
9462 usage_cherrypick();
9463 /* NOTREACHED */
9467 argc -= optind;
9468 argv += optind;
9470 #ifndef PROFILE
9471 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9472 "unveil", NULL) == -1)
9473 err(1, "pledge");
9474 #endif
9475 if (argc != 1)
9476 usage_cherrypick();
9478 cwd = getcwd(NULL, 0);
9479 if (cwd == NULL) {
9480 error = got_error_from_errno("getcwd");
9481 goto done;
9484 error = got_repo_pack_fds_open(&pack_fds);
9485 if (error != NULL)
9486 goto done;
9488 error = got_worktree_open(&worktree, cwd);
9489 if (error) {
9490 if (error->code == GOT_ERR_NOT_WORKTREE)
9491 error = wrap_not_worktree_error(error, "cherrypick",
9492 cwd);
9493 goto done;
9496 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9497 NULL, pack_fds);
9498 if (error != NULL)
9499 goto done;
9501 error = apply_unveil(got_repo_get_path(repo), 0,
9502 got_worktree_get_root_path(worktree));
9503 if (error)
9504 goto done;
9506 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9507 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9508 if (error)
9509 goto done;
9510 error = got_object_id_str(&commit_id_str, commit_id);
9511 if (error)
9512 goto done;
9514 error = got_object_open_as_commit(&commit, repo, commit_id);
9515 if (error)
9516 goto done;
9517 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9518 memset(&upa, 0, sizeof(upa));
9519 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9520 commit_id, repo, update_progress, &upa, check_cancelled,
9521 NULL);
9522 if (error != NULL)
9523 goto done;
9525 if (upa.did_something)
9526 printf("Merged commit %s\n", commit_id_str);
9527 print_merge_progress_stats(&upa);
9528 done:
9529 if (commit)
9530 got_object_commit_close(commit);
9531 free(commit_id_str);
9532 if (worktree)
9533 got_worktree_close(worktree);
9534 if (repo) {
9535 const struct got_error *close_err = got_repo_close(repo);
9536 if (error == NULL)
9537 error = close_err;
9539 if (pack_fds) {
9540 const struct got_error *pack_err =
9541 got_repo_pack_fds_close(pack_fds);
9542 if (error == NULL)
9543 error = pack_err;
9546 return error;
9549 __dead static void
9550 usage_backout(void)
9552 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9553 exit(1);
9556 static const struct got_error *
9557 cmd_backout(int argc, char *argv[])
9559 const struct got_error *error = NULL;
9560 struct got_worktree *worktree = NULL;
9561 struct got_repository *repo = NULL;
9562 char *cwd = NULL, *commit_id_str = NULL;
9563 struct got_object_id *commit_id = NULL;
9564 struct got_commit_object *commit = NULL;
9565 struct got_object_qid *pid;
9566 int ch;
9567 struct got_update_progress_arg upa;
9568 int *pack_fds = NULL;
9570 while ((ch = getopt(argc, argv, "")) != -1) {
9571 switch (ch) {
9572 default:
9573 usage_backout();
9574 /* NOTREACHED */
9578 argc -= optind;
9579 argv += optind;
9581 #ifndef PROFILE
9582 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9583 "unveil", NULL) == -1)
9584 err(1, "pledge");
9585 #endif
9586 if (argc != 1)
9587 usage_backout();
9589 cwd = getcwd(NULL, 0);
9590 if (cwd == NULL) {
9591 error = got_error_from_errno("getcwd");
9592 goto done;
9595 error = got_repo_pack_fds_open(&pack_fds);
9596 if (error != NULL)
9597 goto done;
9599 error = got_worktree_open(&worktree, cwd);
9600 if (error) {
9601 if (error->code == GOT_ERR_NOT_WORKTREE)
9602 error = wrap_not_worktree_error(error, "backout", cwd);
9603 goto done;
9606 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9607 NULL, pack_fds);
9608 if (error != NULL)
9609 goto done;
9611 error = apply_unveil(got_repo_get_path(repo), 0,
9612 got_worktree_get_root_path(worktree));
9613 if (error)
9614 goto done;
9616 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9617 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9618 if (error)
9619 goto done;
9620 error = got_object_id_str(&commit_id_str, commit_id);
9621 if (error)
9622 goto done;
9624 error = got_object_open_as_commit(&commit, repo, commit_id);
9625 if (error)
9626 goto done;
9627 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9628 if (pid == NULL) {
9629 error = got_error(GOT_ERR_ROOT_COMMIT);
9630 goto done;
9633 memset(&upa, 0, sizeof(upa));
9634 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9635 repo, update_progress, &upa, check_cancelled, NULL);
9636 if (error != NULL)
9637 goto done;
9639 if (upa.did_something)
9640 printf("Backed out commit %s\n", commit_id_str);
9641 print_merge_progress_stats(&upa);
9642 done:
9643 if (commit)
9644 got_object_commit_close(commit);
9645 free(commit_id_str);
9646 if (worktree)
9647 got_worktree_close(worktree);
9648 if (repo) {
9649 const struct got_error *close_err = got_repo_close(repo);
9650 if (error == NULL)
9651 error = close_err;
9653 if (pack_fds) {
9654 const struct got_error *pack_err =
9655 got_repo_pack_fds_close(pack_fds);
9656 if (error == NULL)
9657 error = pack_err;
9659 return error;
9662 __dead static void
9663 usage_rebase(void)
9665 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9666 exit(1);
9669 static void
9670 trim_logmsg(char *logmsg, int limit)
9672 char *nl;
9673 size_t len;
9675 len = strlen(logmsg);
9676 if (len > limit)
9677 len = limit;
9678 logmsg[len] = '\0';
9679 nl = strchr(logmsg, '\n');
9680 if (nl)
9681 *nl = '\0';
9684 static const struct got_error *
9685 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9687 const struct got_error *err;
9688 char *logmsg0 = NULL;
9689 const char *s;
9691 err = got_object_commit_get_logmsg(&logmsg0, commit);
9692 if (err)
9693 return err;
9695 s = logmsg0;
9696 while (isspace((unsigned char)s[0]))
9697 s++;
9699 *logmsg = strdup(s);
9700 if (*logmsg == NULL) {
9701 err = got_error_from_errno("strdup");
9702 goto done;
9705 trim_logmsg(*logmsg, limit);
9706 done:
9707 free(logmsg0);
9708 return err;
9711 static const struct got_error *
9712 show_rebase_merge_conflict(struct got_object_id *id,
9713 struct got_repository *repo)
9715 const struct got_error *err;
9716 struct got_commit_object *commit = NULL;
9717 char *id_str = NULL, *logmsg = NULL;
9719 err = got_object_open_as_commit(&commit, repo, id);
9720 if (err)
9721 return err;
9723 err = got_object_id_str(&id_str, id);
9724 if (err)
9725 goto done;
9727 id_str[12] = '\0';
9729 err = get_short_logmsg(&logmsg, 42, commit);
9730 if (err)
9731 goto done;
9733 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9734 done:
9735 free(id_str);
9736 got_object_commit_close(commit);
9737 free(logmsg);
9738 return err;
9741 static const struct got_error *
9742 show_rebase_progress(struct got_commit_object *commit,
9743 struct got_object_id *old_id, struct got_object_id *new_id)
9745 const struct got_error *err;
9746 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9748 err = got_object_id_str(&old_id_str, old_id);
9749 if (err)
9750 goto done;
9752 if (new_id) {
9753 err = got_object_id_str(&new_id_str, new_id);
9754 if (err)
9755 goto done;
9758 old_id_str[12] = '\0';
9759 if (new_id_str)
9760 new_id_str[12] = '\0';
9762 err = get_short_logmsg(&logmsg, 42, commit);
9763 if (err)
9764 goto done;
9766 printf("%s -> %s: %s\n", old_id_str,
9767 new_id_str ? new_id_str : "no-op change", logmsg);
9768 done:
9769 free(old_id_str);
9770 free(new_id_str);
9771 free(logmsg);
9772 return err;
9775 static const struct got_error *
9776 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9777 struct got_reference *branch, struct got_reference *new_base_branch,
9778 struct got_reference *tmp_branch, struct got_repository *repo,
9779 int create_backup)
9781 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9782 return got_worktree_rebase_complete(worktree, fileindex,
9783 new_base_branch, tmp_branch, branch, repo, create_backup);
9786 static const struct got_error *
9787 rebase_commit(struct got_pathlist_head *merged_paths,
9788 struct got_worktree *worktree, struct got_fileindex *fileindex,
9789 struct got_reference *tmp_branch, const char *committer,
9790 struct got_object_id *commit_id, struct got_repository *repo)
9792 const struct got_error *error;
9793 struct got_commit_object *commit;
9794 struct got_object_id *new_commit_id;
9796 error = got_object_open_as_commit(&commit, repo, commit_id);
9797 if (error)
9798 return error;
9800 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9801 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9802 repo);
9803 if (error) {
9804 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9805 goto done;
9806 error = show_rebase_progress(commit, commit_id, NULL);
9807 } else {
9808 error = show_rebase_progress(commit, commit_id, new_commit_id);
9809 free(new_commit_id);
9811 done:
9812 got_object_commit_close(commit);
9813 return error;
9816 struct check_path_prefix_arg {
9817 const char *path_prefix;
9818 size_t len;
9819 int errcode;
9822 static const struct got_error *
9823 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9824 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9825 struct got_object_id *id1, struct got_object_id *id2,
9826 const char *path1, const char *path2,
9827 mode_t mode1, mode_t mode2, struct got_repository *repo)
9829 struct check_path_prefix_arg *a = arg;
9831 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9832 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9833 return got_error(a->errcode);
9835 return NULL;
9838 static const struct got_error *
9839 check_path_prefix(struct got_object_id *parent_id,
9840 struct got_object_id *commit_id, const char *path_prefix,
9841 int errcode, struct got_repository *repo)
9843 const struct got_error *err;
9844 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9845 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9846 struct check_path_prefix_arg cpp_arg;
9848 if (got_path_is_root_dir(path_prefix))
9849 return NULL;
9851 err = got_object_open_as_commit(&commit, repo, commit_id);
9852 if (err)
9853 goto done;
9855 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9856 if (err)
9857 goto done;
9859 err = got_object_open_as_tree(&tree1, repo,
9860 got_object_commit_get_tree_id(parent_commit));
9861 if (err)
9862 goto done;
9864 err = got_object_open_as_tree(&tree2, repo,
9865 got_object_commit_get_tree_id(commit));
9866 if (err)
9867 goto done;
9869 cpp_arg.path_prefix = path_prefix;
9870 while (cpp_arg.path_prefix[0] == '/')
9871 cpp_arg.path_prefix++;
9872 cpp_arg.len = strlen(cpp_arg.path_prefix);
9873 cpp_arg.errcode = errcode;
9874 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9875 check_path_prefix_in_diff, &cpp_arg, 0);
9876 done:
9877 if (tree1)
9878 got_object_tree_close(tree1);
9879 if (tree2)
9880 got_object_tree_close(tree2);
9881 if (commit)
9882 got_object_commit_close(commit);
9883 if (parent_commit)
9884 got_object_commit_close(parent_commit);
9885 return err;
9888 static const struct got_error *
9889 collect_commits(struct got_object_id_queue *commits,
9890 struct got_object_id *initial_commit_id,
9891 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9892 const char *path_prefix, int path_prefix_errcode,
9893 struct got_repository *repo)
9895 const struct got_error *err = NULL;
9896 struct got_commit_graph *graph = NULL;
9897 struct got_object_id parent_id, commit_id;
9898 struct got_object_qid *qid;
9900 err = got_commit_graph_open(&graph, "/", 1);
9901 if (err)
9902 return err;
9904 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9905 check_cancelled, NULL);
9906 if (err)
9907 goto done;
9909 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9910 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9911 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9912 check_cancelled, NULL);
9913 if (err) {
9914 if (err->code == GOT_ERR_ITER_COMPLETED) {
9915 err = got_error_msg(GOT_ERR_ANCESTRY,
9916 "ran out of commits to rebase before "
9917 "youngest common ancestor commit has "
9918 "been reached?!?");
9920 goto done;
9921 } else {
9922 err = check_path_prefix(&parent_id, &commit_id,
9923 path_prefix, path_prefix_errcode, repo);
9924 if (err)
9925 goto done;
9927 err = got_object_qid_alloc(&qid, &commit_id);
9928 if (err)
9929 goto done;
9930 STAILQ_INSERT_HEAD(commits, qid, entry);
9932 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9935 done:
9936 got_commit_graph_close(graph);
9937 return err;
9940 static const struct got_error *
9941 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9943 const struct got_error *err = NULL;
9944 time_t committer_time;
9945 struct tm tm;
9946 char datebuf[11]; /* YYYY-MM-DD + NUL */
9947 char *author0 = NULL, *author, *smallerthan;
9948 char *logmsg0 = NULL, *logmsg, *newline;
9950 committer_time = got_object_commit_get_committer_time(commit);
9951 if (gmtime_r(&committer_time, &tm) == NULL)
9952 return got_error_from_errno("gmtime_r");
9953 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9954 return got_error(GOT_ERR_NO_SPACE);
9956 author0 = strdup(got_object_commit_get_author(commit));
9957 if (author0 == NULL)
9958 return got_error_from_errno("strdup");
9959 author = author0;
9960 smallerthan = strchr(author, '<');
9961 if (smallerthan && smallerthan[1] != '\0')
9962 author = smallerthan + 1;
9963 author[strcspn(author, "@>")] = '\0';
9965 err = got_object_commit_get_logmsg(&logmsg0, commit);
9966 if (err)
9967 goto done;
9968 logmsg = logmsg0;
9969 while (*logmsg == '\n')
9970 logmsg++;
9971 newline = strchr(logmsg, '\n');
9972 if (newline)
9973 *newline = '\0';
9975 if (asprintf(brief_str, "%s %s %s",
9976 datebuf, author, logmsg) == -1)
9977 err = got_error_from_errno("asprintf");
9978 done:
9979 free(author0);
9980 free(logmsg0);
9981 return err;
9984 static const struct got_error *
9985 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9986 struct got_repository *repo)
9988 const struct got_error *err;
9989 char *id_str;
9991 err = got_object_id_str(&id_str, id);
9992 if (err)
9993 return err;
9995 err = got_ref_delete(ref, repo);
9996 if (err)
9997 goto done;
9999 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10000 done:
10001 free(id_str);
10002 return err;
10005 static const struct got_error *
10006 print_backup_ref(const char *branch_name, const char *new_id_str,
10007 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10008 struct got_reflist_object_id_map *refs_idmap,
10009 struct got_repository *repo)
10011 const struct got_error *err = NULL;
10012 struct got_reflist_head *refs;
10013 char *refs_str = NULL;
10014 struct got_object_id *new_commit_id = NULL;
10015 struct got_commit_object *new_commit = NULL;
10016 char *new_commit_brief_str = NULL;
10017 struct got_object_id *yca_id = NULL;
10018 struct got_commit_object *yca_commit = NULL;
10019 char *yca_id_str = NULL, *yca_brief_str = NULL;
10020 char *custom_refs_str;
10022 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10023 return got_error_from_errno("asprintf");
10025 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10026 0, 0, refs_idmap, custom_refs_str);
10027 if (err)
10028 goto done;
10030 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10031 if (err)
10032 goto done;
10034 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10035 if (refs) {
10036 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10037 if (err)
10038 goto done;
10041 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10042 if (err)
10043 goto done;
10045 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10046 if (err)
10047 goto done;
10049 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10050 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10051 if (err)
10052 goto done;
10054 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10055 refs_str ? " (" : "", refs_str ? refs_str : "",
10056 refs_str ? ")" : "", new_commit_brief_str);
10057 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10058 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10059 free(refs_str);
10060 refs_str = NULL;
10062 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10063 if (err)
10064 goto done;
10066 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10067 if (err)
10068 goto done;
10070 err = got_object_id_str(&yca_id_str, yca_id);
10071 if (err)
10072 goto done;
10074 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10075 if (refs) {
10076 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10077 if (err)
10078 goto done;
10080 printf("history forked at %s%s%s%s\n %s\n",
10081 yca_id_str,
10082 refs_str ? " (" : "", refs_str ? refs_str : "",
10083 refs_str ? ")" : "", yca_brief_str);
10085 done:
10086 free(custom_refs_str);
10087 free(new_commit_id);
10088 free(refs_str);
10089 free(yca_id);
10090 free(yca_id_str);
10091 free(yca_brief_str);
10092 if (new_commit)
10093 got_object_commit_close(new_commit);
10094 if (yca_commit)
10095 got_object_commit_close(yca_commit);
10097 return NULL;
10100 static const struct got_error *
10101 process_backup_refs(const char *backup_ref_prefix,
10102 const char *wanted_branch_name,
10103 int delete, struct got_repository *repo)
10105 const struct got_error *err;
10106 struct got_reflist_head refs, backup_refs;
10107 struct got_reflist_entry *re;
10108 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10109 struct got_object_id *old_commit_id = NULL;
10110 char *branch_name = NULL;
10111 struct got_commit_object *old_commit = NULL;
10112 struct got_reflist_object_id_map *refs_idmap = NULL;
10113 int wanted_branch_found = 0;
10115 TAILQ_INIT(&refs);
10116 TAILQ_INIT(&backup_refs);
10118 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10119 if (err)
10120 return err;
10122 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10123 if (err)
10124 goto done;
10126 if (wanted_branch_name) {
10127 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10128 wanted_branch_name += 11;
10131 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10132 got_ref_cmp_by_commit_timestamp_descending, repo);
10133 if (err)
10134 goto done;
10136 TAILQ_FOREACH(re, &backup_refs, entry) {
10137 const char *refname = got_ref_get_name(re->ref);
10138 char *slash;
10140 err = check_cancelled(NULL);
10141 if (err)
10142 break;
10144 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10145 if (err)
10146 break;
10148 err = got_object_open_as_commit(&old_commit, repo,
10149 old_commit_id);
10150 if (err)
10151 break;
10153 if (strncmp(backup_ref_prefix, refname,
10154 backup_ref_prefix_len) == 0)
10155 refname += backup_ref_prefix_len;
10157 while (refname[0] == '/')
10158 refname++;
10160 branch_name = strdup(refname);
10161 if (branch_name == NULL) {
10162 err = got_error_from_errno("strdup");
10163 break;
10165 slash = strrchr(branch_name, '/');
10166 if (slash) {
10167 *slash = '\0';
10168 refname += strlen(branch_name) + 1;
10171 if (wanted_branch_name == NULL ||
10172 strcmp(wanted_branch_name, branch_name) == 0) {
10173 wanted_branch_found = 1;
10174 if (delete) {
10175 err = delete_backup_ref(re->ref,
10176 old_commit_id, repo);
10177 } else {
10178 err = print_backup_ref(branch_name, refname,
10179 old_commit_id, old_commit, refs_idmap,
10180 repo);
10182 if (err)
10183 break;
10186 free(old_commit_id);
10187 old_commit_id = NULL;
10188 free(branch_name);
10189 branch_name = NULL;
10190 got_object_commit_close(old_commit);
10191 old_commit = NULL;
10194 if (wanted_branch_name && !wanted_branch_found) {
10195 err = got_error_fmt(GOT_ERR_NOT_REF,
10196 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10198 done:
10199 if (refs_idmap)
10200 got_reflist_object_id_map_free(refs_idmap);
10201 got_ref_list_free(&refs);
10202 got_ref_list_free(&backup_refs);
10203 free(old_commit_id);
10204 free(branch_name);
10205 if (old_commit)
10206 got_object_commit_close(old_commit);
10207 return err;
10210 static const struct got_error *
10211 abort_progress(void *arg, unsigned char status, const char *path)
10214 * Unversioned files should not clutter progress output when
10215 * an operation is aborted.
10217 if (status == GOT_STATUS_UNVERSIONED)
10218 return NULL;
10220 return update_progress(arg, status, path);
10223 static const struct got_error *
10224 cmd_rebase(int argc, char *argv[])
10226 const struct got_error *error = NULL;
10227 struct got_worktree *worktree = NULL;
10228 struct got_repository *repo = NULL;
10229 struct got_fileindex *fileindex = NULL;
10230 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10231 struct got_reference *branch = NULL;
10232 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10233 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10234 struct got_object_id *resume_commit_id = NULL;
10235 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10236 struct got_object_id *head_commit_id = NULL;
10237 struct got_reference *head_ref = NULL;
10238 struct got_commit_object *commit = NULL;
10239 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10240 int histedit_in_progress = 0, merge_in_progress = 0;
10241 int create_backup = 1, list_backups = 0, delete_backups = 0;
10242 struct got_object_id_queue commits;
10243 struct got_pathlist_head merged_paths;
10244 const struct got_object_id_queue *parent_ids;
10245 struct got_object_qid *qid, *pid;
10246 struct got_update_progress_arg upa;
10247 int *pack_fds = NULL;
10249 STAILQ_INIT(&commits);
10250 TAILQ_INIT(&merged_paths);
10251 memset(&upa, 0, sizeof(upa));
10253 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10254 switch (ch) {
10255 case 'a':
10256 abort_rebase = 1;
10257 break;
10258 case 'c':
10259 continue_rebase = 1;
10260 break;
10261 case 'l':
10262 list_backups = 1;
10263 break;
10264 case 'X':
10265 delete_backups = 1;
10266 break;
10267 default:
10268 usage_rebase();
10269 /* NOTREACHED */
10273 argc -= optind;
10274 argv += optind;
10276 #ifndef PROFILE
10277 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10278 "unveil", NULL) == -1)
10279 err(1, "pledge");
10280 #endif
10281 if (list_backups) {
10282 if (abort_rebase)
10283 option_conflict('l', 'a');
10284 if (continue_rebase)
10285 option_conflict('l', 'c');
10286 if (delete_backups)
10287 option_conflict('l', 'X');
10288 if (argc != 0 && argc != 1)
10289 usage_rebase();
10290 } else if (delete_backups) {
10291 if (abort_rebase)
10292 option_conflict('X', 'a');
10293 if (continue_rebase)
10294 option_conflict('X', 'c');
10295 if (list_backups)
10296 option_conflict('l', 'X');
10297 if (argc != 0 && argc != 1)
10298 usage_rebase();
10299 } else {
10300 if (abort_rebase && continue_rebase)
10301 usage_rebase();
10302 else if (abort_rebase || continue_rebase) {
10303 if (argc != 0)
10304 usage_rebase();
10305 } else if (argc != 1)
10306 usage_rebase();
10309 cwd = getcwd(NULL, 0);
10310 if (cwd == NULL) {
10311 error = got_error_from_errno("getcwd");
10312 goto done;
10315 error = got_repo_pack_fds_open(&pack_fds);
10316 if (error != NULL)
10317 goto done;
10319 error = got_worktree_open(&worktree, cwd);
10320 if (error) {
10321 if (list_backups || delete_backups) {
10322 if (error->code != GOT_ERR_NOT_WORKTREE)
10323 goto done;
10324 } else {
10325 if (error->code == GOT_ERR_NOT_WORKTREE)
10326 error = wrap_not_worktree_error(error,
10327 "rebase", cwd);
10328 goto done;
10332 error = get_gitconfig_path(&gitconfig_path);
10333 if (error)
10334 goto done;
10335 error = got_repo_open(&repo,
10336 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10337 gitconfig_path, pack_fds);
10338 if (error != NULL)
10339 goto done;
10341 error = get_author(&committer, repo, worktree);
10342 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10343 goto done;
10345 error = apply_unveil(got_repo_get_path(repo), 0,
10346 worktree ? got_worktree_get_root_path(worktree) : NULL);
10347 if (error)
10348 goto done;
10350 if (list_backups || delete_backups) {
10351 error = process_backup_refs(
10352 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10353 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10354 goto done; /* nothing else to do */
10357 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10358 worktree);
10359 if (error)
10360 goto done;
10361 if (histedit_in_progress) {
10362 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10363 goto done;
10366 error = got_worktree_merge_in_progress(&merge_in_progress,
10367 worktree, repo);
10368 if (error)
10369 goto done;
10370 if (merge_in_progress) {
10371 error = got_error(GOT_ERR_MERGE_BUSY);
10372 goto done;
10375 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10376 if (error)
10377 goto done;
10379 if (abort_rebase) {
10380 if (!rebase_in_progress) {
10381 error = got_error(GOT_ERR_NOT_REBASING);
10382 goto done;
10384 error = got_worktree_rebase_continue(&resume_commit_id,
10385 &new_base_branch, &tmp_branch, &branch, &fileindex,
10386 worktree, repo);
10387 if (error)
10388 goto done;
10389 printf("Switching work tree to %s\n",
10390 got_ref_get_symref_target(new_base_branch));
10391 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10392 new_base_branch, abort_progress, &upa);
10393 if (error)
10394 goto done;
10395 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10396 print_merge_progress_stats(&upa);
10397 goto done; /* nothing else to do */
10400 if (continue_rebase) {
10401 if (!rebase_in_progress) {
10402 error = got_error(GOT_ERR_NOT_REBASING);
10403 goto done;
10405 error = got_worktree_rebase_continue(&resume_commit_id,
10406 &new_base_branch, &tmp_branch, &branch, &fileindex,
10407 worktree, repo);
10408 if (error)
10409 goto done;
10411 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10412 committer, resume_commit_id, repo);
10413 if (error)
10414 goto done;
10416 yca_id = got_object_id_dup(resume_commit_id);
10417 if (yca_id == NULL) {
10418 error = got_error_from_errno("got_object_id_dup");
10419 goto done;
10421 } else {
10422 error = got_ref_open(&branch, repo, argv[0], 0);
10423 if (error != NULL)
10424 goto done;
10425 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10426 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10427 "will not rebase a branch which lives outside "
10428 "the \"refs/heads/\" reference namespace");
10429 goto done;
10433 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10434 if (error)
10435 goto done;
10437 if (!continue_rebase) {
10438 struct got_object_id *base_commit_id;
10440 error = got_ref_open(&head_ref, repo,
10441 got_worktree_get_head_ref_name(worktree), 0);
10442 if (error)
10443 goto done;
10444 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10445 if (error)
10446 goto done;
10447 base_commit_id = got_worktree_get_base_commit_id(worktree);
10448 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10449 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10450 goto done;
10453 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10454 base_commit_id, branch_head_commit_id, 1, repo,
10455 check_cancelled, NULL);
10456 if (error)
10457 goto done;
10458 if (yca_id == NULL) {
10459 error = got_error_msg(GOT_ERR_ANCESTRY,
10460 "specified branch shares no common ancestry "
10461 "with work tree's branch");
10462 goto done;
10465 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10466 if (error) {
10467 if (error->code != GOT_ERR_ANCESTRY)
10468 goto done;
10469 error = NULL;
10470 } else {
10471 struct got_pathlist_head paths;
10472 printf("%s is already based on %s\n",
10473 got_ref_get_name(branch),
10474 got_worktree_get_head_ref_name(worktree));
10475 error = switch_head_ref(branch, branch_head_commit_id,
10476 worktree, repo);
10477 if (error)
10478 goto done;
10479 error = got_worktree_set_base_commit_id(worktree, repo,
10480 branch_head_commit_id);
10481 if (error)
10482 goto done;
10483 TAILQ_INIT(&paths);
10484 error = got_pathlist_append(&paths, "", NULL);
10485 if (error)
10486 goto done;
10487 error = got_worktree_checkout_files(worktree,
10488 &paths, repo, update_progress, &upa,
10489 check_cancelled, NULL);
10490 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
10491 if (error)
10492 goto done;
10493 if (upa.did_something) {
10494 char *id_str;
10495 error = got_object_id_str(&id_str,
10496 branch_head_commit_id);
10497 if (error)
10498 goto done;
10499 printf("Updated to %s: %s\n",
10500 got_worktree_get_head_ref_name(worktree),
10501 id_str);
10502 free(id_str);
10503 } else
10504 printf("Already up-to-date\n");
10505 print_update_progress_stats(&upa);
10506 goto done;
10510 commit_id = branch_head_commit_id;
10511 error = got_object_open_as_commit(&commit, repo, commit_id);
10512 if (error)
10513 goto done;
10515 parent_ids = got_object_commit_get_parent_ids(commit);
10516 pid = STAILQ_FIRST(parent_ids);
10517 if (pid == NULL) {
10518 error = got_error(GOT_ERR_EMPTY_REBASE);
10519 goto done;
10521 error = collect_commits(&commits, commit_id, &pid->id,
10522 yca_id, got_worktree_get_path_prefix(worktree),
10523 GOT_ERR_REBASE_PATH, repo);
10524 got_object_commit_close(commit);
10525 commit = NULL;
10526 if (error)
10527 goto done;
10529 if (!continue_rebase) {
10530 error = got_worktree_rebase_prepare(&new_base_branch,
10531 &tmp_branch, &fileindex, worktree, branch, repo);
10532 if (error)
10533 goto done;
10536 if (STAILQ_EMPTY(&commits)) {
10537 if (continue_rebase) {
10538 error = rebase_complete(worktree, fileindex,
10539 branch, new_base_branch, tmp_branch, repo,
10540 create_backup);
10541 goto done;
10542 } else {
10543 /* Fast-forward the reference of the branch. */
10544 struct got_object_id *new_head_commit_id;
10545 char *id_str;
10546 error = got_ref_resolve(&new_head_commit_id, repo,
10547 new_base_branch);
10548 if (error)
10549 goto done;
10550 error = got_object_id_str(&id_str, new_head_commit_id);
10551 if (error)
10552 goto done;
10553 printf("Forwarding %s to commit %s\n",
10554 got_ref_get_name(branch), id_str);
10555 free(id_str);
10556 error = got_ref_change_ref(branch,
10557 new_head_commit_id);
10558 if (error)
10559 goto done;
10560 /* No backup needed since objects did not change. */
10561 create_backup = 0;
10565 pid = NULL;
10566 STAILQ_FOREACH(qid, &commits, entry) {
10568 commit_id = &qid->id;
10569 parent_id = pid ? &pid->id : yca_id;
10570 pid = qid;
10572 memset(&upa, 0, sizeof(upa));
10573 error = got_worktree_rebase_merge_files(&merged_paths,
10574 worktree, fileindex, parent_id, commit_id, repo,
10575 update_progress, &upa, check_cancelled, NULL);
10576 if (error)
10577 goto done;
10579 print_merge_progress_stats(&upa);
10580 if (upa.conflicts > 0 || upa.missing > 0 ||
10581 upa.not_deleted > 0 || upa.unversioned > 0) {
10582 if (upa.conflicts > 0) {
10583 error = show_rebase_merge_conflict(&qid->id,
10584 repo);
10585 if (error)
10586 goto done;
10588 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10589 break;
10592 error = rebase_commit(&merged_paths, worktree, fileindex,
10593 tmp_branch, committer, commit_id, repo);
10594 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
10595 if (error)
10596 goto done;
10599 if (upa.conflicts > 0 || upa.missing > 0 ||
10600 upa.not_deleted > 0 || upa.unversioned > 0) {
10601 error = got_worktree_rebase_postpone(worktree, fileindex);
10602 if (error)
10603 goto done;
10604 if (upa.conflicts > 0 && upa.missing == 0 &&
10605 upa.not_deleted == 0 && upa.unversioned == 0) {
10606 error = got_error_msg(GOT_ERR_CONFLICTS,
10607 "conflicts must be resolved before rebasing "
10608 "can continue");
10609 } else if (upa.conflicts > 0) {
10610 error = got_error_msg(GOT_ERR_CONFLICTS,
10611 "conflicts must be resolved before rebasing "
10612 "can continue; changes destined for some "
10613 "files were not yet merged and should be "
10614 "merged manually if required before the "
10615 "rebase operation is continued");
10616 } else {
10617 error = got_error_msg(GOT_ERR_CONFLICTS,
10618 "changes destined for some files were not "
10619 "yet merged and should be merged manually "
10620 "if required before the rebase operation "
10621 "is continued");
10623 } else
10624 error = rebase_complete(worktree, fileindex, branch,
10625 new_base_branch, tmp_branch, repo, create_backup);
10626 done:
10627 free(cwd);
10628 free(committer);
10629 free(gitconfig_path);
10630 got_object_id_queue_free(&commits);
10631 free(branch_head_commit_id);
10632 free(resume_commit_id);
10633 free(head_commit_id);
10634 free(yca_id);
10635 if (commit)
10636 got_object_commit_close(commit);
10637 if (branch)
10638 got_ref_close(branch);
10639 if (new_base_branch)
10640 got_ref_close(new_base_branch);
10641 if (tmp_branch)
10642 got_ref_close(tmp_branch);
10643 if (head_ref)
10644 got_ref_close(head_ref);
10645 if (worktree)
10646 got_worktree_close(worktree);
10647 if (repo) {
10648 const struct got_error *close_err = got_repo_close(repo);
10649 if (error == NULL)
10650 error = close_err;
10652 if (pack_fds) {
10653 const struct got_error *pack_err =
10654 got_repo_pack_fds_close(pack_fds);
10655 if (error == NULL)
10656 error = pack_err;
10658 return error;
10661 __dead static void
10662 usage_histedit(void)
10664 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10665 "[branch]\n", getprogname());
10666 exit(1);
10669 #define GOT_HISTEDIT_PICK 'p'
10670 #define GOT_HISTEDIT_EDIT 'e'
10671 #define GOT_HISTEDIT_FOLD 'f'
10672 #define GOT_HISTEDIT_DROP 'd'
10673 #define GOT_HISTEDIT_MESG 'm'
10675 static const struct got_histedit_cmd {
10676 unsigned char code;
10677 const char *name;
10678 const char *desc;
10679 } got_histedit_cmds[] = {
10680 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10681 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10682 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10683 "be used" },
10684 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10685 { GOT_HISTEDIT_MESG, "mesg",
10686 "single-line log message for commit above (open editor if empty)" },
10689 struct got_histedit_list_entry {
10690 TAILQ_ENTRY(got_histedit_list_entry) entry;
10691 struct got_object_id *commit_id;
10692 const struct got_histedit_cmd *cmd;
10693 char *logmsg;
10695 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10697 static const struct got_error *
10698 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10699 FILE *f, struct got_repository *repo)
10701 const struct got_error *err = NULL;
10702 char *logmsg = NULL, *id_str = NULL;
10703 struct got_commit_object *commit = NULL;
10704 int n;
10706 err = got_object_open_as_commit(&commit, repo, commit_id);
10707 if (err)
10708 goto done;
10710 err = get_short_logmsg(&logmsg, 34, commit);
10711 if (err)
10712 goto done;
10714 err = got_object_id_str(&id_str, commit_id);
10715 if (err)
10716 goto done;
10718 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10719 if (n < 0)
10720 err = got_ferror(f, GOT_ERR_IO);
10721 done:
10722 if (commit)
10723 got_object_commit_close(commit);
10724 free(id_str);
10725 free(logmsg);
10726 return err;
10729 static const struct got_error *
10730 histedit_write_commit_list(struct got_object_id_queue *commits,
10731 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10732 struct got_repository *repo)
10734 const struct got_error *err = NULL;
10735 struct got_object_qid *qid;
10736 const char *histedit_cmd = NULL;
10738 if (STAILQ_EMPTY(commits))
10739 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10741 STAILQ_FOREACH(qid, commits, entry) {
10742 histedit_cmd = got_histedit_cmds[0].name;
10743 if (edit_only)
10744 histedit_cmd = "edit";
10745 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10746 histedit_cmd = "fold";
10747 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10748 if (err)
10749 break;
10750 if (edit_logmsg_only) {
10751 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10752 if (n < 0) {
10753 err = got_ferror(f, GOT_ERR_IO);
10754 break;
10759 return err;
10762 static const struct got_error *
10763 write_cmd_list(FILE *f, const char *branch_name,
10764 struct got_object_id_queue *commits)
10766 const struct got_error *err = NULL;
10767 size_t i;
10768 int n;
10769 char *id_str;
10770 struct got_object_qid *qid;
10772 qid = STAILQ_FIRST(commits);
10773 err = got_object_id_str(&id_str, &qid->id);
10774 if (err)
10775 return err;
10777 n = fprintf(f,
10778 "# Editing the history of branch '%s' starting at\n"
10779 "# commit %s\n"
10780 "# Commits will be processed in order from top to "
10781 "bottom of this file.\n", branch_name, id_str);
10782 if (n < 0) {
10783 err = got_ferror(f, GOT_ERR_IO);
10784 goto done;
10787 n = fprintf(f, "# Available histedit commands:\n");
10788 if (n < 0) {
10789 err = got_ferror(f, GOT_ERR_IO);
10790 goto done;
10793 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10794 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10795 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10796 cmd->desc);
10797 if (n < 0) {
10798 err = got_ferror(f, GOT_ERR_IO);
10799 break;
10802 done:
10803 free(id_str);
10804 return err;
10807 static const struct got_error *
10808 histedit_syntax_error(int lineno)
10810 static char msg[42];
10811 int ret;
10813 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10814 lineno);
10815 if (ret < 0 || (size_t)ret >= sizeof(msg))
10816 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10818 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10821 static const struct got_error *
10822 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10823 char *logmsg, struct got_repository *repo)
10825 const struct got_error *err;
10826 struct got_commit_object *folded_commit = NULL;
10827 char *id_str, *folded_logmsg = NULL;
10829 err = got_object_id_str(&id_str, hle->commit_id);
10830 if (err)
10831 return err;
10833 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10834 if (err)
10835 goto done;
10837 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10838 if (err)
10839 goto done;
10840 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10841 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10842 folded_logmsg) == -1) {
10843 err = got_error_from_errno("asprintf");
10845 done:
10846 if (folded_commit)
10847 got_object_commit_close(folded_commit);
10848 free(id_str);
10849 free(folded_logmsg);
10850 return err;
10853 static struct got_histedit_list_entry *
10854 get_folded_commits(struct got_histedit_list_entry *hle)
10856 struct got_histedit_list_entry *prev, *folded = NULL;
10858 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10859 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10860 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10861 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10862 folded = prev;
10863 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10866 return folded;
10869 static const struct got_error *
10870 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10871 struct got_repository *repo)
10873 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10874 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10875 const struct got_error *err = NULL;
10876 struct got_commit_object *commit = NULL;
10877 int logmsg_len;
10878 int fd;
10879 struct got_histedit_list_entry *folded = NULL;
10881 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10882 if (err)
10883 return err;
10885 folded = get_folded_commits(hle);
10886 if (folded) {
10887 while (folded != hle) {
10888 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10889 folded = TAILQ_NEXT(folded, entry);
10890 continue;
10892 err = append_folded_commit_msg(&new_msg, folded,
10893 logmsg, repo);
10894 if (err)
10895 goto done;
10896 free(logmsg);
10897 logmsg = new_msg;
10898 folded = TAILQ_NEXT(folded, entry);
10902 err = got_object_id_str(&id_str, hle->commit_id);
10903 if (err)
10904 goto done;
10905 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10906 if (err)
10907 goto done;
10908 logmsg_len = asprintf(&new_msg,
10909 "%s\n# original log message of commit %s: %s",
10910 logmsg ? logmsg : "", id_str, orig_logmsg);
10911 if (logmsg_len == -1) {
10912 err = got_error_from_errno("asprintf");
10913 goto done;
10915 free(logmsg);
10916 logmsg = new_msg;
10918 err = got_object_id_str(&id_str, hle->commit_id);
10919 if (err)
10920 goto done;
10922 err = got_opentemp_named_fd(&logmsg_path, &fd,
10923 GOT_TMPDIR_STR "/got-logmsg", "");
10924 if (err)
10925 goto done;
10927 write(fd, logmsg, logmsg_len);
10928 close(fd);
10930 err = get_editor(&editor);
10931 if (err)
10932 goto done;
10934 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10935 logmsg_len, 0);
10936 if (err) {
10937 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10938 goto done;
10939 err = NULL;
10940 hle->logmsg = strdup(new_msg);
10941 if (hle->logmsg == NULL)
10942 err = got_error_from_errno("strdup");
10944 done:
10945 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10946 err = got_error_from_errno2("unlink", logmsg_path);
10947 free(logmsg_path);
10948 free(logmsg);
10949 free(orig_logmsg);
10950 free(editor);
10951 if (commit)
10952 got_object_commit_close(commit);
10953 return err;
10956 static const struct got_error *
10957 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10958 FILE *f, struct got_repository *repo)
10960 const struct got_error *err = NULL;
10961 char *line = NULL, *p, *end;
10962 size_t i, size;
10963 ssize_t len;
10964 int lineno = 0, lastcmd = -1;
10965 const struct got_histedit_cmd *cmd;
10966 struct got_object_id *commit_id = NULL;
10967 struct got_histedit_list_entry *hle = NULL;
10969 for (;;) {
10970 len = getline(&line, &size, f);
10971 if (len == -1) {
10972 const struct got_error *getline_err;
10973 if (feof(f))
10974 break;
10975 getline_err = got_error_from_errno("getline");
10976 err = got_ferror(f, getline_err->code);
10977 break;
10979 lineno++;
10980 p = line;
10981 while (isspace((unsigned char)p[0]))
10982 p++;
10983 if (p[0] == '#' || p[0] == '\0') {
10984 free(line);
10985 line = NULL;
10986 continue;
10988 cmd = NULL;
10989 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10990 cmd = &got_histedit_cmds[i];
10991 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10992 isspace((unsigned char)p[strlen(cmd->name)])) {
10993 p += strlen(cmd->name);
10994 break;
10996 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10997 p++;
10998 break;
11001 if (i == nitems(got_histedit_cmds)) {
11002 err = histedit_syntax_error(lineno);
11003 break;
11005 while (isspace((unsigned char)p[0]))
11006 p++;
11007 if (cmd->code == GOT_HISTEDIT_MESG) {
11008 if (lastcmd != GOT_HISTEDIT_PICK &&
11009 lastcmd != GOT_HISTEDIT_EDIT) {
11010 err = got_error(GOT_ERR_HISTEDIT_CMD);
11011 break;
11013 if (p[0] == '\0') {
11014 err = histedit_edit_logmsg(hle, repo);
11015 if (err)
11016 break;
11017 } else {
11018 hle->logmsg = strdup(p);
11019 if (hle->logmsg == NULL) {
11020 err = got_error_from_errno("strdup");
11021 break;
11024 free(line);
11025 line = NULL;
11026 lastcmd = cmd->code;
11027 continue;
11028 } else {
11029 end = p;
11030 while (end[0] && !isspace((unsigned char)end[0]))
11031 end++;
11032 *end = '\0';
11034 err = got_object_resolve_id_str(&commit_id, repo, p);
11035 if (err) {
11036 /* override error code */
11037 err = histedit_syntax_error(lineno);
11038 break;
11041 hle = malloc(sizeof(*hle));
11042 if (hle == NULL) {
11043 err = got_error_from_errno("malloc");
11044 break;
11046 hle->cmd = cmd;
11047 hle->commit_id = commit_id;
11048 hle->logmsg = NULL;
11049 commit_id = NULL;
11050 free(line);
11051 line = NULL;
11052 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11053 lastcmd = cmd->code;
11056 free(line);
11057 free(commit_id);
11058 return err;
11061 static const struct got_error *
11062 histedit_check_script(struct got_histedit_list *histedit_cmds,
11063 struct got_object_id_queue *commits, struct got_repository *repo)
11065 const struct got_error *err = NULL;
11066 struct got_object_qid *qid;
11067 struct got_histedit_list_entry *hle;
11068 static char msg[92];
11069 char *id_str;
11071 if (TAILQ_EMPTY(histedit_cmds))
11072 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11073 "histedit script contains no commands");
11074 if (STAILQ_EMPTY(commits))
11075 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11077 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11078 struct got_histedit_list_entry *hle2;
11079 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11080 if (hle == hle2)
11081 continue;
11082 if (got_object_id_cmp(hle->commit_id,
11083 hle2->commit_id) != 0)
11084 continue;
11085 err = got_object_id_str(&id_str, hle->commit_id);
11086 if (err)
11087 return err;
11088 snprintf(msg, sizeof(msg), "commit %s is listed "
11089 "more than once in histedit script", id_str);
11090 free(id_str);
11091 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11095 STAILQ_FOREACH(qid, commits, entry) {
11096 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11097 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11098 break;
11100 if (hle == NULL) {
11101 err = got_object_id_str(&id_str, &qid->id);
11102 if (err)
11103 return err;
11104 snprintf(msg, sizeof(msg),
11105 "commit %s missing from histedit script", id_str);
11106 free(id_str);
11107 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11111 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11112 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11113 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11114 "last commit in histedit script cannot be folded");
11116 return NULL;
11119 static const struct got_error *
11120 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11121 const char *path, struct got_object_id_queue *commits,
11122 struct got_repository *repo)
11124 const struct got_error *err = NULL;
11125 char *editor;
11126 FILE *f = NULL;
11128 err = get_editor(&editor);
11129 if (err)
11130 return err;
11132 if (spawn_editor(editor, path) == -1) {
11133 err = got_error_from_errno("failed spawning editor");
11134 goto done;
11137 f = fopen(path, "re");
11138 if (f == NULL) {
11139 err = got_error_from_errno("fopen");
11140 goto done;
11142 err = histedit_parse_list(histedit_cmds, f, repo);
11143 if (err)
11144 goto done;
11146 err = histedit_check_script(histedit_cmds, commits, repo);
11147 done:
11148 if (f && fclose(f) == EOF && err == NULL)
11149 err = got_error_from_errno("fclose");
11150 free(editor);
11151 return err;
11154 static const struct got_error *
11155 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11156 struct got_object_id_queue *, const char *, const char *,
11157 struct got_repository *);
11159 static const struct got_error *
11160 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11161 struct got_object_id_queue *commits, const char *branch_name,
11162 int edit_logmsg_only, int fold_only, int edit_only,
11163 struct got_repository *repo)
11165 const struct got_error *err;
11166 FILE *f = NULL;
11167 char *path = NULL;
11169 err = got_opentemp_named(&path, &f, "got-histedit", "");
11170 if (err)
11171 return err;
11173 err = write_cmd_list(f, branch_name, commits);
11174 if (err)
11175 goto done;
11177 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11178 fold_only, edit_only, repo);
11179 if (err)
11180 goto done;
11182 if (edit_logmsg_only || fold_only || edit_only) {
11183 rewind(f);
11184 err = histedit_parse_list(histedit_cmds, f, repo);
11185 } else {
11186 if (fclose(f) == EOF) {
11187 err = got_error_from_errno("fclose");
11188 goto done;
11190 f = NULL;
11191 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11192 if (err) {
11193 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11194 err->code != GOT_ERR_HISTEDIT_CMD)
11195 goto done;
11196 err = histedit_edit_list_retry(histedit_cmds, err,
11197 commits, path, branch_name, repo);
11200 done:
11201 if (f && fclose(f) == EOF && err == NULL)
11202 err = got_error_from_errno("fclose");
11203 if (path && unlink(path) != 0 && err == NULL)
11204 err = got_error_from_errno2("unlink", path);
11205 free(path);
11206 return err;
11209 static const struct got_error *
11210 histedit_save_list(struct got_histedit_list *histedit_cmds,
11211 struct got_worktree *worktree, struct got_repository *repo)
11213 const struct got_error *err = NULL;
11214 char *path = NULL;
11215 FILE *f = NULL;
11216 struct got_histedit_list_entry *hle;
11217 struct got_commit_object *commit = NULL;
11219 err = got_worktree_get_histedit_script_path(&path, worktree);
11220 if (err)
11221 return err;
11223 f = fopen(path, "we");
11224 if (f == NULL) {
11225 err = got_error_from_errno2("fopen", path);
11226 goto done;
11228 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11229 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11230 repo);
11231 if (err)
11232 break;
11234 if (hle->logmsg) {
11235 int n = fprintf(f, "%c %s\n",
11236 GOT_HISTEDIT_MESG, hle->logmsg);
11237 if (n < 0) {
11238 err = got_ferror(f, GOT_ERR_IO);
11239 break;
11243 done:
11244 if (f && fclose(f) == EOF && err == NULL)
11245 err = got_error_from_errno("fclose");
11246 free(path);
11247 if (commit)
11248 got_object_commit_close(commit);
11249 return err;
11252 static void
11253 histedit_free_list(struct got_histedit_list *histedit_cmds)
11255 struct got_histedit_list_entry *hle;
11257 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11258 TAILQ_REMOVE(histedit_cmds, hle, entry);
11259 free(hle);
11263 static const struct got_error *
11264 histedit_load_list(struct got_histedit_list *histedit_cmds,
11265 const char *path, struct got_repository *repo)
11267 const struct got_error *err = NULL;
11268 FILE *f = NULL;
11270 f = fopen(path, "re");
11271 if (f == NULL) {
11272 err = got_error_from_errno2("fopen", path);
11273 goto done;
11276 err = histedit_parse_list(histedit_cmds, f, repo);
11277 done:
11278 if (f && fclose(f) == EOF && err == NULL)
11279 err = got_error_from_errno("fclose");
11280 return err;
11283 static const struct got_error *
11284 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11285 const struct got_error *edit_err, struct got_object_id_queue *commits,
11286 const char *path, const char *branch_name, struct got_repository *repo)
11288 const struct got_error *err = NULL, *prev_err = edit_err;
11289 int resp = ' ';
11291 while (resp != 'c' && resp != 'r' && resp != 'a') {
11292 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11293 "or (a)bort: ", getprogname(), prev_err->msg);
11294 resp = getchar();
11295 if (resp == '\n')
11296 resp = getchar();
11297 if (resp == 'c') {
11298 histedit_free_list(histedit_cmds);
11299 err = histedit_run_editor(histedit_cmds, path, commits,
11300 repo);
11301 if (err) {
11302 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11303 err->code != GOT_ERR_HISTEDIT_CMD)
11304 break;
11305 prev_err = err;
11306 resp = ' ';
11307 continue;
11309 break;
11310 } else if (resp == 'r') {
11311 histedit_free_list(histedit_cmds);
11312 err = histedit_edit_script(histedit_cmds,
11313 commits, branch_name, 0, 0, 0, repo);
11314 if (err) {
11315 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11316 err->code != GOT_ERR_HISTEDIT_CMD)
11317 break;
11318 prev_err = err;
11319 resp = ' ';
11320 continue;
11322 break;
11323 } else if (resp == 'a') {
11324 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11325 break;
11326 } else
11327 printf("invalid response '%c'\n", resp);
11330 return err;
11333 static const struct got_error *
11334 histedit_complete(struct got_worktree *worktree,
11335 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11336 struct got_reference *branch, struct got_repository *repo)
11338 printf("Switching work tree to %s\n",
11339 got_ref_get_symref_target(branch));
11340 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11341 branch, repo);
11344 static const struct got_error *
11345 show_histedit_progress(struct got_commit_object *commit,
11346 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11348 const struct got_error *err;
11349 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11351 err = got_object_id_str(&old_id_str, hle->commit_id);
11352 if (err)
11353 goto done;
11355 if (new_id) {
11356 err = got_object_id_str(&new_id_str, new_id);
11357 if (err)
11358 goto done;
11361 old_id_str[12] = '\0';
11362 if (new_id_str)
11363 new_id_str[12] = '\0';
11365 if (hle->logmsg) {
11366 logmsg = strdup(hle->logmsg);
11367 if (logmsg == NULL) {
11368 err = got_error_from_errno("strdup");
11369 goto done;
11371 trim_logmsg(logmsg, 42);
11372 } else {
11373 err = get_short_logmsg(&logmsg, 42, commit);
11374 if (err)
11375 goto done;
11378 switch (hle->cmd->code) {
11379 case GOT_HISTEDIT_PICK:
11380 case GOT_HISTEDIT_EDIT:
11381 printf("%s -> %s: %s\n", old_id_str,
11382 new_id_str ? new_id_str : "no-op change", logmsg);
11383 break;
11384 case GOT_HISTEDIT_DROP:
11385 case GOT_HISTEDIT_FOLD:
11386 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11387 logmsg);
11388 break;
11389 default:
11390 break;
11392 done:
11393 free(old_id_str);
11394 free(new_id_str);
11395 return err;
11398 static const struct got_error *
11399 histedit_commit(struct got_pathlist_head *merged_paths,
11400 struct got_worktree *worktree, struct got_fileindex *fileindex,
11401 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11402 const char *committer, struct got_repository *repo)
11404 const struct got_error *err;
11405 struct got_commit_object *commit;
11406 struct got_object_id *new_commit_id;
11408 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11409 && hle->logmsg == NULL) {
11410 err = histedit_edit_logmsg(hle, repo);
11411 if (err)
11412 return err;
11415 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11416 if (err)
11417 return err;
11419 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11420 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11421 hle->logmsg, repo);
11422 if (err) {
11423 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11424 goto done;
11425 err = show_histedit_progress(commit, hle, NULL);
11426 } else {
11427 err = show_histedit_progress(commit, hle, new_commit_id);
11428 free(new_commit_id);
11430 done:
11431 got_object_commit_close(commit);
11432 return err;
11435 static const struct got_error *
11436 histedit_skip_commit(struct got_histedit_list_entry *hle,
11437 struct got_worktree *worktree, struct got_repository *repo)
11439 const struct got_error *error;
11440 struct got_commit_object *commit;
11442 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11443 repo);
11444 if (error)
11445 return error;
11447 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11448 if (error)
11449 return error;
11451 error = show_histedit_progress(commit, hle, NULL);
11452 got_object_commit_close(commit);
11453 return error;
11456 static const struct got_error *
11457 check_local_changes(void *arg, unsigned char status,
11458 unsigned char staged_status, const char *path,
11459 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11460 struct got_object_id *commit_id, int dirfd, const char *de_name)
11462 int *have_local_changes = arg;
11464 switch (status) {
11465 case GOT_STATUS_ADD:
11466 case GOT_STATUS_DELETE:
11467 case GOT_STATUS_MODIFY:
11468 case GOT_STATUS_CONFLICT:
11469 *have_local_changes = 1;
11470 return got_error(GOT_ERR_CANCELLED);
11471 default:
11472 break;
11475 switch (staged_status) {
11476 case GOT_STATUS_ADD:
11477 case GOT_STATUS_DELETE:
11478 case GOT_STATUS_MODIFY:
11479 *have_local_changes = 1;
11480 return got_error(GOT_ERR_CANCELLED);
11481 default:
11482 break;
11485 return NULL;
11488 static const struct got_error *
11489 cmd_histedit(int argc, char *argv[])
11491 const struct got_error *error = NULL;
11492 struct got_worktree *worktree = NULL;
11493 struct got_fileindex *fileindex = NULL;
11494 struct got_repository *repo = NULL;
11495 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11496 struct got_reference *branch = NULL;
11497 struct got_reference *tmp_branch = NULL;
11498 struct got_object_id *resume_commit_id = NULL;
11499 struct got_object_id *base_commit_id = NULL;
11500 struct got_object_id *head_commit_id = NULL;
11501 struct got_commit_object *commit = NULL;
11502 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11503 struct got_update_progress_arg upa;
11504 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11505 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11506 int list_backups = 0, delete_backups = 0;
11507 const char *edit_script_path = NULL;
11508 struct got_object_id_queue commits;
11509 struct got_pathlist_head merged_paths;
11510 const struct got_object_id_queue *parent_ids;
11511 struct got_object_qid *pid;
11512 struct got_histedit_list histedit_cmds;
11513 struct got_histedit_list_entry *hle;
11514 int *pack_fds = NULL;
11516 STAILQ_INIT(&commits);
11517 TAILQ_INIT(&histedit_cmds);
11518 TAILQ_INIT(&merged_paths);
11519 memset(&upa, 0, sizeof(upa));
11521 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11522 switch (ch) {
11523 case 'a':
11524 abort_edit = 1;
11525 break;
11526 case 'c':
11527 continue_edit = 1;
11528 break;
11529 case 'e':
11530 edit_only = 1;
11531 break;
11532 case 'F':
11533 edit_script_path = optarg;
11534 break;
11535 case 'f':
11536 fold_only = 1;
11537 break;
11538 case 'l':
11539 list_backups = 1;
11540 break;
11541 case 'm':
11542 edit_logmsg_only = 1;
11543 break;
11544 case 'X':
11545 delete_backups = 1;
11546 break;
11547 default:
11548 usage_histedit();
11549 /* NOTREACHED */
11553 argc -= optind;
11554 argv += optind;
11556 #ifndef PROFILE
11557 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11558 "unveil", NULL) == -1)
11559 err(1, "pledge");
11560 #endif
11561 if (abort_edit && continue_edit)
11562 option_conflict('a', 'c');
11563 if (edit_script_path && edit_logmsg_only)
11564 option_conflict('F', 'm');
11565 if (abort_edit && edit_logmsg_only)
11566 option_conflict('a', 'm');
11567 if (continue_edit && edit_logmsg_only)
11568 option_conflict('c', 'm');
11569 if (abort_edit && fold_only)
11570 option_conflict('a', 'f');
11571 if (continue_edit && fold_only)
11572 option_conflict('c', 'f');
11573 if (fold_only && edit_logmsg_only)
11574 option_conflict('f', 'm');
11575 if (edit_script_path && fold_only)
11576 option_conflict('F', 'f');
11577 if (abort_edit && edit_only)
11578 option_conflict('a', 'e');
11579 if (continue_edit && edit_only)
11580 option_conflict('c', 'e');
11581 if (edit_only && edit_logmsg_only)
11582 option_conflict('e', 'm');
11583 if (edit_script_path && edit_only)
11584 option_conflict('F', 'e');
11585 if (list_backups) {
11586 if (abort_edit)
11587 option_conflict('l', 'a');
11588 if (continue_edit)
11589 option_conflict('l', 'c');
11590 if (edit_script_path)
11591 option_conflict('l', 'F');
11592 if (edit_logmsg_only)
11593 option_conflict('l', 'm');
11594 if (fold_only)
11595 option_conflict('l', 'f');
11596 if (edit_only)
11597 option_conflict('l', 'e');
11598 if (delete_backups)
11599 option_conflict('l', 'X');
11600 if (argc != 0 && argc != 1)
11601 usage_histedit();
11602 } else if (delete_backups) {
11603 if (abort_edit)
11604 option_conflict('X', 'a');
11605 if (continue_edit)
11606 option_conflict('X', 'c');
11607 if (edit_script_path)
11608 option_conflict('X', 'F');
11609 if (edit_logmsg_only)
11610 option_conflict('X', 'm');
11611 if (fold_only)
11612 option_conflict('X', 'f');
11613 if (edit_only)
11614 option_conflict('X', 'e');
11615 if (list_backups)
11616 option_conflict('X', 'l');
11617 if (argc != 0 && argc != 1)
11618 usage_histedit();
11619 } else if (argc != 0)
11620 usage_histedit();
11623 * This command cannot apply unveil(2) in all cases because the
11624 * user may choose to run an editor to edit the histedit script
11625 * and to edit individual commit log messages.
11626 * unveil(2) traverses exec(2); if an editor is used we have to
11627 * apply unveil after edit script and log messages have been written.
11628 * XXX TODO: Make use of unveil(2) where possible.
11631 cwd = getcwd(NULL, 0);
11632 if (cwd == NULL) {
11633 error = got_error_from_errno("getcwd");
11634 goto done;
11637 error = got_repo_pack_fds_open(&pack_fds);
11638 if (error != NULL)
11639 goto done;
11641 error = got_worktree_open(&worktree, cwd);
11642 if (error) {
11643 if (list_backups || delete_backups) {
11644 if (error->code != GOT_ERR_NOT_WORKTREE)
11645 goto done;
11646 } else {
11647 if (error->code == GOT_ERR_NOT_WORKTREE)
11648 error = wrap_not_worktree_error(error,
11649 "histedit", cwd);
11650 goto done;
11654 if (list_backups || delete_backups) {
11655 error = got_repo_open(&repo,
11656 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11657 NULL, pack_fds);
11658 if (error != NULL)
11659 goto done;
11660 error = apply_unveil(got_repo_get_path(repo), 0,
11661 worktree ? got_worktree_get_root_path(worktree) : NULL);
11662 if (error)
11663 goto done;
11664 error = process_backup_refs(
11665 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11666 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11667 goto done; /* nothing else to do */
11670 error = get_gitconfig_path(&gitconfig_path);
11671 if (error)
11672 goto done;
11673 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11674 gitconfig_path, pack_fds);
11675 if (error != NULL)
11676 goto done;
11678 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11679 if (error)
11680 goto done;
11681 if (rebase_in_progress) {
11682 error = got_error(GOT_ERR_REBASING);
11683 goto done;
11686 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11687 repo);
11688 if (error)
11689 goto done;
11690 if (merge_in_progress) {
11691 error = got_error(GOT_ERR_MERGE_BUSY);
11692 goto done;
11695 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11696 if (error)
11697 goto done;
11699 if (edit_in_progress && edit_logmsg_only) {
11700 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11701 "histedit operation is in progress in this "
11702 "work tree and must be continued or aborted "
11703 "before the -m option can be used");
11704 goto done;
11706 if (edit_in_progress && fold_only) {
11707 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11708 "histedit operation is in progress in this "
11709 "work tree and must be continued or aborted "
11710 "before the -f option can be used");
11711 goto done;
11713 if (edit_in_progress && edit_only) {
11714 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11715 "histedit operation is in progress in this "
11716 "work tree and must be continued or aborted "
11717 "before the -e option can be used");
11718 goto done;
11721 if (edit_in_progress && abort_edit) {
11722 error = got_worktree_histedit_continue(&resume_commit_id,
11723 &tmp_branch, &branch, &base_commit_id, &fileindex,
11724 worktree, repo);
11725 if (error)
11726 goto done;
11727 printf("Switching work tree to %s\n",
11728 got_ref_get_symref_target(branch));
11729 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11730 branch, base_commit_id, abort_progress, &upa);
11731 if (error)
11732 goto done;
11733 printf("Histedit of %s aborted\n",
11734 got_ref_get_symref_target(branch));
11735 print_merge_progress_stats(&upa);
11736 goto done; /* nothing else to do */
11737 } else if (abort_edit) {
11738 error = got_error(GOT_ERR_NOT_HISTEDIT);
11739 goto done;
11742 error = get_author(&committer, repo, worktree);
11743 if (error)
11744 goto done;
11746 if (continue_edit) {
11747 char *path;
11749 if (!edit_in_progress) {
11750 error = got_error(GOT_ERR_NOT_HISTEDIT);
11751 goto done;
11754 error = got_worktree_get_histedit_script_path(&path, worktree);
11755 if (error)
11756 goto done;
11758 error = histedit_load_list(&histedit_cmds, path, repo);
11759 free(path);
11760 if (error)
11761 goto done;
11763 error = got_worktree_histedit_continue(&resume_commit_id,
11764 &tmp_branch, &branch, &base_commit_id, &fileindex,
11765 worktree, repo);
11766 if (error)
11767 goto done;
11769 error = got_ref_resolve(&head_commit_id, repo, branch);
11770 if (error)
11771 goto done;
11773 error = got_object_open_as_commit(&commit, repo,
11774 head_commit_id);
11775 if (error)
11776 goto done;
11777 parent_ids = got_object_commit_get_parent_ids(commit);
11778 pid = STAILQ_FIRST(parent_ids);
11779 if (pid == NULL) {
11780 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11781 goto done;
11783 error = collect_commits(&commits, head_commit_id, &pid->id,
11784 base_commit_id, got_worktree_get_path_prefix(worktree),
11785 GOT_ERR_HISTEDIT_PATH, repo);
11786 got_object_commit_close(commit);
11787 commit = NULL;
11788 if (error)
11789 goto done;
11790 } else {
11791 if (edit_in_progress) {
11792 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11793 goto done;
11796 error = got_ref_open(&branch, repo,
11797 got_worktree_get_head_ref_name(worktree), 0);
11798 if (error != NULL)
11799 goto done;
11801 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11802 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11803 "will not edit commit history of a branch outside "
11804 "the \"refs/heads/\" reference namespace");
11805 goto done;
11808 error = got_ref_resolve(&head_commit_id, repo, branch);
11809 got_ref_close(branch);
11810 branch = NULL;
11811 if (error)
11812 goto done;
11814 error = got_object_open_as_commit(&commit, repo,
11815 head_commit_id);
11816 if (error)
11817 goto done;
11818 parent_ids = got_object_commit_get_parent_ids(commit);
11819 pid = STAILQ_FIRST(parent_ids);
11820 if (pid == NULL) {
11821 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11822 goto done;
11824 error = collect_commits(&commits, head_commit_id, &pid->id,
11825 got_worktree_get_base_commit_id(worktree),
11826 got_worktree_get_path_prefix(worktree),
11827 GOT_ERR_HISTEDIT_PATH, repo);
11828 got_object_commit_close(commit);
11829 commit = NULL;
11830 if (error)
11831 goto done;
11833 if (STAILQ_EMPTY(&commits)) {
11834 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11835 goto done;
11838 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11839 &base_commit_id, &fileindex, worktree, repo);
11840 if (error)
11841 goto done;
11843 if (edit_script_path) {
11844 error = histedit_load_list(&histedit_cmds,
11845 edit_script_path, repo);
11846 if (error) {
11847 got_worktree_histedit_abort(worktree, fileindex,
11848 repo, branch, base_commit_id,
11849 abort_progress, &upa);
11850 print_merge_progress_stats(&upa);
11851 goto done;
11853 } else {
11854 const char *branch_name;
11855 branch_name = got_ref_get_symref_target(branch);
11856 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11857 branch_name += 11;
11858 error = histedit_edit_script(&histedit_cmds, &commits,
11859 branch_name, edit_logmsg_only, fold_only,
11860 edit_only, repo);
11861 if (error) {
11862 got_worktree_histedit_abort(worktree, fileindex,
11863 repo, branch, base_commit_id,
11864 abort_progress, &upa);
11865 print_merge_progress_stats(&upa);
11866 goto done;
11871 error = histedit_save_list(&histedit_cmds, worktree,
11872 repo);
11873 if (error) {
11874 got_worktree_histedit_abort(worktree, fileindex,
11875 repo, branch, base_commit_id,
11876 abort_progress, &upa);
11877 print_merge_progress_stats(&upa);
11878 goto done;
11883 error = histedit_check_script(&histedit_cmds, &commits, repo);
11884 if (error)
11885 goto done;
11887 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11888 if (resume_commit_id) {
11889 if (got_object_id_cmp(hle->commit_id,
11890 resume_commit_id) != 0)
11891 continue;
11893 resume_commit_id = NULL;
11894 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11895 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11896 error = histedit_skip_commit(hle, worktree,
11897 repo);
11898 if (error)
11899 goto done;
11900 } else {
11901 struct got_pathlist_head paths;
11902 int have_changes = 0;
11904 TAILQ_INIT(&paths);
11905 error = got_pathlist_append(&paths, "", NULL);
11906 if (error)
11907 goto done;
11908 error = got_worktree_status(worktree, &paths,
11909 repo, 0, check_local_changes, &have_changes,
11910 check_cancelled, NULL);
11911 got_pathlist_free(&paths,
11912 GOT_PATHLIST_FREE_NONE);
11913 if (error) {
11914 if (error->code != GOT_ERR_CANCELLED)
11915 goto done;
11916 if (sigint_received || sigpipe_received)
11917 goto done;
11919 if (have_changes) {
11920 error = histedit_commit(NULL, worktree,
11921 fileindex, tmp_branch, hle,
11922 committer, repo);
11923 if (error)
11924 goto done;
11925 } else {
11926 error = got_object_open_as_commit(
11927 &commit, repo, hle->commit_id);
11928 if (error)
11929 goto done;
11930 error = show_histedit_progress(commit,
11931 hle, NULL);
11932 got_object_commit_close(commit);
11933 commit = NULL;
11934 if (error)
11935 goto done;
11938 continue;
11941 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11942 error = histedit_skip_commit(hle, worktree, repo);
11943 if (error)
11944 goto done;
11945 continue;
11948 error = got_object_open_as_commit(&commit, repo,
11949 hle->commit_id);
11950 if (error)
11951 goto done;
11952 parent_ids = got_object_commit_get_parent_ids(commit);
11953 pid = STAILQ_FIRST(parent_ids);
11955 error = got_worktree_histedit_merge_files(&merged_paths,
11956 worktree, fileindex, &pid->id, hle->commit_id, repo,
11957 update_progress, &upa, check_cancelled, NULL);
11958 if (error)
11959 goto done;
11960 got_object_commit_close(commit);
11961 commit = NULL;
11963 print_merge_progress_stats(&upa);
11964 if (upa.conflicts > 0 || upa.missing > 0 ||
11965 upa.not_deleted > 0 || upa.unversioned > 0) {
11966 if (upa.conflicts > 0) {
11967 error = show_rebase_merge_conflict(
11968 hle->commit_id, repo);
11969 if (error)
11970 goto done;
11972 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11973 break;
11976 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11977 char *id_str;
11978 error = got_object_id_str(&id_str, hle->commit_id);
11979 if (error)
11980 goto done;
11981 printf("Stopping histedit for amending commit %s\n",
11982 id_str);
11983 free(id_str);
11984 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11985 error = got_worktree_histedit_postpone(worktree,
11986 fileindex);
11987 goto done;
11990 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11991 error = histedit_skip_commit(hle, worktree, repo);
11992 if (error)
11993 goto done;
11994 continue;
11997 error = histedit_commit(&merged_paths, worktree, fileindex,
11998 tmp_branch, hle, committer, repo);
11999 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12000 if (error)
12001 goto done;
12004 if (upa.conflicts > 0 || upa.missing > 0 ||
12005 upa.not_deleted > 0 || upa.unversioned > 0) {
12006 error = got_worktree_histedit_postpone(worktree, fileindex);
12007 if (error)
12008 goto done;
12009 if (upa.conflicts > 0 && upa.missing == 0 &&
12010 upa.not_deleted == 0 && upa.unversioned == 0) {
12011 error = got_error_msg(GOT_ERR_CONFLICTS,
12012 "conflicts must be resolved before histedit "
12013 "can continue");
12014 } else if (upa.conflicts > 0) {
12015 error = got_error_msg(GOT_ERR_CONFLICTS,
12016 "conflicts must be resolved before histedit "
12017 "can continue; changes destined for some "
12018 "files were not yet merged and should be "
12019 "merged manually if required before the "
12020 "histedit operation is continued");
12021 } else {
12022 error = got_error_msg(GOT_ERR_CONFLICTS,
12023 "changes destined for some files were not "
12024 "yet merged and should be merged manually "
12025 "if required before the histedit operation "
12026 "is continued");
12028 } else
12029 error = histedit_complete(worktree, fileindex, tmp_branch,
12030 branch, repo);
12031 done:
12032 free(cwd);
12033 free(committer);
12034 free(gitconfig_path);
12035 got_object_id_queue_free(&commits);
12036 histedit_free_list(&histedit_cmds);
12037 free(head_commit_id);
12038 free(base_commit_id);
12039 free(resume_commit_id);
12040 if (commit)
12041 got_object_commit_close(commit);
12042 if (branch)
12043 got_ref_close(branch);
12044 if (tmp_branch)
12045 got_ref_close(tmp_branch);
12046 if (worktree)
12047 got_worktree_close(worktree);
12048 if (repo) {
12049 const struct got_error *close_err = got_repo_close(repo);
12050 if (error == NULL)
12051 error = close_err;
12053 if (pack_fds) {
12054 const struct got_error *pack_err =
12055 got_repo_pack_fds_close(pack_fds);
12056 if (error == NULL)
12057 error = pack_err;
12059 return error;
12062 __dead static void
12063 usage_integrate(void)
12065 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12066 exit(1);
12069 static const struct got_error *
12070 cmd_integrate(int argc, char *argv[])
12072 const struct got_error *error = NULL;
12073 struct got_repository *repo = NULL;
12074 struct got_worktree *worktree = NULL;
12075 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12076 const char *branch_arg = NULL;
12077 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12078 struct got_fileindex *fileindex = NULL;
12079 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12080 int ch;
12081 struct got_update_progress_arg upa;
12082 int *pack_fds = NULL;
12084 while ((ch = getopt(argc, argv, "")) != -1) {
12085 switch (ch) {
12086 default:
12087 usage_integrate();
12088 /* NOTREACHED */
12092 argc -= optind;
12093 argv += optind;
12095 if (argc != 1)
12096 usage_integrate();
12097 branch_arg = argv[0];
12098 #ifndef PROFILE
12099 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12100 "unveil", NULL) == -1)
12101 err(1, "pledge");
12102 #endif
12103 cwd = getcwd(NULL, 0);
12104 if (cwd == NULL) {
12105 error = got_error_from_errno("getcwd");
12106 goto done;
12109 error = got_repo_pack_fds_open(&pack_fds);
12110 if (error != NULL)
12111 goto done;
12113 error = got_worktree_open(&worktree, cwd);
12114 if (error) {
12115 if (error->code == GOT_ERR_NOT_WORKTREE)
12116 error = wrap_not_worktree_error(error, "integrate",
12117 cwd);
12118 goto done;
12121 error = check_rebase_or_histedit_in_progress(worktree);
12122 if (error)
12123 goto done;
12125 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12126 NULL, pack_fds);
12127 if (error != NULL)
12128 goto done;
12130 error = apply_unveil(got_repo_get_path(repo), 0,
12131 got_worktree_get_root_path(worktree));
12132 if (error)
12133 goto done;
12135 error = check_merge_in_progress(worktree, repo);
12136 if (error)
12137 goto done;
12139 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12140 error = got_error_from_errno("asprintf");
12141 goto done;
12144 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12145 &base_branch_ref, worktree, refname, repo);
12146 if (error)
12147 goto done;
12149 refname = strdup(got_ref_get_name(branch_ref));
12150 if (refname == NULL) {
12151 error = got_error_from_errno("strdup");
12152 got_worktree_integrate_abort(worktree, fileindex, repo,
12153 branch_ref, base_branch_ref);
12154 goto done;
12156 base_refname = strdup(got_ref_get_name(base_branch_ref));
12157 if (base_refname == NULL) {
12158 error = got_error_from_errno("strdup");
12159 got_worktree_integrate_abort(worktree, fileindex, repo,
12160 branch_ref, base_branch_ref);
12161 goto done;
12163 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12164 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12165 got_worktree_integrate_abort(worktree, fileindex, repo,
12166 branch_ref, base_branch_ref);
12167 goto done;
12170 error = got_ref_resolve(&commit_id, repo, branch_ref);
12171 if (error)
12172 goto done;
12174 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12175 if (error)
12176 goto done;
12178 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12179 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12180 "specified branch has already been integrated");
12181 got_worktree_integrate_abort(worktree, fileindex, repo,
12182 branch_ref, base_branch_ref);
12183 goto done;
12186 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12187 if (error) {
12188 if (error->code == GOT_ERR_ANCESTRY)
12189 error = got_error(GOT_ERR_REBASE_REQUIRED);
12190 got_worktree_integrate_abort(worktree, fileindex, repo,
12191 branch_ref, base_branch_ref);
12192 goto done;
12195 memset(&upa, 0, sizeof(upa));
12196 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12197 branch_ref, base_branch_ref, update_progress, &upa,
12198 check_cancelled, NULL);
12199 if (error)
12200 goto done;
12202 printf("Integrated %s into %s\n", refname, base_refname);
12203 print_update_progress_stats(&upa);
12204 done:
12205 if (repo) {
12206 const struct got_error *close_err = got_repo_close(repo);
12207 if (error == NULL)
12208 error = close_err;
12210 if (worktree)
12211 got_worktree_close(worktree);
12212 if (pack_fds) {
12213 const struct got_error *pack_err =
12214 got_repo_pack_fds_close(pack_fds);
12215 if (error == NULL)
12216 error = pack_err;
12218 free(cwd);
12219 free(base_commit_id);
12220 free(commit_id);
12221 free(refname);
12222 free(base_refname);
12223 return error;
12226 __dead static void
12227 usage_merge(void)
12229 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12230 exit(1);
12233 static const struct got_error *
12234 cmd_merge(int argc, char *argv[])
12236 const struct got_error *error = NULL;
12237 struct got_worktree *worktree = NULL;
12238 struct got_repository *repo = NULL;
12239 struct got_fileindex *fileindex = NULL;
12240 char *cwd = NULL, *id_str = NULL, *author = NULL;
12241 struct got_reference *branch = NULL, *wt_branch = NULL;
12242 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12243 struct got_object_id *wt_branch_tip = NULL;
12244 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12245 int interrupt_merge = 0;
12246 struct got_update_progress_arg upa;
12247 struct got_object_id *merge_commit_id = NULL;
12248 char *branch_name = NULL;
12249 int *pack_fds = NULL;
12251 memset(&upa, 0, sizeof(upa));
12253 while ((ch = getopt(argc, argv, "acn")) != -1) {
12254 switch (ch) {
12255 case 'a':
12256 abort_merge = 1;
12257 break;
12258 case 'c':
12259 continue_merge = 1;
12260 break;
12261 case 'n':
12262 interrupt_merge = 1;
12263 break;
12264 default:
12265 usage_rebase();
12266 /* NOTREACHED */
12270 argc -= optind;
12271 argv += optind;
12273 #ifndef PROFILE
12274 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12275 "unveil", NULL) == -1)
12276 err(1, "pledge");
12277 #endif
12279 if (abort_merge && continue_merge)
12280 option_conflict('a', 'c');
12281 if (abort_merge || continue_merge) {
12282 if (argc != 0)
12283 usage_merge();
12284 } else if (argc != 1)
12285 usage_merge();
12287 cwd = getcwd(NULL, 0);
12288 if (cwd == NULL) {
12289 error = got_error_from_errno("getcwd");
12290 goto done;
12293 error = got_repo_pack_fds_open(&pack_fds);
12294 if (error != NULL)
12295 goto done;
12297 error = got_worktree_open(&worktree, cwd);
12298 if (error) {
12299 if (error->code == GOT_ERR_NOT_WORKTREE)
12300 error = wrap_not_worktree_error(error,
12301 "merge", cwd);
12302 goto done;
12305 error = got_repo_open(&repo,
12306 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12307 pack_fds);
12308 if (error != NULL)
12309 goto done;
12311 error = apply_unveil(got_repo_get_path(repo), 0,
12312 worktree ? got_worktree_get_root_path(worktree) : NULL);
12313 if (error)
12314 goto done;
12316 error = check_rebase_or_histedit_in_progress(worktree);
12317 if (error)
12318 goto done;
12320 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12321 repo);
12322 if (error)
12323 goto done;
12325 if (abort_merge) {
12326 if (!merge_in_progress) {
12327 error = got_error(GOT_ERR_NOT_MERGING);
12328 goto done;
12330 error = got_worktree_merge_continue(&branch_name,
12331 &branch_tip, &fileindex, worktree, repo);
12332 if (error)
12333 goto done;
12334 error = got_worktree_merge_abort(worktree, fileindex, repo,
12335 abort_progress, &upa);
12336 if (error)
12337 goto done;
12338 printf("Merge of %s aborted\n", branch_name);
12339 goto done; /* nothing else to do */
12342 error = get_author(&author, repo, worktree);
12343 if (error)
12344 goto done;
12346 if (continue_merge) {
12347 if (!merge_in_progress) {
12348 error = got_error(GOT_ERR_NOT_MERGING);
12349 goto done;
12351 error = got_worktree_merge_continue(&branch_name,
12352 &branch_tip, &fileindex, worktree, repo);
12353 if (error)
12354 goto done;
12355 } else {
12356 error = got_ref_open(&branch, repo, argv[0], 0);
12357 if (error != NULL)
12358 goto done;
12359 branch_name = strdup(got_ref_get_name(branch));
12360 if (branch_name == NULL) {
12361 error = got_error_from_errno("strdup");
12362 goto done;
12364 error = got_ref_resolve(&branch_tip, repo, branch);
12365 if (error)
12366 goto done;
12369 error = got_ref_open(&wt_branch, repo,
12370 got_worktree_get_head_ref_name(worktree), 0);
12371 if (error)
12372 goto done;
12373 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12374 if (error)
12375 goto done;
12376 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12377 wt_branch_tip, branch_tip, 0, repo,
12378 check_cancelled, NULL);
12379 if (error && error->code != GOT_ERR_ANCESTRY)
12380 goto done;
12382 if (!continue_merge) {
12383 error = check_path_prefix(wt_branch_tip, branch_tip,
12384 got_worktree_get_path_prefix(worktree),
12385 GOT_ERR_MERGE_PATH, repo);
12386 if (error)
12387 goto done;
12388 if (yca_id) {
12389 error = check_same_branch(wt_branch_tip, branch,
12390 yca_id, repo);
12391 if (error) {
12392 if (error->code != GOT_ERR_ANCESTRY)
12393 goto done;
12394 error = NULL;
12395 } else {
12396 static char msg[512];
12397 snprintf(msg, sizeof(msg),
12398 "cannot create a merge commit because "
12399 "%s is based on %s; %s can be integrated "
12400 "with 'got integrate' instead", branch_name,
12401 got_worktree_get_head_ref_name(worktree),
12402 branch_name);
12403 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12404 goto done;
12407 error = got_worktree_merge_prepare(&fileindex, worktree,
12408 branch, repo);
12409 if (error)
12410 goto done;
12412 error = got_worktree_merge_branch(worktree, fileindex,
12413 yca_id, branch_tip, repo, update_progress, &upa,
12414 check_cancelled, NULL);
12415 if (error)
12416 goto done;
12417 print_merge_progress_stats(&upa);
12418 if (!upa.did_something) {
12419 error = got_worktree_merge_abort(worktree, fileindex,
12420 repo, abort_progress, &upa);
12421 if (error)
12422 goto done;
12423 printf("Already up-to-date\n");
12424 goto done;
12428 if (interrupt_merge) {
12429 error = got_worktree_merge_postpone(worktree, fileindex);
12430 if (error)
12431 goto done;
12432 printf("Merge of %s interrupted on request\n", branch_name);
12433 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12434 upa.not_deleted > 0 || upa.unversioned > 0) {
12435 error = got_worktree_merge_postpone(worktree, fileindex);
12436 if (error)
12437 goto done;
12438 if (upa.conflicts > 0 && upa.missing == 0 &&
12439 upa.not_deleted == 0 && upa.unversioned == 0) {
12440 error = got_error_msg(GOT_ERR_CONFLICTS,
12441 "conflicts must be resolved before merging "
12442 "can continue");
12443 } else if (upa.conflicts > 0) {
12444 error = got_error_msg(GOT_ERR_CONFLICTS,
12445 "conflicts must be resolved before merging "
12446 "can continue; changes destined for some "
12447 "files were not yet merged and "
12448 "should be merged manually if required before the "
12449 "merge operation is continued");
12450 } else {
12451 error = got_error_msg(GOT_ERR_CONFLICTS,
12452 "changes destined for some "
12453 "files were not yet merged and should be "
12454 "merged manually if required before the "
12455 "merge operation is continued");
12457 goto done;
12458 } else {
12459 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12460 fileindex, author, NULL, 1, branch_tip, branch_name,
12461 repo, continue_merge ? print_status : NULL, NULL);
12462 if (error)
12463 goto done;
12464 error = got_worktree_merge_complete(worktree, fileindex, repo);
12465 if (error)
12466 goto done;
12467 error = got_object_id_str(&id_str, merge_commit_id);
12468 if (error)
12469 goto done;
12470 printf("Merged %s into %s: %s\n", branch_name,
12471 got_worktree_get_head_ref_name(worktree),
12472 id_str);
12475 done:
12476 free(id_str);
12477 free(merge_commit_id);
12478 free(author);
12479 free(branch_tip);
12480 free(branch_name);
12481 free(yca_id);
12482 if (branch)
12483 got_ref_close(branch);
12484 if (wt_branch)
12485 got_ref_close(wt_branch);
12486 if (worktree)
12487 got_worktree_close(worktree);
12488 if (repo) {
12489 const struct got_error *close_err = got_repo_close(repo);
12490 if (error == NULL)
12491 error = close_err;
12493 if (pack_fds) {
12494 const struct got_error *pack_err =
12495 got_repo_pack_fds_close(pack_fds);
12496 if (error == NULL)
12497 error = pack_err;
12499 return error;
12502 __dead static void
12503 usage_stage(void)
12505 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12506 "[path ...]\n", getprogname());
12507 exit(1);
12510 static const struct got_error *
12511 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12512 const char *path, struct got_object_id *blob_id,
12513 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12514 int dirfd, const char *de_name)
12516 const struct got_error *err = NULL;
12517 char *id_str = NULL;
12519 if (staged_status != GOT_STATUS_ADD &&
12520 staged_status != GOT_STATUS_MODIFY &&
12521 staged_status != GOT_STATUS_DELETE)
12522 return NULL;
12524 if (staged_status == GOT_STATUS_ADD ||
12525 staged_status == GOT_STATUS_MODIFY)
12526 err = got_object_id_str(&id_str, staged_blob_id);
12527 else
12528 err = got_object_id_str(&id_str, blob_id);
12529 if (err)
12530 return err;
12532 printf("%s %c %s\n", id_str, staged_status, path);
12533 free(id_str);
12534 return NULL;
12537 static const struct got_error *
12538 cmd_stage(int argc, char *argv[])
12540 const struct got_error *error = NULL;
12541 struct got_repository *repo = NULL;
12542 struct got_worktree *worktree = NULL;
12543 char *cwd = NULL;
12544 struct got_pathlist_head paths;
12545 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12546 FILE *patch_script_file = NULL;
12547 const char *patch_script_path = NULL;
12548 struct choose_patch_arg cpa;
12549 int *pack_fds = NULL;
12551 TAILQ_INIT(&paths);
12553 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12554 switch (ch) {
12555 case 'F':
12556 patch_script_path = optarg;
12557 break;
12558 case 'l':
12559 list_stage = 1;
12560 break;
12561 case 'p':
12562 pflag = 1;
12563 break;
12564 case 'S':
12565 allow_bad_symlinks = 1;
12566 break;
12567 default:
12568 usage_stage();
12569 /* NOTREACHED */
12573 argc -= optind;
12574 argv += optind;
12576 #ifndef PROFILE
12577 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12578 "unveil", NULL) == -1)
12579 err(1, "pledge");
12580 #endif
12581 if (list_stage && (pflag || patch_script_path))
12582 errx(1, "-l option cannot be used with other options");
12583 if (patch_script_path && !pflag)
12584 errx(1, "-F option can only be used together with -p option");
12586 cwd = getcwd(NULL, 0);
12587 if (cwd == NULL) {
12588 error = got_error_from_errno("getcwd");
12589 goto done;
12592 error = got_repo_pack_fds_open(&pack_fds);
12593 if (error != NULL)
12594 goto done;
12596 error = got_worktree_open(&worktree, cwd);
12597 if (error) {
12598 if (error->code == GOT_ERR_NOT_WORKTREE)
12599 error = wrap_not_worktree_error(error, "stage", cwd);
12600 goto done;
12603 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12604 NULL, pack_fds);
12605 if (error != NULL)
12606 goto done;
12608 if (patch_script_path) {
12609 patch_script_file = fopen(patch_script_path, "re");
12610 if (patch_script_file == NULL) {
12611 error = got_error_from_errno2("fopen",
12612 patch_script_path);
12613 goto done;
12616 error = apply_unveil(got_repo_get_path(repo), 0,
12617 got_worktree_get_root_path(worktree));
12618 if (error)
12619 goto done;
12621 error = check_merge_in_progress(worktree, repo);
12622 if (error)
12623 goto done;
12625 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12626 if (error)
12627 goto done;
12629 if (list_stage)
12630 error = got_worktree_status(worktree, &paths, repo, 0,
12631 print_stage, NULL, check_cancelled, NULL);
12632 else {
12633 cpa.patch_script_file = patch_script_file;
12634 cpa.action = "stage";
12635 error = got_worktree_stage(worktree, &paths,
12636 pflag ? NULL : print_status, NULL,
12637 pflag ? choose_patch : NULL, &cpa,
12638 allow_bad_symlinks, repo);
12640 done:
12641 if (patch_script_file && fclose(patch_script_file) == EOF &&
12642 error == NULL)
12643 error = got_error_from_errno2("fclose", patch_script_path);
12644 if (repo) {
12645 const struct got_error *close_err = got_repo_close(repo);
12646 if (error == NULL)
12647 error = close_err;
12649 if (worktree)
12650 got_worktree_close(worktree);
12651 if (pack_fds) {
12652 const struct got_error *pack_err =
12653 got_repo_pack_fds_close(pack_fds);
12654 if (error == NULL)
12655 error = pack_err;
12657 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12658 free(cwd);
12659 return error;
12662 __dead static void
12663 usage_unstage(void)
12665 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12666 "[path ...]\n", getprogname());
12667 exit(1);
12671 static const struct got_error *
12672 cmd_unstage(int argc, char *argv[])
12674 const struct got_error *error = NULL;
12675 struct got_repository *repo = NULL;
12676 struct got_worktree *worktree = NULL;
12677 char *cwd = NULL;
12678 struct got_pathlist_head paths;
12679 int ch, pflag = 0;
12680 struct got_update_progress_arg upa;
12681 FILE *patch_script_file = NULL;
12682 const char *patch_script_path = NULL;
12683 struct choose_patch_arg cpa;
12684 int *pack_fds = NULL;
12686 TAILQ_INIT(&paths);
12688 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12689 switch (ch) {
12690 case 'F':
12691 patch_script_path = optarg;
12692 break;
12693 case 'p':
12694 pflag = 1;
12695 break;
12696 default:
12697 usage_unstage();
12698 /* NOTREACHED */
12702 argc -= optind;
12703 argv += optind;
12705 #ifndef PROFILE
12706 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12707 "unveil", NULL) == -1)
12708 err(1, "pledge");
12709 #endif
12710 if (patch_script_path && !pflag)
12711 errx(1, "-F option can only be used together with -p option");
12713 cwd = getcwd(NULL, 0);
12714 if (cwd == NULL) {
12715 error = got_error_from_errno("getcwd");
12716 goto done;
12719 error = got_repo_pack_fds_open(&pack_fds);
12720 if (error != NULL)
12721 goto done;
12723 error = got_worktree_open(&worktree, cwd);
12724 if (error) {
12725 if (error->code == GOT_ERR_NOT_WORKTREE)
12726 error = wrap_not_worktree_error(error, "unstage", cwd);
12727 goto done;
12730 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12731 NULL, pack_fds);
12732 if (error != NULL)
12733 goto done;
12735 if (patch_script_path) {
12736 patch_script_file = fopen(patch_script_path, "re");
12737 if (patch_script_file == NULL) {
12738 error = got_error_from_errno2("fopen",
12739 patch_script_path);
12740 goto done;
12744 error = apply_unveil(got_repo_get_path(repo), 0,
12745 got_worktree_get_root_path(worktree));
12746 if (error)
12747 goto done;
12749 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12750 if (error)
12751 goto done;
12753 cpa.patch_script_file = patch_script_file;
12754 cpa.action = "unstage";
12755 memset(&upa, 0, sizeof(upa));
12756 error = got_worktree_unstage(worktree, &paths, update_progress,
12757 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12758 if (!error)
12759 print_merge_progress_stats(&upa);
12760 done:
12761 if (patch_script_file && fclose(patch_script_file) == EOF &&
12762 error == NULL)
12763 error = got_error_from_errno2("fclose", patch_script_path);
12764 if (repo) {
12765 const struct got_error *close_err = got_repo_close(repo);
12766 if (error == NULL)
12767 error = close_err;
12769 if (worktree)
12770 got_worktree_close(worktree);
12771 if (pack_fds) {
12772 const struct got_error *pack_err =
12773 got_repo_pack_fds_close(pack_fds);
12774 if (error == NULL)
12775 error = pack_err;
12777 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
12778 free(cwd);
12779 return error;
12782 __dead static void
12783 usage_cat(void)
12785 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12786 "arg ...\n", getprogname());
12787 exit(1);
12790 static const struct got_error *
12791 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12793 const struct got_error *err;
12794 struct got_blob_object *blob;
12795 int fd = -1;
12797 fd = got_opentempfd();
12798 if (fd == -1)
12799 return got_error_from_errno("got_opentempfd");
12801 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12802 if (err)
12803 goto done;
12805 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12806 done:
12807 if (fd != -1 && close(fd) == -1 && err == NULL)
12808 err = got_error_from_errno("close");
12809 if (blob)
12810 got_object_blob_close(blob);
12811 return err;
12814 static const struct got_error *
12815 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12817 const struct got_error *err;
12818 struct got_tree_object *tree;
12819 int nentries, i;
12821 err = got_object_open_as_tree(&tree, repo, id);
12822 if (err)
12823 return err;
12825 nentries = got_object_tree_get_nentries(tree);
12826 for (i = 0; i < nentries; i++) {
12827 struct got_tree_entry *te;
12828 char *id_str;
12829 if (sigint_received || sigpipe_received)
12830 break;
12831 te = got_object_tree_get_entry(tree, i);
12832 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12833 if (err)
12834 break;
12835 fprintf(outfile, "%s %.7o %s\n", id_str,
12836 got_tree_entry_get_mode(te),
12837 got_tree_entry_get_name(te));
12838 free(id_str);
12841 got_object_tree_close(tree);
12842 return err;
12845 static const struct got_error *
12846 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12848 const struct got_error *err;
12849 struct got_commit_object *commit;
12850 const struct got_object_id_queue *parent_ids;
12851 struct got_object_qid *pid;
12852 char *id_str = NULL;
12853 const char *logmsg = NULL;
12854 char gmtoff[6];
12856 err = got_object_open_as_commit(&commit, repo, id);
12857 if (err)
12858 return err;
12860 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12861 if (err)
12862 goto done;
12864 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12865 parent_ids = got_object_commit_get_parent_ids(commit);
12866 fprintf(outfile, "numparents %d\n",
12867 got_object_commit_get_nparents(commit));
12868 STAILQ_FOREACH(pid, parent_ids, entry) {
12869 char *pid_str;
12870 err = got_object_id_str(&pid_str, &pid->id);
12871 if (err)
12872 goto done;
12873 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12874 free(pid_str);
12876 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12877 got_object_commit_get_author_gmtoff(commit));
12878 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12879 got_object_commit_get_author(commit),
12880 (long long)got_object_commit_get_author_time(commit),
12881 gmtoff);
12883 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12884 got_object_commit_get_committer_gmtoff(commit));
12885 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12886 got_object_commit_get_committer(commit),
12887 (long long)got_object_commit_get_committer_time(commit),
12888 gmtoff);
12890 logmsg = got_object_commit_get_logmsg_raw(commit);
12891 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12892 fprintf(outfile, "%s", logmsg);
12893 done:
12894 free(id_str);
12895 got_object_commit_close(commit);
12896 return err;
12899 static const struct got_error *
12900 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12902 const struct got_error *err;
12903 struct got_tag_object *tag;
12904 char *id_str = NULL;
12905 const char *tagmsg = NULL;
12906 char gmtoff[6];
12908 err = got_object_open_as_tag(&tag, repo, id);
12909 if (err)
12910 return err;
12912 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12913 if (err)
12914 goto done;
12916 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12918 switch (got_object_tag_get_object_type(tag)) {
12919 case GOT_OBJ_TYPE_BLOB:
12920 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12921 GOT_OBJ_LABEL_BLOB);
12922 break;
12923 case GOT_OBJ_TYPE_TREE:
12924 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12925 GOT_OBJ_LABEL_TREE);
12926 break;
12927 case GOT_OBJ_TYPE_COMMIT:
12928 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12929 GOT_OBJ_LABEL_COMMIT);
12930 break;
12931 case GOT_OBJ_TYPE_TAG:
12932 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12933 GOT_OBJ_LABEL_TAG);
12934 break;
12935 default:
12936 break;
12939 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12940 got_object_tag_get_name(tag));
12942 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12943 got_object_tag_get_tagger_gmtoff(tag));
12944 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12945 got_object_tag_get_tagger(tag),
12946 (long long)got_object_tag_get_tagger_time(tag),
12947 gmtoff);
12949 tagmsg = got_object_tag_get_message(tag);
12950 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12951 fprintf(outfile, "%s", tagmsg);
12952 done:
12953 free(id_str);
12954 got_object_tag_close(tag);
12955 return err;
12958 static const struct got_error *
12959 cmd_cat(int argc, char *argv[])
12961 const struct got_error *error;
12962 struct got_repository *repo = NULL;
12963 struct got_worktree *worktree = NULL;
12964 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12965 const char *commit_id_str = NULL;
12966 struct got_object_id *id = NULL, *commit_id = NULL;
12967 struct got_commit_object *commit = NULL;
12968 int ch, obj_type, i, force_path = 0;
12969 struct got_reflist_head refs;
12970 int *pack_fds = NULL;
12972 TAILQ_INIT(&refs);
12974 #ifndef PROFILE
12975 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12976 NULL) == -1)
12977 err(1, "pledge");
12978 #endif
12980 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12981 switch (ch) {
12982 case 'c':
12983 commit_id_str = optarg;
12984 break;
12985 case 'P':
12986 force_path = 1;
12987 break;
12988 case 'r':
12989 repo_path = realpath(optarg, NULL);
12990 if (repo_path == NULL)
12991 return got_error_from_errno2("realpath",
12992 optarg);
12993 got_path_strip_trailing_slashes(repo_path);
12994 break;
12995 default:
12996 usage_cat();
12997 /* NOTREACHED */
13001 argc -= optind;
13002 argv += optind;
13004 cwd = getcwd(NULL, 0);
13005 if (cwd == NULL) {
13006 error = got_error_from_errno("getcwd");
13007 goto done;
13010 error = got_repo_pack_fds_open(&pack_fds);
13011 if (error != NULL)
13012 goto done;
13014 if (repo_path == NULL) {
13015 error = got_worktree_open(&worktree, cwd);
13016 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13017 goto done;
13018 if (worktree) {
13019 repo_path = strdup(
13020 got_worktree_get_repo_path(worktree));
13021 if (repo_path == NULL) {
13022 error = got_error_from_errno("strdup");
13023 goto done;
13026 /* Release work tree lock. */
13027 got_worktree_close(worktree);
13028 worktree = NULL;
13032 if (repo_path == NULL) {
13033 repo_path = strdup(cwd);
13034 if (repo_path == NULL)
13035 return got_error_from_errno("strdup");
13038 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13039 free(repo_path);
13040 if (error != NULL)
13041 goto done;
13043 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13044 if (error)
13045 goto done;
13047 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13048 if (error)
13049 goto done;
13051 if (commit_id_str == NULL)
13052 commit_id_str = GOT_REF_HEAD;
13053 error = got_repo_match_object_id(&commit_id, NULL,
13054 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13055 if (error)
13056 goto done;
13058 error = got_object_open_as_commit(&commit, repo, commit_id);
13059 if (error)
13060 goto done;
13062 for (i = 0; i < argc; i++) {
13063 if (force_path) {
13064 error = got_object_id_by_path(&id, repo, commit,
13065 argv[i]);
13066 if (error)
13067 break;
13068 } else {
13069 error = got_repo_match_object_id(&id, &label, argv[i],
13070 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13071 repo);
13072 if (error) {
13073 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13074 error->code != GOT_ERR_NOT_REF)
13075 break;
13076 error = got_object_id_by_path(&id, repo,
13077 commit, argv[i]);
13078 if (error)
13079 break;
13083 error = got_object_get_type(&obj_type, repo, id);
13084 if (error)
13085 break;
13087 switch (obj_type) {
13088 case GOT_OBJ_TYPE_BLOB:
13089 error = cat_blob(id, repo, stdout);
13090 break;
13091 case GOT_OBJ_TYPE_TREE:
13092 error = cat_tree(id, repo, stdout);
13093 break;
13094 case GOT_OBJ_TYPE_COMMIT:
13095 error = cat_commit(id, repo, stdout);
13096 break;
13097 case GOT_OBJ_TYPE_TAG:
13098 error = cat_tag(id, repo, stdout);
13099 break;
13100 default:
13101 error = got_error(GOT_ERR_OBJ_TYPE);
13102 break;
13104 if (error)
13105 break;
13106 free(label);
13107 label = NULL;
13108 free(id);
13109 id = NULL;
13111 done:
13112 free(label);
13113 free(id);
13114 free(commit_id);
13115 if (commit)
13116 got_object_commit_close(commit);
13117 if (worktree)
13118 got_worktree_close(worktree);
13119 if (repo) {
13120 const struct got_error *close_err = got_repo_close(repo);
13121 if (error == NULL)
13122 error = close_err;
13124 if (pack_fds) {
13125 const struct got_error *pack_err =
13126 got_repo_pack_fds_close(pack_fds);
13127 if (error == NULL)
13128 error = pack_err;
13131 got_ref_list_free(&refs);
13132 return error;
13135 __dead static void
13136 usage_info(void)
13138 fprintf(stderr, "usage: %s info [path ...]\n",
13139 getprogname());
13140 exit(1);
13143 static const struct got_error *
13144 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13145 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13146 struct got_object_id *commit_id)
13148 const struct got_error *err = NULL;
13149 char *id_str = NULL;
13150 char datebuf[128];
13151 struct tm mytm, *tm;
13152 struct got_pathlist_head *paths = arg;
13153 struct got_pathlist_entry *pe;
13156 * Clear error indication from any of the path arguments which
13157 * would cause this file index entry to be displayed.
13159 TAILQ_FOREACH(pe, paths, entry) {
13160 if (got_path_cmp(path, pe->path, strlen(path),
13161 pe->path_len) == 0 ||
13162 got_path_is_child(path, pe->path, pe->path_len))
13163 pe->data = NULL; /* no error */
13166 printf(GOT_COMMIT_SEP_STR);
13167 if (S_ISLNK(mode))
13168 printf("symlink: %s\n", path);
13169 else if (S_ISREG(mode)) {
13170 printf("file: %s\n", path);
13171 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13172 } else if (S_ISDIR(mode))
13173 printf("directory: %s\n", path);
13174 else
13175 printf("something: %s\n", path);
13177 tm = localtime_r(&mtime, &mytm);
13178 if (tm == NULL)
13179 return NULL;
13180 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13181 return got_error(GOT_ERR_NO_SPACE);
13182 printf("timestamp: %s\n", datebuf);
13184 if (blob_id) {
13185 err = got_object_id_str(&id_str, blob_id);
13186 if (err)
13187 return err;
13188 printf("based on blob: %s\n", id_str);
13189 free(id_str);
13192 if (staged_blob_id) {
13193 err = got_object_id_str(&id_str, staged_blob_id);
13194 if (err)
13195 return err;
13196 printf("based on staged blob: %s\n", id_str);
13197 free(id_str);
13200 if (commit_id) {
13201 err = got_object_id_str(&id_str, commit_id);
13202 if (err)
13203 return err;
13204 printf("based on commit: %s\n", id_str);
13205 free(id_str);
13208 return NULL;
13211 static const struct got_error *
13212 cmd_info(int argc, char *argv[])
13214 const struct got_error *error = NULL;
13215 struct got_worktree *worktree = NULL;
13216 char *cwd = NULL, *id_str = NULL;
13217 struct got_pathlist_head paths;
13218 char *uuidstr = NULL;
13219 int ch, show_files = 0;
13221 TAILQ_INIT(&paths);
13223 while ((ch = getopt(argc, argv, "")) != -1) {
13224 switch (ch) {
13225 default:
13226 usage_info();
13227 /* NOTREACHED */
13231 argc -= optind;
13232 argv += optind;
13234 #ifndef PROFILE
13235 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13236 NULL) == -1)
13237 err(1, "pledge");
13238 #endif
13239 cwd = getcwd(NULL, 0);
13240 if (cwd == NULL) {
13241 error = got_error_from_errno("getcwd");
13242 goto done;
13245 error = got_worktree_open(&worktree, cwd);
13246 if (error) {
13247 if (error->code == GOT_ERR_NOT_WORKTREE)
13248 error = wrap_not_worktree_error(error, "info", cwd);
13249 goto done;
13252 #ifndef PROFILE
13253 /* Remove "wpath cpath proc exec sendfd" promises. */
13254 if (pledge("stdio rpath flock unveil", NULL) == -1)
13255 err(1, "pledge");
13256 #endif
13257 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13258 if (error)
13259 goto done;
13261 if (argc >= 1) {
13262 error = get_worktree_paths_from_argv(&paths, argc, argv,
13263 worktree);
13264 if (error)
13265 goto done;
13266 show_files = 1;
13269 error = got_object_id_str(&id_str,
13270 got_worktree_get_base_commit_id(worktree));
13271 if (error)
13272 goto done;
13274 error = got_worktree_get_uuid(&uuidstr, worktree);
13275 if (error)
13276 goto done;
13278 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13279 printf("work tree base commit: %s\n", id_str);
13280 printf("work tree path prefix: %s\n",
13281 got_worktree_get_path_prefix(worktree));
13282 printf("work tree branch reference: %s\n",
13283 got_worktree_get_head_ref_name(worktree));
13284 printf("work tree UUID: %s\n", uuidstr);
13285 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13287 if (show_files) {
13288 struct got_pathlist_entry *pe;
13289 TAILQ_FOREACH(pe, &paths, entry) {
13290 if (pe->path_len == 0)
13291 continue;
13293 * Assume this path will fail. This will be corrected
13294 * in print_path_info() in case the path does suceeed.
13296 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13298 error = got_worktree_path_info(worktree, &paths,
13299 print_path_info, &paths, check_cancelled, NULL);
13300 if (error)
13301 goto done;
13302 TAILQ_FOREACH(pe, &paths, entry) {
13303 if (pe->data != NULL) {
13304 const struct got_error *perr;
13306 perr = pe->data;
13307 error = got_error_fmt(perr->code, "%s",
13308 pe->path);
13309 break;
13313 done:
13314 if (worktree)
13315 got_worktree_close(worktree);
13316 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13317 free(cwd);
13318 free(id_str);
13319 free(uuidstr);
13320 return error;