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 TAILQ_FOREACH(pe, &refs, entry) {
1923 free((void *)pe->path);
1924 free(pe->data);
1926 got_pathlist_free(&refs);
1927 TAILQ_FOREACH(pe, &symrefs, entry) {
1928 free((void *)pe->path);
1929 free(pe->data);
1931 got_pathlist_free(&symrefs);
1932 got_pathlist_free(&wanted_branches);
1933 got_pathlist_free(&wanted_refs);
1934 free(pack_hash);
1935 free(proto);
1936 free(host);
1937 free(port);
1938 free(server_path);
1939 free(repo_name);
1940 free(default_destdir);
1941 free(git_url);
1942 return error;
1945 static const struct got_error *
1946 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1947 int replace_tags, int verbosity, struct got_repository *repo)
1949 const struct got_error *err = NULL;
1950 char *new_id_str = NULL;
1951 struct got_object_id *old_id = NULL;
1953 err = got_object_id_str(&new_id_str, new_id);
1954 if (err)
1955 goto done;
1957 if (!replace_tags &&
1958 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1959 err = got_ref_resolve(&old_id, repo, ref);
1960 if (err)
1961 goto done;
1962 if (got_object_id_cmp(old_id, new_id) == 0)
1963 goto done;
1964 if (verbosity >= 0) {
1965 printf("Rejecting update of existing tag %s: %s\n",
1966 got_ref_get_name(ref), new_id_str);
1968 goto done;
1971 if (got_ref_is_symbolic(ref)) {
1972 if (verbosity >= 0) {
1973 printf("Replacing reference %s: %s\n",
1974 got_ref_get_name(ref),
1975 got_ref_get_symref_target(ref));
1977 err = got_ref_change_symref_to_ref(ref, new_id);
1978 if (err)
1979 goto done;
1980 err = got_ref_write(ref, repo);
1981 if (err)
1982 goto done;
1983 } else {
1984 err = got_ref_resolve(&old_id, repo, ref);
1985 if (err)
1986 goto done;
1987 if (got_object_id_cmp(old_id, new_id) == 0)
1988 goto done;
1990 err = got_ref_change_ref(ref, new_id);
1991 if (err)
1992 goto done;
1993 err = got_ref_write(ref, repo);
1994 if (err)
1995 goto done;
1998 if (verbosity >= 0)
1999 printf("Updated %s: %s\n", got_ref_get_name(ref),
2000 new_id_str);
2001 done:
2002 free(old_id);
2003 free(new_id_str);
2004 return err;
2007 static const struct got_error *
2008 update_symref(const char *refname, struct got_reference *target_ref,
2009 int verbosity, struct got_repository *repo)
2011 const struct got_error *err = NULL, *unlock_err;
2012 struct got_reference *symref;
2013 int symref_is_locked = 0;
2015 err = got_ref_open(&symref, repo, refname, 1);
2016 if (err) {
2017 if (err->code != GOT_ERR_NOT_REF)
2018 return err;
2019 err = got_ref_alloc_symref(&symref, refname, target_ref);
2020 if (err)
2021 goto done;
2023 err = got_ref_write(symref, repo);
2024 if (err)
2025 goto done;
2027 if (verbosity >= 0)
2028 printf("Created reference %s: %s\n",
2029 got_ref_get_name(symref),
2030 got_ref_get_symref_target(symref));
2031 } else {
2032 symref_is_locked = 1;
2034 if (strcmp(got_ref_get_symref_target(symref),
2035 got_ref_get_name(target_ref)) == 0)
2036 goto done;
2038 err = got_ref_change_symref(symref,
2039 got_ref_get_name(target_ref));
2040 if (err)
2041 goto done;
2043 err = got_ref_write(symref, repo);
2044 if (err)
2045 goto done;
2047 if (verbosity >= 0)
2048 printf("Updated %s: %s\n", got_ref_get_name(symref),
2049 got_ref_get_symref_target(symref));
2052 done:
2053 if (symref_is_locked) {
2054 unlock_err = got_ref_unlock(symref);
2055 if (unlock_err && err == NULL)
2056 err = unlock_err;
2058 got_ref_close(symref);
2059 return err;
2062 __dead static void
2063 usage_fetch(void)
2065 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2066 "[-R reference] [-r repository-path] [remote-repository]\n",
2067 getprogname());
2068 exit(1);
2071 static const struct got_error *
2072 delete_missing_ref(struct got_reference *ref,
2073 int verbosity, struct got_repository *repo)
2075 const struct got_error *err = NULL;
2076 struct got_object_id *id = NULL;
2077 char *id_str = NULL;
2079 if (got_ref_is_symbolic(ref)) {
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 return err;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref),
2086 got_ref_get_symref_target(ref));
2088 } else {
2089 err = got_ref_resolve(&id, repo, ref);
2090 if (err)
2091 return err;
2092 err = got_object_id_str(&id_str, id);
2093 if (err)
2094 goto done;
2096 err = got_ref_delete(ref, repo);
2097 if (err)
2098 goto done;
2099 if (verbosity >= 0) {
2100 printf("Deleted %s: %s\n",
2101 got_ref_get_name(ref), id_str);
2104 done:
2105 free(id);
2106 free(id_str);
2107 return NULL;
2110 static const struct got_error *
2111 delete_missing_refs(struct got_pathlist_head *their_refs,
2112 struct got_pathlist_head *their_symrefs,
2113 const struct got_remote_repo *remote,
2114 int verbosity, struct got_repository *repo)
2116 const struct got_error *err = NULL, *unlock_err;
2117 struct got_reflist_head my_refs;
2118 struct got_reflist_entry *re;
2119 struct got_pathlist_entry *pe;
2120 char *remote_namespace = NULL;
2121 char *local_refname = NULL;
2123 TAILQ_INIT(&my_refs);
2125 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2126 == -1)
2127 return got_error_from_errno("asprintf");
2129 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2130 if (err)
2131 goto done;
2133 TAILQ_FOREACH(re, &my_refs, entry) {
2134 const char *refname = got_ref_get_name(re->ref);
2135 const char *their_refname;
2137 if (remote->mirror_references) {
2138 their_refname = refname;
2139 } else {
2140 if (strncmp(refname, remote_namespace,
2141 strlen(remote_namespace)) == 0) {
2142 if (strcmp(refname + strlen(remote_namespace),
2143 GOT_REF_HEAD) == 0)
2144 continue;
2145 if (asprintf(&local_refname, "refs/heads/%s",
2146 refname + strlen(remote_namespace)) == -1) {
2147 err = got_error_from_errno("asprintf");
2148 goto done;
2150 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2151 continue;
2153 their_refname = local_refname;
2156 TAILQ_FOREACH(pe, their_refs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 TAILQ_FOREACH(pe, their_symrefs, entry) {
2164 if (strcmp(their_refname, pe->path) == 0)
2165 break;
2167 if (pe != NULL)
2168 continue;
2170 err = delete_missing_ref(re->ref, verbosity, repo);
2171 if (err)
2172 break;
2174 if (local_refname) {
2175 struct got_reference *ref;
2176 err = got_ref_open(&ref, repo, local_refname, 1);
2177 if (err) {
2178 if (err->code != GOT_ERR_NOT_REF)
2179 break;
2180 free(local_refname);
2181 local_refname = NULL;
2182 continue;
2184 err = delete_missing_ref(ref, verbosity, repo);
2185 if (err)
2186 break;
2187 unlock_err = got_ref_unlock(ref);
2188 got_ref_close(ref);
2189 if (unlock_err && err == NULL) {
2190 err = unlock_err;
2191 break;
2194 free(local_refname);
2195 local_refname = NULL;
2198 done:
2199 got_ref_list_free(&my_refs);
2200 free(remote_namespace);
2201 free(local_refname);
2202 return err;
2205 static const struct got_error *
2206 update_wanted_ref(const char *refname, struct got_object_id *id,
2207 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2209 const struct got_error *err, *unlock_err;
2210 char *remote_refname;
2211 struct got_reference *ref;
2213 if (strncmp("refs/", refname, 5) == 0)
2214 refname += 5;
2216 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2217 remote_repo_name, refname) == -1)
2218 return got_error_from_errno("asprintf");
2220 err = got_ref_open(&ref, repo, remote_refname, 1);
2221 if (err) {
2222 if (err->code != GOT_ERR_NOT_REF)
2223 goto done;
2224 err = create_ref(remote_refname, id, verbosity, repo);
2225 } else {
2226 err = update_ref(ref, id, 0, verbosity, repo);
2227 unlock_err = got_ref_unlock(ref);
2228 if (unlock_err && err == NULL)
2229 err = unlock_err;
2230 got_ref_close(ref);
2232 done:
2233 free(remote_refname);
2234 return err;
2237 static const struct got_error *
2238 delete_ref(struct got_repository *repo, struct got_reference *ref)
2240 const struct got_error *err = NULL;
2241 struct got_object_id *id = NULL;
2242 char *id_str = NULL;
2243 const char *target;
2245 if (got_ref_is_symbolic(ref)) {
2246 target = got_ref_get_symref_target(ref);
2247 } else {
2248 err = got_ref_resolve(&id, repo, ref);
2249 if (err)
2250 goto done;
2251 err = got_object_id_str(&id_str, id);
2252 if (err)
2253 goto done;
2254 target = id_str;
2257 err = got_ref_delete(ref, repo);
2258 if (err)
2259 goto done;
2261 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2262 done:
2263 free(id);
2264 free(id_str);
2265 return err;
2268 static const struct got_error *
2269 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2271 const struct got_error *err = NULL;
2272 struct got_reflist_head refs;
2273 struct got_reflist_entry *re;
2274 char *prefix;
2276 TAILQ_INIT(&refs);
2278 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2279 err = got_error_from_errno("asprintf");
2280 goto done;
2282 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2283 if (err)
2284 goto done;
2286 TAILQ_FOREACH(re, &refs, entry)
2287 delete_ref(repo, re->ref);
2288 done:
2289 got_ref_list_free(&refs);
2290 return err;
2293 static const struct got_error *
2294 cmd_fetch(int argc, char *argv[])
2296 const struct got_error *error = NULL, *unlock_err;
2297 char *cwd = NULL, *repo_path = NULL;
2298 const char *remote_name;
2299 char *proto = NULL, *host = NULL, *port = NULL;
2300 char *repo_name = NULL, *server_path = NULL;
2301 const struct got_remote_repo *remotes, *remote = NULL;
2302 int nremotes;
2303 char *id_str = NULL;
2304 struct got_repository *repo = NULL;
2305 struct got_worktree *worktree = NULL;
2306 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2307 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2308 struct got_pathlist_entry *pe;
2309 struct got_object_id *pack_hash = NULL;
2310 int i, ch, fetchfd = -1, fetchstatus;
2311 pid_t fetchpid = -1;
2312 struct got_fetch_progress_arg fpa;
2313 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2314 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2315 int *pack_fds = NULL;
2317 TAILQ_INIT(&refs);
2318 TAILQ_INIT(&symrefs);
2319 TAILQ_INIT(&wanted_branches);
2320 TAILQ_INIT(&wanted_refs);
2322 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2323 switch (ch) {
2324 case 'a':
2325 fetch_all_branches = 1;
2326 break;
2327 case 'b':
2328 error = got_pathlist_append(&wanted_branches,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2463 if (remote == NULL) {
2464 repo_conf = got_repo_get_gotconfig(repo);
2465 if (repo_conf) {
2466 got_gotconfig_get_remotes(&nremotes, &remotes,
2467 repo_conf);
2468 for (i = 0; i < nremotes; i++) {
2469 if (strcmp(remotes[i].name, remote_name) == 0) {
2470 remote = &remotes[i];
2471 break;
2476 if (remote == NULL) {
2477 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2478 for (i = 0; i < nremotes; i++) {
2479 if (strcmp(remotes[i].name, remote_name) == 0) {
2480 remote = &remotes[i];
2481 break;
2485 if (remote == NULL) {
2486 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2487 goto done;
2490 if (TAILQ_EMPTY(&wanted_branches)) {
2491 if (!fetch_all_branches)
2492 fetch_all_branches = remote->fetch_all_branches;
2493 for (i = 0; i < remote->nfetch_branches; i++) {
2494 got_pathlist_append(&wanted_branches,
2495 remote->fetch_branches[i], NULL);
2498 if (TAILQ_EMPTY(&wanted_refs)) {
2499 for (i = 0; i < remote->nfetch_refs; i++) {
2500 got_pathlist_append(&wanted_refs,
2501 remote->fetch_refs[i], NULL);
2505 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2506 &repo_name, remote->fetch_url);
2507 if (error)
2508 goto done;
2510 if (strcmp(proto, "git") == 0) {
2511 #ifndef PROFILE
2512 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2513 "sendfd dns inet unveil", NULL) == -1)
2514 err(1, "pledge");
2515 #endif
2516 } else if (strcmp(proto, "git+ssh") == 0 ||
2517 strcmp(proto, "ssh") == 0) {
2518 #ifndef PROFILE
2519 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2520 "sendfd unveil", NULL) == -1)
2521 err(1, "pledge");
2522 #endif
2523 } else if (strcmp(proto, "http") == 0 ||
2524 strcmp(proto, "git+http") == 0) {
2525 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2526 goto done;
2527 } else {
2528 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2529 goto done;
2532 error = got_dial_apply_unveil(proto);
2533 if (error)
2534 goto done;
2536 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2537 if (error)
2538 goto done;
2540 if (verbosity >= 0) {
2541 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2542 remote->name, proto, host,
2543 port ? ":" : "", port ? port : "",
2544 *server_path == '/' ? "" : "/", server_path);
2547 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2548 server_path, verbosity);
2549 if (error)
2550 goto done;
2552 fpa.last_scaled_size[0] = '\0';
2553 fpa.last_p_indexed = -1;
2554 fpa.last_p_resolved = -1;
2555 fpa.verbosity = verbosity;
2556 fpa.repo = repo;
2557 fpa.create_configs = 0;
2558 fpa.configs_created = 0;
2559 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2560 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2561 remote->mirror_references, fetch_all_branches, &wanted_branches,
2562 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2563 fetch_progress, &fpa);
2564 if (error)
2565 goto done;
2567 if (list_refs_only) {
2568 error = list_remote_refs(&symrefs, &refs);
2569 goto done;
2572 if (pack_hash == NULL) {
2573 if (verbosity >= 0)
2574 printf("Already up-to-date\n");
2575 } else if (verbosity >= 0) {
2576 error = got_object_id_str(&id_str, pack_hash);
2577 if (error)
2578 goto done;
2579 printf("\nFetched %s.pack\n", id_str);
2580 free(id_str);
2581 id_str = NULL;
2584 /* Update references provided with the pack file. */
2585 TAILQ_FOREACH(pe, &refs, entry) {
2586 const char *refname = pe->path;
2587 struct got_object_id *id = pe->data;
2588 struct got_reference *ref;
2589 char *remote_refname;
2591 if (is_wanted_ref(&wanted_refs, refname) &&
2592 !remote->mirror_references) {
2593 error = update_wanted_ref(refname, id,
2594 remote->name, verbosity, repo);
2595 if (error)
2596 goto done;
2597 continue;
2600 if (remote->mirror_references ||
2601 strncmp("refs/tags/", refname, 10) == 0) {
2602 error = got_ref_open(&ref, repo, refname, 1);
2603 if (error) {
2604 if (error->code != GOT_ERR_NOT_REF)
2605 goto done;
2606 error = create_ref(refname, id, verbosity,
2607 repo);
2608 if (error)
2609 goto done;
2610 } else {
2611 error = update_ref(ref, id, replace_tags,
2612 verbosity, repo);
2613 unlock_err = got_ref_unlock(ref);
2614 if (unlock_err && error == NULL)
2615 error = unlock_err;
2616 got_ref_close(ref);
2617 if (error)
2618 goto done;
2620 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2621 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2622 remote_name, refname + 11) == -1) {
2623 error = got_error_from_errno("asprintf");
2624 goto done;
2627 error = got_ref_open(&ref, repo, remote_refname, 1);
2628 if (error) {
2629 if (error->code != GOT_ERR_NOT_REF)
2630 goto done;
2631 error = create_ref(remote_refname, id,
2632 verbosity, repo);
2633 if (error)
2634 goto done;
2635 } else {
2636 error = update_ref(ref, id, replace_tags,
2637 verbosity, repo);
2638 unlock_err = got_ref_unlock(ref);
2639 if (unlock_err && error == NULL)
2640 error = unlock_err;
2641 got_ref_close(ref);
2642 if (error)
2643 goto done;
2646 /* Also create a local branch if none exists yet. */
2647 error = got_ref_open(&ref, repo, refname, 1);
2648 if (error) {
2649 if (error->code != GOT_ERR_NOT_REF)
2650 goto done;
2651 error = create_ref(refname, id, verbosity,
2652 repo);
2653 if (error)
2654 goto done;
2655 } else {
2656 unlock_err = got_ref_unlock(ref);
2657 if (unlock_err && error == NULL)
2658 error = unlock_err;
2659 got_ref_close(ref);
2663 if (delete_refs) {
2664 error = delete_missing_refs(&refs, &symrefs, remote,
2665 verbosity, repo);
2666 if (error)
2667 goto done;
2670 if (!remote->mirror_references) {
2671 /* Update remote HEAD reference if the server provided one. */
2672 TAILQ_FOREACH(pe, &symrefs, entry) {
2673 struct got_reference *target_ref;
2674 const char *refname = pe->path;
2675 const char *target = pe->data;
2676 char *remote_refname = NULL, *remote_target = NULL;
2678 if (strcmp(refname, GOT_REF_HEAD) != 0)
2679 continue;
2681 if (strncmp("refs/heads/", target, 11) != 0)
2682 continue;
2684 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2685 remote->name, refname) == -1) {
2686 error = got_error_from_errno("asprintf");
2687 goto done;
2689 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2690 remote->name, target + 11) == -1) {
2691 error = got_error_from_errno("asprintf");
2692 free(remote_refname);
2693 goto done;
2696 error = got_ref_open(&target_ref, repo, remote_target,
2697 0);
2698 if (error) {
2699 free(remote_refname);
2700 free(remote_target);
2701 if (error->code == GOT_ERR_NOT_REF) {
2702 error = NULL;
2703 continue;
2705 goto done;
2707 error = update_symref(remote_refname, target_ref,
2708 verbosity, repo);
2709 free(remote_refname);
2710 free(remote_target);
2711 got_ref_close(target_ref);
2712 if (error)
2713 goto done;
2716 done:
2717 if (fetchpid > 0) {
2718 if (kill(fetchpid, SIGTERM) == -1)
2719 error = got_error_from_errno("kill");
2720 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2721 error = got_error_from_errno("waitpid");
2723 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2724 error = got_error_from_errno("close");
2725 if (repo) {
2726 const struct got_error *close_err = got_repo_close(repo);
2727 if (error == NULL)
2728 error = close_err;
2730 if (worktree)
2731 got_worktree_close(worktree);
2732 if (pack_fds) {
2733 const struct got_error *pack_err =
2734 got_repo_pack_fds_close(pack_fds);
2735 if (error == NULL)
2736 error = pack_err;
2738 TAILQ_FOREACH(pe, &refs, entry) {
2739 free((void *)pe->path);
2740 free(pe->data);
2742 got_pathlist_free(&refs);
2743 TAILQ_FOREACH(pe, &symrefs, entry) {
2744 free((void *)pe->path);
2745 free(pe->data);
2747 got_pathlist_free(&symrefs);
2748 got_pathlist_free(&wanted_branches);
2749 got_pathlist_free(&wanted_refs);
2750 free(id_str);
2751 free(cwd);
2752 free(repo_path);
2753 free(pack_hash);
2754 free(proto);
2755 free(host);
2756 free(port);
2757 free(server_path);
2758 free(repo_name);
2759 return error;
2763 __dead static void
2764 usage_checkout(void)
2766 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2767 "[-p path-prefix] repository-path [work-tree-path]\n",
2768 getprogname());
2769 exit(1);
2772 static void
2773 show_worktree_base_ref_warning(void)
2775 fprintf(stderr, "%s: warning: could not create a reference "
2776 "to the work tree's base commit; the commit could be "
2777 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2778 "repository writable and running 'got update' will prevent this\n",
2779 getprogname());
2782 struct got_checkout_progress_arg {
2783 const char *worktree_path;
2784 int had_base_commit_ref_error;
2785 int verbosity;
2788 static const struct got_error *
2789 checkout_progress(void *arg, unsigned char status, const char *path)
2791 struct got_checkout_progress_arg *a = arg;
2793 /* Base commit bump happens silently. */
2794 if (status == GOT_STATUS_BUMP_BASE)
2795 return NULL;
2797 if (status == GOT_STATUS_BASE_REF_ERR) {
2798 a->had_base_commit_ref_error = 1;
2799 return NULL;
2802 while (path[0] == '/')
2803 path++;
2805 if (a->verbosity >= 0)
2806 printf("%c %s/%s\n", status, a->worktree_path, path);
2808 return NULL;
2811 static const struct got_error *
2812 check_cancelled(void *arg)
2814 if (sigint_received || sigpipe_received)
2815 return got_error(GOT_ERR_CANCELLED);
2816 return NULL;
2819 static const struct got_error *
2820 check_linear_ancestry(struct got_object_id *commit_id,
2821 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2822 struct got_repository *repo)
2824 const struct got_error *err = NULL;
2825 struct got_object_id *yca_id;
2827 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2828 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2829 if (err)
2830 return err;
2832 if (yca_id == NULL)
2833 return got_error(GOT_ERR_ANCESTRY);
2836 * Require a straight line of history between the target commit
2837 * and the work tree's base commit.
2839 * Non-linear situations such as this require a rebase:
2841 * (commit) D F (base_commit)
2842 * \ /
2843 * C E
2844 * \ /
2845 * B (yca)
2846 * |
2847 * A
2849 * 'got update' only handles linear cases:
2850 * Update forwards in time: A (base/yca) - B - C - D (commit)
2851 * Update backwards in time: D (base) - C - B - A (commit/yca)
2853 if (allow_forwards_in_time_only) {
2854 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2855 return got_error(GOT_ERR_ANCESTRY);
2856 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2857 got_object_id_cmp(base_commit_id, yca_id) != 0)
2858 return got_error(GOT_ERR_ANCESTRY);
2860 free(yca_id);
2861 return NULL;
2864 static const struct got_error *
2865 check_same_branch(struct got_object_id *commit_id,
2866 struct got_reference *head_ref, struct got_object_id *yca_id,
2867 struct got_repository *repo)
2869 const struct got_error *err = NULL;
2870 struct got_commit_graph *graph = NULL;
2871 struct got_object_id *head_commit_id = NULL;
2872 int is_same_branch = 0;
2874 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2875 if (err)
2876 goto done;
2878 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2879 is_same_branch = 1;
2880 goto done;
2882 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2883 is_same_branch = 1;
2884 goto done;
2887 err = got_commit_graph_open(&graph, "/", 1);
2888 if (err)
2889 goto done;
2891 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2892 check_cancelled, NULL);
2893 if (err)
2894 goto done;
2896 for (;;) {
2897 struct got_object_id id;
2899 err = got_commit_graph_iter_next(&id, graph, repo,
2900 check_cancelled, NULL);
2901 if (err) {
2902 if (err->code == GOT_ERR_ITER_COMPLETED)
2903 err = NULL;
2904 break;
2907 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2908 break;
2909 if (got_object_id_cmp(&id, commit_id) == 0) {
2910 is_same_branch = 1;
2911 break;
2914 done:
2915 if (graph)
2916 got_commit_graph_close(graph);
2917 free(head_commit_id);
2918 if (!err && !is_same_branch)
2919 err = got_error(GOT_ERR_ANCESTRY);
2920 return err;
2923 static const struct got_error *
2924 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2926 static char msg[512];
2927 const char *branch_name;
2929 if (got_ref_is_symbolic(ref))
2930 branch_name = got_ref_get_symref_target(ref);
2931 else
2932 branch_name = got_ref_get_name(ref);
2934 if (strncmp("refs/heads/", branch_name, 11) == 0)
2935 branch_name += 11;
2937 snprintf(msg, sizeof(msg),
2938 "target commit is not contained in branch '%s'; "
2939 "the branch to use must be specified with -b; "
2940 "if necessary a new branch can be created for "
2941 "this commit with 'got branch -c %s BRANCH_NAME'",
2942 branch_name, commit_id_str);
2944 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2947 static const struct got_error *
2948 cmd_checkout(int argc, char *argv[])
2950 const struct got_error *error = NULL;
2951 struct got_repository *repo = NULL;
2952 struct got_reference *head_ref = NULL, *ref = NULL;
2953 struct got_worktree *worktree = NULL;
2954 char *repo_path = NULL;
2955 char *worktree_path = NULL;
2956 const char *path_prefix = "";
2957 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2958 char *commit_id_str = NULL;
2959 struct got_object_id *commit_id = NULL;
2960 char *cwd = NULL;
2961 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2962 struct got_pathlist_head paths;
2963 struct got_checkout_progress_arg cpa;
2964 int *pack_fds = NULL;
2966 TAILQ_INIT(&paths);
2968 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2969 switch (ch) {
2970 case 'b':
2971 branch_name = optarg;
2972 break;
2973 case 'c':
2974 commit_id_str = strdup(optarg);
2975 if (commit_id_str == NULL)
2976 return got_error_from_errno("strdup");
2977 break;
2978 case 'E':
2979 allow_nonempty = 1;
2980 break;
2981 case 'p':
2982 path_prefix = optarg;
2983 break;
2984 case 'q':
2985 verbosity = -1;
2986 break;
2987 default:
2988 usage_checkout();
2989 /* NOTREACHED */
2993 argc -= optind;
2994 argv += optind;
2996 #ifndef PROFILE
2997 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2998 "unveil", NULL) == -1)
2999 err(1, "pledge");
3000 #endif
3001 if (argc == 1) {
3002 char *base, *dotgit;
3003 const char *path;
3004 repo_path = realpath(argv[0], NULL);
3005 if (repo_path == NULL)
3006 return got_error_from_errno2("realpath", argv[0]);
3007 cwd = getcwd(NULL, 0);
3008 if (cwd == NULL) {
3009 error = got_error_from_errno("getcwd");
3010 goto done;
3012 if (path_prefix[0])
3013 path = path_prefix;
3014 else
3015 path = repo_path;
3016 error = got_path_basename(&base, path);
3017 if (error)
3018 goto done;
3019 dotgit = strstr(base, ".git");
3020 if (dotgit)
3021 *dotgit = '\0';
3022 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3023 error = got_error_from_errno("asprintf");
3024 free(base);
3025 goto done;
3027 free(base);
3028 } else if (argc == 2) {
3029 repo_path = realpath(argv[0], NULL);
3030 if (repo_path == NULL) {
3031 error = got_error_from_errno2("realpath", argv[0]);
3032 goto done;
3034 worktree_path = realpath(argv[1], NULL);
3035 if (worktree_path == NULL) {
3036 if (errno != ENOENT) {
3037 error = got_error_from_errno2("realpath",
3038 argv[1]);
3039 goto done;
3041 worktree_path = strdup(argv[1]);
3042 if (worktree_path == NULL) {
3043 error = got_error_from_errno("strdup");
3044 goto done;
3047 } else
3048 usage_checkout();
3050 got_path_strip_trailing_slashes(repo_path);
3051 got_path_strip_trailing_slashes(worktree_path);
3053 error = got_repo_pack_fds_open(&pack_fds);
3054 if (error != NULL)
3055 goto done;
3057 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3058 if (error != NULL)
3059 goto done;
3061 /* Pre-create work tree path for unveil(2) */
3062 error = got_path_mkdir(worktree_path);
3063 if (error) {
3064 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3065 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3066 goto done;
3067 if (!allow_nonempty &&
3068 !got_path_dir_is_empty(worktree_path)) {
3069 error = got_error_path(worktree_path,
3070 GOT_ERR_DIR_NOT_EMPTY);
3071 goto done;
3075 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3076 if (error)
3077 goto done;
3079 error = got_ref_open(&head_ref, repo, branch_name, 0);
3080 if (error != NULL)
3081 goto done;
3083 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3084 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3085 goto done;
3087 error = got_worktree_open(&worktree, worktree_path);
3088 if (error != NULL)
3089 goto done;
3091 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3092 path_prefix);
3093 if (error != NULL)
3094 goto done;
3095 if (!same_path_prefix) {
3096 error = got_error(GOT_ERR_PATH_PREFIX);
3097 goto done;
3100 if (commit_id_str) {
3101 struct got_reflist_head refs;
3102 TAILQ_INIT(&refs);
3103 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3104 NULL);
3105 if (error)
3106 goto done;
3107 error = got_repo_match_object_id(&commit_id, NULL,
3108 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3109 got_ref_list_free(&refs);
3110 if (error)
3111 goto done;
3112 error = check_linear_ancestry(commit_id,
3113 got_worktree_get_base_commit_id(worktree), 0, repo);
3114 if (error != NULL) {
3115 if (error->code == GOT_ERR_ANCESTRY) {
3116 error = checkout_ancestry_error(
3117 head_ref, commit_id_str);
3119 goto done;
3121 error = check_same_branch(commit_id, head_ref, NULL, repo);
3122 if (error) {
3123 if (error->code == GOT_ERR_ANCESTRY) {
3124 error = checkout_ancestry_error(
3125 head_ref, commit_id_str);
3127 goto done;
3129 error = got_worktree_set_base_commit_id(worktree, repo,
3130 commit_id);
3131 if (error)
3132 goto done;
3133 /* Expand potentially abbreviated commit ID string. */
3134 free(commit_id_str);
3135 error = got_object_id_str(&commit_id_str, commit_id);
3136 if (error)
3137 goto done;
3138 } else {
3139 commit_id = got_object_id_dup(
3140 got_worktree_get_base_commit_id(worktree));
3141 if (commit_id == NULL) {
3142 error = got_error_from_errno("got_object_id_dup");
3143 goto done;
3145 error = got_object_id_str(&commit_id_str, commit_id);
3146 if (error)
3147 goto done;
3150 error = got_pathlist_append(&paths, "", NULL);
3151 if (error)
3152 goto done;
3153 cpa.worktree_path = worktree_path;
3154 cpa.had_base_commit_ref_error = 0;
3155 cpa.verbosity = verbosity;
3156 error = got_worktree_checkout_files(worktree, &paths, repo,
3157 checkout_progress, &cpa, check_cancelled, NULL);
3158 if (error != NULL)
3159 goto done;
3161 if (got_ref_is_symbolic(head_ref)) {
3162 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3163 if (error)
3164 goto done;
3165 refname = got_ref_get_name(ref);
3166 } else
3167 refname = got_ref_get_name(head_ref);
3168 printf("Checked out %s: %s\n", refname, commit_id_str);
3169 printf("Now shut up and hack\n");
3170 if (cpa.had_base_commit_ref_error)
3171 show_worktree_base_ref_warning();
3172 done:
3173 if (pack_fds) {
3174 const struct got_error *pack_err =
3175 got_repo_pack_fds_close(pack_fds);
3176 if (error == NULL)
3177 error = pack_err;
3179 if (head_ref)
3180 got_ref_close(head_ref);
3181 if (ref)
3182 got_ref_close(ref);
3183 got_pathlist_free(&paths);
3184 free(commit_id_str);
3185 free(commit_id);
3186 free(repo_path);
3187 free(worktree_path);
3188 free(cwd);
3189 return error;
3192 struct got_update_progress_arg {
3193 int did_something;
3194 int conflicts;
3195 int obstructed;
3196 int not_updated;
3197 int missing;
3198 int not_deleted;
3199 int unversioned;
3200 int verbosity;
3203 static void
3204 print_update_progress_stats(struct got_update_progress_arg *upa)
3206 if (!upa->did_something)
3207 return;
3209 if (upa->conflicts > 0)
3210 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3211 if (upa->obstructed > 0)
3212 printf("File paths obstructed by a non-regular file: %d\n",
3213 upa->obstructed);
3214 if (upa->not_updated > 0)
3215 printf("Files not updated because of existing merge "
3216 "conflicts: %d\n", upa->not_updated);
3220 * The meaning of some status codes differs between merge-style operations and
3221 * update operations. For example, the ! status code means "file was missing"
3222 * if changes were merged into the work tree, and "missing file was restored"
3223 * if the work tree was updated. This function should be used by any operation
3224 * which merges changes into the work tree without updating the work tree.
3226 static void
3227 print_merge_progress_stats(struct got_update_progress_arg *upa)
3229 if (!upa->did_something)
3230 return;
3232 if (upa->conflicts > 0)
3233 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3234 if (upa->obstructed > 0)
3235 printf("File paths obstructed by a non-regular file: %d\n",
3236 upa->obstructed);
3237 if (upa->missing > 0)
3238 printf("Files which had incoming changes but could not be "
3239 "found in the work tree: %d\n", upa->missing);
3240 if (upa->not_deleted > 0)
3241 printf("Files not deleted due to differences in deleted "
3242 "content: %d\n", upa->not_deleted);
3243 if (upa->unversioned > 0)
3244 printf("Files not merged because an unversioned file was "
3245 "found in the work tree: %d\n", upa->unversioned);
3248 __dead static void
3249 usage_update(void)
3251 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3252 "[path ...]\n", getprogname());
3253 exit(1);
3256 static const struct got_error *
3257 update_progress(void *arg, unsigned char status, const char *path)
3259 struct got_update_progress_arg *upa = arg;
3261 if (status == GOT_STATUS_EXISTS ||
3262 status == GOT_STATUS_BASE_REF_ERR)
3263 return NULL;
3265 upa->did_something = 1;
3267 /* Base commit bump happens silently. */
3268 if (status == GOT_STATUS_BUMP_BASE)
3269 return NULL;
3271 if (status == GOT_STATUS_CONFLICT)
3272 upa->conflicts++;
3273 if (status == GOT_STATUS_OBSTRUCTED)
3274 upa->obstructed++;
3275 if (status == GOT_STATUS_CANNOT_UPDATE)
3276 upa->not_updated++;
3277 if (status == GOT_STATUS_MISSING)
3278 upa->missing++;
3279 if (status == GOT_STATUS_CANNOT_DELETE)
3280 upa->not_deleted++;
3281 if (status == GOT_STATUS_UNVERSIONED)
3282 upa->unversioned++;
3284 while (path[0] == '/')
3285 path++;
3286 if (upa->verbosity >= 0)
3287 printf("%c %s\n", status, path);
3289 return NULL;
3292 static const struct got_error *
3293 switch_head_ref(struct got_reference *head_ref,
3294 struct got_object_id *commit_id, struct got_worktree *worktree,
3295 struct got_repository *repo)
3297 const struct got_error *err = NULL;
3298 char *base_id_str;
3299 int ref_has_moved = 0;
3301 /* Trivial case: switching between two different references. */
3302 if (strcmp(got_ref_get_name(head_ref),
3303 got_worktree_get_head_ref_name(worktree)) != 0) {
3304 printf("Switching work tree from %s to %s\n",
3305 got_worktree_get_head_ref_name(worktree),
3306 got_ref_get_name(head_ref));
3307 return got_worktree_set_head_ref(worktree, head_ref);
3310 err = check_linear_ancestry(commit_id,
3311 got_worktree_get_base_commit_id(worktree), 0, repo);
3312 if (err) {
3313 if (err->code != GOT_ERR_ANCESTRY)
3314 return err;
3315 ref_has_moved = 1;
3317 if (!ref_has_moved)
3318 return NULL;
3320 /* Switching to a rebased branch with the same reference name. */
3321 err = got_object_id_str(&base_id_str,
3322 got_worktree_get_base_commit_id(worktree));
3323 if (err)
3324 return err;
3325 printf("Reference %s now points at a different branch\n",
3326 got_worktree_get_head_ref_name(worktree));
3327 printf("Switching work tree from %s to %s\n", base_id_str,
3328 got_worktree_get_head_ref_name(worktree));
3329 return NULL;
3332 static const struct got_error *
3333 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3335 const struct got_error *err;
3336 int in_progress;
3338 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3339 if (err)
3340 return err;
3341 if (in_progress)
3342 return got_error(GOT_ERR_REBASING);
3344 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_HISTEDIT_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 check_merge_in_progress(struct got_worktree *worktree,
3355 struct got_repository *repo)
3357 const struct got_error *err;
3358 int in_progress;
3360 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3361 if (err)
3362 return err;
3363 if (in_progress)
3364 return got_error(GOT_ERR_MERGE_BUSY);
3366 return NULL;
3369 static const struct got_error *
3370 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3371 char *argv[], struct got_worktree *worktree)
3373 const struct got_error *err = NULL;
3374 char *path;
3375 struct got_pathlist_entry *new;
3376 int i;
3378 if (argc == 0) {
3379 path = strdup("");
3380 if (path == NULL)
3381 return got_error_from_errno("strdup");
3382 return got_pathlist_append(paths, path, NULL);
3385 for (i = 0; i < argc; i++) {
3386 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3387 if (err)
3388 break;
3389 err = got_pathlist_insert(&new, paths, path, NULL);
3390 if (err || new == NULL /* duplicate */) {
3391 free(path);
3392 if (err)
3393 break;
3397 return err;
3400 static const struct got_error *
3401 wrap_not_worktree_error(const struct got_error *orig_err,
3402 const char *cmdname, const char *path)
3404 const struct got_error *err;
3405 struct got_repository *repo;
3406 static char msg[512];
3407 int *pack_fds = NULL;
3409 err = got_repo_pack_fds_open(&pack_fds);
3410 if (err)
3411 return err;
3413 err = got_repo_open(&repo, path, NULL, pack_fds);
3414 if (err)
3415 return orig_err;
3417 snprintf(msg, sizeof(msg),
3418 "'got %s' needs a work tree in addition to a git repository\n"
3419 "Work trees can be checked out from this Git repository with "
3420 "'got checkout'.\n"
3421 "The got(1) manual page contains more information.", cmdname);
3422 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3423 got_repo_close(repo);
3424 if (pack_fds) {
3425 const struct got_error *pack_err =
3426 got_repo_pack_fds_close(pack_fds);
3427 if (err == NULL)
3428 err = pack_err;
3430 return err;
3433 static const struct got_error *
3434 cmd_update(int argc, char *argv[])
3436 const struct got_error *error = NULL;
3437 struct got_repository *repo = NULL;
3438 struct got_worktree *worktree = NULL;
3439 char *worktree_path = NULL;
3440 struct got_object_id *commit_id = NULL;
3441 char *commit_id_str = NULL;
3442 const char *branch_name = NULL;
3443 struct got_reference *head_ref = NULL;
3444 struct got_pathlist_head paths;
3445 struct got_pathlist_entry *pe;
3446 int ch, verbosity = 0;
3447 struct got_update_progress_arg upa;
3448 int *pack_fds = NULL;
3450 TAILQ_INIT(&paths);
3452 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3453 switch (ch) {
3454 case 'b':
3455 branch_name = optarg;
3456 break;
3457 case 'c':
3458 commit_id_str = strdup(optarg);
3459 if (commit_id_str == NULL)
3460 return got_error_from_errno("strdup");
3461 break;
3462 case 'q':
3463 verbosity = -1;
3464 break;
3465 default:
3466 usage_update();
3467 /* NOTREACHED */
3471 argc -= optind;
3472 argv += optind;
3474 #ifndef PROFILE
3475 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3476 "unveil", NULL) == -1)
3477 err(1, "pledge");
3478 #endif
3479 worktree_path = getcwd(NULL, 0);
3480 if (worktree_path == NULL) {
3481 error = got_error_from_errno("getcwd");
3482 goto done;
3485 error = got_repo_pack_fds_open(&pack_fds);
3486 if (error != NULL)
3487 goto done;
3489 error = got_worktree_open(&worktree, worktree_path);
3490 if (error) {
3491 if (error->code == GOT_ERR_NOT_WORKTREE)
3492 error = wrap_not_worktree_error(error, "update",
3493 worktree_path);
3494 goto done;
3497 error = check_rebase_or_histedit_in_progress(worktree);
3498 if (error)
3499 goto done;
3501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3502 NULL, pack_fds);
3503 if (error != NULL)
3504 goto done;
3506 error = apply_unveil(got_repo_get_path(repo), 0,
3507 got_worktree_get_root_path(worktree));
3508 if (error)
3509 goto done;
3511 error = check_merge_in_progress(worktree, repo);
3512 if (error)
3513 goto done;
3515 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3516 if (error)
3517 goto done;
3519 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3520 got_worktree_get_head_ref_name(worktree), 0);
3521 if (error != NULL)
3522 goto done;
3523 if (commit_id_str == NULL) {
3524 error = got_ref_resolve(&commit_id, repo, head_ref);
3525 if (error != NULL)
3526 goto done;
3527 error = got_object_id_str(&commit_id_str, commit_id);
3528 if (error != NULL)
3529 goto done;
3530 } else {
3531 struct got_reflist_head refs;
3532 TAILQ_INIT(&refs);
3533 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3534 NULL);
3535 if (error)
3536 goto done;
3537 error = got_repo_match_object_id(&commit_id, NULL,
3538 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3539 got_ref_list_free(&refs);
3540 free(commit_id_str);
3541 commit_id_str = NULL;
3542 if (error)
3543 goto done;
3544 error = got_object_id_str(&commit_id_str, commit_id);
3545 if (error)
3546 goto done;
3549 if (branch_name) {
3550 struct got_object_id *head_commit_id;
3551 TAILQ_FOREACH(pe, &paths, entry) {
3552 if (pe->path_len == 0)
3553 continue;
3554 error = got_error_msg(GOT_ERR_BAD_PATH,
3555 "switching between branches requires that "
3556 "the entire work tree gets updated");
3557 goto done;
3559 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3560 if (error)
3561 goto done;
3562 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3563 repo);
3564 free(head_commit_id);
3565 if (error != NULL)
3566 goto done;
3567 error = check_same_branch(commit_id, head_ref, NULL, repo);
3568 if (error)
3569 goto done;
3570 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3571 if (error)
3572 goto done;
3573 } else {
3574 error = check_linear_ancestry(commit_id,
3575 got_worktree_get_base_commit_id(worktree), 0, repo);
3576 if (error != NULL) {
3577 if (error->code == GOT_ERR_ANCESTRY)
3578 error = got_error(GOT_ERR_BRANCH_MOVED);
3579 goto done;
3581 error = check_same_branch(commit_id, head_ref, NULL, repo);
3582 if (error)
3583 goto done;
3586 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3587 commit_id) != 0) {
3588 error = got_worktree_set_base_commit_id(worktree, repo,
3589 commit_id);
3590 if (error)
3591 goto done;
3594 memset(&upa, 0, sizeof(upa));
3595 upa.verbosity = verbosity;
3596 error = got_worktree_checkout_files(worktree, &paths, repo,
3597 update_progress, &upa, check_cancelled, NULL);
3598 if (error != NULL)
3599 goto done;
3601 if (upa.did_something) {
3602 printf("Updated to %s: %s\n",
3603 got_worktree_get_head_ref_name(worktree), commit_id_str);
3604 } else
3605 printf("Already up-to-date\n");
3607 print_update_progress_stats(&upa);
3608 done:
3609 if (pack_fds) {
3610 const struct got_error *pack_err =
3611 got_repo_pack_fds_close(pack_fds);
3612 if (error == NULL)
3613 error = pack_err;
3615 free(worktree_path);
3616 TAILQ_FOREACH(pe, &paths, entry)
3617 free((char *)pe->path);
3618 got_pathlist_free(&paths);
3619 free(commit_id);
3620 free(commit_id_str);
3621 return error;
3624 static const struct got_error *
3625 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3626 const char *path, int diff_context, int ignore_whitespace,
3627 int force_text_diff, struct got_repository *repo, FILE *outfile)
3629 const struct got_error *err = NULL;
3630 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3631 FILE *f1 = NULL, *f2 = NULL;
3632 int fd1 = -1, fd2 = -1;
3634 fd1 = got_opentempfd();
3635 if (fd1 == -1)
3636 return got_error_from_errno("got_opentempfd");
3637 fd2 = got_opentempfd();
3638 if (fd2 == -1) {
3639 err = got_error_from_errno("got_opentempfd");
3640 goto done;
3643 if (blob_id1) {
3644 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3645 fd1);
3646 if (err)
3647 goto done;
3650 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3651 if (err)
3652 goto done;
3654 f1 = got_opentemp();
3655 if (f1 == NULL) {
3656 err = got_error_from_errno("got_opentemp");
3657 goto done;
3659 f2 = got_opentemp();
3660 if (f2 == NULL) {
3661 err = got_error_from_errno("got_opentemp");
3662 goto done;
3665 while (path[0] == '/')
3666 path++;
3667 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3668 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3669 force_text_diff, outfile);
3670 done:
3671 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3672 err = got_error_from_errno("close");
3673 if (blob1)
3674 got_object_blob_close(blob1);
3675 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3676 err = got_error_from_errno("close");
3677 got_object_blob_close(blob2);
3678 if (f1 && fclose(f1) == EOF && err == NULL)
3679 err = got_error_from_errno("fclose");
3680 if (f2 && fclose(f2) == EOF && err == NULL)
3681 err = got_error_from_errno("fclose");
3682 return err;
3685 static const struct got_error *
3686 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3687 const char *path, int diff_context, int ignore_whitespace,
3688 int force_text_diff, struct got_repository *repo, FILE *outfile)
3690 const struct got_error *err = NULL;
3691 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3692 struct got_diff_blob_output_unidiff_arg arg;
3693 FILE *f1 = NULL, *f2 = NULL;
3694 int fd1 = -1, fd2 = -1;
3696 if (tree_id1) {
3697 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3698 if (err)
3699 goto done;
3700 fd1 = got_opentempfd();
3701 if (fd1 == -1) {
3702 err = got_error_from_errno("got_opentempfd");
3703 goto done;
3707 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3708 if (err)
3709 goto done;
3711 f1 = got_opentemp();
3712 if (f1 == NULL) {
3713 err = got_error_from_errno("got_opentemp");
3714 goto done;
3717 f2 = got_opentemp();
3718 if (f2 == NULL) {
3719 err = got_error_from_errno("got_opentemp");
3720 goto done;
3722 fd2 = got_opentempfd();
3723 if (fd2 == -1) {
3724 err = got_error_from_errno("got_opentempfd");
3725 goto done;
3727 arg.diff_context = diff_context;
3728 arg.ignore_whitespace = ignore_whitespace;
3729 arg.force_text_diff = force_text_diff;
3730 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3731 arg.outfile = outfile;
3732 arg.lines = NULL;
3733 arg.nlines = 0;
3734 while (path[0] == '/')
3735 path++;
3736 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3737 got_diff_blob_output_unidiff, &arg, 1);
3738 done:
3739 if (tree1)
3740 got_object_tree_close(tree1);
3741 if (tree2)
3742 got_object_tree_close(tree2);
3743 if (f1 && fclose(f1) == EOF && err == NULL)
3744 err = got_error_from_errno("fclose");
3745 if (f2 && fclose(f2) == EOF && err == NULL)
3746 err = got_error_from_errno("fclose");
3747 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3748 err = got_error_from_errno("close");
3749 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3750 err = got_error_from_errno("close");
3751 return err;
3754 static const struct got_error *
3755 get_changed_paths(struct got_pathlist_head *paths,
3756 struct got_commit_object *commit, struct got_repository *repo,
3757 struct got_diffstat_cb_arg *dsa)
3759 const struct got_error *err = NULL;
3760 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3761 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3762 struct got_object_qid *qid;
3763 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3764 FILE *f1 = NULL, *f2 = NULL;
3765 int fd1 = -1, fd2 = -1;
3767 if (dsa) {
3768 cb = got_diff_tree_compute_diffstat;
3770 f1 = got_opentemp();
3771 if (f1 == NULL) {
3772 err = got_error_from_errno("got_opentemp");
3773 goto done;
3775 f2 = got_opentemp();
3776 if (f2 == NULL) {
3777 err = got_error_from_errno("got_opentemp");
3778 goto done;
3780 fd1 = got_opentempfd();
3781 if (fd1 == -1) {
3782 err = got_error_from_errno("got_opentempfd");
3783 goto done;
3785 fd2 = got_opentempfd();
3786 if (fd2 == -1) {
3787 err = got_error_from_errno("got_opentempfd");
3788 goto done;
3792 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3793 if (qid != NULL) {
3794 struct got_commit_object *pcommit;
3795 err = got_object_open_as_commit(&pcommit, repo,
3796 &qid->id);
3797 if (err)
3798 return err;
3800 tree_id1 = got_object_id_dup(
3801 got_object_commit_get_tree_id(pcommit));
3802 if (tree_id1 == NULL) {
3803 got_object_commit_close(pcommit);
3804 return got_error_from_errno("got_object_id_dup");
3806 got_object_commit_close(pcommit);
3810 if (tree_id1) {
3811 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3812 if (err)
3813 goto done;
3816 tree_id2 = got_object_commit_get_tree_id(commit);
3817 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3818 if (err)
3819 goto done;
3821 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3822 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3823 done:
3824 if (tree1)
3825 got_object_tree_close(tree1);
3826 if (tree2)
3827 got_object_tree_close(tree2);
3828 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3829 err = got_error_from_errno("close");
3830 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3831 err = got_error_from_errno("close");
3832 if (f1 && fclose(f1) == EOF && err == NULL)
3833 err = got_error_from_errno("fclose");
3834 if (f2 && fclose(f2) == EOF && err == NULL)
3835 err = got_error_from_errno("fclose");
3836 free(tree_id1);
3837 return err;
3840 static const struct got_error *
3841 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3842 const char *path, int diff_context, struct got_repository *repo,
3843 FILE *outfile)
3845 const struct got_error *err = NULL;
3846 struct got_commit_object *pcommit = NULL;
3847 char *id_str1 = NULL, *id_str2 = NULL;
3848 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3849 struct got_object_qid *qid;
3851 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3852 if (qid != NULL) {
3853 err = got_object_open_as_commit(&pcommit, repo,
3854 &qid->id);
3855 if (err)
3856 return err;
3857 err = got_object_id_str(&id_str1, &qid->id);
3858 if (err)
3859 goto done;
3862 err = got_object_id_str(&id_str2, id);
3863 if (err)
3864 goto done;
3866 if (path && path[0] != '\0') {
3867 int obj_type;
3868 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3869 if (err)
3870 goto done;
3871 if (pcommit) {
3872 err = got_object_id_by_path(&obj_id1, repo,
3873 pcommit, path);
3874 if (err) {
3875 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3876 free(obj_id2);
3877 goto done;
3881 err = got_object_get_type(&obj_type, repo, obj_id2);
3882 if (err) {
3883 free(obj_id2);
3884 goto done;
3886 fprintf(outfile,
3887 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3888 fprintf(outfile, "commit - %s\n",
3889 id_str1 ? id_str1 : "/dev/null");
3890 fprintf(outfile, "commit + %s\n", id_str2);
3891 switch (obj_type) {
3892 case GOT_OBJ_TYPE_BLOB:
3893 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3894 0, 0, repo, outfile);
3895 break;
3896 case GOT_OBJ_TYPE_TREE:
3897 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3898 0, 0, repo, outfile);
3899 break;
3900 default:
3901 err = got_error(GOT_ERR_OBJ_TYPE);
3902 break;
3904 free(obj_id1);
3905 free(obj_id2);
3906 } else {
3907 obj_id2 = got_object_commit_get_tree_id(commit);
3908 if (pcommit)
3909 obj_id1 = got_object_commit_get_tree_id(pcommit);
3910 fprintf(outfile,
3911 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3912 fprintf(outfile, "commit - %s\n",
3913 id_str1 ? id_str1 : "/dev/null");
3914 fprintf(outfile, "commit + %s\n", id_str2);
3915 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3916 repo, outfile);
3918 done:
3919 free(id_str1);
3920 free(id_str2);
3921 if (pcommit)
3922 got_object_commit_close(pcommit);
3923 return err;
3926 static char *
3927 get_datestr(time_t *time, char *datebuf)
3929 struct tm mytm, *tm;
3930 char *p, *s;
3932 tm = gmtime_r(time, &mytm);
3933 if (tm == NULL)
3934 return NULL;
3935 s = asctime_r(tm, datebuf);
3936 if (s == NULL)
3937 return NULL;
3938 p = strchr(s, '\n');
3939 if (p)
3940 *p = '\0';
3941 return s;
3944 static const struct got_error *
3945 match_commit(int *have_match, struct got_object_id *id,
3946 struct got_commit_object *commit, regex_t *regex)
3948 const struct got_error *err = NULL;
3949 regmatch_t regmatch;
3950 char *id_str = NULL, *logmsg = NULL;
3952 *have_match = 0;
3954 err = got_object_id_str(&id_str, id);
3955 if (err)
3956 return err;
3958 err = got_object_commit_get_logmsg(&logmsg, commit);
3959 if (err)
3960 goto done;
3962 if (regexec(regex, got_object_commit_get_author(commit), 1,
3963 &regmatch, 0) == 0 ||
3964 regexec(regex, got_object_commit_get_committer(commit), 1,
3965 &regmatch, 0) == 0 ||
3966 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3967 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3968 *have_match = 1;
3969 done:
3970 free(id_str);
3971 free(logmsg);
3972 return err;
3975 static void
3976 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3977 regex_t *regex)
3979 regmatch_t regmatch;
3980 struct got_pathlist_entry *pe;
3982 *have_match = 0;
3984 TAILQ_FOREACH(pe, changed_paths, entry) {
3985 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3986 *have_match = 1;
3987 break;
3992 static const struct got_error *
3993 match_patch(int *have_match, struct got_commit_object *commit,
3994 struct got_object_id *id, const char *path, int diff_context,
3995 struct got_repository *repo, regex_t *regex, FILE *f)
3997 const struct got_error *err = NULL;
3998 char *line = NULL;
3999 size_t linesize = 0;
4000 regmatch_t regmatch;
4002 *have_match = 0;
4004 err = got_opentemp_truncate(f);
4005 if (err)
4006 return err;
4008 err = print_patch(commit, id, path, diff_context, repo, f);
4009 if (err)
4010 goto done;
4012 if (fseeko(f, 0L, SEEK_SET) == -1) {
4013 err = got_error_from_errno("fseeko");
4014 goto done;
4017 while (getline(&line, &linesize, f) != -1) {
4018 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4019 *have_match = 1;
4020 break;
4023 done:
4024 free(line);
4025 return err;
4028 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4030 static const struct got_error*
4031 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4032 struct got_object_id *id, struct got_repository *repo,
4033 int local_only)
4035 static const struct got_error *err = NULL;
4036 struct got_reflist_entry *re;
4037 char *s;
4038 const char *name;
4040 *refs_str = NULL;
4042 TAILQ_FOREACH(re, refs, entry) {
4043 struct got_tag_object *tag = NULL;
4044 struct got_object_id *ref_id;
4045 int cmp;
4047 name = got_ref_get_name(re->ref);
4048 if (strcmp(name, GOT_REF_HEAD) == 0)
4049 continue;
4050 if (strncmp(name, "refs/", 5) == 0)
4051 name += 5;
4052 if (strncmp(name, "got/", 4) == 0)
4053 continue;
4054 if (strncmp(name, "heads/", 6) == 0)
4055 name += 6;
4056 if (strncmp(name, "remotes/", 8) == 0) {
4057 if (local_only)
4058 continue;
4059 name += 8;
4060 s = strstr(name, "/" GOT_REF_HEAD);
4061 if (s != NULL && s[strlen(s)] == '\0')
4062 continue;
4064 err = got_ref_resolve(&ref_id, repo, re->ref);
4065 if (err)
4066 break;
4067 if (strncmp(name, "tags/", 5) == 0) {
4068 err = got_object_open_as_tag(&tag, repo, ref_id);
4069 if (err) {
4070 if (err->code != GOT_ERR_OBJ_TYPE) {
4071 free(ref_id);
4072 break;
4074 /* Ref points at something other than a tag. */
4075 err = NULL;
4076 tag = NULL;
4079 cmp = got_object_id_cmp(tag ?
4080 got_object_tag_get_object_id(tag) : ref_id, id);
4081 free(ref_id);
4082 if (tag)
4083 got_object_tag_close(tag);
4084 if (cmp != 0)
4085 continue;
4086 s = *refs_str;
4087 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4088 s ? ", " : "", name) == -1) {
4089 err = got_error_from_errno("asprintf");
4090 free(s);
4091 *refs_str = NULL;
4092 break;
4094 free(s);
4097 return err;
4100 static const struct got_error *
4101 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4102 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4104 const struct got_error *err = NULL;
4105 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4106 char *comma, *s, *nl;
4107 struct got_reflist_head *refs;
4108 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4109 struct tm tm;
4110 time_t committer_time;
4112 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4113 if (refs) {
4114 err = build_refs_str(&ref_str, refs, id, repo, 1);
4115 if (err)
4116 return err;
4118 /* Display the first matching ref only. */
4119 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4120 *comma = '\0';
4123 if (ref_str == NULL) {
4124 err = got_object_id_str(&id_str, id);
4125 if (err)
4126 return err;
4129 committer_time = got_object_commit_get_committer_time(commit);
4130 if (gmtime_r(&committer_time, &tm) == NULL) {
4131 err = got_error_from_errno("gmtime_r");
4132 goto done;
4134 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4135 err = got_error(GOT_ERR_NO_SPACE);
4136 goto done;
4139 err = got_object_commit_get_logmsg(&logmsg0, commit);
4140 if (err)
4141 goto done;
4143 s = logmsg0;
4144 while (isspace((unsigned char)s[0]))
4145 s++;
4147 nl = strchr(s, '\n');
4148 if (nl) {
4149 *nl = '\0';
4152 if (ref_str)
4153 printf("%s%-7s %s\n", datebuf, ref_str, s);
4154 else
4155 printf("%s%.7s %s\n", datebuf, id_str, s);
4157 if (fflush(stdout) != 0 && err == NULL)
4158 err = got_error_from_errno("fflush");
4159 done:
4160 free(id_str);
4161 free(ref_str);
4162 free(logmsg0);
4163 return err;
4166 static const struct got_error *
4167 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4168 struct got_repository *repo, const char *path,
4169 struct got_pathlist_head *changed_paths, struct got_diffstat_cb_arg *dsa,
4170 int show_patch, int diff_context,
4171 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str)
4173 const struct got_error *err = NULL;
4174 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4175 char datebuf[26];
4176 time_t committer_time;
4177 const char *author, *committer;
4178 char *refs_str = NULL;
4180 err = got_object_id_str(&id_str, id);
4181 if (err)
4182 return err;
4184 if (custom_refs_str == NULL) {
4185 struct got_reflist_head *refs;
4186 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4187 if (refs) {
4188 err = build_refs_str(&refs_str, refs, id, repo, 0);
4189 if (err)
4190 goto done;
4194 printf(GOT_COMMIT_SEP_STR);
4195 if (custom_refs_str)
4196 printf("commit %s (%s)\n", id_str, custom_refs_str);
4197 else
4198 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4199 refs_str ? refs_str : "", refs_str ? ")" : "");
4200 free(id_str);
4201 id_str = NULL;
4202 free(refs_str);
4203 refs_str = NULL;
4204 printf("from: %s\n", got_object_commit_get_author(commit));
4205 author = got_object_commit_get_author(commit);
4206 committer = got_object_commit_get_committer(commit);
4207 if (strcmp(author, committer) != 0)
4208 printf("via: %s\n", committer);
4209 committer_time = got_object_commit_get_committer_time(commit);
4210 datestr = get_datestr(&committer_time, datebuf);
4211 if (datestr)
4212 printf("date: %s UTC\n", datestr);
4213 if (got_object_commit_get_nparents(commit) > 1) {
4214 const struct got_object_id_queue *parent_ids;
4215 struct got_object_qid *qid;
4216 int n = 1;
4217 parent_ids = got_object_commit_get_parent_ids(commit);
4218 STAILQ_FOREACH(qid, parent_ids, entry) {
4219 err = got_object_id_str(&id_str, &qid->id);
4220 if (err)
4221 goto done;
4222 printf("parent %d: %s\n", n++, id_str);
4223 free(id_str);
4224 id_str = NULL;
4228 err = got_object_commit_get_logmsg(&logmsg0, commit);
4229 if (err)
4230 goto done;
4232 logmsg = logmsg0;
4233 do {
4234 line = strsep(&logmsg, "\n");
4235 if (line)
4236 printf(" %s\n", line);
4237 } while (line);
4238 free(logmsg0);
4240 if (changed_paths) {
4241 struct got_pathlist_entry *pe;
4243 TAILQ_FOREACH(pe, changed_paths, entry) {
4244 struct got_diff_changed_path *cp = pe->data;
4245 char *stat = NULL;
4247 if (dsa) {
4248 int pad = dsa->max_path_len - pe->path_len + 1;
4250 if (asprintf(&stat, "%*c | %*d+ %*d-",
4251 pad, ' ', dsa->add_cols + 1, cp->add,
4252 dsa->rm_cols + 1, cp->rm) == -1) {
4253 err = got_error_from_errno("asprintf");
4254 goto done;
4257 printf(" %c %s%s\n", cp->status, pe->path,
4258 stat ? stat : "");
4259 free(stat);
4261 if (dsa)
4262 printf("\n%d file%s changed, %d insertions(+), "
4263 "%d deletions(-)\n", dsa->nfiles,
4264 dsa->nfiles > 1 ? "s" : "", dsa->ins, dsa->del);
4265 printf("\n");
4267 if (show_patch) {
4268 err = print_patch(commit, id, path, diff_context, repo, stdout);
4269 if (err == 0)
4270 printf("\n");
4273 if (fflush(stdout) != 0 && err == NULL)
4274 err = got_error_from_errno("fflush");
4275 done:
4276 free(id_str);
4277 free(refs_str);
4278 return err;
4281 static const struct got_error *
4282 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4283 struct got_repository *repo, const char *path, int show_changed_paths,
4284 int show_diffstat, int show_patch, const char *search_pattern,
4285 int diff_context, int limit, int log_branches, int reverse_display_order,
4286 struct got_reflist_object_id_map *refs_idmap, int one_line,
4287 FILE *tmpfile)
4289 const struct got_error *err;
4290 struct got_commit_graph *graph;
4291 regex_t regex;
4292 int have_match;
4293 struct got_object_id_queue reversed_commits;
4294 struct got_object_qid *qid;
4295 struct got_commit_object *commit;
4296 struct got_pathlist_head changed_paths;
4297 struct got_pathlist_entry *pe;
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 TAILQ_FOREACH(pe, &changed_paths, entry) {
4360 free((char *)pe->path);
4361 free(pe->data);
4363 got_pathlist_free(&changed_paths);
4364 continue;
4368 if (reverse_display_order) {
4369 err = got_object_qid_alloc(&qid, &id);
4370 if (err)
4371 break;
4372 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4373 got_object_commit_close(commit);
4374 } else {
4375 if (one_line)
4376 err = print_commit_oneline(commit, &id,
4377 repo, refs_idmap);
4378 else
4379 err = print_commit(commit, &id, repo, path,
4380 (show_changed_paths || show_diffstat) ?
4381 &changed_paths : NULL,
4382 show_diffstat ? &dsa : NULL, show_patch,
4383 diff_context, refs_idmap, NULL);
4384 got_object_commit_close(commit);
4385 if (err)
4386 break;
4388 if ((limit && --limit == 0) ||
4389 (end_id && got_object_id_cmp(&id, end_id) == 0))
4390 break;
4392 TAILQ_FOREACH(pe, &changed_paths, entry) {
4393 free((char *)pe->path);
4394 free(pe->data);
4396 got_pathlist_free(&changed_paths);
4398 if (reverse_display_order) {
4399 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4400 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4401 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4403 err = got_object_open_as_commit(&commit, repo,
4404 &qid->id);
4405 if (err)
4406 break;
4407 if (show_changed_paths || show_diffstat) {
4408 err = get_changed_paths(&changed_paths,
4409 commit, repo, show_diffstat ? &dsa : NULL);
4410 if (err)
4411 break;
4413 if (one_line)
4414 err = print_commit_oneline(commit, &qid->id,
4415 repo, refs_idmap);
4416 else
4417 err = print_commit(commit, &qid->id, repo, path,
4418 (show_changed_paths || show_diffstat) ?
4419 &changed_paths : NULL,
4420 show_diffstat ? &dsa : NULL, show_patch,
4421 diff_context, refs_idmap, NULL);
4422 got_object_commit_close(commit);
4423 if (err)
4424 break;
4425 TAILQ_FOREACH(pe, &changed_paths, entry) {
4426 free((char *)pe->path);
4427 free(pe->data);
4429 got_pathlist_free(&changed_paths);
4432 done:
4433 while (!STAILQ_EMPTY(&reversed_commits)) {
4434 qid = STAILQ_FIRST(&reversed_commits);
4435 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4436 got_object_qid_free(qid);
4438 TAILQ_FOREACH(pe, &changed_paths, entry) {
4439 free((char *)pe->path);
4440 free(pe->data);
4442 got_pathlist_free(&changed_paths);
4443 if (search_pattern)
4444 regfree(&regex);
4445 got_commit_graph_close(graph);
4446 return err;
4449 __dead static void
4450 usage_log(void)
4452 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4453 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4454 "[path]\n", getprogname());
4455 exit(1);
4458 static int
4459 get_default_log_limit(void)
4461 const char *got_default_log_limit;
4462 long long n;
4463 const char *errstr;
4465 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4466 if (got_default_log_limit == NULL)
4467 return 0;
4468 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4469 if (errstr != NULL)
4470 return 0;
4471 return n;
4474 static const struct got_error *
4475 cmd_log(int argc, char *argv[])
4477 const struct got_error *error;
4478 struct got_repository *repo = NULL;
4479 struct got_worktree *worktree = NULL;
4480 struct got_object_id *start_id = NULL, *end_id = NULL;
4481 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4482 const char *start_commit = NULL, *end_commit = NULL;
4483 const char *search_pattern = NULL;
4484 int diff_context = -1, ch;
4485 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4486 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4487 const char *errstr;
4488 struct got_reflist_head refs;
4489 struct got_reflist_object_id_map *refs_idmap = NULL;
4490 FILE *tmpfile = NULL;
4491 int *pack_fds = NULL;
4493 TAILQ_INIT(&refs);
4495 #ifndef PROFILE
4496 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4497 NULL)
4498 == -1)
4499 err(1, "pledge");
4500 #endif
4502 limit = get_default_log_limit();
4504 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4505 switch (ch) {
4506 case 'b':
4507 log_branches = 1;
4508 break;
4509 case 'C':
4510 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4511 &errstr);
4512 if (errstr != NULL)
4513 errx(1, "number of context lines is %s: %s",
4514 errstr, optarg);
4515 break;
4516 case 'c':
4517 start_commit = optarg;
4518 break;
4519 case 'd':
4520 show_diffstat = 1;
4521 break;
4522 case 'l':
4523 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4524 if (errstr != NULL)
4525 errx(1, "number of commits is %s: %s",
4526 errstr, optarg);
4527 break;
4528 case 'P':
4529 show_changed_paths = 1;
4530 break;
4531 case 'p':
4532 show_patch = 1;
4533 break;
4534 case 'R':
4535 reverse_display_order = 1;
4536 break;
4537 case 'r':
4538 repo_path = realpath(optarg, NULL);
4539 if (repo_path == NULL)
4540 return got_error_from_errno2("realpath",
4541 optarg);
4542 got_path_strip_trailing_slashes(repo_path);
4543 break;
4544 case 'S':
4545 search_pattern = optarg;
4546 break;
4547 case 's':
4548 one_line = 1;
4549 break;
4550 case 'x':
4551 end_commit = optarg;
4552 break;
4553 default:
4554 usage_log();
4555 /* NOTREACHED */
4559 argc -= optind;
4560 argv += optind;
4562 if (diff_context == -1)
4563 diff_context = 3;
4564 else if (!show_patch)
4565 errx(1, "-C requires -p");
4567 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4568 errx(1, "cannot use -s with -d, -p or -P");
4570 cwd = getcwd(NULL, 0);
4571 if (cwd == NULL) {
4572 error = got_error_from_errno("getcwd");
4573 goto done;
4576 error = got_repo_pack_fds_open(&pack_fds);
4577 if (error != NULL)
4578 goto done;
4580 if (repo_path == NULL) {
4581 error = got_worktree_open(&worktree, cwd);
4582 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4583 goto done;
4584 error = NULL;
4587 if (argc == 1) {
4588 if (worktree) {
4589 error = got_worktree_resolve_path(&path, worktree,
4590 argv[0]);
4591 if (error)
4592 goto done;
4593 } else {
4594 path = strdup(argv[0]);
4595 if (path == NULL) {
4596 error = got_error_from_errno("strdup");
4597 goto done;
4600 } else if (argc != 0)
4601 usage_log();
4603 if (repo_path == NULL) {
4604 repo_path = worktree ?
4605 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4607 if (repo_path == NULL) {
4608 error = got_error_from_errno("strdup");
4609 goto done;
4612 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4613 if (error != NULL)
4614 goto done;
4616 error = apply_unveil(got_repo_get_path(repo), 1,
4617 worktree ? got_worktree_get_root_path(worktree) : NULL);
4618 if (error)
4619 goto done;
4621 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4622 if (error)
4623 goto done;
4625 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4626 if (error)
4627 goto done;
4629 if (start_commit == NULL) {
4630 struct got_reference *head_ref;
4631 struct got_commit_object *commit = NULL;
4632 error = got_ref_open(&head_ref, repo,
4633 worktree ? got_worktree_get_head_ref_name(worktree)
4634 : GOT_REF_HEAD, 0);
4635 if (error != NULL)
4636 goto done;
4637 error = got_ref_resolve(&start_id, repo, head_ref);
4638 got_ref_close(head_ref);
4639 if (error != NULL)
4640 goto done;
4641 error = got_object_open_as_commit(&commit, repo,
4642 start_id);
4643 if (error != NULL)
4644 goto done;
4645 got_object_commit_close(commit);
4646 } else {
4647 error = got_repo_match_object_id(&start_id, NULL,
4648 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4649 if (error != NULL)
4650 goto done;
4652 if (end_commit != NULL) {
4653 error = got_repo_match_object_id(&end_id, NULL,
4654 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4655 if (error != NULL)
4656 goto done;
4659 if (worktree) {
4661 * If a path was specified on the command line it was resolved
4662 * to a path in the work tree above. Prepend the work tree's
4663 * path prefix to obtain the corresponding in-repository path.
4665 if (path) {
4666 const char *prefix;
4667 prefix = got_worktree_get_path_prefix(worktree);
4668 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4669 (path[0] != '\0') ? "/" : "", path) == -1) {
4670 error = got_error_from_errno("asprintf");
4671 goto done;
4674 } else
4675 error = got_repo_map_path(&in_repo_path, repo,
4676 path ? path : "");
4677 if (error != NULL)
4678 goto done;
4679 if (in_repo_path) {
4680 free(path);
4681 path = in_repo_path;
4684 if (worktree) {
4685 /* Release work tree lock. */
4686 got_worktree_close(worktree);
4687 worktree = NULL;
4690 if (search_pattern && show_patch) {
4691 tmpfile = got_opentemp();
4692 if (tmpfile == NULL) {
4693 error = got_error_from_errno("got_opentemp");
4694 goto done;
4698 error = print_commits(start_id, end_id, repo, path ? path : "",
4699 show_changed_paths, show_diffstat, show_patch, search_pattern,
4700 diff_context, limit, log_branches, reverse_display_order,
4701 refs_idmap, one_line, tmpfile);
4702 done:
4703 free(path);
4704 free(repo_path);
4705 free(cwd);
4706 if (worktree)
4707 got_worktree_close(worktree);
4708 if (repo) {
4709 const struct got_error *close_err = got_repo_close(repo);
4710 if (error == NULL)
4711 error = close_err;
4713 if (pack_fds) {
4714 const struct got_error *pack_err =
4715 got_repo_pack_fds_close(pack_fds);
4716 if (error == NULL)
4717 error = pack_err;
4719 if (refs_idmap)
4720 got_reflist_object_id_map_free(refs_idmap);
4721 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4722 error = got_error_from_errno("fclose");
4723 got_ref_list_free(&refs);
4724 return error;
4727 __dead static void
4728 usage_diff(void)
4730 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4731 "[-r repository-path] [object1 object2 | path ...]\n",
4732 getprogname());
4733 exit(1);
4736 struct print_diff_arg {
4737 struct got_repository *repo;
4738 struct got_worktree *worktree;
4739 int diff_context;
4740 const char *id_str;
4741 int header_shown;
4742 int diff_staged;
4743 enum got_diff_algorithm diff_algo;
4744 int ignore_whitespace;
4745 int force_text_diff;
4746 FILE *f1;
4747 FILE *f2;
4751 * Create a file which contains the target path of a symlink so we can feed
4752 * it as content to the diff engine.
4754 static const struct got_error *
4755 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4756 const char *abspath)
4758 const struct got_error *err = NULL;
4759 char target_path[PATH_MAX];
4760 ssize_t target_len, outlen;
4762 *fd = -1;
4764 if (dirfd != -1) {
4765 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4766 if (target_len == -1)
4767 return got_error_from_errno2("readlinkat", abspath);
4768 } else {
4769 target_len = readlink(abspath, target_path, PATH_MAX);
4770 if (target_len == -1)
4771 return got_error_from_errno2("readlink", abspath);
4774 *fd = got_opentempfd();
4775 if (*fd == -1)
4776 return got_error_from_errno("got_opentempfd");
4778 outlen = write(*fd, target_path, target_len);
4779 if (outlen == -1) {
4780 err = got_error_from_errno("got_opentempfd");
4781 goto done;
4784 if (lseek(*fd, 0, SEEK_SET) == -1) {
4785 err = got_error_from_errno2("lseek", abspath);
4786 goto done;
4788 done:
4789 if (err) {
4790 close(*fd);
4791 *fd = -1;
4793 return err;
4796 static const struct got_error *
4797 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4798 const char *path, struct got_object_id *blob_id,
4799 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4800 int dirfd, const char *de_name)
4802 struct print_diff_arg *a = arg;
4803 const struct got_error *err = NULL;
4804 struct got_blob_object *blob1 = NULL;
4805 int fd = -1, fd1 = -1, fd2 = -1;
4806 FILE *f2 = NULL;
4807 char *abspath = NULL, *label1 = NULL;
4808 struct stat sb;
4809 off_t size1 = 0;
4810 int f2_exists = 0;
4812 memset(&sb, 0, sizeof(sb));
4814 if (a->diff_staged) {
4815 if (staged_status != GOT_STATUS_MODIFY &&
4816 staged_status != GOT_STATUS_ADD &&
4817 staged_status != GOT_STATUS_DELETE)
4818 return NULL;
4819 } else {
4820 if (staged_status == GOT_STATUS_DELETE)
4821 return NULL;
4822 if (status == GOT_STATUS_NONEXISTENT)
4823 return got_error_set_errno(ENOENT, path);
4824 if (status != GOT_STATUS_MODIFY &&
4825 status != GOT_STATUS_ADD &&
4826 status != GOT_STATUS_DELETE &&
4827 status != GOT_STATUS_CONFLICT)
4828 return NULL;
4831 err = got_opentemp_truncate(a->f1);
4832 if (err)
4833 return got_error_from_errno("got_opentemp_truncate");
4834 err = got_opentemp_truncate(a->f2);
4835 if (err)
4836 return got_error_from_errno("got_opentemp_truncate");
4838 if (!a->header_shown) {
4839 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4840 got_worktree_get_root_path(a->worktree));
4841 printf("commit - %s\n", a->id_str);
4842 printf("path + %s%s\n",
4843 got_worktree_get_root_path(a->worktree),
4844 a->diff_staged ? " (staged changes)" : "");
4845 a->header_shown = 1;
4848 if (a->diff_staged) {
4849 const char *label1 = NULL, *label2 = NULL;
4850 switch (staged_status) {
4851 case GOT_STATUS_MODIFY:
4852 label1 = path;
4853 label2 = path;
4854 break;
4855 case GOT_STATUS_ADD:
4856 label2 = path;
4857 break;
4858 case GOT_STATUS_DELETE:
4859 label1 = path;
4860 break;
4861 default:
4862 return got_error(GOT_ERR_FILE_STATUS);
4864 fd1 = got_opentempfd();
4865 if (fd1 == -1) {
4866 err = got_error_from_errno("got_opentempfd");
4867 goto done;
4869 fd2 = got_opentempfd();
4870 if (fd2 == -1) {
4871 err = got_error_from_errno("got_opentempfd");
4872 goto done;
4874 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4875 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4876 a->diff_algo, a->diff_context, a->ignore_whitespace,
4877 a->force_text_diff, a->repo, stdout);
4878 goto done;
4881 fd1 = got_opentempfd();
4882 if (fd1 == -1) {
4883 err = got_error_from_errno("got_opentempfd");
4884 goto done;
4887 if (staged_status == GOT_STATUS_ADD ||
4888 staged_status == GOT_STATUS_MODIFY) {
4889 char *id_str;
4890 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4891 8192, fd1);
4892 if (err)
4893 goto done;
4894 err = got_object_id_str(&id_str, staged_blob_id);
4895 if (err)
4896 goto done;
4897 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4898 err = got_error_from_errno("asprintf");
4899 free(id_str);
4900 goto done;
4902 free(id_str);
4903 } else if (status != GOT_STATUS_ADD) {
4904 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4905 fd1);
4906 if (err)
4907 goto done;
4910 if (status != GOT_STATUS_DELETE) {
4911 if (asprintf(&abspath, "%s/%s",
4912 got_worktree_get_root_path(a->worktree), path) == -1) {
4913 err = got_error_from_errno("asprintf");
4914 goto done;
4917 if (dirfd != -1) {
4918 fd = openat(dirfd, de_name,
4919 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4920 if (fd == -1) {
4921 if (!got_err_open_nofollow_on_symlink()) {
4922 err = got_error_from_errno2("openat",
4923 abspath);
4924 goto done;
4926 err = get_symlink_target_file(&fd, dirfd,
4927 de_name, abspath);
4928 if (err)
4929 goto done;
4931 } else {
4932 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4933 if (fd == -1) {
4934 if (!got_err_open_nofollow_on_symlink()) {
4935 err = got_error_from_errno2("open",
4936 abspath);
4937 goto done;
4939 err = get_symlink_target_file(&fd, dirfd,
4940 de_name, abspath);
4941 if (err)
4942 goto done;
4945 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4946 err = got_error_from_errno2("fstatat", abspath);
4947 goto done;
4949 f2 = fdopen(fd, "r");
4950 if (f2 == NULL) {
4951 err = got_error_from_errno2("fdopen", abspath);
4952 goto done;
4954 fd = -1;
4955 f2_exists = 1;
4958 if (blob1) {
4959 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4960 a->f1, blob1);
4961 if (err)
4962 goto done;
4965 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4966 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4967 a->ignore_whitespace, a->force_text_diff, stdout);
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 cmd_diff(int argc, char *argv[])
4986 const struct got_error *error;
4987 struct got_repository *repo = NULL;
4988 struct got_worktree *worktree = NULL;
4989 char *cwd = NULL, *repo_path = NULL;
4990 const char *commit_args[2] = { NULL, NULL };
4991 int ncommit_args = 0;
4992 struct got_object_id *ids[2] = { NULL, NULL };
4993 char *labels[2] = { NULL, NULL };
4994 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4995 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4996 int force_text_diff = 0, force_path = 0, rflag = 0;
4997 const char *errstr;
4998 struct got_reflist_head refs;
4999 struct got_pathlist_head paths;
5000 struct got_pathlist_entry *pe;
5001 FILE *f1 = NULL, *f2 = NULL;
5002 int fd1 = -1, fd2 = -1;
5003 int *pack_fds = NULL;
5005 TAILQ_INIT(&refs);
5006 TAILQ_INIT(&paths);
5008 #ifndef PROFILE
5009 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5010 NULL) == -1)
5011 err(1, "pledge");
5012 #endif
5014 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
5015 switch (ch) {
5016 case 'a':
5017 force_text_diff = 1;
5018 break;
5019 case 'C':
5020 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5021 &errstr);
5022 if (errstr != NULL)
5023 errx(1, "number of context lines is %s: %s",
5024 errstr, optarg);
5025 break;
5026 case 'c':
5027 if (ncommit_args >= 2)
5028 errx(1, "too many -c options used");
5029 commit_args[ncommit_args++] = optarg;
5030 break;
5031 case 'P':
5032 force_path = 1;
5033 break;
5034 case 'r':
5035 repo_path = realpath(optarg, NULL);
5036 if (repo_path == NULL)
5037 return got_error_from_errno2("realpath",
5038 optarg);
5039 got_path_strip_trailing_slashes(repo_path);
5040 rflag = 1;
5041 break;
5042 case 's':
5043 diff_staged = 1;
5044 break;
5045 case 'w':
5046 ignore_whitespace = 1;
5047 break;
5048 default:
5049 usage_diff();
5050 /* NOTREACHED */
5054 argc -= optind;
5055 argv += optind;
5057 cwd = getcwd(NULL, 0);
5058 if (cwd == NULL) {
5059 error = got_error_from_errno("getcwd");
5060 goto done;
5063 error = got_repo_pack_fds_open(&pack_fds);
5064 if (error != NULL)
5065 goto done;
5067 if (repo_path == NULL) {
5068 error = got_worktree_open(&worktree, cwd);
5069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5070 goto done;
5071 else
5072 error = NULL;
5073 if (worktree) {
5074 repo_path =
5075 strdup(got_worktree_get_repo_path(worktree));
5076 if (repo_path == NULL) {
5077 error = got_error_from_errno("strdup");
5078 goto done;
5080 } else {
5081 repo_path = strdup(cwd);
5082 if (repo_path == NULL) {
5083 error = got_error_from_errno("strdup");
5084 goto done;
5089 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5090 free(repo_path);
5091 if (error != NULL)
5092 goto done;
5094 if (rflag || worktree == NULL || ncommit_args > 0) {
5095 if (force_path) {
5096 error = got_error_msg(GOT_ERR_NOT_IMPL,
5097 "-P option can only be used when diffing "
5098 "a work tree");
5099 goto done;
5101 if (diff_staged) {
5102 error = got_error_msg(GOT_ERR_NOT_IMPL,
5103 "-s option can only be used when diffing "
5104 "a work tree");
5105 goto done;
5109 error = apply_unveil(got_repo_get_path(repo), 1,
5110 worktree ? got_worktree_get_root_path(worktree) : NULL);
5111 if (error)
5112 goto done;
5114 if ((!force_path && argc == 2) || ncommit_args > 0) {
5115 int obj_type = (ncommit_args > 0 ?
5116 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5117 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5118 NULL);
5119 if (error)
5120 goto done;
5121 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5122 const char *arg;
5123 if (ncommit_args > 0)
5124 arg = commit_args[i];
5125 else
5126 arg = argv[i];
5127 error = got_repo_match_object_id(&ids[i], &labels[i],
5128 arg, obj_type, &refs, repo);
5129 if (error) {
5130 if (error->code != GOT_ERR_NOT_REF &&
5131 error->code != GOT_ERR_NO_OBJ)
5132 goto done;
5133 if (ncommit_args > 0)
5134 goto done;
5135 error = NULL;
5136 break;
5141 f1 = got_opentemp();
5142 if (f1 == NULL) {
5143 error = got_error_from_errno("got_opentemp");
5144 goto done;
5147 f2 = got_opentemp();
5148 if (f2 == NULL) {
5149 error = got_error_from_errno("got_opentemp");
5150 goto done;
5153 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5154 struct print_diff_arg arg;
5155 char *id_str;
5157 if (worktree == NULL) {
5158 if (argc == 2 && ids[0] == NULL) {
5159 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5160 goto done;
5161 } else if (argc == 2 && ids[1] == NULL) {
5162 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5163 goto done;
5164 } else if (argc > 0) {
5165 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5166 "%s", "specified paths cannot be resolved");
5167 goto done;
5168 } else {
5169 error = got_error(GOT_ERR_NOT_WORKTREE);
5170 goto done;
5174 error = get_worktree_paths_from_argv(&paths, argc, argv,
5175 worktree);
5176 if (error)
5177 goto done;
5179 error = got_object_id_str(&id_str,
5180 got_worktree_get_base_commit_id(worktree));
5181 if (error)
5182 goto done;
5183 arg.repo = repo;
5184 arg.worktree = worktree;
5185 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5186 arg.diff_context = diff_context;
5187 arg.id_str = id_str;
5188 arg.header_shown = 0;
5189 arg.diff_staged = diff_staged;
5190 arg.ignore_whitespace = ignore_whitespace;
5191 arg.force_text_diff = force_text_diff;
5192 arg.f1 = f1;
5193 arg.f2 = f2;
5195 error = got_worktree_status(worktree, &paths, repo, 0,
5196 print_diff, &arg, check_cancelled, NULL);
5197 free(id_str);
5198 goto done;
5201 if (ncommit_args == 1) {
5202 struct got_commit_object *commit;
5203 error = got_object_open_as_commit(&commit, repo, ids[0]);
5204 if (error)
5205 goto done;
5207 labels[1] = labels[0];
5208 ids[1] = ids[0];
5209 if (got_object_commit_get_nparents(commit) > 0) {
5210 const struct got_object_id_queue *pids;
5211 struct got_object_qid *pid;
5212 pids = got_object_commit_get_parent_ids(commit);
5213 pid = STAILQ_FIRST(pids);
5214 ids[0] = got_object_id_dup(&pid->id);
5215 if (ids[0] == NULL) {
5216 error = got_error_from_errno(
5217 "got_object_id_dup");
5218 got_object_commit_close(commit);
5219 goto done;
5221 error = got_object_id_str(&labels[0], ids[0]);
5222 if (error) {
5223 got_object_commit_close(commit);
5224 goto done;
5226 } else {
5227 ids[0] = NULL;
5228 labels[0] = strdup("/dev/null");
5229 if (labels[0] == NULL) {
5230 error = got_error_from_errno("strdup");
5231 got_object_commit_close(commit);
5232 goto done;
5236 got_object_commit_close(commit);
5239 if (ncommit_args == 0 && argc > 2) {
5240 error = got_error_msg(GOT_ERR_BAD_PATH,
5241 "path arguments cannot be used when diffing two objects");
5242 goto done;
5245 if (ids[0]) {
5246 error = got_object_get_type(&type1, repo, ids[0]);
5247 if (error)
5248 goto done;
5251 error = got_object_get_type(&type2, repo, ids[1]);
5252 if (error)
5253 goto done;
5254 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5255 error = got_error(GOT_ERR_OBJ_TYPE);
5256 goto done;
5258 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5259 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5260 "path arguments cannot be used when diffing blobs");
5261 goto done;
5264 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5265 char *in_repo_path;
5266 struct got_pathlist_entry *new;
5267 if (worktree) {
5268 const char *prefix;
5269 char *p;
5270 error = got_worktree_resolve_path(&p, worktree,
5271 argv[i]);
5272 if (error)
5273 goto done;
5274 prefix = got_worktree_get_path_prefix(worktree);
5275 while (prefix[0] == '/')
5276 prefix++;
5277 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5278 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5279 p) == -1) {
5280 error = got_error_from_errno("asprintf");
5281 free(p);
5282 goto done;
5284 free(p);
5285 } else {
5286 char *mapped_path, *s;
5287 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5288 if (error)
5289 goto done;
5290 s = mapped_path;
5291 while (s[0] == '/')
5292 s++;
5293 in_repo_path = strdup(s);
5294 if (in_repo_path == NULL) {
5295 error = got_error_from_errno("asprintf");
5296 free(mapped_path);
5297 goto done;
5299 free(mapped_path);
5302 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5303 if (error || new == NULL /* duplicate */)
5304 free(in_repo_path);
5305 if (error)
5306 goto done;
5309 if (worktree) {
5310 /* Release work tree lock. */
5311 got_worktree_close(worktree);
5312 worktree = NULL;
5315 fd1 = got_opentempfd();
5316 if (fd1 == -1) {
5317 error = got_error_from_errno("got_opentempfd");
5318 goto done;
5321 fd2 = got_opentempfd();
5322 if (fd2 == -1) {
5323 error = got_error_from_errno("got_opentempfd");
5324 goto done;
5327 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5328 case GOT_OBJ_TYPE_BLOB:
5329 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5330 fd1, fd2, ids[0], ids[1], NULL, NULL,
5331 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5332 ignore_whitespace, force_text_diff, repo, stdout);
5333 break;
5334 case GOT_OBJ_TYPE_TREE:
5335 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5336 ids[0], ids[1], &paths, "", "",
5337 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5338 ignore_whitespace, force_text_diff, repo, stdout);
5339 break;
5340 case GOT_OBJ_TYPE_COMMIT:
5341 printf("diff %s %s\n", labels[0], labels[1]);
5342 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5343 fd1, fd2, ids[0], ids[1], &paths,
5344 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5345 ignore_whitespace, force_text_diff, repo, stdout);
5346 break;
5347 default:
5348 error = got_error(GOT_ERR_OBJ_TYPE);
5350 done:
5351 free(labels[0]);
5352 free(labels[1]);
5353 free(ids[0]);
5354 free(ids[1]);
5355 if (worktree)
5356 got_worktree_close(worktree);
5357 if (repo) {
5358 const struct got_error *close_err = got_repo_close(repo);
5359 if (error == NULL)
5360 error = close_err;
5362 if (pack_fds) {
5363 const struct got_error *pack_err =
5364 got_repo_pack_fds_close(pack_fds);
5365 if (error == NULL)
5366 error = pack_err;
5368 TAILQ_FOREACH(pe, &paths, entry)
5369 free((char *)pe->path);
5370 got_pathlist_free(&paths);
5371 got_ref_list_free(&refs);
5372 if (f1 && fclose(f1) == EOF && error == NULL)
5373 error = got_error_from_errno("fclose");
5374 if (f2 && fclose(f2) == EOF && error == NULL)
5375 error = got_error_from_errno("fclose");
5376 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5377 error = got_error_from_errno("close");
5378 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5379 error = got_error_from_errno("close");
5380 return error;
5383 __dead static void
5384 usage_blame(void)
5386 fprintf(stderr,
5387 "usage: %s blame [-c commit] [-r repository-path] path\n",
5388 getprogname());
5389 exit(1);
5392 struct blame_line {
5393 int annotated;
5394 char *id_str;
5395 char *committer;
5396 char datebuf[11]; /* YYYY-MM-DD + NUL */
5399 struct blame_cb_args {
5400 struct blame_line *lines;
5401 int nlines;
5402 int nlines_prec;
5403 int lineno_cur;
5404 off_t *line_offsets;
5405 FILE *f;
5406 struct got_repository *repo;
5409 static const struct got_error *
5410 blame_cb(void *arg, int nlines, int lineno,
5411 struct got_commit_object *commit, struct got_object_id *id)
5413 const struct got_error *err = NULL;
5414 struct blame_cb_args *a = arg;
5415 struct blame_line *bline;
5416 char *line = NULL;
5417 size_t linesize = 0;
5418 off_t offset;
5419 struct tm tm;
5420 time_t committer_time;
5422 if (nlines != a->nlines ||
5423 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5424 return got_error(GOT_ERR_RANGE);
5426 if (sigint_received)
5427 return got_error(GOT_ERR_ITER_COMPLETED);
5429 if (lineno == -1)
5430 return NULL; /* no change in this commit */
5432 /* Annotate this line. */
5433 bline = &a->lines[lineno - 1];
5434 if (bline->annotated)
5435 return NULL;
5436 err = got_object_id_str(&bline->id_str, id);
5437 if (err)
5438 return err;
5440 bline->committer = strdup(got_object_commit_get_committer(commit));
5441 if (bline->committer == NULL) {
5442 err = got_error_from_errno("strdup");
5443 goto done;
5446 committer_time = got_object_commit_get_committer_time(commit);
5447 if (gmtime_r(&committer_time, &tm) == NULL)
5448 return got_error_from_errno("gmtime_r");
5449 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5450 &tm) == 0) {
5451 err = got_error(GOT_ERR_NO_SPACE);
5452 goto done;
5454 bline->annotated = 1;
5456 /* Print lines annotated so far. */
5457 bline = &a->lines[a->lineno_cur - 1];
5458 if (!bline->annotated)
5459 goto done;
5461 offset = a->line_offsets[a->lineno_cur - 1];
5462 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5463 err = got_error_from_errno("fseeko");
5464 goto done;
5467 while (a->lineno_cur <= a->nlines && bline->annotated) {
5468 char *smallerthan, *at, *nl, *committer;
5469 size_t len;
5471 if (getline(&line, &linesize, a->f) == -1) {
5472 if (ferror(a->f))
5473 err = got_error_from_errno("getline");
5474 break;
5477 committer = bline->committer;
5478 smallerthan = strchr(committer, '<');
5479 if (smallerthan && smallerthan[1] != '\0')
5480 committer = smallerthan + 1;
5481 at = strchr(committer, '@');
5482 if (at)
5483 *at = '\0';
5484 len = strlen(committer);
5485 if (len >= 9)
5486 committer[8] = '\0';
5488 nl = strchr(line, '\n');
5489 if (nl)
5490 *nl = '\0';
5491 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5492 bline->id_str, bline->datebuf, committer, line);
5494 a->lineno_cur++;
5495 bline = &a->lines[a->lineno_cur - 1];
5497 done:
5498 free(line);
5499 return err;
5502 static const struct got_error *
5503 cmd_blame(int argc, char *argv[])
5505 const struct got_error *error;
5506 struct got_repository *repo = NULL;
5507 struct got_worktree *worktree = NULL;
5508 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5509 char *link_target = NULL;
5510 struct got_object_id *obj_id = NULL;
5511 struct got_object_id *commit_id = NULL;
5512 struct got_commit_object *commit = NULL;
5513 struct got_blob_object *blob = NULL;
5514 char *commit_id_str = NULL;
5515 struct blame_cb_args bca;
5516 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5517 off_t filesize;
5518 int *pack_fds = NULL;
5519 FILE *f1 = NULL, *f2 = NULL;
5521 fd1 = got_opentempfd();
5522 if (fd1 == -1)
5523 return got_error_from_errno("got_opentempfd");
5525 memset(&bca, 0, sizeof(bca));
5527 #ifndef PROFILE
5528 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5529 NULL) == -1)
5530 err(1, "pledge");
5531 #endif
5533 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5534 switch (ch) {
5535 case 'c':
5536 commit_id_str = optarg;
5537 break;
5538 case 'r':
5539 repo_path = realpath(optarg, NULL);
5540 if (repo_path == NULL)
5541 return got_error_from_errno2("realpath",
5542 optarg);
5543 got_path_strip_trailing_slashes(repo_path);
5544 break;
5545 default:
5546 usage_blame();
5547 /* NOTREACHED */
5551 argc -= optind;
5552 argv += optind;
5554 if (argc == 1)
5555 path = argv[0];
5556 else
5557 usage_blame();
5559 cwd = getcwd(NULL, 0);
5560 if (cwd == NULL) {
5561 error = got_error_from_errno("getcwd");
5562 goto done;
5565 error = got_repo_pack_fds_open(&pack_fds);
5566 if (error != NULL)
5567 goto done;
5569 if (repo_path == NULL) {
5570 error = got_worktree_open(&worktree, cwd);
5571 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5572 goto done;
5573 else
5574 error = NULL;
5575 if (worktree) {
5576 repo_path =
5577 strdup(got_worktree_get_repo_path(worktree));
5578 if (repo_path == NULL) {
5579 error = got_error_from_errno("strdup");
5580 if (error)
5581 goto done;
5583 } else {
5584 repo_path = strdup(cwd);
5585 if (repo_path == NULL) {
5586 error = got_error_from_errno("strdup");
5587 goto done;
5592 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5593 if (error != NULL)
5594 goto done;
5596 if (worktree) {
5597 const char *prefix = got_worktree_get_path_prefix(worktree);
5598 char *p;
5600 error = got_worktree_resolve_path(&p, worktree, path);
5601 if (error)
5602 goto done;
5603 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5604 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5605 p) == -1) {
5606 error = got_error_from_errno("asprintf");
5607 free(p);
5608 goto done;
5610 free(p);
5611 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5612 } else {
5613 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5614 if (error)
5615 goto done;
5616 error = got_repo_map_path(&in_repo_path, repo, path);
5618 if (error)
5619 goto done;
5621 if (commit_id_str == NULL) {
5622 struct got_reference *head_ref;
5623 error = got_ref_open(&head_ref, repo, worktree ?
5624 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5625 if (error != NULL)
5626 goto done;
5627 error = got_ref_resolve(&commit_id, repo, head_ref);
5628 got_ref_close(head_ref);
5629 if (error != NULL)
5630 goto done;
5631 } else {
5632 struct got_reflist_head refs;
5633 TAILQ_INIT(&refs);
5634 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5635 NULL);
5636 if (error)
5637 goto done;
5638 error = got_repo_match_object_id(&commit_id, NULL,
5639 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5640 got_ref_list_free(&refs);
5641 if (error)
5642 goto done;
5645 if (worktree) {
5646 /* Release work tree lock. */
5647 got_worktree_close(worktree);
5648 worktree = NULL;
5651 error = got_object_open_as_commit(&commit, repo, commit_id);
5652 if (error)
5653 goto done;
5655 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5656 commit, repo);
5657 if (error)
5658 goto done;
5660 error = got_object_id_by_path(&obj_id, repo, commit,
5661 link_target ? link_target : in_repo_path);
5662 if (error)
5663 goto done;
5665 error = got_object_get_type(&obj_type, repo, obj_id);
5666 if (error)
5667 goto done;
5669 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5670 error = got_error_path(link_target ? link_target : in_repo_path,
5671 GOT_ERR_OBJ_TYPE);
5672 goto done;
5675 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5676 if (error)
5677 goto done;
5678 bca.f = got_opentemp();
5679 if (bca.f == NULL) {
5680 error = got_error_from_errno("got_opentemp");
5681 goto done;
5683 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5684 &bca.line_offsets, bca.f, blob);
5685 if (error || bca.nlines == 0)
5686 goto done;
5688 /* Don't include \n at EOF in the blame line count. */
5689 if (bca.line_offsets[bca.nlines - 1] == filesize)
5690 bca.nlines--;
5692 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5693 if (bca.lines == NULL) {
5694 error = got_error_from_errno("calloc");
5695 goto done;
5697 bca.lineno_cur = 1;
5698 bca.nlines_prec = 0;
5699 i = bca.nlines;
5700 while (i > 0) {
5701 i /= 10;
5702 bca.nlines_prec++;
5704 bca.repo = repo;
5706 fd2 = got_opentempfd();
5707 if (fd2 == -1) {
5708 error = got_error_from_errno("got_opentempfd");
5709 goto done;
5711 fd3 = got_opentempfd();
5712 if (fd3 == -1) {
5713 error = got_error_from_errno("got_opentempfd");
5714 goto done;
5716 f1 = got_opentemp();
5717 if (f1 == NULL) {
5718 error = got_error_from_errno("got_opentemp");
5719 goto done;
5721 f2 = got_opentemp();
5722 if (f2 == NULL) {
5723 error = got_error_from_errno("got_opentemp");
5724 goto done;
5726 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5727 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5728 check_cancelled, NULL, fd2, fd3, f1, f2);
5729 done:
5730 free(in_repo_path);
5731 free(link_target);
5732 free(repo_path);
5733 free(cwd);
5734 free(commit_id);
5735 free(obj_id);
5736 if (commit)
5737 got_object_commit_close(commit);
5739 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5740 error = got_error_from_errno("close");
5741 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5742 error = got_error_from_errno("close");
5743 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5744 error = got_error_from_errno("close");
5745 if (f1 && fclose(f1) == EOF && error == NULL)
5746 error = got_error_from_errno("fclose");
5747 if (f2 && fclose(f2) == EOF && error == NULL)
5748 error = got_error_from_errno("fclose");
5750 if (blob)
5751 got_object_blob_close(blob);
5752 if (worktree)
5753 got_worktree_close(worktree);
5754 if (repo) {
5755 const struct got_error *close_err = got_repo_close(repo);
5756 if (error == NULL)
5757 error = close_err;
5759 if (pack_fds) {
5760 const struct got_error *pack_err =
5761 got_repo_pack_fds_close(pack_fds);
5762 if (error == NULL)
5763 error = pack_err;
5765 if (bca.lines) {
5766 for (i = 0; i < bca.nlines; i++) {
5767 struct blame_line *bline = &bca.lines[i];
5768 free(bline->id_str);
5769 free(bline->committer);
5771 free(bca.lines);
5773 free(bca.line_offsets);
5774 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5775 error = got_error_from_errno("fclose");
5776 return error;
5779 __dead static void
5780 usage_tree(void)
5782 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5783 "[path]\n", getprogname());
5784 exit(1);
5787 static const struct got_error *
5788 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5789 const char *root_path, struct got_repository *repo)
5791 const struct got_error *err = NULL;
5792 int is_root_path = (strcmp(path, root_path) == 0);
5793 const char *modestr = "";
5794 mode_t mode = got_tree_entry_get_mode(te);
5795 char *link_target = NULL;
5797 path += strlen(root_path);
5798 while (path[0] == '/')
5799 path++;
5801 if (got_object_tree_entry_is_submodule(te))
5802 modestr = "$";
5803 else if (S_ISLNK(mode)) {
5804 int i;
5806 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5807 if (err)
5808 return err;
5809 for (i = 0; i < strlen(link_target); i++) {
5810 if (!isprint((unsigned char)link_target[i]))
5811 link_target[i] = '?';
5814 modestr = "@";
5816 else if (S_ISDIR(mode))
5817 modestr = "/";
5818 else if (mode & S_IXUSR)
5819 modestr = "*";
5821 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5822 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5823 link_target ? " -> ": "", link_target ? link_target : "");
5825 free(link_target);
5826 return NULL;
5829 static const struct got_error *
5830 print_tree(const char *path, struct got_commit_object *commit,
5831 int show_ids, int recurse, const char *root_path,
5832 struct got_repository *repo)
5834 const struct got_error *err = NULL;
5835 struct got_object_id *tree_id = NULL;
5836 struct got_tree_object *tree = NULL;
5837 int nentries, i;
5839 err = got_object_id_by_path(&tree_id, repo, commit, path);
5840 if (err)
5841 goto done;
5843 err = got_object_open_as_tree(&tree, repo, tree_id);
5844 if (err)
5845 goto done;
5846 nentries = got_object_tree_get_nentries(tree);
5847 for (i = 0; i < nentries; i++) {
5848 struct got_tree_entry *te;
5849 char *id = NULL;
5851 if (sigint_received || sigpipe_received)
5852 break;
5854 te = got_object_tree_get_entry(tree, i);
5855 if (show_ids) {
5856 char *id_str;
5857 err = got_object_id_str(&id_str,
5858 got_tree_entry_get_id(te));
5859 if (err)
5860 goto done;
5861 if (asprintf(&id, "%s ", id_str) == -1) {
5862 err = got_error_from_errno("asprintf");
5863 free(id_str);
5864 goto done;
5866 free(id_str);
5868 err = print_entry(te, id, path, root_path, repo);
5869 free(id);
5870 if (err)
5871 goto done;
5873 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5874 char *child_path;
5875 if (asprintf(&child_path, "%s%s%s", path,
5876 path[0] == '/' && path[1] == '\0' ? "" : "/",
5877 got_tree_entry_get_name(te)) == -1) {
5878 err = got_error_from_errno("asprintf");
5879 goto done;
5881 err = print_tree(child_path, commit, show_ids, 1,
5882 root_path, repo);
5883 free(child_path);
5884 if (err)
5885 goto done;
5888 done:
5889 if (tree)
5890 got_object_tree_close(tree);
5891 free(tree_id);
5892 return err;
5895 static const struct got_error *
5896 cmd_tree(int argc, char *argv[])
5898 const struct got_error *error;
5899 struct got_repository *repo = NULL;
5900 struct got_worktree *worktree = NULL;
5901 const char *path, *refname = NULL;
5902 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5903 struct got_object_id *commit_id = NULL;
5904 struct got_commit_object *commit = NULL;
5905 char *commit_id_str = NULL;
5906 int show_ids = 0, recurse = 0;
5907 int ch;
5908 int *pack_fds = NULL;
5910 #ifndef PROFILE
5911 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5912 NULL) == -1)
5913 err(1, "pledge");
5914 #endif
5916 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5917 switch (ch) {
5918 case 'c':
5919 commit_id_str = optarg;
5920 break;
5921 case 'i':
5922 show_ids = 1;
5923 break;
5924 case 'R':
5925 recurse = 1;
5926 break;
5927 case 'r':
5928 repo_path = realpath(optarg, NULL);
5929 if (repo_path == NULL)
5930 return got_error_from_errno2("realpath",
5931 optarg);
5932 got_path_strip_trailing_slashes(repo_path);
5933 break;
5934 default:
5935 usage_tree();
5936 /* NOTREACHED */
5940 argc -= optind;
5941 argv += optind;
5943 if (argc == 1)
5944 path = argv[0];
5945 else if (argc > 1)
5946 usage_tree();
5947 else
5948 path = NULL;
5950 cwd = getcwd(NULL, 0);
5951 if (cwd == NULL) {
5952 error = got_error_from_errno("getcwd");
5953 goto done;
5956 error = got_repo_pack_fds_open(&pack_fds);
5957 if (error != NULL)
5958 goto done;
5960 if (repo_path == NULL) {
5961 error = got_worktree_open(&worktree, cwd);
5962 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5963 goto done;
5964 else
5965 error = NULL;
5966 if (worktree) {
5967 repo_path =
5968 strdup(got_worktree_get_repo_path(worktree));
5969 if (repo_path == NULL)
5970 error = got_error_from_errno("strdup");
5971 if (error)
5972 goto done;
5973 } else {
5974 repo_path = strdup(cwd);
5975 if (repo_path == NULL) {
5976 error = got_error_from_errno("strdup");
5977 goto done;
5982 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5983 if (error != NULL)
5984 goto done;
5986 if (worktree) {
5987 const char *prefix = got_worktree_get_path_prefix(worktree);
5988 char *p;
5990 if (path == NULL)
5991 path = "";
5992 error = got_worktree_resolve_path(&p, worktree, path);
5993 if (error)
5994 goto done;
5995 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5996 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5997 p) == -1) {
5998 error = got_error_from_errno("asprintf");
5999 free(p);
6000 goto done;
6002 free(p);
6003 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6004 if (error)
6005 goto done;
6006 } else {
6007 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6008 if (error)
6009 goto done;
6010 if (path == NULL)
6011 path = "/";
6012 error = got_repo_map_path(&in_repo_path, repo, path);
6013 if (error != NULL)
6014 goto done;
6017 if (commit_id_str == NULL) {
6018 struct got_reference *head_ref;
6019 if (worktree)
6020 refname = got_worktree_get_head_ref_name(worktree);
6021 else
6022 refname = GOT_REF_HEAD;
6023 error = got_ref_open(&head_ref, repo, refname, 0);
6024 if (error != NULL)
6025 goto done;
6026 error = got_ref_resolve(&commit_id, repo, head_ref);
6027 got_ref_close(head_ref);
6028 if (error != NULL)
6029 goto done;
6030 } else {
6031 struct got_reflist_head refs;
6032 TAILQ_INIT(&refs);
6033 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6034 NULL);
6035 if (error)
6036 goto done;
6037 error = got_repo_match_object_id(&commit_id, NULL,
6038 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6039 got_ref_list_free(&refs);
6040 if (error)
6041 goto done;
6044 if (worktree) {
6045 /* Release work tree lock. */
6046 got_worktree_close(worktree);
6047 worktree = NULL;
6050 error = got_object_open_as_commit(&commit, repo, commit_id);
6051 if (error)
6052 goto done;
6054 error = print_tree(in_repo_path, commit, show_ids, recurse,
6055 in_repo_path, repo);
6056 done:
6057 free(in_repo_path);
6058 free(repo_path);
6059 free(cwd);
6060 free(commit_id);
6061 if (commit)
6062 got_object_commit_close(commit);
6063 if (worktree)
6064 got_worktree_close(worktree);
6065 if (repo) {
6066 const struct got_error *close_err = got_repo_close(repo);
6067 if (error == NULL)
6068 error = close_err;
6070 if (pack_fds) {
6071 const struct got_error *pack_err =
6072 got_repo_pack_fds_close(pack_fds);
6073 if (error == NULL)
6074 error = pack_err;
6076 return error;
6079 __dead static void
6080 usage_status(void)
6082 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6083 "[-s status-codes] [path ...]\n", getprogname());
6084 exit(1);
6087 struct got_status_arg {
6088 char *status_codes;
6089 int suppress;
6092 static const struct got_error *
6093 print_status(void *arg, unsigned char status, unsigned char staged_status,
6094 const char *path, struct got_object_id *blob_id,
6095 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6096 int dirfd, const char *de_name)
6098 struct got_status_arg *st = arg;
6100 if (status == staged_status && (status == GOT_STATUS_DELETE))
6101 status = GOT_STATUS_NO_CHANGE;
6102 if (st != NULL && st->status_codes) {
6103 size_t ncodes = strlen(st->status_codes);
6104 int i, j = 0;
6106 for (i = 0; i < ncodes ; i++) {
6107 if (st->suppress) {
6108 if (status == st->status_codes[i] ||
6109 staged_status == st->status_codes[i]) {
6110 j++;
6111 continue;
6113 } else {
6114 if (status == st->status_codes[i] ||
6115 staged_status == st->status_codes[i])
6116 break;
6120 if (st->suppress && j == 0)
6121 goto print;
6123 if (i == ncodes)
6124 return NULL;
6126 print:
6127 printf("%c%c %s\n", status, staged_status, path);
6128 return NULL;
6131 static const struct got_error *
6132 cmd_status(int argc, char *argv[])
6134 const struct got_error *error = NULL;
6135 struct got_repository *repo = NULL;
6136 struct got_worktree *worktree = NULL;
6137 struct got_status_arg st;
6138 char *cwd = NULL;
6139 struct got_pathlist_head paths;
6140 struct got_pathlist_entry *pe;
6141 int ch, i, no_ignores = 0;
6142 int *pack_fds = NULL;
6144 TAILQ_INIT(&paths);
6146 memset(&st, 0, sizeof(st));
6147 st.status_codes = NULL;
6148 st.suppress = 0;
6150 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6151 switch (ch) {
6152 case 'I':
6153 no_ignores = 1;
6154 break;
6155 case 'S':
6156 if (st.status_codes != NULL && st.suppress == 0)
6157 option_conflict('S', 's');
6158 st.suppress = 1;
6159 /* fallthrough */
6160 case 's':
6161 for (i = 0; i < strlen(optarg); i++) {
6162 switch (optarg[i]) {
6163 case GOT_STATUS_MODIFY:
6164 case GOT_STATUS_ADD:
6165 case GOT_STATUS_DELETE:
6166 case GOT_STATUS_CONFLICT:
6167 case GOT_STATUS_MISSING:
6168 case GOT_STATUS_OBSTRUCTED:
6169 case GOT_STATUS_UNVERSIONED:
6170 case GOT_STATUS_MODE_CHANGE:
6171 case GOT_STATUS_NONEXISTENT:
6172 break;
6173 default:
6174 errx(1, "invalid status code '%c'",
6175 optarg[i]);
6178 if (ch == 's' && st.suppress)
6179 option_conflict('s', 'S');
6180 st.status_codes = optarg;
6181 break;
6182 default:
6183 usage_status();
6184 /* NOTREACHED */
6188 argc -= optind;
6189 argv += optind;
6191 #ifndef PROFILE
6192 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6193 NULL) == -1)
6194 err(1, "pledge");
6195 #endif
6196 cwd = getcwd(NULL, 0);
6197 if (cwd == NULL) {
6198 error = got_error_from_errno("getcwd");
6199 goto done;
6202 error = got_repo_pack_fds_open(&pack_fds);
6203 if (error != NULL)
6204 goto done;
6206 error = got_worktree_open(&worktree, cwd);
6207 if (error) {
6208 if (error->code == GOT_ERR_NOT_WORKTREE)
6209 error = wrap_not_worktree_error(error, "status", cwd);
6210 goto done;
6213 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6214 NULL, pack_fds);
6215 if (error != NULL)
6216 goto done;
6218 error = apply_unveil(got_repo_get_path(repo), 1,
6219 got_worktree_get_root_path(worktree));
6220 if (error)
6221 goto done;
6223 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6224 if (error)
6225 goto done;
6227 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6228 print_status, &st, check_cancelled, NULL);
6229 done:
6230 if (pack_fds) {
6231 const struct got_error *pack_err =
6232 got_repo_pack_fds_close(pack_fds);
6233 if (error == NULL)
6234 error = pack_err;
6237 TAILQ_FOREACH(pe, &paths, entry)
6238 free((char *)pe->path);
6239 got_pathlist_free(&paths);
6240 free(cwd);
6241 return error;
6244 __dead static void
6245 usage_ref(void)
6247 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6248 "[-s reference] [name]\n", getprogname());
6249 exit(1);
6252 static const struct got_error *
6253 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6255 static const struct got_error *err = NULL;
6256 struct got_reflist_head refs;
6257 struct got_reflist_entry *re;
6259 TAILQ_INIT(&refs);
6260 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6261 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6262 repo);
6263 if (err)
6264 return err;
6266 TAILQ_FOREACH(re, &refs, entry) {
6267 char *refstr;
6268 refstr = got_ref_to_str(re->ref);
6269 if (refstr == NULL) {
6270 err = got_error_from_errno("got_ref_to_str");
6271 break;
6273 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6274 free(refstr);
6277 got_ref_list_free(&refs);
6278 return err;
6281 static const struct got_error *
6282 delete_ref_by_name(struct got_repository *repo, const char *refname)
6284 const struct got_error *err;
6285 struct got_reference *ref;
6287 err = got_ref_open(&ref, repo, refname, 0);
6288 if (err)
6289 return err;
6291 err = delete_ref(repo, ref);
6292 got_ref_close(ref);
6293 return err;
6296 static const struct got_error *
6297 add_ref(struct got_repository *repo, const char *refname, const char *target)
6299 const struct got_error *err = NULL;
6300 struct got_object_id *id = NULL;
6301 struct got_reference *ref = NULL;
6302 struct got_reflist_head refs;
6305 * Don't let the user create a reference name with a leading '-'.
6306 * While technically a valid reference name, this case is usually
6307 * an unintended typo.
6309 if (refname[0] == '-')
6310 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6312 TAILQ_INIT(&refs);
6313 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6314 if (err)
6315 goto done;
6316 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6317 &refs, repo);
6318 got_ref_list_free(&refs);
6319 if (err)
6320 goto done;
6322 err = got_ref_alloc(&ref, refname, id);
6323 if (err)
6324 goto done;
6326 err = got_ref_write(ref, repo);
6327 done:
6328 if (ref)
6329 got_ref_close(ref);
6330 free(id);
6331 return err;
6334 static const struct got_error *
6335 add_symref(struct got_repository *repo, const char *refname, const char *target)
6337 const struct got_error *err = NULL;
6338 struct got_reference *ref = NULL;
6339 struct got_reference *target_ref = NULL;
6342 * Don't let the user create a reference name with a leading '-'.
6343 * While technically a valid reference name, this case is usually
6344 * an unintended typo.
6346 if (refname[0] == '-')
6347 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6349 err = got_ref_open(&target_ref, repo, target, 0);
6350 if (err)
6351 return err;
6353 err = got_ref_alloc_symref(&ref, refname, target_ref);
6354 if (err)
6355 goto done;
6357 err = got_ref_write(ref, repo);
6358 done:
6359 if (target_ref)
6360 got_ref_close(target_ref);
6361 if (ref)
6362 got_ref_close(ref);
6363 return err;
6366 static const struct got_error *
6367 cmd_ref(int argc, char *argv[])
6369 const struct got_error *error = NULL;
6370 struct got_repository *repo = NULL;
6371 struct got_worktree *worktree = NULL;
6372 char *cwd = NULL, *repo_path = NULL;
6373 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6374 const char *obj_arg = NULL, *symref_target= NULL;
6375 char *refname = NULL;
6376 int *pack_fds = NULL;
6378 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6379 switch (ch) {
6380 case 'c':
6381 obj_arg = optarg;
6382 break;
6383 case 'd':
6384 do_delete = 1;
6385 break;
6386 case 'l':
6387 do_list = 1;
6388 break;
6389 case 'r':
6390 repo_path = realpath(optarg, NULL);
6391 if (repo_path == NULL)
6392 return got_error_from_errno2("realpath",
6393 optarg);
6394 got_path_strip_trailing_slashes(repo_path);
6395 break;
6396 case 's':
6397 symref_target = optarg;
6398 break;
6399 case 't':
6400 sort_by_time = 1;
6401 break;
6402 default:
6403 usage_ref();
6404 /* NOTREACHED */
6408 if (obj_arg && do_list)
6409 option_conflict('c', 'l');
6410 if (obj_arg && do_delete)
6411 option_conflict('c', 'd');
6412 if (obj_arg && symref_target)
6413 option_conflict('c', 's');
6414 if (symref_target && do_delete)
6415 option_conflict('s', 'd');
6416 if (symref_target && do_list)
6417 option_conflict('s', 'l');
6418 if (do_delete && do_list)
6419 option_conflict('d', 'l');
6420 if (sort_by_time && !do_list)
6421 errx(1, "-t option requires -l option");
6423 argc -= optind;
6424 argv += optind;
6426 if (do_list) {
6427 if (argc != 0 && argc != 1)
6428 usage_ref();
6429 if (argc == 1) {
6430 refname = strdup(argv[0]);
6431 if (refname == NULL) {
6432 error = got_error_from_errno("strdup");
6433 goto done;
6436 } else {
6437 if (argc != 1)
6438 usage_ref();
6439 refname = strdup(argv[0]);
6440 if (refname == NULL) {
6441 error = got_error_from_errno("strdup");
6442 goto done;
6446 if (refname)
6447 got_path_strip_trailing_slashes(refname);
6449 #ifndef PROFILE
6450 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6451 "sendfd unveil", NULL) == -1)
6452 err(1, "pledge");
6453 #endif
6454 cwd = getcwd(NULL, 0);
6455 if (cwd == NULL) {
6456 error = got_error_from_errno("getcwd");
6457 goto done;
6460 error = got_repo_pack_fds_open(&pack_fds);
6461 if (error != NULL)
6462 goto done;
6464 if (repo_path == NULL) {
6465 error = got_worktree_open(&worktree, cwd);
6466 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6467 goto done;
6468 else
6469 error = NULL;
6470 if (worktree) {
6471 repo_path =
6472 strdup(got_worktree_get_repo_path(worktree));
6473 if (repo_path == NULL)
6474 error = got_error_from_errno("strdup");
6475 if (error)
6476 goto done;
6477 } else {
6478 repo_path = strdup(cwd);
6479 if (repo_path == NULL) {
6480 error = got_error_from_errno("strdup");
6481 goto done;
6486 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6487 if (error != NULL)
6488 goto done;
6490 #ifndef PROFILE
6491 if (do_list) {
6492 /* Remove "cpath" promise. */
6493 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6494 NULL) == -1)
6495 err(1, "pledge");
6497 #endif
6499 error = apply_unveil(got_repo_get_path(repo), do_list,
6500 worktree ? got_worktree_get_root_path(worktree) : NULL);
6501 if (error)
6502 goto done;
6504 if (do_list)
6505 error = list_refs(repo, refname, sort_by_time);
6506 else if (do_delete)
6507 error = delete_ref_by_name(repo, refname);
6508 else if (symref_target)
6509 error = add_symref(repo, refname, symref_target);
6510 else {
6511 if (obj_arg == NULL)
6512 usage_ref();
6513 error = add_ref(repo, refname, obj_arg);
6515 done:
6516 free(refname);
6517 if (repo) {
6518 const struct got_error *close_err = got_repo_close(repo);
6519 if (error == NULL)
6520 error = close_err;
6522 if (worktree)
6523 got_worktree_close(worktree);
6524 if (pack_fds) {
6525 const struct got_error *pack_err =
6526 got_repo_pack_fds_close(pack_fds);
6527 if (error == NULL)
6528 error = pack_err;
6530 free(cwd);
6531 free(repo_path);
6532 return error;
6535 __dead static void
6536 usage_branch(void)
6538 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6539 "[-r repository-path] [name]\n", getprogname());
6540 exit(1);
6543 static const struct got_error *
6544 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6545 struct got_reference *ref)
6547 const struct got_error *err = NULL;
6548 const char *refname, *marker = " ";
6549 char *refstr;
6551 refname = got_ref_get_name(ref);
6552 if (worktree && strcmp(refname,
6553 got_worktree_get_head_ref_name(worktree)) == 0) {
6554 struct got_object_id *id = NULL;
6556 err = got_ref_resolve(&id, repo, ref);
6557 if (err)
6558 return err;
6559 if (got_object_id_cmp(id,
6560 got_worktree_get_base_commit_id(worktree)) == 0)
6561 marker = "* ";
6562 else
6563 marker = "~ ";
6564 free(id);
6567 if (strncmp(refname, "refs/heads/", 11) == 0)
6568 refname += 11;
6569 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6570 refname += 18;
6571 if (strncmp(refname, "refs/remotes/", 13) == 0)
6572 refname += 13;
6574 refstr = got_ref_to_str(ref);
6575 if (refstr == NULL)
6576 return got_error_from_errno("got_ref_to_str");
6578 printf("%s%s: %s\n", marker, refname, refstr);
6579 free(refstr);
6580 return NULL;
6583 static const struct got_error *
6584 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6586 const char *refname;
6588 if (worktree == NULL)
6589 return got_error(GOT_ERR_NOT_WORKTREE);
6591 refname = got_worktree_get_head_ref_name(worktree);
6593 if (strncmp(refname, "refs/heads/", 11) == 0)
6594 refname += 11;
6595 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6596 refname += 18;
6598 printf("%s\n", refname);
6600 return NULL;
6603 static const struct got_error *
6604 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6605 int sort_by_time)
6607 static const struct got_error *err = NULL;
6608 struct got_reflist_head refs;
6609 struct got_reflist_entry *re;
6610 struct got_reference *temp_ref = NULL;
6611 int rebase_in_progress, histedit_in_progress;
6613 TAILQ_INIT(&refs);
6615 if (worktree) {
6616 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6617 worktree);
6618 if (err)
6619 return err;
6621 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6622 worktree);
6623 if (err)
6624 return err;
6626 if (rebase_in_progress || histedit_in_progress) {
6627 err = got_ref_open(&temp_ref, repo,
6628 got_worktree_get_head_ref_name(worktree), 0);
6629 if (err)
6630 return err;
6631 list_branch(repo, worktree, temp_ref);
6632 got_ref_close(temp_ref);
6636 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6637 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6638 repo);
6639 if (err)
6640 return err;
6642 TAILQ_FOREACH(re, &refs, entry)
6643 list_branch(repo, worktree, re->ref);
6645 got_ref_list_free(&refs);
6647 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6648 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6649 repo);
6650 if (err)
6651 return err;
6653 TAILQ_FOREACH(re, &refs, entry)
6654 list_branch(repo, worktree, re->ref);
6656 got_ref_list_free(&refs);
6658 return NULL;
6661 static const struct got_error *
6662 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6663 const char *branch_name)
6665 const struct got_error *err = NULL;
6666 struct got_reference *ref = NULL;
6667 char *refname, *remote_refname = NULL;
6669 if (strncmp(branch_name, "refs/", 5) == 0)
6670 branch_name += 5;
6671 if (strncmp(branch_name, "heads/", 6) == 0)
6672 branch_name += 6;
6673 else if (strncmp(branch_name, "remotes/", 8) == 0)
6674 branch_name += 8;
6676 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6677 return got_error_from_errno("asprintf");
6679 if (asprintf(&remote_refname, "refs/remotes/%s",
6680 branch_name) == -1) {
6681 err = got_error_from_errno("asprintf");
6682 goto done;
6685 err = got_ref_open(&ref, repo, refname, 0);
6686 if (err) {
6687 const struct got_error *err2;
6688 if (err->code != GOT_ERR_NOT_REF)
6689 goto done;
6691 * Keep 'err' intact such that if neither branch exists
6692 * we report "refs/heads" rather than "refs/remotes" in
6693 * our error message.
6695 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6696 if (err2)
6697 goto done;
6698 err = NULL;
6701 if (worktree &&
6702 strcmp(got_worktree_get_head_ref_name(worktree),
6703 got_ref_get_name(ref)) == 0) {
6704 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6705 "will not delete this work tree's current branch");
6706 goto done;
6709 err = delete_ref(repo, ref);
6710 done:
6711 if (ref)
6712 got_ref_close(ref);
6713 free(refname);
6714 free(remote_refname);
6715 return err;
6718 static const struct got_error *
6719 add_branch(struct got_repository *repo, const char *branch_name,
6720 struct got_object_id *base_commit_id)
6722 const struct got_error *err = NULL;
6723 struct got_reference *ref = NULL;
6724 char *base_refname = NULL, *refname = NULL;
6727 * Don't let the user create a branch name with a leading '-'.
6728 * While technically a valid reference name, this case is usually
6729 * an unintended typo.
6731 if (branch_name[0] == '-')
6732 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6734 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6735 branch_name += 11;
6737 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6738 err = got_error_from_errno("asprintf");
6739 goto done;
6742 err = got_ref_open(&ref, repo, refname, 0);
6743 if (err == NULL) {
6744 err = got_error(GOT_ERR_BRANCH_EXISTS);
6745 goto done;
6746 } else if (err->code != GOT_ERR_NOT_REF)
6747 goto done;
6749 err = got_ref_alloc(&ref, refname, base_commit_id);
6750 if (err)
6751 goto done;
6753 err = got_ref_write(ref, repo);
6754 done:
6755 if (ref)
6756 got_ref_close(ref);
6757 free(base_refname);
6758 free(refname);
6759 return err;
6762 static const struct got_error *
6763 cmd_branch(int argc, char *argv[])
6765 const struct got_error *error = NULL;
6766 struct got_repository *repo = NULL;
6767 struct got_worktree *worktree = NULL;
6768 char *cwd = NULL, *repo_path = NULL;
6769 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6770 const char *delref = NULL, *commit_id_arg = NULL;
6771 struct got_reference *ref = NULL;
6772 struct got_pathlist_head paths;
6773 struct got_pathlist_entry *pe;
6774 struct got_object_id *commit_id = NULL;
6775 char *commit_id_str = NULL;
6776 int *pack_fds = NULL;
6778 TAILQ_INIT(&paths);
6780 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6781 switch (ch) {
6782 case 'c':
6783 commit_id_arg = optarg;
6784 break;
6785 case 'd':
6786 delref = optarg;
6787 break;
6788 case 'l':
6789 do_list = 1;
6790 break;
6791 case 'n':
6792 do_update = 0;
6793 break;
6794 case 'r':
6795 repo_path = realpath(optarg, NULL);
6796 if (repo_path == NULL)
6797 return got_error_from_errno2("realpath",
6798 optarg);
6799 got_path_strip_trailing_slashes(repo_path);
6800 break;
6801 case 't':
6802 sort_by_time = 1;
6803 break;
6804 default:
6805 usage_branch();
6806 /* NOTREACHED */
6810 if (do_list && delref)
6811 option_conflict('l', 'd');
6812 if (sort_by_time && !do_list)
6813 errx(1, "-t option requires -l option");
6815 argc -= optind;
6816 argv += optind;
6818 if (!do_list && !delref && argc == 0)
6819 do_show = 1;
6821 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6822 errx(1, "-c option can only be used when creating a branch");
6824 if (do_list || delref) {
6825 if (argc > 0)
6826 usage_branch();
6827 } else if (!do_show && argc != 1)
6828 usage_branch();
6830 #ifndef PROFILE
6831 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6832 "sendfd unveil", NULL) == -1)
6833 err(1, "pledge");
6834 #endif
6835 cwd = getcwd(NULL, 0);
6836 if (cwd == NULL) {
6837 error = got_error_from_errno("getcwd");
6838 goto done;
6841 error = got_repo_pack_fds_open(&pack_fds);
6842 if (error != NULL)
6843 goto done;
6845 if (repo_path == NULL) {
6846 error = got_worktree_open(&worktree, cwd);
6847 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6848 goto done;
6849 else
6850 error = NULL;
6851 if (worktree) {
6852 repo_path =
6853 strdup(got_worktree_get_repo_path(worktree));
6854 if (repo_path == NULL)
6855 error = got_error_from_errno("strdup");
6856 if (error)
6857 goto done;
6858 } else {
6859 repo_path = strdup(cwd);
6860 if (repo_path == NULL) {
6861 error = got_error_from_errno("strdup");
6862 goto done;
6867 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6868 if (error != NULL)
6869 goto done;
6871 #ifndef PROFILE
6872 if (do_list || do_show) {
6873 /* Remove "cpath" promise. */
6874 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6875 NULL) == -1)
6876 err(1, "pledge");
6878 #endif
6880 error = apply_unveil(got_repo_get_path(repo), do_list,
6881 worktree ? got_worktree_get_root_path(worktree) : NULL);
6882 if (error)
6883 goto done;
6885 if (do_show)
6886 error = show_current_branch(repo, worktree);
6887 else if (do_list)
6888 error = list_branches(repo, worktree, sort_by_time);
6889 else if (delref)
6890 error = delete_branch(repo, worktree, delref);
6891 else {
6892 struct got_reflist_head refs;
6893 TAILQ_INIT(&refs);
6894 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6895 NULL);
6896 if (error)
6897 goto done;
6898 if (commit_id_arg == NULL)
6899 commit_id_arg = worktree ?
6900 got_worktree_get_head_ref_name(worktree) :
6901 GOT_REF_HEAD;
6902 error = got_repo_match_object_id(&commit_id, NULL,
6903 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6904 got_ref_list_free(&refs);
6905 if (error)
6906 goto done;
6907 error = add_branch(repo, argv[0], commit_id);
6908 if (error)
6909 goto done;
6910 if (worktree && do_update) {
6911 struct got_update_progress_arg upa;
6912 char *branch_refname = NULL;
6914 error = got_object_id_str(&commit_id_str, commit_id);
6915 if (error)
6916 goto done;
6917 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6918 worktree);
6919 if (error)
6920 goto done;
6921 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6922 == -1) {
6923 error = got_error_from_errno("asprintf");
6924 goto done;
6926 error = got_ref_open(&ref, repo, branch_refname, 0);
6927 free(branch_refname);
6928 if (error)
6929 goto done;
6930 error = switch_head_ref(ref, commit_id, worktree,
6931 repo);
6932 if (error)
6933 goto done;
6934 error = got_worktree_set_base_commit_id(worktree, repo,
6935 commit_id);
6936 if (error)
6937 goto done;
6938 memset(&upa, 0, sizeof(upa));
6939 error = got_worktree_checkout_files(worktree, &paths,
6940 repo, update_progress, &upa, check_cancelled,
6941 NULL);
6942 if (error)
6943 goto done;
6944 if (upa.did_something) {
6945 printf("Updated to %s: %s\n",
6946 got_worktree_get_head_ref_name(worktree),
6947 commit_id_str);
6949 print_update_progress_stats(&upa);
6952 done:
6953 if (ref)
6954 got_ref_close(ref);
6955 if (repo) {
6956 const struct got_error *close_err = got_repo_close(repo);
6957 if (error == NULL)
6958 error = close_err;
6960 if (worktree)
6961 got_worktree_close(worktree);
6962 if (pack_fds) {
6963 const struct got_error *pack_err =
6964 got_repo_pack_fds_close(pack_fds);
6965 if (error == NULL)
6966 error = pack_err;
6968 free(cwd);
6969 free(repo_path);
6970 free(commit_id);
6971 free(commit_id_str);
6972 TAILQ_FOREACH(pe, &paths, entry)
6973 free((char *)pe->path);
6974 got_pathlist_free(&paths);
6975 return error;
6979 __dead static void
6980 usage_tag(void)
6982 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6983 "[-r repository-path] [-s signer-id] name\n", getprogname());
6984 exit(1);
6987 #if 0
6988 static const struct got_error *
6989 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6991 const struct got_error *err = NULL;
6992 struct got_reflist_entry *re, *se, *new;
6993 struct got_object_id *re_id, *se_id;
6994 struct got_tag_object *re_tag, *se_tag;
6995 time_t re_time, se_time;
6997 STAILQ_FOREACH(re, tags, entry) {
6998 se = STAILQ_FIRST(sorted);
6999 if (se == NULL) {
7000 err = got_reflist_entry_dup(&new, re);
7001 if (err)
7002 return err;
7003 STAILQ_INSERT_HEAD(sorted, new, entry);
7004 continue;
7005 } else {
7006 err = got_ref_resolve(&re_id, repo, re->ref);
7007 if (err)
7008 break;
7009 err = got_object_open_as_tag(&re_tag, repo, re_id);
7010 free(re_id);
7011 if (err)
7012 break;
7013 re_time = got_object_tag_get_tagger_time(re_tag);
7014 got_object_tag_close(re_tag);
7017 while (se) {
7018 err = got_ref_resolve(&se_id, repo, re->ref);
7019 if (err)
7020 break;
7021 err = got_object_open_as_tag(&se_tag, repo, se_id);
7022 free(se_id);
7023 if (err)
7024 break;
7025 se_time = got_object_tag_get_tagger_time(se_tag);
7026 got_object_tag_close(se_tag);
7028 if (se_time > re_time) {
7029 err = got_reflist_entry_dup(&new, re);
7030 if (err)
7031 return err;
7032 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7033 break;
7035 se = STAILQ_NEXT(se, entry);
7036 continue;
7039 done:
7040 return err;
7042 #endif
7044 static const struct got_error *
7045 get_tag_refname(char **refname, const char *tag_name)
7047 const struct got_error *err;
7049 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7050 *refname = strdup(tag_name);
7051 if (*refname == NULL)
7052 return got_error_from_errno("strdup");
7053 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7054 err = got_error_from_errno("asprintf");
7055 *refname = NULL;
7056 return err;
7059 return NULL;
7062 static const struct got_error *
7063 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7064 const char *allowed_signers, const char *revoked_signers, int verbosity)
7066 static const struct got_error *err = NULL;
7067 struct got_reflist_head refs;
7068 struct got_reflist_entry *re;
7069 char *wanted_refname = NULL;
7070 int bad_sigs = 0;
7072 TAILQ_INIT(&refs);
7074 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7075 if (err)
7076 return err;
7078 if (tag_name) {
7079 struct got_reference *ref;
7080 err = get_tag_refname(&wanted_refname, tag_name);
7081 if (err)
7082 goto done;
7083 /* Wanted tag reference should exist. */
7084 err = got_ref_open(&ref, repo, wanted_refname, 0);
7085 if (err)
7086 goto done;
7087 got_ref_close(ref);
7090 TAILQ_FOREACH(re, &refs, entry) {
7091 const char *refname;
7092 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7093 char datebuf[26];
7094 const char *tagger, *ssh_sig = NULL;
7095 char *sig_msg = NULL;
7096 time_t tagger_time;
7097 struct got_object_id *id;
7098 struct got_tag_object *tag;
7099 struct got_commit_object *commit = NULL;
7101 refname = got_ref_get_name(re->ref);
7102 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7103 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7104 continue;
7105 refname += 10;
7106 refstr = got_ref_to_str(re->ref);
7107 if (refstr == NULL) {
7108 err = got_error_from_errno("got_ref_to_str");
7109 break;
7112 err = got_ref_resolve(&id, repo, re->ref);
7113 if (err)
7114 break;
7115 err = got_object_open_as_tag(&tag, repo, id);
7116 if (err) {
7117 if (err->code != GOT_ERR_OBJ_TYPE) {
7118 free(id);
7119 break;
7121 /* "lightweight" tag */
7122 err = got_object_open_as_commit(&commit, repo, id);
7123 if (err) {
7124 free(id);
7125 break;
7127 tagger = got_object_commit_get_committer(commit);
7128 tagger_time =
7129 got_object_commit_get_committer_time(commit);
7130 err = got_object_id_str(&id_str, id);
7131 free(id);
7132 if (err)
7133 break;
7134 } else {
7135 free(id);
7136 tagger = got_object_tag_get_tagger(tag);
7137 tagger_time = got_object_tag_get_tagger_time(tag);
7138 err = got_object_id_str(&id_str,
7139 got_object_tag_get_object_id(tag));
7140 if (err)
7141 break;
7144 if (tag && verify_tags) {
7145 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7146 got_object_tag_get_message(tag));
7147 if (ssh_sig && allowed_signers == NULL) {
7148 err = got_error_msg(
7149 GOT_ERR_VERIFY_TAG_SIGNATURE,
7150 "SSH signature verification requires "
7151 "setting allowed_signers in "
7152 "got.conf(5)");
7153 break;
7157 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7158 free(refstr);
7159 printf("from: %s\n", tagger);
7160 datestr = get_datestr(&tagger_time, datebuf);
7161 if (datestr)
7162 printf("date: %s UTC\n", datestr);
7163 if (commit)
7164 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7165 else {
7166 switch (got_object_tag_get_object_type(tag)) {
7167 case GOT_OBJ_TYPE_BLOB:
7168 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7169 id_str);
7170 break;
7171 case GOT_OBJ_TYPE_TREE:
7172 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7173 id_str);
7174 break;
7175 case GOT_OBJ_TYPE_COMMIT:
7176 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7177 id_str);
7178 break;
7179 case GOT_OBJ_TYPE_TAG:
7180 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7181 id_str);
7182 break;
7183 default:
7184 break;
7187 free(id_str);
7189 if (ssh_sig) {
7190 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7191 allowed_signers, revoked_signers, verbosity);
7192 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7193 bad_sigs = 1;
7194 else if (err)
7195 break;
7196 printf("signature: %s", sig_msg);
7197 free(sig_msg);
7198 sig_msg = NULL;
7201 if (commit) {
7202 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7203 if (err)
7204 break;
7205 got_object_commit_close(commit);
7206 } else {
7207 tagmsg0 = strdup(got_object_tag_get_message(tag));
7208 got_object_tag_close(tag);
7209 if (tagmsg0 == NULL) {
7210 err = got_error_from_errno("strdup");
7211 break;
7215 tagmsg = tagmsg0;
7216 do {
7217 line = strsep(&tagmsg, "\n");
7218 if (line)
7219 printf(" %s\n", line);
7220 } while (line);
7221 free(tagmsg0);
7223 done:
7224 got_ref_list_free(&refs);
7225 free(wanted_refname);
7227 if (err == NULL && bad_sigs)
7228 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7229 return err;
7232 static const struct got_error *
7233 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7234 const char *tag_name, const char *repo_path)
7236 const struct got_error *err = NULL;
7237 char *template = NULL, *initial_content = NULL;
7238 char *editor = NULL;
7239 int initial_content_len;
7240 int fd = -1;
7242 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7243 err = got_error_from_errno("asprintf");
7244 goto done;
7247 initial_content_len = asprintf(&initial_content,
7248 "\n# tagging commit %s as %s\n",
7249 commit_id_str, tag_name);
7250 if (initial_content_len == -1) {
7251 err = got_error_from_errno("asprintf");
7252 goto done;
7255 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7256 if (err)
7257 goto done;
7259 if (write(fd, initial_content, initial_content_len) == -1) {
7260 err = got_error_from_errno2("write", *tagmsg_path);
7261 goto done;
7264 err = get_editor(&editor);
7265 if (err)
7266 goto done;
7267 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7268 initial_content_len, 1);
7269 done:
7270 free(initial_content);
7271 free(template);
7272 free(editor);
7274 if (fd != -1 && close(fd) == -1 && err == NULL)
7275 err = got_error_from_errno2("close", *tagmsg_path);
7277 if (err) {
7278 free(*tagmsg);
7279 *tagmsg = NULL;
7281 return err;
7284 static const struct got_error *
7285 add_tag(struct got_repository *repo, const char *tagger,
7286 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7287 const char *signer_id, int verbosity)
7289 const struct got_error *err = NULL;
7290 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7291 char *label = NULL, *commit_id_str = NULL;
7292 struct got_reference *ref = NULL;
7293 char *refname = NULL, *tagmsg = NULL;
7294 char *tagmsg_path = NULL, *tag_id_str = NULL;
7295 int preserve_tagmsg = 0;
7296 struct got_reflist_head refs;
7298 TAILQ_INIT(&refs);
7301 * Don't let the user create a tag name with a leading '-'.
7302 * While technically a valid reference name, this case is usually
7303 * an unintended typo.
7305 if (tag_name[0] == '-')
7306 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7308 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7309 if (err)
7310 goto done;
7312 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7313 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7314 if (err)
7315 goto done;
7317 err = got_object_id_str(&commit_id_str, commit_id);
7318 if (err)
7319 goto done;
7321 err = get_tag_refname(&refname, tag_name);
7322 if (err)
7323 goto done;
7324 if (strncmp("refs/tags/", tag_name, 10) == 0)
7325 tag_name += 10;
7327 err = got_ref_open(&ref, repo, refname, 0);
7328 if (err == NULL) {
7329 err = got_error(GOT_ERR_TAG_EXISTS);
7330 goto done;
7331 } else if (err->code != GOT_ERR_NOT_REF)
7332 goto done;
7334 if (tagmsg_arg == NULL) {
7335 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7336 tag_name, got_repo_get_path(repo));
7337 if (err) {
7338 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7339 tagmsg_path != NULL)
7340 preserve_tagmsg = 1;
7341 goto done;
7343 /* Editor is done; we can now apply unveil(2) */
7344 err = got_sigs_apply_unveil();
7345 if (err)
7346 goto done;
7347 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7348 if (err)
7349 goto done;
7352 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7353 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7354 verbosity);
7355 if (err) {
7356 if (tagmsg_path)
7357 preserve_tagmsg = 1;
7358 goto done;
7361 err = got_ref_alloc(&ref, refname, tag_id);
7362 if (err) {
7363 if (tagmsg_path)
7364 preserve_tagmsg = 1;
7365 goto done;
7368 err = got_ref_write(ref, repo);
7369 if (err) {
7370 if (tagmsg_path)
7371 preserve_tagmsg = 1;
7372 goto done;
7375 err = got_object_id_str(&tag_id_str, tag_id);
7376 if (err) {
7377 if (tagmsg_path)
7378 preserve_tagmsg = 1;
7379 goto done;
7381 printf("Created tag %s\n", tag_id_str);
7382 done:
7383 if (preserve_tagmsg) {
7384 fprintf(stderr, "%s: tag message preserved in %s\n",
7385 getprogname(), tagmsg_path);
7386 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7387 err = got_error_from_errno2("unlink", tagmsg_path);
7388 free(tag_id_str);
7389 if (ref)
7390 got_ref_close(ref);
7391 free(commit_id);
7392 free(commit_id_str);
7393 free(refname);
7394 free(tagmsg);
7395 free(tagmsg_path);
7396 got_ref_list_free(&refs);
7397 return err;
7400 static const struct got_error *
7401 cmd_tag(int argc, char *argv[])
7403 const struct got_error *error = NULL;
7404 struct got_repository *repo = NULL;
7405 struct got_worktree *worktree = NULL;
7406 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7407 char *gitconfig_path = NULL, *tagger = NULL;
7408 char *allowed_signers = NULL, *revoked_signers = NULL;
7409 char *signer_id = NULL;
7410 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7411 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7412 int *pack_fds = NULL;
7414 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7415 switch (ch) {
7416 case 'c':
7417 commit_id_arg = optarg;
7418 break;
7419 case 'l':
7420 do_list = 1;
7421 break;
7422 case 'm':
7423 tagmsg = optarg;
7424 break;
7425 case 'r':
7426 repo_path = realpath(optarg, NULL);
7427 if (repo_path == NULL) {
7428 error = got_error_from_errno2("realpath",
7429 optarg);
7430 goto done;
7432 got_path_strip_trailing_slashes(repo_path);
7433 break;
7434 case 's':
7435 signer_id = strdup(optarg);
7436 if (signer_id == NULL) {
7437 error = got_error_from_errno("strdup");
7438 goto done;
7440 break;
7441 case 'V':
7442 verify_tags = 1;
7443 break;
7444 case 'v':
7445 if (verbosity < 0)
7446 verbosity = 0;
7447 else if (verbosity < 3)
7448 verbosity++;
7449 break;
7450 default:
7451 usage_tag();
7452 /* NOTREACHED */
7456 argc -= optind;
7457 argv += optind;
7459 if (do_list || verify_tags) {
7460 if (commit_id_arg != NULL)
7461 errx(1,
7462 "-c option can only be used when creating a tag");
7463 if (tagmsg) {
7464 if (do_list)
7465 option_conflict('l', 'm');
7466 else
7467 option_conflict('V', 'm');
7469 if (signer_id) {
7470 if (do_list)
7471 option_conflict('l', 's');
7472 else
7473 option_conflict('V', 's');
7475 if (argc > 1)
7476 usage_tag();
7477 } else if (argc != 1)
7478 usage_tag();
7480 if (argc == 1)
7481 tag_name = argv[0];
7483 #ifndef PROFILE
7484 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7485 "sendfd unveil", NULL) == -1)
7486 err(1, "pledge");
7487 #endif
7488 cwd = getcwd(NULL, 0);
7489 if (cwd == NULL) {
7490 error = got_error_from_errno("getcwd");
7491 goto done;
7494 error = got_repo_pack_fds_open(&pack_fds);
7495 if (error != NULL)
7496 goto done;
7498 if (repo_path == NULL) {
7499 error = got_worktree_open(&worktree, cwd);
7500 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7501 goto done;
7502 else
7503 error = NULL;
7504 if (worktree) {
7505 repo_path =
7506 strdup(got_worktree_get_repo_path(worktree));
7507 if (repo_path == NULL)
7508 error = got_error_from_errno("strdup");
7509 if (error)
7510 goto done;
7511 } else {
7512 repo_path = strdup(cwd);
7513 if (repo_path == NULL) {
7514 error = got_error_from_errno("strdup");
7515 goto done;
7520 if (do_list || verify_tags) {
7521 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7522 if (error != NULL)
7523 goto done;
7524 error = get_allowed_signers(&allowed_signers, repo, worktree);
7525 if (error)
7526 goto done;
7527 error = get_revoked_signers(&revoked_signers, repo, worktree);
7528 if (error)
7529 goto done;
7530 if (worktree) {
7531 /* Release work tree lock. */
7532 got_worktree_close(worktree);
7533 worktree = NULL;
7537 * Remove "cpath" promise unless needed for signature tmpfile
7538 * creation.
7540 if (verify_tags)
7541 got_sigs_apply_unveil();
7542 else {
7543 #ifndef PROFILE
7544 if (pledge("stdio rpath wpath flock proc exec sendfd "
7545 "unveil", NULL) == -1)
7546 err(1, "pledge");
7547 #endif
7549 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7550 if (error)
7551 goto done;
7552 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7553 revoked_signers, verbosity);
7554 } else {
7555 error = get_gitconfig_path(&gitconfig_path);
7556 if (error)
7557 goto done;
7558 error = got_repo_open(&repo, repo_path, gitconfig_path,
7559 pack_fds);
7560 if (error != NULL)
7561 goto done;
7563 error = get_author(&tagger, repo, worktree);
7564 if (error)
7565 goto done;
7566 if (signer_id == NULL) {
7567 error = get_signer_id(&signer_id, repo, worktree);
7568 if (error)
7569 goto done;
7572 if (tagmsg) {
7573 if (signer_id) {
7574 error = got_sigs_apply_unveil();
7575 if (error)
7576 goto done;
7578 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7579 if (error)
7580 goto done;
7583 if (commit_id_arg == NULL) {
7584 struct got_reference *head_ref;
7585 struct got_object_id *commit_id;
7586 error = got_ref_open(&head_ref, repo,
7587 worktree ? got_worktree_get_head_ref_name(worktree)
7588 : GOT_REF_HEAD, 0);
7589 if (error)
7590 goto done;
7591 error = got_ref_resolve(&commit_id, repo, head_ref);
7592 got_ref_close(head_ref);
7593 if (error)
7594 goto done;
7595 error = got_object_id_str(&commit_id_str, commit_id);
7596 free(commit_id);
7597 if (error)
7598 goto done;
7601 if (worktree) {
7602 /* Release work tree lock. */
7603 got_worktree_close(worktree);
7604 worktree = NULL;
7607 error = add_tag(repo, tagger, tag_name,
7608 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7609 signer_id, verbosity);
7611 done:
7612 if (repo) {
7613 const struct got_error *close_err = got_repo_close(repo);
7614 if (error == NULL)
7615 error = close_err;
7617 if (worktree)
7618 got_worktree_close(worktree);
7619 if (pack_fds) {
7620 const struct got_error *pack_err =
7621 got_repo_pack_fds_close(pack_fds);
7622 if (error == NULL)
7623 error = pack_err;
7625 free(cwd);
7626 free(repo_path);
7627 free(gitconfig_path);
7628 free(commit_id_str);
7629 free(tagger);
7630 free(allowed_signers);
7631 free(revoked_signers);
7632 free(signer_id);
7633 return error;
7636 __dead static void
7637 usage_add(void)
7639 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7640 exit(1);
7643 static const struct got_error *
7644 add_progress(void *arg, unsigned char status, const char *path)
7646 while (path[0] == '/')
7647 path++;
7648 printf("%c %s\n", status, path);
7649 return NULL;
7652 static const struct got_error *
7653 cmd_add(int argc, char *argv[])
7655 const struct got_error *error = NULL;
7656 struct got_repository *repo = NULL;
7657 struct got_worktree *worktree = NULL;
7658 char *cwd = NULL;
7659 struct got_pathlist_head paths;
7660 struct got_pathlist_entry *pe;
7661 int ch, can_recurse = 0, no_ignores = 0;
7662 int *pack_fds = NULL;
7664 TAILQ_INIT(&paths);
7666 while ((ch = getopt(argc, argv, "IR")) != -1) {
7667 switch (ch) {
7668 case 'I':
7669 no_ignores = 1;
7670 break;
7671 case 'R':
7672 can_recurse = 1;
7673 break;
7674 default:
7675 usage_add();
7676 /* NOTREACHED */
7680 argc -= optind;
7681 argv += optind;
7683 #ifndef PROFILE
7684 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7685 NULL) == -1)
7686 err(1, "pledge");
7687 #endif
7688 if (argc < 1)
7689 usage_add();
7691 cwd = getcwd(NULL, 0);
7692 if (cwd == NULL) {
7693 error = got_error_from_errno("getcwd");
7694 goto done;
7697 error = got_repo_pack_fds_open(&pack_fds);
7698 if (error != NULL)
7699 goto done;
7701 error = got_worktree_open(&worktree, cwd);
7702 if (error) {
7703 if (error->code == GOT_ERR_NOT_WORKTREE)
7704 error = wrap_not_worktree_error(error, "add", cwd);
7705 goto done;
7708 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7709 NULL, pack_fds);
7710 if (error != NULL)
7711 goto done;
7713 error = apply_unveil(got_repo_get_path(repo), 1,
7714 got_worktree_get_root_path(worktree));
7715 if (error)
7716 goto done;
7718 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7719 if (error)
7720 goto done;
7722 if (!can_recurse) {
7723 char *ondisk_path;
7724 struct stat sb;
7725 TAILQ_FOREACH(pe, &paths, entry) {
7726 if (asprintf(&ondisk_path, "%s/%s",
7727 got_worktree_get_root_path(worktree),
7728 pe->path) == -1) {
7729 error = got_error_from_errno("asprintf");
7730 goto done;
7732 if (lstat(ondisk_path, &sb) == -1) {
7733 if (errno == ENOENT) {
7734 free(ondisk_path);
7735 continue;
7737 error = got_error_from_errno2("lstat",
7738 ondisk_path);
7739 free(ondisk_path);
7740 goto done;
7742 free(ondisk_path);
7743 if (S_ISDIR(sb.st_mode)) {
7744 error = got_error_msg(GOT_ERR_BAD_PATH,
7745 "adding directories requires -R option");
7746 goto done;
7751 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7752 NULL, repo, no_ignores);
7753 done:
7754 if (repo) {
7755 const struct got_error *close_err = got_repo_close(repo);
7756 if (error == NULL)
7757 error = close_err;
7759 if (worktree)
7760 got_worktree_close(worktree);
7761 if (pack_fds) {
7762 const struct got_error *pack_err =
7763 got_repo_pack_fds_close(pack_fds);
7764 if (error == NULL)
7765 error = pack_err;
7767 TAILQ_FOREACH(pe, &paths, entry)
7768 free((char *)pe->path);
7769 got_pathlist_free(&paths);
7770 free(cwd);
7771 return error;
7774 __dead static void
7775 usage_remove(void)
7777 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7778 getprogname());
7779 exit(1);
7782 static const struct got_error *
7783 print_remove_status(void *arg, unsigned char status,
7784 unsigned char staged_status, const char *path)
7786 while (path[0] == '/')
7787 path++;
7788 if (status == GOT_STATUS_NONEXISTENT)
7789 return NULL;
7790 if (status == staged_status && (status == GOT_STATUS_DELETE))
7791 status = GOT_STATUS_NO_CHANGE;
7792 printf("%c%c %s\n", status, staged_status, path);
7793 return NULL;
7796 static const struct got_error *
7797 cmd_remove(int argc, char *argv[])
7799 const struct got_error *error = NULL;
7800 struct got_worktree *worktree = NULL;
7801 struct got_repository *repo = NULL;
7802 const char *status_codes = NULL;
7803 char *cwd = NULL;
7804 struct got_pathlist_head paths;
7805 struct got_pathlist_entry *pe;
7806 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7807 int ignore_missing_paths = 0;
7808 int *pack_fds = NULL;
7810 TAILQ_INIT(&paths);
7812 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7813 switch (ch) {
7814 case 'f':
7815 delete_local_mods = 1;
7816 ignore_missing_paths = 1;
7817 break;
7818 case 'k':
7819 keep_on_disk = 1;
7820 break;
7821 case 'R':
7822 can_recurse = 1;
7823 break;
7824 case 's':
7825 for (i = 0; i < strlen(optarg); i++) {
7826 switch (optarg[i]) {
7827 case GOT_STATUS_MODIFY:
7828 delete_local_mods = 1;
7829 break;
7830 case GOT_STATUS_MISSING:
7831 ignore_missing_paths = 1;
7832 break;
7833 default:
7834 errx(1, "invalid status code '%c'",
7835 optarg[i]);
7838 status_codes = optarg;
7839 break;
7840 default:
7841 usage_remove();
7842 /* NOTREACHED */
7846 argc -= optind;
7847 argv += optind;
7849 #ifndef PROFILE
7850 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7851 NULL) == -1)
7852 err(1, "pledge");
7853 #endif
7854 if (argc < 1)
7855 usage_remove();
7857 cwd = getcwd(NULL, 0);
7858 if (cwd == NULL) {
7859 error = got_error_from_errno("getcwd");
7860 goto done;
7863 error = got_repo_pack_fds_open(&pack_fds);
7864 if (error != NULL)
7865 goto done;
7867 error = got_worktree_open(&worktree, cwd);
7868 if (error) {
7869 if (error->code == GOT_ERR_NOT_WORKTREE)
7870 error = wrap_not_worktree_error(error, "remove", cwd);
7871 goto done;
7874 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7875 NULL, pack_fds);
7876 if (error)
7877 goto done;
7879 error = apply_unveil(got_repo_get_path(repo), 1,
7880 got_worktree_get_root_path(worktree));
7881 if (error)
7882 goto done;
7884 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7885 if (error)
7886 goto done;
7888 if (!can_recurse) {
7889 char *ondisk_path;
7890 struct stat sb;
7891 TAILQ_FOREACH(pe, &paths, entry) {
7892 if (asprintf(&ondisk_path, "%s/%s",
7893 got_worktree_get_root_path(worktree),
7894 pe->path) == -1) {
7895 error = got_error_from_errno("asprintf");
7896 goto done;
7898 if (lstat(ondisk_path, &sb) == -1) {
7899 if (errno == ENOENT) {
7900 free(ondisk_path);
7901 continue;
7903 error = got_error_from_errno2("lstat",
7904 ondisk_path);
7905 free(ondisk_path);
7906 goto done;
7908 free(ondisk_path);
7909 if (S_ISDIR(sb.st_mode)) {
7910 error = got_error_msg(GOT_ERR_BAD_PATH,
7911 "removing directories requires -R option");
7912 goto done;
7917 error = got_worktree_schedule_delete(worktree, &paths,
7918 delete_local_mods, status_codes, print_remove_status, NULL,
7919 repo, keep_on_disk, ignore_missing_paths);
7920 done:
7921 if (repo) {
7922 const struct got_error *close_err = got_repo_close(repo);
7923 if (error == NULL)
7924 error = close_err;
7926 if (worktree)
7927 got_worktree_close(worktree);
7928 if (pack_fds) {
7929 const struct got_error *pack_err =
7930 got_repo_pack_fds_close(pack_fds);
7931 if (error == NULL)
7932 error = pack_err;
7934 TAILQ_FOREACH(pe, &paths, entry)
7935 free((char *)pe->path);
7936 got_pathlist_free(&paths);
7937 free(cwd);
7938 return error;
7941 __dead static void
7942 usage_patch(void)
7944 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7945 "[patchfile]\n", getprogname());
7946 exit(1);
7949 static const struct got_error *
7950 patch_from_stdin(int *patchfd)
7952 const struct got_error *err = NULL;
7953 ssize_t r;
7954 char buf[BUFSIZ];
7955 sig_t sighup, sigint, sigquit;
7957 *patchfd = got_opentempfd();
7958 if (*patchfd == -1)
7959 return got_error_from_errno("got_opentempfd");
7961 sighup = signal(SIGHUP, SIG_DFL);
7962 sigint = signal(SIGINT, SIG_DFL);
7963 sigquit = signal(SIGQUIT, SIG_DFL);
7965 for (;;) {
7966 r = read(0, buf, sizeof(buf));
7967 if (r == -1) {
7968 err = got_error_from_errno("read");
7969 break;
7971 if (r == 0)
7972 break;
7973 if (write(*patchfd, buf, r) == -1) {
7974 err = got_error_from_errno("write");
7975 break;
7979 signal(SIGHUP, sighup);
7980 signal(SIGINT, sigint);
7981 signal(SIGQUIT, sigquit);
7983 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7984 err = got_error_from_errno("lseek");
7986 if (err != NULL) {
7987 close(*patchfd);
7988 *patchfd = -1;
7991 return err;
7994 static const struct got_error *
7995 patch_progress(void *arg, const char *old, const char *new,
7996 unsigned char status, const struct got_error *error, int old_from,
7997 int old_lines, int new_from, int new_lines, int offset,
7998 int ws_mangled, const struct got_error *hunk_err)
8000 const char *path = new == NULL ? old : new;
8002 while (*path == '/')
8003 path++;
8005 if (status != 0)
8006 printf("%c %s\n", status, path);
8008 if (error != NULL)
8009 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8011 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8012 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8013 old_lines, new_from, new_lines);
8014 if (hunk_err != NULL)
8015 printf("%s\n", hunk_err->msg);
8016 else if (offset != 0)
8017 printf("applied with offset %d\n", offset);
8018 else
8019 printf("hunk contains mangled whitespace\n");
8022 return NULL;
8025 static const struct got_error *
8026 cmd_patch(int argc, char *argv[])
8028 const struct got_error *error = NULL, *close_error = NULL;
8029 struct got_worktree *worktree = NULL;
8030 struct got_repository *repo = NULL;
8031 struct got_reflist_head refs;
8032 struct got_object_id *commit_id = NULL;
8033 const char *commit_id_str = NULL;
8034 struct stat sb;
8035 const char *errstr;
8036 char *cwd = NULL;
8037 int ch, nop = 0, strip = -1, reverse = 0;
8038 int patchfd;
8039 int *pack_fds = NULL;
8041 TAILQ_INIT(&refs);
8043 #ifndef PROFILE
8044 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8045 "unveil", NULL) == -1)
8046 err(1, "pledge");
8047 #endif
8049 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8050 switch (ch) {
8051 case 'c':
8052 commit_id_str = optarg;
8053 break;
8054 case 'n':
8055 nop = 1;
8056 break;
8057 case 'p':
8058 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8059 if (errstr != NULL)
8060 errx(1, "pathname strip count is %s: %s",
8061 errstr, optarg);
8062 break;
8063 case 'R':
8064 reverse = 1;
8065 break;
8066 default:
8067 usage_patch();
8068 /* NOTREACHED */
8072 argc -= optind;
8073 argv += optind;
8075 if (argc == 0) {
8076 error = patch_from_stdin(&patchfd);
8077 if (error)
8078 return error;
8079 } else if (argc == 1) {
8080 patchfd = open(argv[0], O_RDONLY);
8081 if (patchfd == -1) {
8082 error = got_error_from_errno2("open", argv[0]);
8083 return error;
8085 if (fstat(patchfd, &sb) == -1) {
8086 error = got_error_from_errno2("fstat", argv[0]);
8087 goto done;
8089 if (!S_ISREG(sb.st_mode)) {
8090 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8091 goto done;
8093 } else
8094 usage_patch();
8096 if ((cwd = getcwd(NULL, 0)) == NULL) {
8097 error = got_error_from_errno("getcwd");
8098 goto done;
8101 error = got_repo_pack_fds_open(&pack_fds);
8102 if (error != NULL)
8103 goto done;
8105 error = got_worktree_open(&worktree, cwd);
8106 if (error != NULL)
8107 goto done;
8109 const char *repo_path = got_worktree_get_repo_path(worktree);
8110 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8111 if (error != NULL)
8112 goto done;
8114 error = apply_unveil(got_repo_get_path(repo), 0,
8115 got_worktree_get_root_path(worktree));
8116 if (error != NULL)
8117 goto done;
8119 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8120 if (error)
8121 goto done;
8123 if (commit_id_str != NULL) {
8124 error = got_repo_match_object_id(&commit_id, NULL,
8125 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8126 if (error)
8127 goto done;
8130 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8131 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8133 done:
8134 got_ref_list_free(&refs);
8135 free(commit_id);
8136 if (repo) {
8137 close_error = got_repo_close(repo);
8138 if (error == NULL)
8139 error = close_error;
8141 if (worktree != NULL) {
8142 close_error = got_worktree_close(worktree);
8143 if (error == NULL)
8144 error = close_error;
8146 if (pack_fds) {
8147 const struct got_error *pack_err =
8148 got_repo_pack_fds_close(pack_fds);
8149 if (error == NULL)
8150 error = pack_err;
8152 free(cwd);
8153 return error;
8156 __dead static void
8157 usage_revert(void)
8159 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8160 getprogname());
8161 exit(1);
8164 static const struct got_error *
8165 revert_progress(void *arg, unsigned char status, const char *path)
8167 if (status == GOT_STATUS_UNVERSIONED)
8168 return NULL;
8170 while (path[0] == '/')
8171 path++;
8172 printf("%c %s\n", status, path);
8173 return NULL;
8176 struct choose_patch_arg {
8177 FILE *patch_script_file;
8178 const char *action;
8181 static const struct got_error *
8182 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8183 int nchanges, const char *action)
8185 const struct got_error *err;
8186 char *line = NULL;
8187 size_t linesize = 0;
8188 ssize_t linelen;
8190 switch (status) {
8191 case GOT_STATUS_ADD:
8192 printf("A %s\n%s this addition? [y/n] ", path, action);
8193 break;
8194 case GOT_STATUS_DELETE:
8195 printf("D %s\n%s this deletion? [y/n] ", path, action);
8196 break;
8197 case GOT_STATUS_MODIFY:
8198 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8199 return got_error_from_errno("fseek");
8200 printf(GOT_COMMIT_SEP_STR);
8201 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8202 printf("%s", line);
8203 if (linelen == -1 && ferror(patch_file)) {
8204 err = got_error_from_errno("getline");
8205 free(line);
8206 return err;
8208 free(line);
8209 printf(GOT_COMMIT_SEP_STR);
8210 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8211 path, n, nchanges, action);
8212 break;
8213 default:
8214 return got_error_path(path, GOT_ERR_FILE_STATUS);
8217 fflush(stdout);
8218 return NULL;
8221 static const struct got_error *
8222 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8223 FILE *patch_file, int n, int nchanges)
8225 const struct got_error *err = NULL;
8226 char *line = NULL;
8227 size_t linesize = 0;
8228 ssize_t linelen;
8229 int resp = ' ';
8230 struct choose_patch_arg *a = arg;
8232 *choice = GOT_PATCH_CHOICE_NONE;
8234 if (a->patch_script_file) {
8235 char *nl;
8236 err = show_change(status, path, patch_file, n, nchanges,
8237 a->action);
8238 if (err)
8239 return err;
8240 linelen = getline(&line, &linesize, a->patch_script_file);
8241 if (linelen == -1) {
8242 if (ferror(a->patch_script_file))
8243 return got_error_from_errno("getline");
8244 return NULL;
8246 nl = strchr(line, '\n');
8247 if (nl)
8248 *nl = '\0';
8249 if (strcmp(line, "y") == 0) {
8250 *choice = GOT_PATCH_CHOICE_YES;
8251 printf("y\n");
8252 } else if (strcmp(line, "n") == 0) {
8253 *choice = GOT_PATCH_CHOICE_NO;
8254 printf("n\n");
8255 } else if (strcmp(line, "q") == 0 &&
8256 status == GOT_STATUS_MODIFY) {
8257 *choice = GOT_PATCH_CHOICE_QUIT;
8258 printf("q\n");
8259 } else
8260 printf("invalid response '%s'\n", line);
8261 free(line);
8262 return NULL;
8265 while (resp != 'y' && resp != 'n' && resp != 'q') {
8266 err = show_change(status, path, patch_file, n, nchanges,
8267 a->action);
8268 if (err)
8269 return err;
8270 resp = getchar();
8271 if (resp == '\n')
8272 resp = getchar();
8273 if (status == GOT_STATUS_MODIFY) {
8274 if (resp != 'y' && resp != 'n' && resp != 'q') {
8275 printf("invalid response '%c'\n", resp);
8276 resp = ' ';
8278 } else if (resp != 'y' && resp != 'n') {
8279 printf("invalid response '%c'\n", resp);
8280 resp = ' ';
8284 if (resp == 'y')
8285 *choice = GOT_PATCH_CHOICE_YES;
8286 else if (resp == 'n')
8287 *choice = GOT_PATCH_CHOICE_NO;
8288 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8289 *choice = GOT_PATCH_CHOICE_QUIT;
8291 return NULL;
8294 static const struct got_error *
8295 cmd_revert(int argc, char *argv[])
8297 const struct got_error *error = NULL;
8298 struct got_worktree *worktree = NULL;
8299 struct got_repository *repo = NULL;
8300 char *cwd = NULL, *path = NULL;
8301 struct got_pathlist_head paths;
8302 struct got_pathlist_entry *pe;
8303 int ch, can_recurse = 0, pflag = 0;
8304 FILE *patch_script_file = NULL;
8305 const char *patch_script_path = NULL;
8306 struct choose_patch_arg cpa;
8307 int *pack_fds = NULL;
8309 TAILQ_INIT(&paths);
8311 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8312 switch (ch) {
8313 case 'F':
8314 patch_script_path = optarg;
8315 break;
8316 case 'p':
8317 pflag = 1;
8318 break;
8319 case 'R':
8320 can_recurse = 1;
8321 break;
8322 default:
8323 usage_revert();
8324 /* NOTREACHED */
8328 argc -= optind;
8329 argv += optind;
8331 #ifndef PROFILE
8332 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8333 "unveil", NULL) == -1)
8334 err(1, "pledge");
8335 #endif
8336 if (argc < 1)
8337 usage_revert();
8338 if (patch_script_path && !pflag)
8339 errx(1, "-F option can only be used together with -p option");
8341 cwd = getcwd(NULL, 0);
8342 if (cwd == NULL) {
8343 error = got_error_from_errno("getcwd");
8344 goto done;
8347 error = got_repo_pack_fds_open(&pack_fds);
8348 if (error != NULL)
8349 goto done;
8351 error = got_worktree_open(&worktree, cwd);
8352 if (error) {
8353 if (error->code == GOT_ERR_NOT_WORKTREE)
8354 error = wrap_not_worktree_error(error, "revert", cwd);
8355 goto done;
8358 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8359 NULL, pack_fds);
8360 if (error != NULL)
8361 goto done;
8363 if (patch_script_path) {
8364 patch_script_file = fopen(patch_script_path, "re");
8365 if (patch_script_file == NULL) {
8366 error = got_error_from_errno2("fopen",
8367 patch_script_path);
8368 goto done;
8371 error = apply_unveil(got_repo_get_path(repo), 1,
8372 got_worktree_get_root_path(worktree));
8373 if (error)
8374 goto done;
8376 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8377 if (error)
8378 goto done;
8380 if (!can_recurse) {
8381 char *ondisk_path;
8382 struct stat sb;
8383 TAILQ_FOREACH(pe, &paths, entry) {
8384 if (asprintf(&ondisk_path, "%s/%s",
8385 got_worktree_get_root_path(worktree),
8386 pe->path) == -1) {
8387 error = got_error_from_errno("asprintf");
8388 goto done;
8390 if (lstat(ondisk_path, &sb) == -1) {
8391 if (errno == ENOENT) {
8392 free(ondisk_path);
8393 continue;
8395 error = got_error_from_errno2("lstat",
8396 ondisk_path);
8397 free(ondisk_path);
8398 goto done;
8400 free(ondisk_path);
8401 if (S_ISDIR(sb.st_mode)) {
8402 error = got_error_msg(GOT_ERR_BAD_PATH,
8403 "reverting directories requires -R option");
8404 goto done;
8409 cpa.patch_script_file = patch_script_file;
8410 cpa.action = "revert";
8411 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8412 pflag ? choose_patch : NULL, &cpa, repo);
8413 done:
8414 if (patch_script_file && fclose(patch_script_file) == EOF &&
8415 error == NULL)
8416 error = got_error_from_errno2("fclose", patch_script_path);
8417 if (repo) {
8418 const struct got_error *close_err = got_repo_close(repo);
8419 if (error == NULL)
8420 error = close_err;
8422 if (worktree)
8423 got_worktree_close(worktree);
8424 if (pack_fds) {
8425 const struct got_error *pack_err =
8426 got_repo_pack_fds_close(pack_fds);
8427 if (error == NULL)
8428 error = pack_err;
8430 free(path);
8431 free(cwd);
8432 return error;
8435 __dead static void
8436 usage_commit(void)
8438 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8439 "[-m message] [path ...]\n", getprogname());
8440 exit(1);
8443 struct collect_commit_logmsg_arg {
8444 const char *cmdline_log;
8445 const char *prepared_log;
8446 int non_interactive;
8447 const char *editor;
8448 const char *worktree_path;
8449 const char *branch_name;
8450 const char *repo_path;
8451 char *logmsg_path;
8455 static const struct got_error *
8456 read_prepared_logmsg(char **logmsg, const char *path)
8458 const struct got_error *err = NULL;
8459 FILE *f = NULL;
8460 struct stat sb;
8461 size_t r;
8463 *logmsg = NULL;
8464 memset(&sb, 0, sizeof(sb));
8466 f = fopen(path, "re");
8467 if (f == NULL)
8468 return got_error_from_errno2("fopen", path);
8470 if (fstat(fileno(f), &sb) == -1) {
8471 err = got_error_from_errno2("fstat", path);
8472 goto done;
8474 if (sb.st_size == 0) {
8475 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8476 goto done;
8479 *logmsg = malloc(sb.st_size + 1);
8480 if (*logmsg == NULL) {
8481 err = got_error_from_errno("malloc");
8482 goto done;
8485 r = fread(*logmsg, 1, sb.st_size, f);
8486 if (r != sb.st_size) {
8487 if (ferror(f))
8488 err = got_error_from_errno2("fread", path);
8489 else
8490 err = got_error(GOT_ERR_IO);
8491 goto done;
8493 (*logmsg)[sb.st_size] = '\0';
8494 done:
8495 if (fclose(f) == EOF && err == NULL)
8496 err = got_error_from_errno2("fclose", path);
8497 if (err) {
8498 free(*logmsg);
8499 *logmsg = NULL;
8501 return err;
8504 static const struct got_error *
8505 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8506 const char *diff_path, char **logmsg, void *arg)
8508 char *initial_content = NULL;
8509 struct got_pathlist_entry *pe;
8510 const struct got_error *err = NULL;
8511 char *template = NULL;
8512 struct collect_commit_logmsg_arg *a = arg;
8513 int initial_content_len;
8514 int fd = -1;
8515 size_t len;
8517 /* if a message was specified on the command line, just use it */
8518 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8519 len = strlen(a->cmdline_log) + 1;
8520 *logmsg = malloc(len + 1);
8521 if (*logmsg == NULL)
8522 return got_error_from_errno("malloc");
8523 strlcpy(*logmsg, a->cmdline_log, len);
8524 return NULL;
8525 } else if (a->prepared_log != NULL && a->non_interactive)
8526 return read_prepared_logmsg(logmsg, a->prepared_log);
8528 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8529 return got_error_from_errno("asprintf");
8531 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8532 if (err)
8533 goto done;
8535 if (a->prepared_log) {
8536 char *msg;
8537 err = read_prepared_logmsg(&msg, a->prepared_log);
8538 if (err)
8539 goto done;
8540 if (write(fd, msg, strlen(msg)) == -1) {
8541 err = got_error_from_errno2("write", a->logmsg_path);
8542 free(msg);
8543 goto done;
8545 free(msg);
8548 initial_content_len = asprintf(&initial_content,
8549 "\n# changes to be committed on branch %s:\n",
8550 a->branch_name);
8551 if (initial_content_len == -1) {
8552 err = got_error_from_errno("asprintf");
8553 goto done;
8556 if (write(fd, initial_content, initial_content_len) == -1) {
8557 err = got_error_from_errno2("write", a->logmsg_path);
8558 goto done;
8561 TAILQ_FOREACH(pe, commitable_paths, entry) {
8562 struct got_commitable *ct = pe->data;
8563 dprintf(fd, "# %c %s\n",
8564 got_commitable_get_status(ct),
8565 got_commitable_get_path(ct));
8568 if (diff_path) {
8569 dprintf(fd, "# detailed changes can be viewed in %s\n",
8570 diff_path);
8573 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8574 initial_content_len, a->prepared_log ? 0 : 1);
8575 done:
8576 free(initial_content);
8577 free(template);
8579 if (fd != -1 && close(fd) == -1 && err == NULL)
8580 err = got_error_from_errno2("close", a->logmsg_path);
8582 /* Editor is done; we can now apply unveil(2) */
8583 if (err == NULL)
8584 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8585 if (err) {
8586 free(*logmsg);
8587 *logmsg = NULL;
8589 return err;
8592 static const struct got_error *
8593 cmd_commit(int argc, char *argv[])
8595 const struct got_error *error = NULL;
8596 struct got_worktree *worktree = NULL;
8597 struct got_repository *repo = NULL;
8598 char *cwd = NULL, *id_str = NULL;
8599 struct got_object_id *id = NULL;
8600 const char *logmsg = NULL;
8601 char *prepared_logmsg = NULL;
8602 struct collect_commit_logmsg_arg cl_arg;
8603 const char *author = NULL;
8604 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8605 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8606 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8607 int show_diff = 1;
8608 struct got_pathlist_head paths;
8609 int *pack_fds = NULL;
8611 TAILQ_INIT(&paths);
8612 cl_arg.logmsg_path = NULL;
8614 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8615 switch (ch) {
8616 case 'A':
8617 author = optarg;
8618 error = valid_author(author);
8619 if (error)
8620 return error;
8621 break;
8622 case 'F':
8623 if (logmsg != NULL)
8624 option_conflict('F', 'm');
8625 prepared_logmsg = realpath(optarg, NULL);
8626 if (prepared_logmsg == NULL)
8627 return got_error_from_errno2("realpath",
8628 optarg);
8629 break;
8630 case 'm':
8631 if (prepared_logmsg)
8632 option_conflict('m', 'F');
8633 logmsg = optarg;
8634 break;
8635 case 'N':
8636 non_interactive = 1;
8637 break;
8638 case 'n':
8639 show_diff = 0;
8640 break;
8641 case 'S':
8642 allow_bad_symlinks = 1;
8643 break;
8644 default:
8645 usage_commit();
8646 /* NOTREACHED */
8650 argc -= optind;
8651 argv += optind;
8653 #ifndef PROFILE
8654 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8655 "unveil", NULL) == -1)
8656 err(1, "pledge");
8657 #endif
8658 cwd = getcwd(NULL, 0);
8659 if (cwd == NULL) {
8660 error = got_error_from_errno("getcwd");
8661 goto done;
8664 error = got_repo_pack_fds_open(&pack_fds);
8665 if (error != NULL)
8666 goto done;
8668 error = got_worktree_open(&worktree, cwd);
8669 if (error) {
8670 if (error->code == GOT_ERR_NOT_WORKTREE)
8671 error = wrap_not_worktree_error(error, "commit", cwd);
8672 goto done;
8675 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8676 if (error)
8677 goto done;
8678 if (rebase_in_progress) {
8679 error = got_error(GOT_ERR_REBASING);
8680 goto done;
8683 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8684 worktree);
8685 if (error)
8686 goto done;
8688 error = get_gitconfig_path(&gitconfig_path);
8689 if (error)
8690 goto done;
8691 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8692 gitconfig_path, pack_fds);
8693 if (error != NULL)
8694 goto done;
8696 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8697 if (error)
8698 goto done;
8699 if (merge_in_progress) {
8700 error = got_error(GOT_ERR_MERGE_BUSY);
8701 goto done;
8704 error = get_author(&committer, repo, worktree);
8705 if (error)
8706 goto done;
8708 if (author != NULL && !strcmp(committer, author)) {
8709 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8710 goto done;
8713 if (author == NULL)
8714 author = committer;
8717 * unveil(2) traverses exec(2); if an editor is used we have
8718 * to apply unveil after the log message has been written.
8720 if (logmsg == NULL || strlen(logmsg) == 0)
8721 error = get_editor(&editor);
8722 else
8723 error = apply_unveil(got_repo_get_path(repo), 0,
8724 got_worktree_get_root_path(worktree));
8725 if (error)
8726 goto done;
8728 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8729 if (error)
8730 goto done;
8732 cl_arg.editor = editor;
8733 cl_arg.cmdline_log = logmsg;
8734 cl_arg.prepared_log = prepared_logmsg;
8735 cl_arg.non_interactive = non_interactive;
8736 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8737 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8738 if (!histedit_in_progress) {
8739 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8740 error = got_error(GOT_ERR_COMMIT_BRANCH);
8741 goto done;
8743 cl_arg.branch_name += 11;
8745 cl_arg.repo_path = got_repo_get_path(repo);
8746 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8747 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8748 print_status, NULL, repo);
8749 if (error) {
8750 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8751 cl_arg.logmsg_path != NULL)
8752 preserve_logmsg = 1;
8753 goto done;
8756 error = got_object_id_str(&id_str, id);
8757 if (error)
8758 goto done;
8759 printf("Created commit %s\n", id_str);
8760 done:
8761 if (preserve_logmsg) {
8762 fprintf(stderr, "%s: log message preserved in %s\n",
8763 getprogname(), cl_arg.logmsg_path);
8764 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8765 error == NULL)
8766 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8767 free(cl_arg.logmsg_path);
8768 if (repo) {
8769 const struct got_error *close_err = got_repo_close(repo);
8770 if (error == NULL)
8771 error = close_err;
8773 if (worktree)
8774 got_worktree_close(worktree);
8775 if (pack_fds) {
8776 const struct got_error *pack_err =
8777 got_repo_pack_fds_close(pack_fds);
8778 if (error == NULL)
8779 error = pack_err;
8781 free(cwd);
8782 free(id_str);
8783 free(gitconfig_path);
8784 free(editor);
8785 free(committer);
8786 free(prepared_logmsg);
8787 return error;
8790 __dead static void
8791 usage_send(void)
8793 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8794 "[-r repository-path] [-t tag] [remote-repository]\n",
8795 getprogname());
8796 exit(1);
8799 static void
8800 print_load_info(int print_colored, int print_found, int print_trees,
8801 int ncolored, int nfound, int ntrees)
8803 if (print_colored) {
8804 printf("%d commit%s colored", ncolored,
8805 ncolored == 1 ? "" : "s");
8807 if (print_found) {
8808 printf("%s%d object%s found",
8809 ncolored > 0 ? "; " : "",
8810 nfound, nfound == 1 ? "" : "s");
8812 if (print_trees) {
8813 printf("; %d tree%s scanned", ntrees,
8814 ntrees == 1 ? "" : "s");
8818 struct got_send_progress_arg {
8819 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8820 int verbosity;
8821 int last_ncolored;
8822 int last_nfound;
8823 int last_ntrees;
8824 int loading_done;
8825 int last_ncommits;
8826 int last_nobj_total;
8827 int last_p_deltify;
8828 int last_p_written;
8829 int last_p_sent;
8830 int printed_something;
8831 int sent_something;
8832 struct got_pathlist_head *delete_branches;
8835 static const struct got_error *
8836 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8837 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8838 int nobj_written, off_t bytes_sent, const char *refname,
8839 const char *errmsg, int success)
8841 struct got_send_progress_arg *a = arg;
8842 char scaled_packsize[FMT_SCALED_STRSIZE];
8843 char scaled_sent[FMT_SCALED_STRSIZE];
8844 int p_deltify = 0, p_written = 0, p_sent = 0;
8845 int print_colored = 0, print_found = 0, print_trees = 0;
8846 int print_searching = 0, print_total = 0;
8847 int print_deltify = 0, print_written = 0, print_sent = 0;
8849 if (a->verbosity < 0)
8850 return NULL;
8852 if (refname) {
8853 const char *status = success ? "accepted" : "rejected";
8855 if (success) {
8856 struct got_pathlist_entry *pe;
8857 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8858 const char *branchname = pe->path;
8859 if (got_path_cmp(branchname, refname,
8860 strlen(branchname), strlen(refname)) == 0) {
8861 status = "deleted";
8862 a->sent_something = 1;
8863 break;
8868 if (a->printed_something)
8869 putchar('\n');
8870 printf("Server has %s %s", status, refname);
8871 if (errmsg)
8872 printf(": %s", errmsg);
8873 a->printed_something = 1;
8874 return NULL;
8877 if (a->last_ncolored != ncolored) {
8878 print_colored = 1;
8879 a->last_ncolored = ncolored;
8882 if (a->last_nfound != nfound) {
8883 print_colored = 1;
8884 print_found = 1;
8885 a->last_nfound = nfound;
8888 if (a->last_ntrees != ntrees) {
8889 print_colored = 1;
8890 print_found = 1;
8891 print_trees = 1;
8892 a->last_ntrees = ntrees;
8895 if ((print_colored || print_found || print_trees) &&
8896 !a->loading_done) {
8897 printf("\r");
8898 print_load_info(print_colored, print_found, print_trees,
8899 ncolored, nfound, ntrees);
8900 a->printed_something = 1;
8901 fflush(stdout);
8902 return NULL;
8903 } else if (!a->loading_done) {
8904 printf("\r");
8905 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8906 printf("\n");
8907 a->loading_done = 1;
8910 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8911 return got_error_from_errno("fmt_scaled");
8912 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8913 return got_error_from_errno("fmt_scaled");
8915 if (a->last_ncommits != ncommits) {
8916 print_searching = 1;
8917 a->last_ncommits = ncommits;
8920 if (a->last_nobj_total != nobj_total) {
8921 print_searching = 1;
8922 print_total = 1;
8923 a->last_nobj_total = nobj_total;
8926 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8927 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8928 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8929 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8930 return got_error(GOT_ERR_NO_SPACE);
8933 if (nobj_deltify > 0 || nobj_written > 0) {
8934 if (nobj_deltify > 0) {
8935 p_deltify = (nobj_deltify * 100) / nobj_total;
8936 if (p_deltify != a->last_p_deltify) {
8937 a->last_p_deltify = p_deltify;
8938 print_searching = 1;
8939 print_total = 1;
8940 print_deltify = 1;
8943 if (nobj_written > 0) {
8944 p_written = (nobj_written * 100) / nobj_total;
8945 if (p_written != a->last_p_written) {
8946 a->last_p_written = p_written;
8947 print_searching = 1;
8948 print_total = 1;
8949 print_deltify = 1;
8950 print_written = 1;
8955 if (bytes_sent > 0) {
8956 p_sent = (bytes_sent * 100) / packfile_size;
8957 if (p_sent != a->last_p_sent) {
8958 a->last_p_sent = p_sent;
8959 print_searching = 1;
8960 print_total = 1;
8961 print_deltify = 1;
8962 print_written = 1;
8963 print_sent = 1;
8965 a->sent_something = 1;
8968 if (print_searching || print_total || print_deltify || print_written ||
8969 print_sent)
8970 printf("\r");
8971 if (print_searching)
8972 printf("packing %d reference%s", ncommits,
8973 ncommits == 1 ? "" : "s");
8974 if (print_total)
8975 printf("; %d object%s", nobj_total,
8976 nobj_total == 1 ? "" : "s");
8977 if (print_deltify)
8978 printf("; deltify: %d%%", p_deltify);
8979 if (print_sent)
8980 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8981 scaled_packsize, p_sent);
8982 else if (print_written)
8983 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8984 scaled_packsize, p_written);
8985 if (print_searching || print_total || print_deltify ||
8986 print_written || print_sent) {
8987 a->printed_something = 1;
8988 fflush(stdout);
8990 return NULL;
8993 static const struct got_error *
8994 cmd_send(int argc, char *argv[])
8996 const struct got_error *error = NULL;
8997 char *cwd = NULL, *repo_path = NULL;
8998 const char *remote_name;
8999 char *proto = NULL, *host = NULL, *port = NULL;
9000 char *repo_name = NULL, *server_path = NULL;
9001 const struct got_remote_repo *remotes, *remote = NULL;
9002 int nremotes, nbranches = 0, ndelete_branches = 0;
9003 struct got_repository *repo = NULL;
9004 struct got_worktree *worktree = NULL;
9005 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9006 struct got_pathlist_head branches;
9007 struct got_pathlist_head tags;
9008 struct got_reflist_head all_branches;
9009 struct got_reflist_head all_tags;
9010 struct got_pathlist_head delete_args;
9011 struct got_pathlist_head delete_branches;
9012 struct got_reflist_entry *re;
9013 struct got_pathlist_entry *pe;
9014 int i, ch, sendfd = -1, sendstatus;
9015 pid_t sendpid = -1;
9016 struct got_send_progress_arg spa;
9017 int verbosity = 0, overwrite_refs = 0;
9018 int send_all_branches = 0, send_all_tags = 0;
9019 struct got_reference *ref = NULL;
9020 int *pack_fds = NULL;
9022 TAILQ_INIT(&branches);
9023 TAILQ_INIT(&tags);
9024 TAILQ_INIT(&all_branches);
9025 TAILQ_INIT(&all_tags);
9026 TAILQ_INIT(&delete_args);
9027 TAILQ_INIT(&delete_branches);
9029 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9030 switch (ch) {
9031 case 'a':
9032 send_all_branches = 1;
9033 break;
9034 case 'b':
9035 error = got_pathlist_append(&branches, optarg, NULL);
9036 if (error)
9037 return error;
9038 nbranches++;
9039 break;
9040 case 'd':
9041 error = got_pathlist_append(&delete_args, optarg, NULL);
9042 if (error)
9043 return error;
9044 break;
9045 case 'f':
9046 overwrite_refs = 1;
9047 break;
9048 case 'q':
9049 verbosity = -1;
9050 break;
9051 case 'r':
9052 repo_path = realpath(optarg, NULL);
9053 if (repo_path == NULL)
9054 return got_error_from_errno2("realpath",
9055 optarg);
9056 got_path_strip_trailing_slashes(repo_path);
9057 break;
9058 case 'T':
9059 send_all_tags = 1;
9060 break;
9061 case 't':
9062 error = got_pathlist_append(&tags, optarg, NULL);
9063 if (error)
9064 return error;
9065 break;
9066 case 'v':
9067 if (verbosity < 0)
9068 verbosity = 0;
9069 else if (verbosity < 3)
9070 verbosity++;
9071 break;
9072 default:
9073 usage_send();
9074 /* NOTREACHED */
9077 argc -= optind;
9078 argv += optind;
9080 if (send_all_branches && !TAILQ_EMPTY(&branches))
9081 option_conflict('a', 'b');
9082 if (send_all_tags && !TAILQ_EMPTY(&tags))
9083 option_conflict('T', 't');
9086 if (argc == 0)
9087 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9088 else if (argc == 1)
9089 remote_name = argv[0];
9090 else
9091 usage_send();
9093 cwd = getcwd(NULL, 0);
9094 if (cwd == NULL) {
9095 error = got_error_from_errno("getcwd");
9096 goto done;
9099 error = got_repo_pack_fds_open(&pack_fds);
9100 if (error != NULL)
9101 goto done;
9103 if (repo_path == NULL) {
9104 error = got_worktree_open(&worktree, cwd);
9105 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9106 goto done;
9107 else
9108 error = NULL;
9109 if (worktree) {
9110 repo_path =
9111 strdup(got_worktree_get_repo_path(worktree));
9112 if (repo_path == NULL)
9113 error = got_error_from_errno("strdup");
9114 if (error)
9115 goto done;
9116 } else {
9117 repo_path = strdup(cwd);
9118 if (repo_path == NULL) {
9119 error = got_error_from_errno("strdup");
9120 goto done;
9125 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9126 if (error)
9127 goto done;
9129 if (worktree) {
9130 worktree_conf = got_worktree_get_gotconfig(worktree);
9131 if (worktree_conf) {
9132 got_gotconfig_get_remotes(&nremotes, &remotes,
9133 worktree_conf);
9134 for (i = 0; i < nremotes; i++) {
9135 if (strcmp(remotes[i].name, remote_name) == 0) {
9136 remote = &remotes[i];
9137 break;
9142 if (remote == NULL) {
9143 repo_conf = got_repo_get_gotconfig(repo);
9144 if (repo_conf) {
9145 got_gotconfig_get_remotes(&nremotes, &remotes,
9146 repo_conf);
9147 for (i = 0; i < nremotes; i++) {
9148 if (strcmp(remotes[i].name, remote_name) == 0) {
9149 remote = &remotes[i];
9150 break;
9155 if (remote == NULL) {
9156 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9157 for (i = 0; i < nremotes; i++) {
9158 if (strcmp(remotes[i].name, remote_name) == 0) {
9159 remote = &remotes[i];
9160 break;
9164 if (remote == NULL) {
9165 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9166 goto done;
9169 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9170 &repo_name, remote->send_url);
9171 if (error)
9172 goto done;
9174 if (strcmp(proto, "git") == 0) {
9175 #ifndef PROFILE
9176 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9177 "sendfd dns inet unveil", NULL) == -1)
9178 err(1, "pledge");
9179 #endif
9180 } else if (strcmp(proto, "git+ssh") == 0 ||
9181 strcmp(proto, "ssh") == 0) {
9182 #ifndef PROFILE
9183 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9184 "sendfd unveil", NULL) == -1)
9185 err(1, "pledge");
9186 #endif
9187 } else if (strcmp(proto, "http") == 0 ||
9188 strcmp(proto, "git+http") == 0) {
9189 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9190 goto done;
9191 } else {
9192 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9193 goto done;
9196 error = got_dial_apply_unveil(proto);
9197 if (error)
9198 goto done;
9200 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9201 if (error)
9202 goto done;
9204 if (send_all_branches) {
9205 error = got_ref_list(&all_branches, repo, "refs/heads",
9206 got_ref_cmp_by_name, NULL);
9207 if (error)
9208 goto done;
9209 TAILQ_FOREACH(re, &all_branches, entry) {
9210 const char *branchname = got_ref_get_name(re->ref);
9211 error = got_pathlist_append(&branches,
9212 branchname, NULL);
9213 if (error)
9214 goto done;
9215 nbranches++;
9217 } else if (nbranches == 0) {
9218 for (i = 0; i < remote->nsend_branches; i++) {
9219 got_pathlist_append(&branches,
9220 remote->send_branches[i], NULL);
9224 if (send_all_tags) {
9225 error = got_ref_list(&all_tags, repo, "refs/tags",
9226 got_ref_cmp_by_name, NULL);
9227 if (error)
9228 goto done;
9229 TAILQ_FOREACH(re, &all_tags, entry) {
9230 const char *tagname = got_ref_get_name(re->ref);
9231 error = got_pathlist_append(&tags,
9232 tagname, NULL);
9233 if (error)
9234 goto done;
9239 * To prevent accidents only branches in refs/heads/ can be deleted
9240 * with 'got send -d'.
9241 * Deleting anything else requires local repository access or Git.
9243 TAILQ_FOREACH(pe, &delete_args, entry) {
9244 const char *branchname = pe->path;
9245 char *s;
9246 struct got_pathlist_entry *new;
9247 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9248 s = strdup(branchname);
9249 if (s == NULL) {
9250 error = got_error_from_errno("strdup");
9251 goto done;
9253 } else {
9254 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9255 error = got_error_from_errno("asprintf");
9256 goto done;
9259 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9260 if (error || new == NULL /* duplicate */)
9261 free(s);
9262 if (error)
9263 goto done;
9264 ndelete_branches++;
9267 if (nbranches == 0 && ndelete_branches == 0) {
9268 struct got_reference *head_ref;
9269 if (worktree)
9270 error = got_ref_open(&head_ref, repo,
9271 got_worktree_get_head_ref_name(worktree), 0);
9272 else
9273 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9274 if (error)
9275 goto done;
9276 if (got_ref_is_symbolic(head_ref)) {
9277 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9278 got_ref_close(head_ref);
9279 if (error)
9280 goto done;
9281 } else
9282 ref = head_ref;
9283 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9284 NULL);
9285 if (error)
9286 goto done;
9287 nbranches++;
9290 if (verbosity >= 0) {
9291 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9292 remote->name, proto, host,
9293 port ? ":" : "", port ? port : "",
9294 *server_path == '/' ? "" : "/", server_path);
9297 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9298 server_path, verbosity);
9299 if (error)
9300 goto done;
9302 memset(&spa, 0, sizeof(spa));
9303 spa.last_scaled_packsize[0] = '\0';
9304 spa.last_p_deltify = -1;
9305 spa.last_p_written = -1;
9306 spa.verbosity = verbosity;
9307 spa.delete_branches = &delete_branches;
9308 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9309 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9310 check_cancelled, NULL);
9311 if (spa.printed_something)
9312 putchar('\n');
9313 if (error)
9314 goto done;
9315 if (!spa.sent_something && verbosity >= 0)
9316 printf("Already up-to-date\n");
9317 done:
9318 if (sendpid > 0) {
9319 if (kill(sendpid, SIGTERM) == -1)
9320 error = got_error_from_errno("kill");
9321 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9322 error = got_error_from_errno("waitpid");
9324 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9325 error = got_error_from_errno("close");
9326 if (repo) {
9327 const struct got_error *close_err = got_repo_close(repo);
9328 if (error == NULL)
9329 error = close_err;
9331 if (worktree)
9332 got_worktree_close(worktree);
9333 if (pack_fds) {
9334 const struct got_error *pack_err =
9335 got_repo_pack_fds_close(pack_fds);
9336 if (error == NULL)
9337 error = pack_err;
9339 if (ref)
9340 got_ref_close(ref);
9341 got_pathlist_free(&branches);
9342 got_pathlist_free(&tags);
9343 got_ref_list_free(&all_branches);
9344 got_ref_list_free(&all_tags);
9345 got_pathlist_free(&delete_args);
9346 TAILQ_FOREACH(pe, &delete_branches, entry)
9347 free((char *)pe->path);
9348 got_pathlist_free(&delete_branches);
9349 free(cwd);
9350 free(repo_path);
9351 free(proto);
9352 free(host);
9353 free(port);
9354 free(server_path);
9355 free(repo_name);
9356 return error;
9359 __dead static void
9360 usage_cherrypick(void)
9362 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9363 exit(1);
9366 static const struct got_error *
9367 cmd_cherrypick(int argc, char *argv[])
9369 const struct got_error *error = NULL;
9370 struct got_worktree *worktree = NULL;
9371 struct got_repository *repo = NULL;
9372 char *cwd = NULL, *commit_id_str = NULL;
9373 struct got_object_id *commit_id = NULL;
9374 struct got_commit_object *commit = NULL;
9375 struct got_object_qid *pid;
9376 int ch;
9377 struct got_update_progress_arg upa;
9378 int *pack_fds = NULL;
9380 while ((ch = getopt(argc, argv, "")) != -1) {
9381 switch (ch) {
9382 default:
9383 usage_cherrypick();
9384 /* NOTREACHED */
9388 argc -= optind;
9389 argv += optind;
9391 #ifndef PROFILE
9392 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9393 "unveil", NULL) == -1)
9394 err(1, "pledge");
9395 #endif
9396 if (argc != 1)
9397 usage_cherrypick();
9399 cwd = getcwd(NULL, 0);
9400 if (cwd == NULL) {
9401 error = got_error_from_errno("getcwd");
9402 goto done;
9405 error = got_repo_pack_fds_open(&pack_fds);
9406 if (error != NULL)
9407 goto done;
9409 error = got_worktree_open(&worktree, cwd);
9410 if (error) {
9411 if (error->code == GOT_ERR_NOT_WORKTREE)
9412 error = wrap_not_worktree_error(error, "cherrypick",
9413 cwd);
9414 goto done;
9417 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9418 NULL, pack_fds);
9419 if (error != NULL)
9420 goto done;
9422 error = apply_unveil(got_repo_get_path(repo), 0,
9423 got_worktree_get_root_path(worktree));
9424 if (error)
9425 goto done;
9427 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9428 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9429 if (error)
9430 goto done;
9431 error = got_object_id_str(&commit_id_str, commit_id);
9432 if (error)
9433 goto done;
9435 error = got_object_open_as_commit(&commit, repo, commit_id);
9436 if (error)
9437 goto done;
9438 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9439 memset(&upa, 0, sizeof(upa));
9440 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9441 commit_id, repo, update_progress, &upa, check_cancelled,
9442 NULL);
9443 if (error != NULL)
9444 goto done;
9446 if (upa.did_something)
9447 printf("Merged commit %s\n", commit_id_str);
9448 print_merge_progress_stats(&upa);
9449 done:
9450 if (commit)
9451 got_object_commit_close(commit);
9452 free(commit_id_str);
9453 if (worktree)
9454 got_worktree_close(worktree);
9455 if (repo) {
9456 const struct got_error *close_err = got_repo_close(repo);
9457 if (error == NULL)
9458 error = close_err;
9460 if (pack_fds) {
9461 const struct got_error *pack_err =
9462 got_repo_pack_fds_close(pack_fds);
9463 if (error == NULL)
9464 error = pack_err;
9467 return error;
9470 __dead static void
9471 usage_backout(void)
9473 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9474 exit(1);
9477 static const struct got_error *
9478 cmd_backout(int argc, char *argv[])
9480 const struct got_error *error = NULL;
9481 struct got_worktree *worktree = NULL;
9482 struct got_repository *repo = NULL;
9483 char *cwd = NULL, *commit_id_str = NULL;
9484 struct got_object_id *commit_id = NULL;
9485 struct got_commit_object *commit = NULL;
9486 struct got_object_qid *pid;
9487 int ch;
9488 struct got_update_progress_arg upa;
9489 int *pack_fds = NULL;
9491 while ((ch = getopt(argc, argv, "")) != -1) {
9492 switch (ch) {
9493 default:
9494 usage_backout();
9495 /* NOTREACHED */
9499 argc -= optind;
9500 argv += optind;
9502 #ifndef PROFILE
9503 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9504 "unveil", NULL) == -1)
9505 err(1, "pledge");
9506 #endif
9507 if (argc != 1)
9508 usage_backout();
9510 cwd = getcwd(NULL, 0);
9511 if (cwd == NULL) {
9512 error = got_error_from_errno("getcwd");
9513 goto done;
9516 error = got_repo_pack_fds_open(&pack_fds);
9517 if (error != NULL)
9518 goto done;
9520 error = got_worktree_open(&worktree, cwd);
9521 if (error) {
9522 if (error->code == GOT_ERR_NOT_WORKTREE)
9523 error = wrap_not_worktree_error(error, "backout", cwd);
9524 goto done;
9527 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9528 NULL, pack_fds);
9529 if (error != NULL)
9530 goto done;
9532 error = apply_unveil(got_repo_get_path(repo), 0,
9533 got_worktree_get_root_path(worktree));
9534 if (error)
9535 goto done;
9537 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9538 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9539 if (error)
9540 goto done;
9541 error = got_object_id_str(&commit_id_str, commit_id);
9542 if (error)
9543 goto done;
9545 error = got_object_open_as_commit(&commit, repo, commit_id);
9546 if (error)
9547 goto done;
9548 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9549 if (pid == NULL) {
9550 error = got_error(GOT_ERR_ROOT_COMMIT);
9551 goto done;
9554 memset(&upa, 0, sizeof(upa));
9555 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9556 repo, update_progress, &upa, check_cancelled, NULL);
9557 if (error != NULL)
9558 goto done;
9560 if (upa.did_something)
9561 printf("Backed out commit %s\n", commit_id_str);
9562 print_merge_progress_stats(&upa);
9563 done:
9564 if (commit)
9565 got_object_commit_close(commit);
9566 free(commit_id_str);
9567 if (worktree)
9568 got_worktree_close(worktree);
9569 if (repo) {
9570 const struct got_error *close_err = got_repo_close(repo);
9571 if (error == NULL)
9572 error = close_err;
9574 if (pack_fds) {
9575 const struct got_error *pack_err =
9576 got_repo_pack_fds_close(pack_fds);
9577 if (error == NULL)
9578 error = pack_err;
9580 return error;
9583 __dead static void
9584 usage_rebase(void)
9586 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9587 exit(1);
9590 static void
9591 trim_logmsg(char *logmsg, int limit)
9593 char *nl;
9594 size_t len;
9596 len = strlen(logmsg);
9597 if (len > limit)
9598 len = limit;
9599 logmsg[len] = '\0';
9600 nl = strchr(logmsg, '\n');
9601 if (nl)
9602 *nl = '\0';
9605 static const struct got_error *
9606 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9608 const struct got_error *err;
9609 char *logmsg0 = NULL;
9610 const char *s;
9612 err = got_object_commit_get_logmsg(&logmsg0, commit);
9613 if (err)
9614 return err;
9616 s = logmsg0;
9617 while (isspace((unsigned char)s[0]))
9618 s++;
9620 *logmsg = strdup(s);
9621 if (*logmsg == NULL) {
9622 err = got_error_from_errno("strdup");
9623 goto done;
9626 trim_logmsg(*logmsg, limit);
9627 done:
9628 free(logmsg0);
9629 return err;
9632 static const struct got_error *
9633 show_rebase_merge_conflict(struct got_object_id *id,
9634 struct got_repository *repo)
9636 const struct got_error *err;
9637 struct got_commit_object *commit = NULL;
9638 char *id_str = NULL, *logmsg = NULL;
9640 err = got_object_open_as_commit(&commit, repo, id);
9641 if (err)
9642 return err;
9644 err = got_object_id_str(&id_str, id);
9645 if (err)
9646 goto done;
9648 id_str[12] = '\0';
9650 err = get_short_logmsg(&logmsg, 42, commit);
9651 if (err)
9652 goto done;
9654 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9655 done:
9656 free(id_str);
9657 got_object_commit_close(commit);
9658 free(logmsg);
9659 return err;
9662 static const struct got_error *
9663 show_rebase_progress(struct got_commit_object *commit,
9664 struct got_object_id *old_id, struct got_object_id *new_id)
9666 const struct got_error *err;
9667 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9669 err = got_object_id_str(&old_id_str, old_id);
9670 if (err)
9671 goto done;
9673 if (new_id) {
9674 err = got_object_id_str(&new_id_str, new_id);
9675 if (err)
9676 goto done;
9679 old_id_str[12] = '\0';
9680 if (new_id_str)
9681 new_id_str[12] = '\0';
9683 err = get_short_logmsg(&logmsg, 42, commit);
9684 if (err)
9685 goto done;
9687 printf("%s -> %s: %s\n", old_id_str,
9688 new_id_str ? new_id_str : "no-op change", logmsg);
9689 done:
9690 free(old_id_str);
9691 free(new_id_str);
9692 free(logmsg);
9693 return err;
9696 static const struct got_error *
9697 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9698 struct got_reference *branch, struct got_reference *new_base_branch,
9699 struct got_reference *tmp_branch, struct got_repository *repo,
9700 int create_backup)
9702 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9703 return got_worktree_rebase_complete(worktree, fileindex,
9704 new_base_branch, tmp_branch, branch, repo, create_backup);
9707 static const struct got_error *
9708 rebase_commit(struct got_pathlist_head *merged_paths,
9709 struct got_worktree *worktree, struct got_fileindex *fileindex,
9710 struct got_reference *tmp_branch, const char *committer,
9711 struct got_object_id *commit_id, struct got_repository *repo)
9713 const struct got_error *error;
9714 struct got_commit_object *commit;
9715 struct got_object_id *new_commit_id;
9717 error = got_object_open_as_commit(&commit, repo, commit_id);
9718 if (error)
9719 return error;
9721 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9722 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9723 repo);
9724 if (error) {
9725 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9726 goto done;
9727 error = show_rebase_progress(commit, commit_id, NULL);
9728 } else {
9729 error = show_rebase_progress(commit, commit_id, new_commit_id);
9730 free(new_commit_id);
9732 done:
9733 got_object_commit_close(commit);
9734 return error;
9737 struct check_path_prefix_arg {
9738 const char *path_prefix;
9739 size_t len;
9740 int errcode;
9743 static const struct got_error *
9744 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9745 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9746 struct got_object_id *id1, struct got_object_id *id2,
9747 const char *path1, const char *path2,
9748 mode_t mode1, mode_t mode2, struct got_repository *repo)
9750 struct check_path_prefix_arg *a = arg;
9752 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9753 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9754 return got_error(a->errcode);
9756 return NULL;
9759 static const struct got_error *
9760 check_path_prefix(struct got_object_id *parent_id,
9761 struct got_object_id *commit_id, const char *path_prefix,
9762 int errcode, struct got_repository *repo)
9764 const struct got_error *err;
9765 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9766 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9767 struct check_path_prefix_arg cpp_arg;
9769 if (got_path_is_root_dir(path_prefix))
9770 return NULL;
9772 err = got_object_open_as_commit(&commit, repo, commit_id);
9773 if (err)
9774 goto done;
9776 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9777 if (err)
9778 goto done;
9780 err = got_object_open_as_tree(&tree1, repo,
9781 got_object_commit_get_tree_id(parent_commit));
9782 if (err)
9783 goto done;
9785 err = got_object_open_as_tree(&tree2, repo,
9786 got_object_commit_get_tree_id(commit));
9787 if (err)
9788 goto done;
9790 cpp_arg.path_prefix = path_prefix;
9791 while (cpp_arg.path_prefix[0] == '/')
9792 cpp_arg.path_prefix++;
9793 cpp_arg.len = strlen(cpp_arg.path_prefix);
9794 cpp_arg.errcode = errcode;
9795 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9796 check_path_prefix_in_diff, &cpp_arg, 0);
9797 done:
9798 if (tree1)
9799 got_object_tree_close(tree1);
9800 if (tree2)
9801 got_object_tree_close(tree2);
9802 if (commit)
9803 got_object_commit_close(commit);
9804 if (parent_commit)
9805 got_object_commit_close(parent_commit);
9806 return err;
9809 static const struct got_error *
9810 collect_commits(struct got_object_id_queue *commits,
9811 struct got_object_id *initial_commit_id,
9812 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9813 const char *path_prefix, int path_prefix_errcode,
9814 struct got_repository *repo)
9816 const struct got_error *err = NULL;
9817 struct got_commit_graph *graph = NULL;
9818 struct got_object_id parent_id, commit_id;
9819 struct got_object_qid *qid;
9821 err = got_commit_graph_open(&graph, "/", 1);
9822 if (err)
9823 return err;
9825 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9826 check_cancelled, NULL);
9827 if (err)
9828 goto done;
9830 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9831 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9832 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9833 check_cancelled, NULL);
9834 if (err) {
9835 if (err->code == GOT_ERR_ITER_COMPLETED) {
9836 err = got_error_msg(GOT_ERR_ANCESTRY,
9837 "ran out of commits to rebase before "
9838 "youngest common ancestor commit has "
9839 "been reached?!?");
9841 goto done;
9842 } else {
9843 err = check_path_prefix(&parent_id, &commit_id,
9844 path_prefix, path_prefix_errcode, repo);
9845 if (err)
9846 goto done;
9848 err = got_object_qid_alloc(&qid, &commit_id);
9849 if (err)
9850 goto done;
9851 STAILQ_INSERT_HEAD(commits, qid, entry);
9853 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9856 done:
9857 got_commit_graph_close(graph);
9858 return err;
9861 static const struct got_error *
9862 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9864 const struct got_error *err = NULL;
9865 time_t committer_time;
9866 struct tm tm;
9867 char datebuf[11]; /* YYYY-MM-DD + NUL */
9868 char *author0 = NULL, *author, *smallerthan;
9869 char *logmsg0 = NULL, *logmsg, *newline;
9871 committer_time = got_object_commit_get_committer_time(commit);
9872 if (gmtime_r(&committer_time, &tm) == NULL)
9873 return got_error_from_errno("gmtime_r");
9874 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9875 return got_error(GOT_ERR_NO_SPACE);
9877 author0 = strdup(got_object_commit_get_author(commit));
9878 if (author0 == NULL)
9879 return got_error_from_errno("strdup");
9880 author = author0;
9881 smallerthan = strchr(author, '<');
9882 if (smallerthan && smallerthan[1] != '\0')
9883 author = smallerthan + 1;
9884 author[strcspn(author, "@>")] = '\0';
9886 err = got_object_commit_get_logmsg(&logmsg0, commit);
9887 if (err)
9888 goto done;
9889 logmsg = logmsg0;
9890 while (*logmsg == '\n')
9891 logmsg++;
9892 newline = strchr(logmsg, '\n');
9893 if (newline)
9894 *newline = '\0';
9896 if (asprintf(brief_str, "%s %s %s",
9897 datebuf, author, logmsg) == -1)
9898 err = got_error_from_errno("asprintf");
9899 done:
9900 free(author0);
9901 free(logmsg0);
9902 return err;
9905 static const struct got_error *
9906 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9907 struct got_repository *repo)
9909 const struct got_error *err;
9910 char *id_str;
9912 err = got_object_id_str(&id_str, id);
9913 if (err)
9914 return err;
9916 err = got_ref_delete(ref, repo);
9917 if (err)
9918 goto done;
9920 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9921 done:
9922 free(id_str);
9923 return err;
9926 static const struct got_error *
9927 print_backup_ref(const char *branch_name, const char *new_id_str,
9928 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9929 struct got_reflist_object_id_map *refs_idmap,
9930 struct got_repository *repo)
9932 const struct got_error *err = NULL;
9933 struct got_reflist_head *refs;
9934 char *refs_str = NULL;
9935 struct got_object_id *new_commit_id = NULL;
9936 struct got_commit_object *new_commit = NULL;
9937 char *new_commit_brief_str = NULL;
9938 struct got_object_id *yca_id = NULL;
9939 struct got_commit_object *yca_commit = NULL;
9940 char *yca_id_str = NULL, *yca_brief_str = NULL;
9941 char *custom_refs_str;
9943 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9944 return got_error_from_errno("asprintf");
9946 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
9947 0, 0, refs_idmap, custom_refs_str);
9948 if (err)
9949 goto done;
9951 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9952 if (err)
9953 goto done;
9955 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9956 if (refs) {
9957 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9958 if (err)
9959 goto done;
9962 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9963 if (err)
9964 goto done;
9966 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9967 if (err)
9968 goto done;
9970 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9971 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9972 if (err)
9973 goto done;
9975 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9976 refs_str ? " (" : "", refs_str ? refs_str : "",
9977 refs_str ? ")" : "", new_commit_brief_str);
9978 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9979 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9980 free(refs_str);
9981 refs_str = NULL;
9983 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9984 if (err)
9985 goto done;
9987 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9988 if (err)
9989 goto done;
9991 err = got_object_id_str(&yca_id_str, yca_id);
9992 if (err)
9993 goto done;
9995 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9996 if (refs) {
9997 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9998 if (err)
9999 goto done;
10001 printf("history forked at %s%s%s%s\n %s\n",
10002 yca_id_str,
10003 refs_str ? " (" : "", refs_str ? refs_str : "",
10004 refs_str ? ")" : "", yca_brief_str);
10006 done:
10007 free(custom_refs_str);
10008 free(new_commit_id);
10009 free(refs_str);
10010 free(yca_id);
10011 free(yca_id_str);
10012 free(yca_brief_str);
10013 if (new_commit)
10014 got_object_commit_close(new_commit);
10015 if (yca_commit)
10016 got_object_commit_close(yca_commit);
10018 return NULL;
10021 static const struct got_error *
10022 process_backup_refs(const char *backup_ref_prefix,
10023 const char *wanted_branch_name,
10024 int delete, struct got_repository *repo)
10026 const struct got_error *err;
10027 struct got_reflist_head refs, backup_refs;
10028 struct got_reflist_entry *re;
10029 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10030 struct got_object_id *old_commit_id = NULL;
10031 char *branch_name = NULL;
10032 struct got_commit_object *old_commit = NULL;
10033 struct got_reflist_object_id_map *refs_idmap = NULL;
10034 int wanted_branch_found = 0;
10036 TAILQ_INIT(&refs);
10037 TAILQ_INIT(&backup_refs);
10039 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10040 if (err)
10041 return err;
10043 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10044 if (err)
10045 goto done;
10047 if (wanted_branch_name) {
10048 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10049 wanted_branch_name += 11;
10052 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10053 got_ref_cmp_by_commit_timestamp_descending, repo);
10054 if (err)
10055 goto done;
10057 TAILQ_FOREACH(re, &backup_refs, entry) {
10058 const char *refname = got_ref_get_name(re->ref);
10059 char *slash;
10061 err = check_cancelled(NULL);
10062 if (err)
10063 break;
10065 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10066 if (err)
10067 break;
10069 err = got_object_open_as_commit(&old_commit, repo,
10070 old_commit_id);
10071 if (err)
10072 break;
10074 if (strncmp(backup_ref_prefix, refname,
10075 backup_ref_prefix_len) == 0)
10076 refname += backup_ref_prefix_len;
10078 while (refname[0] == '/')
10079 refname++;
10081 branch_name = strdup(refname);
10082 if (branch_name == NULL) {
10083 err = got_error_from_errno("strdup");
10084 break;
10086 slash = strrchr(branch_name, '/');
10087 if (slash) {
10088 *slash = '\0';
10089 refname += strlen(branch_name) + 1;
10092 if (wanted_branch_name == NULL ||
10093 strcmp(wanted_branch_name, branch_name) == 0) {
10094 wanted_branch_found = 1;
10095 if (delete) {
10096 err = delete_backup_ref(re->ref,
10097 old_commit_id, repo);
10098 } else {
10099 err = print_backup_ref(branch_name, refname,
10100 old_commit_id, old_commit, refs_idmap,
10101 repo);
10103 if (err)
10104 break;
10107 free(old_commit_id);
10108 old_commit_id = NULL;
10109 free(branch_name);
10110 branch_name = NULL;
10111 got_object_commit_close(old_commit);
10112 old_commit = NULL;
10115 if (wanted_branch_name && !wanted_branch_found) {
10116 err = got_error_fmt(GOT_ERR_NOT_REF,
10117 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10119 done:
10120 if (refs_idmap)
10121 got_reflist_object_id_map_free(refs_idmap);
10122 got_ref_list_free(&refs);
10123 got_ref_list_free(&backup_refs);
10124 free(old_commit_id);
10125 free(branch_name);
10126 if (old_commit)
10127 got_object_commit_close(old_commit);
10128 return err;
10131 static const struct got_error *
10132 abort_progress(void *arg, unsigned char status, const char *path)
10135 * Unversioned files should not clutter progress output when
10136 * an operation is aborted.
10138 if (status == GOT_STATUS_UNVERSIONED)
10139 return NULL;
10141 return update_progress(arg, status, path);
10144 static const struct got_error *
10145 cmd_rebase(int argc, char *argv[])
10147 const struct got_error *error = NULL;
10148 struct got_worktree *worktree = NULL;
10149 struct got_repository *repo = NULL;
10150 struct got_fileindex *fileindex = NULL;
10151 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10152 struct got_reference *branch = NULL;
10153 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10154 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10155 struct got_object_id *resume_commit_id = NULL;
10156 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10157 struct got_object_id *head_commit_id = NULL;
10158 struct got_reference *head_ref = NULL;
10159 struct got_commit_object *commit = NULL;
10160 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10161 int histedit_in_progress = 0, merge_in_progress = 0;
10162 int create_backup = 1, list_backups = 0, delete_backups = 0;
10163 struct got_object_id_queue commits;
10164 struct got_pathlist_head merged_paths;
10165 const struct got_object_id_queue *parent_ids;
10166 struct got_object_qid *qid, *pid;
10167 struct got_update_progress_arg upa;
10168 int *pack_fds = NULL;
10170 STAILQ_INIT(&commits);
10171 TAILQ_INIT(&merged_paths);
10172 memset(&upa, 0, sizeof(upa));
10174 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10175 switch (ch) {
10176 case 'a':
10177 abort_rebase = 1;
10178 break;
10179 case 'c':
10180 continue_rebase = 1;
10181 break;
10182 case 'l':
10183 list_backups = 1;
10184 break;
10185 case 'X':
10186 delete_backups = 1;
10187 break;
10188 default:
10189 usage_rebase();
10190 /* NOTREACHED */
10194 argc -= optind;
10195 argv += optind;
10197 #ifndef PROFILE
10198 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10199 "unveil", NULL) == -1)
10200 err(1, "pledge");
10201 #endif
10202 if (list_backups) {
10203 if (abort_rebase)
10204 option_conflict('l', 'a');
10205 if (continue_rebase)
10206 option_conflict('l', 'c');
10207 if (delete_backups)
10208 option_conflict('l', 'X');
10209 if (argc != 0 && argc != 1)
10210 usage_rebase();
10211 } else if (delete_backups) {
10212 if (abort_rebase)
10213 option_conflict('X', 'a');
10214 if (continue_rebase)
10215 option_conflict('X', 'c');
10216 if (list_backups)
10217 option_conflict('l', 'X');
10218 if (argc != 0 && argc != 1)
10219 usage_rebase();
10220 } else {
10221 if (abort_rebase && continue_rebase)
10222 usage_rebase();
10223 else if (abort_rebase || continue_rebase) {
10224 if (argc != 0)
10225 usage_rebase();
10226 } else if (argc != 1)
10227 usage_rebase();
10230 cwd = getcwd(NULL, 0);
10231 if (cwd == NULL) {
10232 error = got_error_from_errno("getcwd");
10233 goto done;
10236 error = got_repo_pack_fds_open(&pack_fds);
10237 if (error != NULL)
10238 goto done;
10240 error = got_worktree_open(&worktree, cwd);
10241 if (error) {
10242 if (list_backups || delete_backups) {
10243 if (error->code != GOT_ERR_NOT_WORKTREE)
10244 goto done;
10245 } else {
10246 if (error->code == GOT_ERR_NOT_WORKTREE)
10247 error = wrap_not_worktree_error(error,
10248 "rebase", cwd);
10249 goto done;
10253 error = get_gitconfig_path(&gitconfig_path);
10254 if (error)
10255 goto done;
10256 error = got_repo_open(&repo,
10257 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10258 gitconfig_path, pack_fds);
10259 if (error != NULL)
10260 goto done;
10262 error = get_author(&committer, repo, worktree);
10263 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10264 goto done;
10266 error = apply_unveil(got_repo_get_path(repo), 0,
10267 worktree ? got_worktree_get_root_path(worktree) : NULL);
10268 if (error)
10269 goto done;
10271 if (list_backups || delete_backups) {
10272 error = process_backup_refs(
10273 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10274 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10275 goto done; /* nothing else to do */
10278 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10279 worktree);
10280 if (error)
10281 goto done;
10282 if (histedit_in_progress) {
10283 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10284 goto done;
10287 error = got_worktree_merge_in_progress(&merge_in_progress,
10288 worktree, repo);
10289 if (error)
10290 goto done;
10291 if (merge_in_progress) {
10292 error = got_error(GOT_ERR_MERGE_BUSY);
10293 goto done;
10296 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10297 if (error)
10298 goto done;
10300 if (abort_rebase) {
10301 if (!rebase_in_progress) {
10302 error = got_error(GOT_ERR_NOT_REBASING);
10303 goto done;
10305 error = got_worktree_rebase_continue(&resume_commit_id,
10306 &new_base_branch, &tmp_branch, &branch, &fileindex,
10307 worktree, repo);
10308 if (error)
10309 goto done;
10310 printf("Switching work tree to %s\n",
10311 got_ref_get_symref_target(new_base_branch));
10312 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10313 new_base_branch, abort_progress, &upa);
10314 if (error)
10315 goto done;
10316 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10317 print_merge_progress_stats(&upa);
10318 goto done; /* nothing else to do */
10321 if (continue_rebase) {
10322 if (!rebase_in_progress) {
10323 error = got_error(GOT_ERR_NOT_REBASING);
10324 goto done;
10326 error = got_worktree_rebase_continue(&resume_commit_id,
10327 &new_base_branch, &tmp_branch, &branch, &fileindex,
10328 worktree, repo);
10329 if (error)
10330 goto done;
10332 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10333 committer, resume_commit_id, repo);
10334 if (error)
10335 goto done;
10337 yca_id = got_object_id_dup(resume_commit_id);
10338 if (yca_id == NULL) {
10339 error = got_error_from_errno("got_object_id_dup");
10340 goto done;
10342 } else {
10343 error = got_ref_open(&branch, repo, argv[0], 0);
10344 if (error != NULL)
10345 goto done;
10346 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10347 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10348 "will not rebase a branch which lives outside "
10349 "the \"refs/heads/\" reference namespace");
10350 goto done;
10354 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10355 if (error)
10356 goto done;
10358 if (!continue_rebase) {
10359 struct got_object_id *base_commit_id;
10361 error = got_ref_open(&head_ref, repo,
10362 got_worktree_get_head_ref_name(worktree), 0);
10363 if (error)
10364 goto done;
10365 error = got_ref_resolve(&head_commit_id, repo, head_ref);
10366 if (error)
10367 goto done;
10368 base_commit_id = got_worktree_get_base_commit_id(worktree);
10369 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
10370 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
10371 goto done;
10374 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10375 base_commit_id, branch_head_commit_id, 1, repo,
10376 check_cancelled, NULL);
10377 if (error)
10378 goto done;
10379 if (yca_id == NULL) {
10380 error = got_error_msg(GOT_ERR_ANCESTRY,
10381 "specified branch shares no common ancestry "
10382 "with work tree's branch");
10383 goto done;
10386 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10387 if (error) {
10388 if (error->code != GOT_ERR_ANCESTRY)
10389 goto done;
10390 error = NULL;
10391 } else {
10392 struct got_pathlist_head paths;
10393 printf("%s is already based on %s\n",
10394 got_ref_get_name(branch),
10395 got_worktree_get_head_ref_name(worktree));
10396 error = switch_head_ref(branch, branch_head_commit_id,
10397 worktree, repo);
10398 if (error)
10399 goto done;
10400 error = got_worktree_set_base_commit_id(worktree, repo,
10401 branch_head_commit_id);
10402 if (error)
10403 goto done;
10404 TAILQ_INIT(&paths);
10405 error = got_pathlist_append(&paths, "", NULL);
10406 if (error)
10407 goto done;
10408 error = got_worktree_checkout_files(worktree,
10409 &paths, repo, update_progress, &upa,
10410 check_cancelled, NULL);
10411 got_pathlist_free(&paths);
10412 if (error)
10413 goto done;
10414 if (upa.did_something) {
10415 char *id_str;
10416 error = got_object_id_str(&id_str,
10417 branch_head_commit_id);
10418 if (error)
10419 goto done;
10420 printf("Updated to %s: %s\n",
10421 got_worktree_get_head_ref_name(worktree),
10422 id_str);
10423 free(id_str);
10424 } else
10425 printf("Already up-to-date\n");
10426 print_update_progress_stats(&upa);
10427 goto done;
10431 commit_id = branch_head_commit_id;
10432 error = got_object_open_as_commit(&commit, repo, commit_id);
10433 if (error)
10434 goto done;
10436 parent_ids = got_object_commit_get_parent_ids(commit);
10437 pid = STAILQ_FIRST(parent_ids);
10438 if (pid == NULL) {
10439 error = got_error(GOT_ERR_EMPTY_REBASE);
10440 goto done;
10442 error = collect_commits(&commits, commit_id, &pid->id,
10443 yca_id, got_worktree_get_path_prefix(worktree),
10444 GOT_ERR_REBASE_PATH, repo);
10445 got_object_commit_close(commit);
10446 commit = NULL;
10447 if (error)
10448 goto done;
10450 if (!continue_rebase) {
10451 error = got_worktree_rebase_prepare(&new_base_branch,
10452 &tmp_branch, &fileindex, worktree, branch, repo);
10453 if (error)
10454 goto done;
10457 if (STAILQ_EMPTY(&commits)) {
10458 if (continue_rebase) {
10459 error = rebase_complete(worktree, fileindex,
10460 branch, new_base_branch, tmp_branch, repo,
10461 create_backup);
10462 goto done;
10463 } else {
10464 /* Fast-forward the reference of the branch. */
10465 struct got_object_id *new_head_commit_id;
10466 char *id_str;
10467 error = got_ref_resolve(&new_head_commit_id, repo,
10468 new_base_branch);
10469 if (error)
10470 goto done;
10471 error = got_object_id_str(&id_str, new_head_commit_id);
10472 if (error)
10473 goto done;
10474 printf("Forwarding %s to commit %s\n",
10475 got_ref_get_name(branch), id_str);
10476 free(id_str);
10477 error = got_ref_change_ref(branch,
10478 new_head_commit_id);
10479 if (error)
10480 goto done;
10481 /* No backup needed since objects did not change. */
10482 create_backup = 0;
10486 pid = NULL;
10487 STAILQ_FOREACH(qid, &commits, entry) {
10489 commit_id = &qid->id;
10490 parent_id = pid ? &pid->id : yca_id;
10491 pid = qid;
10493 memset(&upa, 0, sizeof(upa));
10494 error = got_worktree_rebase_merge_files(&merged_paths,
10495 worktree, fileindex, parent_id, commit_id, repo,
10496 update_progress, &upa, check_cancelled, NULL);
10497 if (error)
10498 goto done;
10500 print_merge_progress_stats(&upa);
10501 if (upa.conflicts > 0 || upa.missing > 0 ||
10502 upa.not_deleted > 0 || upa.unversioned > 0) {
10503 if (upa.conflicts > 0) {
10504 error = show_rebase_merge_conflict(&qid->id,
10505 repo);
10506 if (error)
10507 goto done;
10509 got_worktree_rebase_pathlist_free(&merged_paths);
10510 break;
10513 error = rebase_commit(&merged_paths, worktree, fileindex,
10514 tmp_branch, committer, commit_id, repo);
10515 got_worktree_rebase_pathlist_free(&merged_paths);
10516 if (error)
10517 goto done;
10520 if (upa.conflicts > 0 || upa.missing > 0 ||
10521 upa.not_deleted > 0 || upa.unversioned > 0) {
10522 error = got_worktree_rebase_postpone(worktree, fileindex);
10523 if (error)
10524 goto done;
10525 if (upa.conflicts > 0 && upa.missing == 0 &&
10526 upa.not_deleted == 0 && upa.unversioned == 0) {
10527 error = got_error_msg(GOT_ERR_CONFLICTS,
10528 "conflicts must be resolved before rebasing "
10529 "can continue");
10530 } else if (upa.conflicts > 0) {
10531 error = got_error_msg(GOT_ERR_CONFLICTS,
10532 "conflicts must be resolved before rebasing "
10533 "can continue; changes destined for some "
10534 "files were not yet merged and should be "
10535 "merged manually if required before the "
10536 "rebase operation is continued");
10537 } else {
10538 error = got_error_msg(GOT_ERR_CONFLICTS,
10539 "changes destined for some files were not "
10540 "yet merged and should be merged manually "
10541 "if required before the rebase operation "
10542 "is continued");
10544 } else
10545 error = rebase_complete(worktree, fileindex, branch,
10546 new_base_branch, tmp_branch, repo, create_backup);
10547 done:
10548 free(cwd);
10549 free(committer);
10550 free(gitconfig_path);
10551 got_object_id_queue_free(&commits);
10552 free(branch_head_commit_id);
10553 free(resume_commit_id);
10554 free(head_commit_id);
10555 free(yca_id);
10556 if (commit)
10557 got_object_commit_close(commit);
10558 if (branch)
10559 got_ref_close(branch);
10560 if (new_base_branch)
10561 got_ref_close(new_base_branch);
10562 if (tmp_branch)
10563 got_ref_close(tmp_branch);
10564 if (head_ref)
10565 got_ref_close(head_ref);
10566 if (worktree)
10567 got_worktree_close(worktree);
10568 if (repo) {
10569 const struct got_error *close_err = got_repo_close(repo);
10570 if (error == NULL)
10571 error = close_err;
10573 if (pack_fds) {
10574 const struct got_error *pack_err =
10575 got_repo_pack_fds_close(pack_fds);
10576 if (error == NULL)
10577 error = pack_err;
10579 return error;
10582 __dead static void
10583 usage_histedit(void)
10585 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10586 "[branch]\n", getprogname());
10587 exit(1);
10590 #define GOT_HISTEDIT_PICK 'p'
10591 #define GOT_HISTEDIT_EDIT 'e'
10592 #define GOT_HISTEDIT_FOLD 'f'
10593 #define GOT_HISTEDIT_DROP 'd'
10594 #define GOT_HISTEDIT_MESG 'm'
10596 static const struct got_histedit_cmd {
10597 unsigned char code;
10598 const char *name;
10599 const char *desc;
10600 } got_histedit_cmds[] = {
10601 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10602 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10603 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10604 "be used" },
10605 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10606 { GOT_HISTEDIT_MESG, "mesg",
10607 "single-line log message for commit above (open editor if empty)" },
10610 struct got_histedit_list_entry {
10611 TAILQ_ENTRY(got_histedit_list_entry) entry;
10612 struct got_object_id *commit_id;
10613 const struct got_histedit_cmd *cmd;
10614 char *logmsg;
10616 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10618 static const struct got_error *
10619 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10620 FILE *f, struct got_repository *repo)
10622 const struct got_error *err = NULL;
10623 char *logmsg = NULL, *id_str = NULL;
10624 struct got_commit_object *commit = NULL;
10625 int n;
10627 err = got_object_open_as_commit(&commit, repo, commit_id);
10628 if (err)
10629 goto done;
10631 err = get_short_logmsg(&logmsg, 34, commit);
10632 if (err)
10633 goto done;
10635 err = got_object_id_str(&id_str, commit_id);
10636 if (err)
10637 goto done;
10639 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10640 if (n < 0)
10641 err = got_ferror(f, GOT_ERR_IO);
10642 done:
10643 if (commit)
10644 got_object_commit_close(commit);
10645 free(id_str);
10646 free(logmsg);
10647 return err;
10650 static const struct got_error *
10651 histedit_write_commit_list(struct got_object_id_queue *commits,
10652 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10653 struct got_repository *repo)
10655 const struct got_error *err = NULL;
10656 struct got_object_qid *qid;
10657 const char *histedit_cmd = NULL;
10659 if (STAILQ_EMPTY(commits))
10660 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10662 STAILQ_FOREACH(qid, commits, entry) {
10663 histedit_cmd = got_histedit_cmds[0].name;
10664 if (edit_only)
10665 histedit_cmd = "edit";
10666 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10667 histedit_cmd = "fold";
10668 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10669 if (err)
10670 break;
10671 if (edit_logmsg_only) {
10672 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10673 if (n < 0) {
10674 err = got_ferror(f, GOT_ERR_IO);
10675 break;
10680 return err;
10683 static const struct got_error *
10684 write_cmd_list(FILE *f, const char *branch_name,
10685 struct got_object_id_queue *commits)
10687 const struct got_error *err = NULL;
10688 size_t i;
10689 int n;
10690 char *id_str;
10691 struct got_object_qid *qid;
10693 qid = STAILQ_FIRST(commits);
10694 err = got_object_id_str(&id_str, &qid->id);
10695 if (err)
10696 return err;
10698 n = fprintf(f,
10699 "# Editing the history of branch '%s' starting at\n"
10700 "# commit %s\n"
10701 "# Commits will be processed in order from top to "
10702 "bottom of this file.\n", branch_name, id_str);
10703 if (n < 0) {
10704 err = got_ferror(f, GOT_ERR_IO);
10705 goto done;
10708 n = fprintf(f, "# Available histedit commands:\n");
10709 if (n < 0) {
10710 err = got_ferror(f, GOT_ERR_IO);
10711 goto done;
10714 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10715 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10716 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10717 cmd->desc);
10718 if (n < 0) {
10719 err = got_ferror(f, GOT_ERR_IO);
10720 break;
10723 done:
10724 free(id_str);
10725 return err;
10728 static const struct got_error *
10729 histedit_syntax_error(int lineno)
10731 static char msg[42];
10732 int ret;
10734 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10735 lineno);
10736 if (ret < 0 || (size_t)ret >= sizeof(msg))
10737 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10739 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10742 static const struct got_error *
10743 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10744 char *logmsg, struct got_repository *repo)
10746 const struct got_error *err;
10747 struct got_commit_object *folded_commit = NULL;
10748 char *id_str, *folded_logmsg = NULL;
10750 err = got_object_id_str(&id_str, hle->commit_id);
10751 if (err)
10752 return err;
10754 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10755 if (err)
10756 goto done;
10758 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10759 if (err)
10760 goto done;
10761 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10762 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10763 folded_logmsg) == -1) {
10764 err = got_error_from_errno("asprintf");
10766 done:
10767 if (folded_commit)
10768 got_object_commit_close(folded_commit);
10769 free(id_str);
10770 free(folded_logmsg);
10771 return err;
10774 static struct got_histedit_list_entry *
10775 get_folded_commits(struct got_histedit_list_entry *hle)
10777 struct got_histedit_list_entry *prev, *folded = NULL;
10779 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10780 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10781 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10782 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10783 folded = prev;
10784 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10787 return folded;
10790 static const struct got_error *
10791 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10792 struct got_repository *repo)
10794 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10795 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10796 const struct got_error *err = NULL;
10797 struct got_commit_object *commit = NULL;
10798 int logmsg_len;
10799 int fd;
10800 struct got_histedit_list_entry *folded = NULL;
10802 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10803 if (err)
10804 return err;
10806 folded = get_folded_commits(hle);
10807 if (folded) {
10808 while (folded != hle) {
10809 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10810 folded = TAILQ_NEXT(folded, entry);
10811 continue;
10813 err = append_folded_commit_msg(&new_msg, folded,
10814 logmsg, repo);
10815 if (err)
10816 goto done;
10817 free(logmsg);
10818 logmsg = new_msg;
10819 folded = TAILQ_NEXT(folded, entry);
10823 err = got_object_id_str(&id_str, hle->commit_id);
10824 if (err)
10825 goto done;
10826 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10827 if (err)
10828 goto done;
10829 logmsg_len = asprintf(&new_msg,
10830 "%s\n# original log message of commit %s: %s",
10831 logmsg ? logmsg : "", id_str, orig_logmsg);
10832 if (logmsg_len == -1) {
10833 err = got_error_from_errno("asprintf");
10834 goto done;
10836 free(logmsg);
10837 logmsg = new_msg;
10839 err = got_object_id_str(&id_str, hle->commit_id);
10840 if (err)
10841 goto done;
10843 err = got_opentemp_named_fd(&logmsg_path, &fd,
10844 GOT_TMPDIR_STR "/got-logmsg", "");
10845 if (err)
10846 goto done;
10848 write(fd, logmsg, logmsg_len);
10849 close(fd);
10851 err = get_editor(&editor);
10852 if (err)
10853 goto done;
10855 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10856 logmsg_len, 0);
10857 if (err) {
10858 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10859 goto done;
10860 err = NULL;
10861 hle->logmsg = strdup(new_msg);
10862 if (hle->logmsg == NULL)
10863 err = got_error_from_errno("strdup");
10865 done:
10866 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10867 err = got_error_from_errno2("unlink", logmsg_path);
10868 free(logmsg_path);
10869 free(logmsg);
10870 free(orig_logmsg);
10871 free(editor);
10872 if (commit)
10873 got_object_commit_close(commit);
10874 return err;
10877 static const struct got_error *
10878 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10879 FILE *f, struct got_repository *repo)
10881 const struct got_error *err = NULL;
10882 char *line = NULL, *p, *end;
10883 size_t i, size;
10884 ssize_t len;
10885 int lineno = 0, lastcmd = -1;
10886 const struct got_histedit_cmd *cmd;
10887 struct got_object_id *commit_id = NULL;
10888 struct got_histedit_list_entry *hle = NULL;
10890 for (;;) {
10891 len = getline(&line, &size, f);
10892 if (len == -1) {
10893 const struct got_error *getline_err;
10894 if (feof(f))
10895 break;
10896 getline_err = got_error_from_errno("getline");
10897 err = got_ferror(f, getline_err->code);
10898 break;
10900 lineno++;
10901 p = line;
10902 while (isspace((unsigned char)p[0]))
10903 p++;
10904 if (p[0] == '#' || p[0] == '\0') {
10905 free(line);
10906 line = NULL;
10907 continue;
10909 cmd = NULL;
10910 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10911 cmd = &got_histedit_cmds[i];
10912 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10913 isspace((unsigned char)p[strlen(cmd->name)])) {
10914 p += strlen(cmd->name);
10915 break;
10917 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10918 p++;
10919 break;
10922 if (i == nitems(got_histedit_cmds)) {
10923 err = histedit_syntax_error(lineno);
10924 break;
10926 while (isspace((unsigned char)p[0]))
10927 p++;
10928 if (cmd->code == GOT_HISTEDIT_MESG) {
10929 if (lastcmd != GOT_HISTEDIT_PICK &&
10930 lastcmd != GOT_HISTEDIT_EDIT) {
10931 err = got_error(GOT_ERR_HISTEDIT_CMD);
10932 break;
10934 if (p[0] == '\0') {
10935 err = histedit_edit_logmsg(hle, repo);
10936 if (err)
10937 break;
10938 } else {
10939 hle->logmsg = strdup(p);
10940 if (hle->logmsg == NULL) {
10941 err = got_error_from_errno("strdup");
10942 break;
10945 free(line);
10946 line = NULL;
10947 lastcmd = cmd->code;
10948 continue;
10949 } else {
10950 end = p;
10951 while (end[0] && !isspace((unsigned char)end[0]))
10952 end++;
10953 *end = '\0';
10955 err = got_object_resolve_id_str(&commit_id, repo, p);
10956 if (err) {
10957 /* override error code */
10958 err = histedit_syntax_error(lineno);
10959 break;
10962 hle = malloc(sizeof(*hle));
10963 if (hle == NULL) {
10964 err = got_error_from_errno("malloc");
10965 break;
10967 hle->cmd = cmd;
10968 hle->commit_id = commit_id;
10969 hle->logmsg = NULL;
10970 commit_id = NULL;
10971 free(line);
10972 line = NULL;
10973 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10974 lastcmd = cmd->code;
10977 free(line);
10978 free(commit_id);
10979 return err;
10982 static const struct got_error *
10983 histedit_check_script(struct got_histedit_list *histedit_cmds,
10984 struct got_object_id_queue *commits, struct got_repository *repo)
10986 const struct got_error *err = NULL;
10987 struct got_object_qid *qid;
10988 struct got_histedit_list_entry *hle;
10989 static char msg[92];
10990 char *id_str;
10992 if (TAILQ_EMPTY(histedit_cmds))
10993 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10994 "histedit script contains no commands");
10995 if (STAILQ_EMPTY(commits))
10996 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10998 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10999 struct got_histedit_list_entry *hle2;
11000 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11001 if (hle == hle2)
11002 continue;
11003 if (got_object_id_cmp(hle->commit_id,
11004 hle2->commit_id) != 0)
11005 continue;
11006 err = got_object_id_str(&id_str, hle->commit_id);
11007 if (err)
11008 return err;
11009 snprintf(msg, sizeof(msg), "commit %s is listed "
11010 "more than once in histedit script", id_str);
11011 free(id_str);
11012 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11016 STAILQ_FOREACH(qid, commits, entry) {
11017 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11018 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11019 break;
11021 if (hle == NULL) {
11022 err = got_object_id_str(&id_str, &qid->id);
11023 if (err)
11024 return err;
11025 snprintf(msg, sizeof(msg),
11026 "commit %s missing from histedit script", id_str);
11027 free(id_str);
11028 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11032 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11033 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11034 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11035 "last commit in histedit script cannot be folded");
11037 return NULL;
11040 static const struct got_error *
11041 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11042 const char *path, struct got_object_id_queue *commits,
11043 struct got_repository *repo)
11045 const struct got_error *err = NULL;
11046 char *editor;
11047 FILE *f = NULL;
11049 err = get_editor(&editor);
11050 if (err)
11051 return err;
11053 if (spawn_editor(editor, path) == -1) {
11054 err = got_error_from_errno("failed spawning editor");
11055 goto done;
11058 f = fopen(path, "re");
11059 if (f == NULL) {
11060 err = got_error_from_errno("fopen");
11061 goto done;
11063 err = histedit_parse_list(histedit_cmds, f, repo);
11064 if (err)
11065 goto done;
11067 err = histedit_check_script(histedit_cmds, commits, repo);
11068 done:
11069 if (f && fclose(f) == EOF && err == NULL)
11070 err = got_error_from_errno("fclose");
11071 free(editor);
11072 return err;
11075 static const struct got_error *
11076 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11077 struct got_object_id_queue *, const char *, const char *,
11078 struct got_repository *);
11080 static const struct got_error *
11081 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11082 struct got_object_id_queue *commits, const char *branch_name,
11083 int edit_logmsg_only, int fold_only, int edit_only,
11084 struct got_repository *repo)
11086 const struct got_error *err;
11087 FILE *f = NULL;
11088 char *path = NULL;
11090 err = got_opentemp_named(&path, &f, "got-histedit", "");
11091 if (err)
11092 return err;
11094 err = write_cmd_list(f, branch_name, commits);
11095 if (err)
11096 goto done;
11098 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11099 fold_only, edit_only, repo);
11100 if (err)
11101 goto done;
11103 if (edit_logmsg_only || fold_only || edit_only) {
11104 rewind(f);
11105 err = histedit_parse_list(histedit_cmds, f, repo);
11106 } else {
11107 if (fclose(f) == EOF) {
11108 err = got_error_from_errno("fclose");
11109 goto done;
11111 f = NULL;
11112 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11113 if (err) {
11114 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11115 err->code != GOT_ERR_HISTEDIT_CMD)
11116 goto done;
11117 err = histedit_edit_list_retry(histedit_cmds, err,
11118 commits, path, branch_name, repo);
11121 done:
11122 if (f && fclose(f) == EOF && err == NULL)
11123 err = got_error_from_errno("fclose");
11124 if (path && unlink(path) != 0 && err == NULL)
11125 err = got_error_from_errno2("unlink", path);
11126 free(path);
11127 return err;
11130 static const struct got_error *
11131 histedit_save_list(struct got_histedit_list *histedit_cmds,
11132 struct got_worktree *worktree, struct got_repository *repo)
11134 const struct got_error *err = NULL;
11135 char *path = NULL;
11136 FILE *f = NULL;
11137 struct got_histedit_list_entry *hle;
11138 struct got_commit_object *commit = NULL;
11140 err = got_worktree_get_histedit_script_path(&path, worktree);
11141 if (err)
11142 return err;
11144 f = fopen(path, "we");
11145 if (f == NULL) {
11146 err = got_error_from_errno2("fopen", path);
11147 goto done;
11149 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11150 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11151 repo);
11152 if (err)
11153 break;
11155 if (hle->logmsg) {
11156 int n = fprintf(f, "%c %s\n",
11157 GOT_HISTEDIT_MESG, hle->logmsg);
11158 if (n < 0) {
11159 err = got_ferror(f, GOT_ERR_IO);
11160 break;
11164 done:
11165 if (f && fclose(f) == EOF && err == NULL)
11166 err = got_error_from_errno("fclose");
11167 free(path);
11168 if (commit)
11169 got_object_commit_close(commit);
11170 return err;
11173 static void
11174 histedit_free_list(struct got_histedit_list *histedit_cmds)
11176 struct got_histedit_list_entry *hle;
11178 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11179 TAILQ_REMOVE(histedit_cmds, hle, entry);
11180 free(hle);
11184 static const struct got_error *
11185 histedit_load_list(struct got_histedit_list *histedit_cmds,
11186 const char *path, struct got_repository *repo)
11188 const struct got_error *err = NULL;
11189 FILE *f = NULL;
11191 f = fopen(path, "re");
11192 if (f == NULL) {
11193 err = got_error_from_errno2("fopen", path);
11194 goto done;
11197 err = histedit_parse_list(histedit_cmds, f, repo);
11198 done:
11199 if (f && fclose(f) == EOF && err == NULL)
11200 err = got_error_from_errno("fclose");
11201 return err;
11204 static const struct got_error *
11205 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11206 const struct got_error *edit_err, struct got_object_id_queue *commits,
11207 const char *path, const char *branch_name, struct got_repository *repo)
11209 const struct got_error *err = NULL, *prev_err = edit_err;
11210 int resp = ' ';
11212 while (resp != 'c' && resp != 'r' && resp != 'a') {
11213 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11214 "or (a)bort: ", getprogname(), prev_err->msg);
11215 resp = getchar();
11216 if (resp == '\n')
11217 resp = getchar();
11218 if (resp == 'c') {
11219 histedit_free_list(histedit_cmds);
11220 err = histedit_run_editor(histedit_cmds, path, commits,
11221 repo);
11222 if (err) {
11223 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11224 err->code != GOT_ERR_HISTEDIT_CMD)
11225 break;
11226 prev_err = err;
11227 resp = ' ';
11228 continue;
11230 break;
11231 } else if (resp == 'r') {
11232 histedit_free_list(histedit_cmds);
11233 err = histedit_edit_script(histedit_cmds,
11234 commits, branch_name, 0, 0, 0, repo);
11235 if (err) {
11236 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11237 err->code != GOT_ERR_HISTEDIT_CMD)
11238 break;
11239 prev_err = err;
11240 resp = ' ';
11241 continue;
11243 break;
11244 } else if (resp == 'a') {
11245 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11246 break;
11247 } else
11248 printf("invalid response '%c'\n", resp);
11251 return err;
11254 static const struct got_error *
11255 histedit_complete(struct got_worktree *worktree,
11256 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11257 struct got_reference *branch, struct got_repository *repo)
11259 printf("Switching work tree to %s\n",
11260 got_ref_get_symref_target(branch));
11261 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11262 branch, repo);
11265 static const struct got_error *
11266 show_histedit_progress(struct got_commit_object *commit,
11267 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11269 const struct got_error *err;
11270 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11272 err = got_object_id_str(&old_id_str, hle->commit_id);
11273 if (err)
11274 goto done;
11276 if (new_id) {
11277 err = got_object_id_str(&new_id_str, new_id);
11278 if (err)
11279 goto done;
11282 old_id_str[12] = '\0';
11283 if (new_id_str)
11284 new_id_str[12] = '\0';
11286 if (hle->logmsg) {
11287 logmsg = strdup(hle->logmsg);
11288 if (logmsg == NULL) {
11289 err = got_error_from_errno("strdup");
11290 goto done;
11292 trim_logmsg(logmsg, 42);
11293 } else {
11294 err = get_short_logmsg(&logmsg, 42, commit);
11295 if (err)
11296 goto done;
11299 switch (hle->cmd->code) {
11300 case GOT_HISTEDIT_PICK:
11301 case GOT_HISTEDIT_EDIT:
11302 printf("%s -> %s: %s\n", old_id_str,
11303 new_id_str ? new_id_str : "no-op change", logmsg);
11304 break;
11305 case GOT_HISTEDIT_DROP:
11306 case GOT_HISTEDIT_FOLD:
11307 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11308 logmsg);
11309 break;
11310 default:
11311 break;
11313 done:
11314 free(old_id_str);
11315 free(new_id_str);
11316 return err;
11319 static const struct got_error *
11320 histedit_commit(struct got_pathlist_head *merged_paths,
11321 struct got_worktree *worktree, struct got_fileindex *fileindex,
11322 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11323 const char *committer, struct got_repository *repo)
11325 const struct got_error *err;
11326 struct got_commit_object *commit;
11327 struct got_object_id *new_commit_id;
11329 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11330 && hle->logmsg == NULL) {
11331 err = histedit_edit_logmsg(hle, repo);
11332 if (err)
11333 return err;
11336 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11337 if (err)
11338 return err;
11340 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11341 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11342 hle->logmsg, repo);
11343 if (err) {
11344 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11345 goto done;
11346 err = show_histedit_progress(commit, hle, NULL);
11347 } else {
11348 err = show_histedit_progress(commit, hle, new_commit_id);
11349 free(new_commit_id);
11351 done:
11352 got_object_commit_close(commit);
11353 return err;
11356 static const struct got_error *
11357 histedit_skip_commit(struct got_histedit_list_entry *hle,
11358 struct got_worktree *worktree, struct got_repository *repo)
11360 const struct got_error *error;
11361 struct got_commit_object *commit;
11363 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11364 repo);
11365 if (error)
11366 return error;
11368 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11369 if (error)
11370 return error;
11372 error = show_histedit_progress(commit, hle, NULL);
11373 got_object_commit_close(commit);
11374 return error;
11377 static const struct got_error *
11378 check_local_changes(void *arg, unsigned char status,
11379 unsigned char staged_status, const char *path,
11380 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11381 struct got_object_id *commit_id, int dirfd, const char *de_name)
11383 int *have_local_changes = arg;
11385 switch (status) {
11386 case GOT_STATUS_ADD:
11387 case GOT_STATUS_DELETE:
11388 case GOT_STATUS_MODIFY:
11389 case GOT_STATUS_CONFLICT:
11390 *have_local_changes = 1;
11391 return got_error(GOT_ERR_CANCELLED);
11392 default:
11393 break;
11396 switch (staged_status) {
11397 case GOT_STATUS_ADD:
11398 case GOT_STATUS_DELETE:
11399 case GOT_STATUS_MODIFY:
11400 *have_local_changes = 1;
11401 return got_error(GOT_ERR_CANCELLED);
11402 default:
11403 break;
11406 return NULL;
11409 static const struct got_error *
11410 cmd_histedit(int argc, char *argv[])
11412 const struct got_error *error = NULL;
11413 struct got_worktree *worktree = NULL;
11414 struct got_fileindex *fileindex = NULL;
11415 struct got_repository *repo = NULL;
11416 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11417 struct got_reference *branch = NULL;
11418 struct got_reference *tmp_branch = NULL;
11419 struct got_object_id *resume_commit_id = NULL;
11420 struct got_object_id *base_commit_id = NULL;
11421 struct got_object_id *head_commit_id = NULL;
11422 struct got_commit_object *commit = NULL;
11423 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11424 struct got_update_progress_arg upa;
11425 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11426 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11427 int list_backups = 0, delete_backups = 0;
11428 const char *edit_script_path = NULL;
11429 struct got_object_id_queue commits;
11430 struct got_pathlist_head merged_paths;
11431 const struct got_object_id_queue *parent_ids;
11432 struct got_object_qid *pid;
11433 struct got_histedit_list histedit_cmds;
11434 struct got_histedit_list_entry *hle;
11435 int *pack_fds = NULL;
11437 STAILQ_INIT(&commits);
11438 TAILQ_INIT(&histedit_cmds);
11439 TAILQ_INIT(&merged_paths);
11440 memset(&upa, 0, sizeof(upa));
11442 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11443 switch (ch) {
11444 case 'a':
11445 abort_edit = 1;
11446 break;
11447 case 'c':
11448 continue_edit = 1;
11449 break;
11450 case 'e':
11451 edit_only = 1;
11452 break;
11453 case 'F':
11454 edit_script_path = optarg;
11455 break;
11456 case 'f':
11457 fold_only = 1;
11458 break;
11459 case 'l':
11460 list_backups = 1;
11461 break;
11462 case 'm':
11463 edit_logmsg_only = 1;
11464 break;
11465 case 'X':
11466 delete_backups = 1;
11467 break;
11468 default:
11469 usage_histedit();
11470 /* NOTREACHED */
11474 argc -= optind;
11475 argv += optind;
11477 #ifndef PROFILE
11478 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11479 "unveil", NULL) == -1)
11480 err(1, "pledge");
11481 #endif
11482 if (abort_edit && continue_edit)
11483 option_conflict('a', 'c');
11484 if (edit_script_path && edit_logmsg_only)
11485 option_conflict('F', 'm');
11486 if (abort_edit && edit_logmsg_only)
11487 option_conflict('a', 'm');
11488 if (continue_edit && edit_logmsg_only)
11489 option_conflict('c', 'm');
11490 if (abort_edit && fold_only)
11491 option_conflict('a', 'f');
11492 if (continue_edit && fold_only)
11493 option_conflict('c', 'f');
11494 if (fold_only && edit_logmsg_only)
11495 option_conflict('f', 'm');
11496 if (edit_script_path && fold_only)
11497 option_conflict('F', 'f');
11498 if (abort_edit && edit_only)
11499 option_conflict('a', 'e');
11500 if (continue_edit && edit_only)
11501 option_conflict('c', 'e');
11502 if (edit_only && edit_logmsg_only)
11503 option_conflict('e', 'm');
11504 if (edit_script_path && edit_only)
11505 option_conflict('F', 'e');
11506 if (list_backups) {
11507 if (abort_edit)
11508 option_conflict('l', 'a');
11509 if (continue_edit)
11510 option_conflict('l', 'c');
11511 if (edit_script_path)
11512 option_conflict('l', 'F');
11513 if (edit_logmsg_only)
11514 option_conflict('l', 'm');
11515 if (fold_only)
11516 option_conflict('l', 'f');
11517 if (edit_only)
11518 option_conflict('l', 'e');
11519 if (delete_backups)
11520 option_conflict('l', 'X');
11521 if (argc != 0 && argc != 1)
11522 usage_histedit();
11523 } else if (delete_backups) {
11524 if (abort_edit)
11525 option_conflict('X', 'a');
11526 if (continue_edit)
11527 option_conflict('X', 'c');
11528 if (edit_script_path)
11529 option_conflict('X', 'F');
11530 if (edit_logmsg_only)
11531 option_conflict('X', 'm');
11532 if (fold_only)
11533 option_conflict('X', 'f');
11534 if (edit_only)
11535 option_conflict('X', 'e');
11536 if (list_backups)
11537 option_conflict('X', 'l');
11538 if (argc != 0 && argc != 1)
11539 usage_histedit();
11540 } else if (argc != 0)
11541 usage_histedit();
11544 * This command cannot apply unveil(2) in all cases because the
11545 * user may choose to run an editor to edit the histedit script
11546 * and to edit individual commit log messages.
11547 * unveil(2) traverses exec(2); if an editor is used we have to
11548 * apply unveil after edit script and log messages have been written.
11549 * XXX TODO: Make use of unveil(2) where possible.
11552 cwd = getcwd(NULL, 0);
11553 if (cwd == NULL) {
11554 error = got_error_from_errno("getcwd");
11555 goto done;
11558 error = got_repo_pack_fds_open(&pack_fds);
11559 if (error != NULL)
11560 goto done;
11562 error = got_worktree_open(&worktree, cwd);
11563 if (error) {
11564 if (list_backups || delete_backups) {
11565 if (error->code != GOT_ERR_NOT_WORKTREE)
11566 goto done;
11567 } else {
11568 if (error->code == GOT_ERR_NOT_WORKTREE)
11569 error = wrap_not_worktree_error(error,
11570 "histedit", cwd);
11571 goto done;
11575 if (list_backups || delete_backups) {
11576 error = got_repo_open(&repo,
11577 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11578 NULL, pack_fds);
11579 if (error != NULL)
11580 goto done;
11581 error = apply_unveil(got_repo_get_path(repo), 0,
11582 worktree ? got_worktree_get_root_path(worktree) : NULL);
11583 if (error)
11584 goto done;
11585 error = process_backup_refs(
11586 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11587 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11588 goto done; /* nothing else to do */
11591 error = get_gitconfig_path(&gitconfig_path);
11592 if (error)
11593 goto done;
11594 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11595 gitconfig_path, pack_fds);
11596 if (error != NULL)
11597 goto done;
11599 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11600 if (error)
11601 goto done;
11602 if (rebase_in_progress) {
11603 error = got_error(GOT_ERR_REBASING);
11604 goto done;
11607 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11608 repo);
11609 if (error)
11610 goto done;
11611 if (merge_in_progress) {
11612 error = got_error(GOT_ERR_MERGE_BUSY);
11613 goto done;
11616 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11617 if (error)
11618 goto done;
11620 if (edit_in_progress && edit_logmsg_only) {
11621 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11622 "histedit operation is in progress in this "
11623 "work tree and must be continued or aborted "
11624 "before the -m option can be used");
11625 goto done;
11627 if (edit_in_progress && fold_only) {
11628 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11629 "histedit operation is in progress in this "
11630 "work tree and must be continued or aborted "
11631 "before the -f option can be used");
11632 goto done;
11634 if (edit_in_progress && edit_only) {
11635 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11636 "histedit operation is in progress in this "
11637 "work tree and must be continued or aborted "
11638 "before the -e option can be used");
11639 goto done;
11642 if (edit_in_progress && abort_edit) {
11643 error = got_worktree_histedit_continue(&resume_commit_id,
11644 &tmp_branch, &branch, &base_commit_id, &fileindex,
11645 worktree, repo);
11646 if (error)
11647 goto done;
11648 printf("Switching work tree to %s\n",
11649 got_ref_get_symref_target(branch));
11650 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11651 branch, base_commit_id, abort_progress, &upa);
11652 if (error)
11653 goto done;
11654 printf("Histedit of %s aborted\n",
11655 got_ref_get_symref_target(branch));
11656 print_merge_progress_stats(&upa);
11657 goto done; /* nothing else to do */
11658 } else if (abort_edit) {
11659 error = got_error(GOT_ERR_NOT_HISTEDIT);
11660 goto done;
11663 error = get_author(&committer, repo, worktree);
11664 if (error)
11665 goto done;
11667 if (continue_edit) {
11668 char *path;
11670 if (!edit_in_progress) {
11671 error = got_error(GOT_ERR_NOT_HISTEDIT);
11672 goto done;
11675 error = got_worktree_get_histedit_script_path(&path, worktree);
11676 if (error)
11677 goto done;
11679 error = histedit_load_list(&histedit_cmds, path, repo);
11680 free(path);
11681 if (error)
11682 goto done;
11684 error = got_worktree_histedit_continue(&resume_commit_id,
11685 &tmp_branch, &branch, &base_commit_id, &fileindex,
11686 worktree, repo);
11687 if (error)
11688 goto done;
11690 error = got_ref_resolve(&head_commit_id, repo, branch);
11691 if (error)
11692 goto done;
11694 error = got_object_open_as_commit(&commit, repo,
11695 head_commit_id);
11696 if (error)
11697 goto done;
11698 parent_ids = got_object_commit_get_parent_ids(commit);
11699 pid = STAILQ_FIRST(parent_ids);
11700 if (pid == NULL) {
11701 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11702 goto done;
11704 error = collect_commits(&commits, head_commit_id, &pid->id,
11705 base_commit_id, got_worktree_get_path_prefix(worktree),
11706 GOT_ERR_HISTEDIT_PATH, repo);
11707 got_object_commit_close(commit);
11708 commit = NULL;
11709 if (error)
11710 goto done;
11711 } else {
11712 if (edit_in_progress) {
11713 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11714 goto done;
11717 error = got_ref_open(&branch, repo,
11718 got_worktree_get_head_ref_name(worktree), 0);
11719 if (error != NULL)
11720 goto done;
11722 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11723 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11724 "will not edit commit history of a branch outside "
11725 "the \"refs/heads/\" reference namespace");
11726 goto done;
11729 error = got_ref_resolve(&head_commit_id, repo, branch);
11730 got_ref_close(branch);
11731 branch = NULL;
11732 if (error)
11733 goto done;
11735 error = got_object_open_as_commit(&commit, repo,
11736 head_commit_id);
11737 if (error)
11738 goto done;
11739 parent_ids = got_object_commit_get_parent_ids(commit);
11740 pid = STAILQ_FIRST(parent_ids);
11741 if (pid == NULL) {
11742 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11743 goto done;
11745 error = collect_commits(&commits, head_commit_id, &pid->id,
11746 got_worktree_get_base_commit_id(worktree),
11747 got_worktree_get_path_prefix(worktree),
11748 GOT_ERR_HISTEDIT_PATH, repo);
11749 got_object_commit_close(commit);
11750 commit = NULL;
11751 if (error)
11752 goto done;
11754 if (STAILQ_EMPTY(&commits)) {
11755 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11756 goto done;
11759 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11760 &base_commit_id, &fileindex, worktree, repo);
11761 if (error)
11762 goto done;
11764 if (edit_script_path) {
11765 error = histedit_load_list(&histedit_cmds,
11766 edit_script_path, repo);
11767 if (error) {
11768 got_worktree_histedit_abort(worktree, fileindex,
11769 repo, branch, base_commit_id,
11770 abort_progress, &upa);
11771 print_merge_progress_stats(&upa);
11772 goto done;
11774 } else {
11775 const char *branch_name;
11776 branch_name = got_ref_get_symref_target(branch);
11777 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11778 branch_name += 11;
11779 error = histedit_edit_script(&histedit_cmds, &commits,
11780 branch_name, edit_logmsg_only, fold_only,
11781 edit_only, repo);
11782 if (error) {
11783 got_worktree_histedit_abort(worktree, fileindex,
11784 repo, branch, base_commit_id,
11785 abort_progress, &upa);
11786 print_merge_progress_stats(&upa);
11787 goto done;
11792 error = histedit_save_list(&histedit_cmds, worktree,
11793 repo);
11794 if (error) {
11795 got_worktree_histedit_abort(worktree, fileindex,
11796 repo, branch, base_commit_id,
11797 abort_progress, &upa);
11798 print_merge_progress_stats(&upa);
11799 goto done;
11804 error = histedit_check_script(&histedit_cmds, &commits, repo);
11805 if (error)
11806 goto done;
11808 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11809 if (resume_commit_id) {
11810 if (got_object_id_cmp(hle->commit_id,
11811 resume_commit_id) != 0)
11812 continue;
11814 resume_commit_id = NULL;
11815 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11816 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11817 error = histedit_skip_commit(hle, worktree,
11818 repo);
11819 if (error)
11820 goto done;
11821 } else {
11822 struct got_pathlist_head paths;
11823 int have_changes = 0;
11825 TAILQ_INIT(&paths);
11826 error = got_pathlist_append(&paths, "", NULL);
11827 if (error)
11828 goto done;
11829 error = got_worktree_status(worktree, &paths,
11830 repo, 0, check_local_changes, &have_changes,
11831 check_cancelled, NULL);
11832 got_pathlist_free(&paths);
11833 if (error) {
11834 if (error->code != GOT_ERR_CANCELLED)
11835 goto done;
11836 if (sigint_received || sigpipe_received)
11837 goto done;
11839 if (have_changes) {
11840 error = histedit_commit(NULL, worktree,
11841 fileindex, tmp_branch, hle,
11842 committer, repo);
11843 if (error)
11844 goto done;
11845 } else {
11846 error = got_object_open_as_commit(
11847 &commit, repo, hle->commit_id);
11848 if (error)
11849 goto done;
11850 error = show_histedit_progress(commit,
11851 hle, NULL);
11852 got_object_commit_close(commit);
11853 commit = NULL;
11854 if (error)
11855 goto done;
11858 continue;
11861 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11862 error = histedit_skip_commit(hle, worktree, repo);
11863 if (error)
11864 goto done;
11865 continue;
11868 error = got_object_open_as_commit(&commit, repo,
11869 hle->commit_id);
11870 if (error)
11871 goto done;
11872 parent_ids = got_object_commit_get_parent_ids(commit);
11873 pid = STAILQ_FIRST(parent_ids);
11875 error = got_worktree_histedit_merge_files(&merged_paths,
11876 worktree, fileindex, &pid->id, hle->commit_id, repo,
11877 update_progress, &upa, check_cancelled, NULL);
11878 if (error)
11879 goto done;
11880 got_object_commit_close(commit);
11881 commit = NULL;
11883 print_merge_progress_stats(&upa);
11884 if (upa.conflicts > 0 || upa.missing > 0 ||
11885 upa.not_deleted > 0 || upa.unversioned > 0) {
11886 if (upa.conflicts > 0) {
11887 error = show_rebase_merge_conflict(
11888 hle->commit_id, repo);
11889 if (error)
11890 goto done;
11892 got_worktree_rebase_pathlist_free(&merged_paths);
11893 break;
11896 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11897 char *id_str;
11898 error = got_object_id_str(&id_str, hle->commit_id);
11899 if (error)
11900 goto done;
11901 printf("Stopping histedit for amending commit %s\n",
11902 id_str);
11903 free(id_str);
11904 got_worktree_rebase_pathlist_free(&merged_paths);
11905 error = got_worktree_histedit_postpone(worktree,
11906 fileindex);
11907 goto done;
11910 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11911 error = histedit_skip_commit(hle, worktree, repo);
11912 if (error)
11913 goto done;
11914 continue;
11917 error = histedit_commit(&merged_paths, worktree, fileindex,
11918 tmp_branch, hle, committer, repo);
11919 got_worktree_rebase_pathlist_free(&merged_paths);
11920 if (error)
11921 goto done;
11924 if (upa.conflicts > 0 || upa.missing > 0 ||
11925 upa.not_deleted > 0 || upa.unversioned > 0) {
11926 error = got_worktree_histedit_postpone(worktree, fileindex);
11927 if (error)
11928 goto done;
11929 if (upa.conflicts > 0 && upa.missing == 0 &&
11930 upa.not_deleted == 0 && upa.unversioned == 0) {
11931 error = got_error_msg(GOT_ERR_CONFLICTS,
11932 "conflicts must be resolved before histedit "
11933 "can continue");
11934 } else if (upa.conflicts > 0) {
11935 error = got_error_msg(GOT_ERR_CONFLICTS,
11936 "conflicts must be resolved before histedit "
11937 "can continue; changes destined for some "
11938 "files were not yet merged and should be "
11939 "merged manually if required before the "
11940 "histedit operation is continued");
11941 } else {
11942 error = got_error_msg(GOT_ERR_CONFLICTS,
11943 "changes destined for some files were not "
11944 "yet merged and should be merged manually "
11945 "if required before the histedit operation "
11946 "is continued");
11948 } else
11949 error = histedit_complete(worktree, fileindex, tmp_branch,
11950 branch, repo);
11951 done:
11952 free(cwd);
11953 free(committer);
11954 free(gitconfig_path);
11955 got_object_id_queue_free(&commits);
11956 histedit_free_list(&histedit_cmds);
11957 free(head_commit_id);
11958 free(base_commit_id);
11959 free(resume_commit_id);
11960 if (commit)
11961 got_object_commit_close(commit);
11962 if (branch)
11963 got_ref_close(branch);
11964 if (tmp_branch)
11965 got_ref_close(tmp_branch);
11966 if (worktree)
11967 got_worktree_close(worktree);
11968 if (repo) {
11969 const struct got_error *close_err = got_repo_close(repo);
11970 if (error == NULL)
11971 error = close_err;
11973 if (pack_fds) {
11974 const struct got_error *pack_err =
11975 got_repo_pack_fds_close(pack_fds);
11976 if (error == NULL)
11977 error = pack_err;
11979 return error;
11982 __dead static void
11983 usage_integrate(void)
11985 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11986 exit(1);
11989 static const struct got_error *
11990 cmd_integrate(int argc, char *argv[])
11992 const struct got_error *error = NULL;
11993 struct got_repository *repo = NULL;
11994 struct got_worktree *worktree = NULL;
11995 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11996 const char *branch_arg = NULL;
11997 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11998 struct got_fileindex *fileindex = NULL;
11999 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12000 int ch;
12001 struct got_update_progress_arg upa;
12002 int *pack_fds = NULL;
12004 while ((ch = getopt(argc, argv, "")) != -1) {
12005 switch (ch) {
12006 default:
12007 usage_integrate();
12008 /* NOTREACHED */
12012 argc -= optind;
12013 argv += optind;
12015 if (argc != 1)
12016 usage_integrate();
12017 branch_arg = argv[0];
12018 #ifndef PROFILE
12019 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12020 "unveil", NULL) == -1)
12021 err(1, "pledge");
12022 #endif
12023 cwd = getcwd(NULL, 0);
12024 if (cwd == NULL) {
12025 error = got_error_from_errno("getcwd");
12026 goto done;
12029 error = got_repo_pack_fds_open(&pack_fds);
12030 if (error != NULL)
12031 goto done;
12033 error = got_worktree_open(&worktree, cwd);
12034 if (error) {
12035 if (error->code == GOT_ERR_NOT_WORKTREE)
12036 error = wrap_not_worktree_error(error, "integrate",
12037 cwd);
12038 goto done;
12041 error = check_rebase_or_histedit_in_progress(worktree);
12042 if (error)
12043 goto done;
12045 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12046 NULL, pack_fds);
12047 if (error != NULL)
12048 goto done;
12050 error = apply_unveil(got_repo_get_path(repo), 0,
12051 got_worktree_get_root_path(worktree));
12052 if (error)
12053 goto done;
12055 error = check_merge_in_progress(worktree, repo);
12056 if (error)
12057 goto done;
12059 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12060 error = got_error_from_errno("asprintf");
12061 goto done;
12064 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12065 &base_branch_ref, worktree, refname, repo);
12066 if (error)
12067 goto done;
12069 refname = strdup(got_ref_get_name(branch_ref));
12070 if (refname == NULL) {
12071 error = got_error_from_errno("strdup");
12072 got_worktree_integrate_abort(worktree, fileindex, repo,
12073 branch_ref, base_branch_ref);
12074 goto done;
12076 base_refname = strdup(got_ref_get_name(base_branch_ref));
12077 if (base_refname == NULL) {
12078 error = got_error_from_errno("strdup");
12079 got_worktree_integrate_abort(worktree, fileindex, repo,
12080 branch_ref, base_branch_ref);
12081 goto done;
12083 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12084 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12085 got_worktree_integrate_abort(worktree, fileindex, repo,
12086 branch_ref, base_branch_ref);
12087 goto done;
12090 error = got_ref_resolve(&commit_id, repo, branch_ref);
12091 if (error)
12092 goto done;
12094 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12095 if (error)
12096 goto done;
12098 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12099 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12100 "specified branch has already been integrated");
12101 got_worktree_integrate_abort(worktree, fileindex, repo,
12102 branch_ref, base_branch_ref);
12103 goto done;
12106 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12107 if (error) {
12108 if (error->code == GOT_ERR_ANCESTRY)
12109 error = got_error(GOT_ERR_REBASE_REQUIRED);
12110 got_worktree_integrate_abort(worktree, fileindex, repo,
12111 branch_ref, base_branch_ref);
12112 goto done;
12115 memset(&upa, 0, sizeof(upa));
12116 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12117 branch_ref, base_branch_ref, update_progress, &upa,
12118 check_cancelled, NULL);
12119 if (error)
12120 goto done;
12122 printf("Integrated %s into %s\n", refname, base_refname);
12123 print_update_progress_stats(&upa);
12124 done:
12125 if (repo) {
12126 const struct got_error *close_err = got_repo_close(repo);
12127 if (error == NULL)
12128 error = close_err;
12130 if (worktree)
12131 got_worktree_close(worktree);
12132 if (pack_fds) {
12133 const struct got_error *pack_err =
12134 got_repo_pack_fds_close(pack_fds);
12135 if (error == NULL)
12136 error = pack_err;
12138 free(cwd);
12139 free(base_commit_id);
12140 free(commit_id);
12141 free(refname);
12142 free(base_refname);
12143 return error;
12146 __dead static void
12147 usage_merge(void)
12149 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12150 exit(1);
12153 static const struct got_error *
12154 cmd_merge(int argc, char *argv[])
12156 const struct got_error *error = NULL;
12157 struct got_worktree *worktree = NULL;
12158 struct got_repository *repo = NULL;
12159 struct got_fileindex *fileindex = NULL;
12160 char *cwd = NULL, *id_str = NULL, *author = NULL;
12161 struct got_reference *branch = NULL, *wt_branch = NULL;
12162 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12163 struct got_object_id *wt_branch_tip = NULL;
12164 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12165 int interrupt_merge = 0;
12166 struct got_update_progress_arg upa;
12167 struct got_object_id *merge_commit_id = NULL;
12168 char *branch_name = NULL;
12169 int *pack_fds = NULL;
12171 memset(&upa, 0, sizeof(upa));
12173 while ((ch = getopt(argc, argv, "acn")) != -1) {
12174 switch (ch) {
12175 case 'a':
12176 abort_merge = 1;
12177 break;
12178 case 'c':
12179 continue_merge = 1;
12180 break;
12181 case 'n':
12182 interrupt_merge = 1;
12183 break;
12184 default:
12185 usage_rebase();
12186 /* NOTREACHED */
12190 argc -= optind;
12191 argv += optind;
12193 #ifndef PROFILE
12194 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12195 "unveil", NULL) == -1)
12196 err(1, "pledge");
12197 #endif
12199 if (abort_merge && continue_merge)
12200 option_conflict('a', 'c');
12201 if (abort_merge || continue_merge) {
12202 if (argc != 0)
12203 usage_merge();
12204 } else if (argc != 1)
12205 usage_merge();
12207 cwd = getcwd(NULL, 0);
12208 if (cwd == NULL) {
12209 error = got_error_from_errno("getcwd");
12210 goto done;
12213 error = got_repo_pack_fds_open(&pack_fds);
12214 if (error != NULL)
12215 goto done;
12217 error = got_worktree_open(&worktree, cwd);
12218 if (error) {
12219 if (error->code == GOT_ERR_NOT_WORKTREE)
12220 error = wrap_not_worktree_error(error,
12221 "merge", cwd);
12222 goto done;
12225 error = got_repo_open(&repo,
12226 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12227 pack_fds);
12228 if (error != NULL)
12229 goto done;
12231 error = apply_unveil(got_repo_get_path(repo), 0,
12232 worktree ? got_worktree_get_root_path(worktree) : NULL);
12233 if (error)
12234 goto done;
12236 error = check_rebase_or_histedit_in_progress(worktree);
12237 if (error)
12238 goto done;
12240 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12241 repo);
12242 if (error)
12243 goto done;
12245 if (abort_merge) {
12246 if (!merge_in_progress) {
12247 error = got_error(GOT_ERR_NOT_MERGING);
12248 goto done;
12250 error = got_worktree_merge_continue(&branch_name,
12251 &branch_tip, &fileindex, worktree, repo);
12252 if (error)
12253 goto done;
12254 error = got_worktree_merge_abort(worktree, fileindex, repo,
12255 abort_progress, &upa);
12256 if (error)
12257 goto done;
12258 printf("Merge of %s aborted\n", branch_name);
12259 goto done; /* nothing else to do */
12262 error = get_author(&author, repo, worktree);
12263 if (error)
12264 goto done;
12266 if (continue_merge) {
12267 if (!merge_in_progress) {
12268 error = got_error(GOT_ERR_NOT_MERGING);
12269 goto done;
12271 error = got_worktree_merge_continue(&branch_name,
12272 &branch_tip, &fileindex, worktree, repo);
12273 if (error)
12274 goto done;
12275 } else {
12276 error = got_ref_open(&branch, repo, argv[0], 0);
12277 if (error != NULL)
12278 goto done;
12279 branch_name = strdup(got_ref_get_name(branch));
12280 if (branch_name == NULL) {
12281 error = got_error_from_errno("strdup");
12282 goto done;
12284 error = got_ref_resolve(&branch_tip, repo, branch);
12285 if (error)
12286 goto done;
12289 error = got_ref_open(&wt_branch, repo,
12290 got_worktree_get_head_ref_name(worktree), 0);
12291 if (error)
12292 goto done;
12293 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12294 if (error)
12295 goto done;
12296 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12297 wt_branch_tip, branch_tip, 0, repo,
12298 check_cancelled, NULL);
12299 if (error && error->code != GOT_ERR_ANCESTRY)
12300 goto done;
12302 if (!continue_merge) {
12303 error = check_path_prefix(wt_branch_tip, branch_tip,
12304 got_worktree_get_path_prefix(worktree),
12305 GOT_ERR_MERGE_PATH, repo);
12306 if (error)
12307 goto done;
12308 if (yca_id) {
12309 error = check_same_branch(wt_branch_tip, branch,
12310 yca_id, repo);
12311 if (error) {
12312 if (error->code != GOT_ERR_ANCESTRY)
12313 goto done;
12314 error = NULL;
12315 } else {
12316 static char msg[512];
12317 snprintf(msg, sizeof(msg),
12318 "cannot create a merge commit because "
12319 "%s is based on %s; %s can be integrated "
12320 "with 'got integrate' instead", branch_name,
12321 got_worktree_get_head_ref_name(worktree),
12322 branch_name);
12323 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12324 goto done;
12327 error = got_worktree_merge_prepare(&fileindex, worktree,
12328 branch, repo);
12329 if (error)
12330 goto done;
12332 error = got_worktree_merge_branch(worktree, fileindex,
12333 yca_id, branch_tip, repo, update_progress, &upa,
12334 check_cancelled, NULL);
12335 if (error)
12336 goto done;
12337 print_merge_progress_stats(&upa);
12338 if (!upa.did_something) {
12339 error = got_worktree_merge_abort(worktree, fileindex,
12340 repo, abort_progress, &upa);
12341 if (error)
12342 goto done;
12343 printf("Already up-to-date\n");
12344 goto done;
12348 if (interrupt_merge) {
12349 error = got_worktree_merge_postpone(worktree, fileindex);
12350 if (error)
12351 goto done;
12352 printf("Merge of %s interrupted on request\n", branch_name);
12353 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12354 upa.not_deleted > 0 || upa.unversioned > 0) {
12355 error = got_worktree_merge_postpone(worktree, fileindex);
12356 if (error)
12357 goto done;
12358 if (upa.conflicts > 0 && upa.missing == 0 &&
12359 upa.not_deleted == 0 && upa.unversioned == 0) {
12360 error = got_error_msg(GOT_ERR_CONFLICTS,
12361 "conflicts must be resolved before merging "
12362 "can continue");
12363 } else if (upa.conflicts > 0) {
12364 error = got_error_msg(GOT_ERR_CONFLICTS,
12365 "conflicts must be resolved before merging "
12366 "can continue; changes destined for some "
12367 "files were not yet merged and "
12368 "should be merged manually if required before the "
12369 "merge operation is continued");
12370 } else {
12371 error = got_error_msg(GOT_ERR_CONFLICTS,
12372 "changes destined for some "
12373 "files were not yet merged and should be "
12374 "merged manually if required before the "
12375 "merge operation is continued");
12377 goto done;
12378 } else {
12379 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12380 fileindex, author, NULL, 1, branch_tip, branch_name,
12381 repo, continue_merge ? print_status : NULL, NULL);
12382 if (error)
12383 goto done;
12384 error = got_worktree_merge_complete(worktree, fileindex, repo);
12385 if (error)
12386 goto done;
12387 error = got_object_id_str(&id_str, merge_commit_id);
12388 if (error)
12389 goto done;
12390 printf("Merged %s into %s: %s\n", branch_name,
12391 got_worktree_get_head_ref_name(worktree),
12392 id_str);
12395 done:
12396 free(id_str);
12397 free(merge_commit_id);
12398 free(author);
12399 free(branch_tip);
12400 free(branch_name);
12401 free(yca_id);
12402 if (branch)
12403 got_ref_close(branch);
12404 if (wt_branch)
12405 got_ref_close(wt_branch);
12406 if (worktree)
12407 got_worktree_close(worktree);
12408 if (repo) {
12409 const struct got_error *close_err = got_repo_close(repo);
12410 if (error == NULL)
12411 error = close_err;
12413 if (pack_fds) {
12414 const struct got_error *pack_err =
12415 got_repo_pack_fds_close(pack_fds);
12416 if (error == NULL)
12417 error = pack_err;
12419 return error;
12422 __dead static void
12423 usage_stage(void)
12425 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12426 "[path ...]\n", getprogname());
12427 exit(1);
12430 static const struct got_error *
12431 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12432 const char *path, struct got_object_id *blob_id,
12433 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12434 int dirfd, const char *de_name)
12436 const struct got_error *err = NULL;
12437 char *id_str = NULL;
12439 if (staged_status != GOT_STATUS_ADD &&
12440 staged_status != GOT_STATUS_MODIFY &&
12441 staged_status != GOT_STATUS_DELETE)
12442 return NULL;
12444 if (staged_status == GOT_STATUS_ADD ||
12445 staged_status == GOT_STATUS_MODIFY)
12446 err = got_object_id_str(&id_str, staged_blob_id);
12447 else
12448 err = got_object_id_str(&id_str, blob_id);
12449 if (err)
12450 return err;
12452 printf("%s %c %s\n", id_str, staged_status, path);
12453 free(id_str);
12454 return NULL;
12457 static const struct got_error *
12458 cmd_stage(int argc, char *argv[])
12460 const struct got_error *error = NULL;
12461 struct got_repository *repo = NULL;
12462 struct got_worktree *worktree = NULL;
12463 char *cwd = NULL;
12464 struct got_pathlist_head paths;
12465 struct got_pathlist_entry *pe;
12466 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12467 FILE *patch_script_file = NULL;
12468 const char *patch_script_path = NULL;
12469 struct choose_patch_arg cpa;
12470 int *pack_fds = NULL;
12472 TAILQ_INIT(&paths);
12474 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12475 switch (ch) {
12476 case 'F':
12477 patch_script_path = optarg;
12478 break;
12479 case 'l':
12480 list_stage = 1;
12481 break;
12482 case 'p':
12483 pflag = 1;
12484 break;
12485 case 'S':
12486 allow_bad_symlinks = 1;
12487 break;
12488 default:
12489 usage_stage();
12490 /* NOTREACHED */
12494 argc -= optind;
12495 argv += optind;
12497 #ifndef PROFILE
12498 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12499 "unveil", NULL) == -1)
12500 err(1, "pledge");
12501 #endif
12502 if (list_stage && (pflag || patch_script_path))
12503 errx(1, "-l option cannot be used with other options");
12504 if (patch_script_path && !pflag)
12505 errx(1, "-F option can only be used together with -p option");
12507 cwd = getcwd(NULL, 0);
12508 if (cwd == NULL) {
12509 error = got_error_from_errno("getcwd");
12510 goto done;
12513 error = got_repo_pack_fds_open(&pack_fds);
12514 if (error != NULL)
12515 goto done;
12517 error = got_worktree_open(&worktree, cwd);
12518 if (error) {
12519 if (error->code == GOT_ERR_NOT_WORKTREE)
12520 error = wrap_not_worktree_error(error, "stage", cwd);
12521 goto done;
12524 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12525 NULL, pack_fds);
12526 if (error != NULL)
12527 goto done;
12529 if (patch_script_path) {
12530 patch_script_file = fopen(patch_script_path, "re");
12531 if (patch_script_file == NULL) {
12532 error = got_error_from_errno2("fopen",
12533 patch_script_path);
12534 goto done;
12537 error = apply_unveil(got_repo_get_path(repo), 0,
12538 got_worktree_get_root_path(worktree));
12539 if (error)
12540 goto done;
12542 error = check_merge_in_progress(worktree, repo);
12543 if (error)
12544 goto done;
12546 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12547 if (error)
12548 goto done;
12550 if (list_stage)
12551 error = got_worktree_status(worktree, &paths, repo, 0,
12552 print_stage, NULL, check_cancelled, NULL);
12553 else {
12554 cpa.patch_script_file = patch_script_file;
12555 cpa.action = "stage";
12556 error = got_worktree_stage(worktree, &paths,
12557 pflag ? NULL : print_status, NULL,
12558 pflag ? choose_patch : NULL, &cpa,
12559 allow_bad_symlinks, repo);
12561 done:
12562 if (patch_script_file && fclose(patch_script_file) == EOF &&
12563 error == NULL)
12564 error = got_error_from_errno2("fclose", patch_script_path);
12565 if (repo) {
12566 const struct got_error *close_err = got_repo_close(repo);
12567 if (error == NULL)
12568 error = close_err;
12570 if (worktree)
12571 got_worktree_close(worktree);
12572 if (pack_fds) {
12573 const struct got_error *pack_err =
12574 got_repo_pack_fds_close(pack_fds);
12575 if (error == NULL)
12576 error = pack_err;
12578 TAILQ_FOREACH(pe, &paths, entry)
12579 free((char *)pe->path);
12580 got_pathlist_free(&paths);
12581 free(cwd);
12582 return error;
12585 __dead static void
12586 usage_unstage(void)
12588 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12589 "[path ...]\n", getprogname());
12590 exit(1);
12594 static const struct got_error *
12595 cmd_unstage(int argc, char *argv[])
12597 const struct got_error *error = NULL;
12598 struct got_repository *repo = NULL;
12599 struct got_worktree *worktree = NULL;
12600 char *cwd = NULL;
12601 struct got_pathlist_head paths;
12602 struct got_pathlist_entry *pe;
12603 int ch, pflag = 0;
12604 struct got_update_progress_arg upa;
12605 FILE *patch_script_file = NULL;
12606 const char *patch_script_path = NULL;
12607 struct choose_patch_arg cpa;
12608 int *pack_fds = NULL;
12610 TAILQ_INIT(&paths);
12612 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12613 switch (ch) {
12614 case 'F':
12615 patch_script_path = optarg;
12616 break;
12617 case 'p':
12618 pflag = 1;
12619 break;
12620 default:
12621 usage_unstage();
12622 /* NOTREACHED */
12626 argc -= optind;
12627 argv += optind;
12629 #ifndef PROFILE
12630 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12631 "unveil", NULL) == -1)
12632 err(1, "pledge");
12633 #endif
12634 if (patch_script_path && !pflag)
12635 errx(1, "-F option can only be used together with -p option");
12637 cwd = getcwd(NULL, 0);
12638 if (cwd == NULL) {
12639 error = got_error_from_errno("getcwd");
12640 goto done;
12643 error = got_repo_pack_fds_open(&pack_fds);
12644 if (error != NULL)
12645 goto done;
12647 error = got_worktree_open(&worktree, cwd);
12648 if (error) {
12649 if (error->code == GOT_ERR_NOT_WORKTREE)
12650 error = wrap_not_worktree_error(error, "unstage", cwd);
12651 goto done;
12654 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12655 NULL, pack_fds);
12656 if (error != NULL)
12657 goto done;
12659 if (patch_script_path) {
12660 patch_script_file = fopen(patch_script_path, "re");
12661 if (patch_script_file == NULL) {
12662 error = got_error_from_errno2("fopen",
12663 patch_script_path);
12664 goto done;
12668 error = apply_unveil(got_repo_get_path(repo), 0,
12669 got_worktree_get_root_path(worktree));
12670 if (error)
12671 goto done;
12673 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12674 if (error)
12675 goto done;
12677 cpa.patch_script_file = patch_script_file;
12678 cpa.action = "unstage";
12679 memset(&upa, 0, sizeof(upa));
12680 error = got_worktree_unstage(worktree, &paths, update_progress,
12681 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12682 if (!error)
12683 print_merge_progress_stats(&upa);
12684 done:
12685 if (patch_script_file && fclose(patch_script_file) == EOF &&
12686 error == NULL)
12687 error = got_error_from_errno2("fclose", patch_script_path);
12688 if (repo) {
12689 const struct got_error *close_err = got_repo_close(repo);
12690 if (error == NULL)
12691 error = close_err;
12693 if (worktree)
12694 got_worktree_close(worktree);
12695 if (pack_fds) {
12696 const struct got_error *pack_err =
12697 got_repo_pack_fds_close(pack_fds);
12698 if (error == NULL)
12699 error = pack_err;
12701 TAILQ_FOREACH(pe, &paths, entry)
12702 free((char *)pe->path);
12703 got_pathlist_free(&paths);
12704 free(cwd);
12705 return error;
12708 __dead static void
12709 usage_cat(void)
12711 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12712 "arg ...\n", getprogname());
12713 exit(1);
12716 static const struct got_error *
12717 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12719 const struct got_error *err;
12720 struct got_blob_object *blob;
12721 int fd = -1;
12723 fd = got_opentempfd();
12724 if (fd == -1)
12725 return got_error_from_errno("got_opentempfd");
12727 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12728 if (err)
12729 goto done;
12731 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12732 done:
12733 if (fd != -1 && close(fd) == -1 && err == NULL)
12734 err = got_error_from_errno("close");
12735 if (blob)
12736 got_object_blob_close(blob);
12737 return err;
12740 static const struct got_error *
12741 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12743 const struct got_error *err;
12744 struct got_tree_object *tree;
12745 int nentries, i;
12747 err = got_object_open_as_tree(&tree, repo, id);
12748 if (err)
12749 return err;
12751 nentries = got_object_tree_get_nentries(tree);
12752 for (i = 0; i < nentries; i++) {
12753 struct got_tree_entry *te;
12754 char *id_str;
12755 if (sigint_received || sigpipe_received)
12756 break;
12757 te = got_object_tree_get_entry(tree, i);
12758 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12759 if (err)
12760 break;
12761 fprintf(outfile, "%s %.7o %s\n", id_str,
12762 got_tree_entry_get_mode(te),
12763 got_tree_entry_get_name(te));
12764 free(id_str);
12767 got_object_tree_close(tree);
12768 return err;
12771 static const struct got_error *
12772 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12774 const struct got_error *err;
12775 struct got_commit_object *commit;
12776 const struct got_object_id_queue *parent_ids;
12777 struct got_object_qid *pid;
12778 char *id_str = NULL;
12779 const char *logmsg = NULL;
12780 char gmtoff[6];
12782 err = got_object_open_as_commit(&commit, repo, id);
12783 if (err)
12784 return err;
12786 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12787 if (err)
12788 goto done;
12790 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12791 parent_ids = got_object_commit_get_parent_ids(commit);
12792 fprintf(outfile, "numparents %d\n",
12793 got_object_commit_get_nparents(commit));
12794 STAILQ_FOREACH(pid, parent_ids, entry) {
12795 char *pid_str;
12796 err = got_object_id_str(&pid_str, &pid->id);
12797 if (err)
12798 goto done;
12799 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12800 free(pid_str);
12802 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12803 got_object_commit_get_author_gmtoff(commit));
12804 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12805 got_object_commit_get_author(commit),
12806 (long long)got_object_commit_get_author_time(commit),
12807 gmtoff);
12809 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12810 got_object_commit_get_committer_gmtoff(commit));
12811 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12812 got_object_commit_get_committer(commit),
12813 (long long)got_object_commit_get_committer_time(commit),
12814 gmtoff);
12816 logmsg = got_object_commit_get_logmsg_raw(commit);
12817 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12818 fprintf(outfile, "%s", logmsg);
12819 done:
12820 free(id_str);
12821 got_object_commit_close(commit);
12822 return err;
12825 static const struct got_error *
12826 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12828 const struct got_error *err;
12829 struct got_tag_object *tag;
12830 char *id_str = NULL;
12831 const char *tagmsg = NULL;
12832 char gmtoff[6];
12834 err = got_object_open_as_tag(&tag, repo, id);
12835 if (err)
12836 return err;
12838 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12839 if (err)
12840 goto done;
12842 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12844 switch (got_object_tag_get_object_type(tag)) {
12845 case GOT_OBJ_TYPE_BLOB:
12846 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12847 GOT_OBJ_LABEL_BLOB);
12848 break;
12849 case GOT_OBJ_TYPE_TREE:
12850 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12851 GOT_OBJ_LABEL_TREE);
12852 break;
12853 case GOT_OBJ_TYPE_COMMIT:
12854 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12855 GOT_OBJ_LABEL_COMMIT);
12856 break;
12857 case GOT_OBJ_TYPE_TAG:
12858 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12859 GOT_OBJ_LABEL_TAG);
12860 break;
12861 default:
12862 break;
12865 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12866 got_object_tag_get_name(tag));
12868 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12869 got_object_tag_get_tagger_gmtoff(tag));
12870 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12871 got_object_tag_get_tagger(tag),
12872 (long long)got_object_tag_get_tagger_time(tag),
12873 gmtoff);
12875 tagmsg = got_object_tag_get_message(tag);
12876 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12877 fprintf(outfile, "%s", tagmsg);
12878 done:
12879 free(id_str);
12880 got_object_tag_close(tag);
12881 return err;
12884 static const struct got_error *
12885 cmd_cat(int argc, char *argv[])
12887 const struct got_error *error;
12888 struct got_repository *repo = NULL;
12889 struct got_worktree *worktree = NULL;
12890 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12891 const char *commit_id_str = NULL;
12892 struct got_object_id *id = NULL, *commit_id = NULL;
12893 struct got_commit_object *commit = NULL;
12894 int ch, obj_type, i, force_path = 0;
12895 struct got_reflist_head refs;
12896 int *pack_fds = NULL;
12898 TAILQ_INIT(&refs);
12900 #ifndef PROFILE
12901 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12902 NULL) == -1)
12903 err(1, "pledge");
12904 #endif
12906 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12907 switch (ch) {
12908 case 'c':
12909 commit_id_str = optarg;
12910 break;
12911 case 'P':
12912 force_path = 1;
12913 break;
12914 case 'r':
12915 repo_path = realpath(optarg, NULL);
12916 if (repo_path == NULL)
12917 return got_error_from_errno2("realpath",
12918 optarg);
12919 got_path_strip_trailing_slashes(repo_path);
12920 break;
12921 default:
12922 usage_cat();
12923 /* NOTREACHED */
12927 argc -= optind;
12928 argv += optind;
12930 cwd = getcwd(NULL, 0);
12931 if (cwd == NULL) {
12932 error = got_error_from_errno("getcwd");
12933 goto done;
12936 error = got_repo_pack_fds_open(&pack_fds);
12937 if (error != NULL)
12938 goto done;
12940 if (repo_path == NULL) {
12941 error = got_worktree_open(&worktree, cwd);
12942 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12943 goto done;
12944 if (worktree) {
12945 repo_path = strdup(
12946 got_worktree_get_repo_path(worktree));
12947 if (repo_path == NULL) {
12948 error = got_error_from_errno("strdup");
12949 goto done;
12952 /* Release work tree lock. */
12953 got_worktree_close(worktree);
12954 worktree = NULL;
12958 if (repo_path == NULL) {
12959 repo_path = strdup(cwd);
12960 if (repo_path == NULL)
12961 return got_error_from_errno("strdup");
12964 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12965 free(repo_path);
12966 if (error != NULL)
12967 goto done;
12969 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12970 if (error)
12971 goto done;
12973 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12974 if (error)
12975 goto done;
12977 if (commit_id_str == NULL)
12978 commit_id_str = GOT_REF_HEAD;
12979 error = got_repo_match_object_id(&commit_id, NULL,
12980 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12981 if (error)
12982 goto done;
12984 error = got_object_open_as_commit(&commit, repo, commit_id);
12985 if (error)
12986 goto done;
12988 for (i = 0; i < argc; i++) {
12989 if (force_path) {
12990 error = got_object_id_by_path(&id, repo, commit,
12991 argv[i]);
12992 if (error)
12993 break;
12994 } else {
12995 error = got_repo_match_object_id(&id, &label, argv[i],
12996 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12997 repo);
12998 if (error) {
12999 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13000 error->code != GOT_ERR_NOT_REF)
13001 break;
13002 error = got_object_id_by_path(&id, repo,
13003 commit, argv[i]);
13004 if (error)
13005 break;
13009 error = got_object_get_type(&obj_type, repo, id);
13010 if (error)
13011 break;
13013 switch (obj_type) {
13014 case GOT_OBJ_TYPE_BLOB:
13015 error = cat_blob(id, repo, stdout);
13016 break;
13017 case GOT_OBJ_TYPE_TREE:
13018 error = cat_tree(id, repo, stdout);
13019 break;
13020 case GOT_OBJ_TYPE_COMMIT:
13021 error = cat_commit(id, repo, stdout);
13022 break;
13023 case GOT_OBJ_TYPE_TAG:
13024 error = cat_tag(id, repo, stdout);
13025 break;
13026 default:
13027 error = got_error(GOT_ERR_OBJ_TYPE);
13028 break;
13030 if (error)
13031 break;
13032 free(label);
13033 label = NULL;
13034 free(id);
13035 id = NULL;
13037 done:
13038 free(label);
13039 free(id);
13040 free(commit_id);
13041 if (commit)
13042 got_object_commit_close(commit);
13043 if (worktree)
13044 got_worktree_close(worktree);
13045 if (repo) {
13046 const struct got_error *close_err = got_repo_close(repo);
13047 if (error == NULL)
13048 error = close_err;
13050 if (pack_fds) {
13051 const struct got_error *pack_err =
13052 got_repo_pack_fds_close(pack_fds);
13053 if (error == NULL)
13054 error = pack_err;
13057 got_ref_list_free(&refs);
13058 return error;
13061 __dead static void
13062 usage_info(void)
13064 fprintf(stderr, "usage: %s info [path ...]\n",
13065 getprogname());
13066 exit(1);
13069 static const struct got_error *
13070 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13071 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13072 struct got_object_id *commit_id)
13074 const struct got_error *err = NULL;
13075 char *id_str = NULL;
13076 char datebuf[128];
13077 struct tm mytm, *tm;
13078 struct got_pathlist_head *paths = arg;
13079 struct got_pathlist_entry *pe;
13082 * Clear error indication from any of the path arguments which
13083 * would cause this file index entry to be displayed.
13085 TAILQ_FOREACH(pe, paths, entry) {
13086 if (got_path_cmp(path, pe->path, strlen(path),
13087 pe->path_len) == 0 ||
13088 got_path_is_child(path, pe->path, pe->path_len))
13089 pe->data = NULL; /* no error */
13092 printf(GOT_COMMIT_SEP_STR);
13093 if (S_ISLNK(mode))
13094 printf("symlink: %s\n", path);
13095 else if (S_ISREG(mode)) {
13096 printf("file: %s\n", path);
13097 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13098 } else if (S_ISDIR(mode))
13099 printf("directory: %s\n", path);
13100 else
13101 printf("something: %s\n", path);
13103 tm = localtime_r(&mtime, &mytm);
13104 if (tm == NULL)
13105 return NULL;
13106 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13107 return got_error(GOT_ERR_NO_SPACE);
13108 printf("timestamp: %s\n", datebuf);
13110 if (blob_id) {
13111 err = got_object_id_str(&id_str, blob_id);
13112 if (err)
13113 return err;
13114 printf("based on blob: %s\n", id_str);
13115 free(id_str);
13118 if (staged_blob_id) {
13119 err = got_object_id_str(&id_str, staged_blob_id);
13120 if (err)
13121 return err;
13122 printf("based on staged blob: %s\n", id_str);
13123 free(id_str);
13126 if (commit_id) {
13127 err = got_object_id_str(&id_str, commit_id);
13128 if (err)
13129 return err;
13130 printf("based on commit: %s\n", id_str);
13131 free(id_str);
13134 return NULL;
13137 static const struct got_error *
13138 cmd_info(int argc, char *argv[])
13140 const struct got_error *error = NULL;
13141 struct got_worktree *worktree = NULL;
13142 char *cwd = NULL, *id_str = NULL;
13143 struct got_pathlist_head paths;
13144 struct got_pathlist_entry *pe;
13145 char *uuidstr = NULL;
13146 int ch, show_files = 0;
13148 TAILQ_INIT(&paths);
13150 while ((ch = getopt(argc, argv, "")) != -1) {
13151 switch (ch) {
13152 default:
13153 usage_info();
13154 /* NOTREACHED */
13158 argc -= optind;
13159 argv += optind;
13161 #ifndef PROFILE
13162 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13163 NULL) == -1)
13164 err(1, "pledge");
13165 #endif
13166 cwd = getcwd(NULL, 0);
13167 if (cwd == NULL) {
13168 error = got_error_from_errno("getcwd");
13169 goto done;
13172 error = got_worktree_open(&worktree, cwd);
13173 if (error) {
13174 if (error->code == GOT_ERR_NOT_WORKTREE)
13175 error = wrap_not_worktree_error(error, "info", cwd);
13176 goto done;
13179 #ifndef PROFILE
13180 /* Remove "wpath cpath proc exec sendfd" promises. */
13181 if (pledge("stdio rpath flock unveil", NULL) == -1)
13182 err(1, "pledge");
13183 #endif
13184 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13185 if (error)
13186 goto done;
13188 if (argc >= 1) {
13189 error = get_worktree_paths_from_argv(&paths, argc, argv,
13190 worktree);
13191 if (error)
13192 goto done;
13193 show_files = 1;
13196 error = got_object_id_str(&id_str,
13197 got_worktree_get_base_commit_id(worktree));
13198 if (error)
13199 goto done;
13201 error = got_worktree_get_uuid(&uuidstr, worktree);
13202 if (error)
13203 goto done;
13205 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13206 printf("work tree base commit: %s\n", id_str);
13207 printf("work tree path prefix: %s\n",
13208 got_worktree_get_path_prefix(worktree));
13209 printf("work tree branch reference: %s\n",
13210 got_worktree_get_head_ref_name(worktree));
13211 printf("work tree UUID: %s\n", uuidstr);
13212 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13214 if (show_files) {
13215 struct got_pathlist_entry *pe;
13216 TAILQ_FOREACH(pe, &paths, entry) {
13217 if (pe->path_len == 0)
13218 continue;
13220 * Assume this path will fail. This will be corrected
13221 * in print_path_info() in case the path does suceeed.
13223 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13225 error = got_worktree_path_info(worktree, &paths,
13226 print_path_info, &paths, check_cancelled, NULL);
13227 if (error)
13228 goto done;
13229 TAILQ_FOREACH(pe, &paths, entry) {
13230 if (pe->data != NULL) {
13231 const struct got_error *perr;
13233 perr = pe->data;
13234 error = got_error_fmt(perr->code, "%s",
13235 pe->path);
13236 break;
13240 done:
13241 if (worktree)
13242 got_worktree_close(worktree);
13243 TAILQ_FOREACH(pe, &paths, entry)
13244 free((char *)pe->path);
13245 got_pathlist_free(&paths);
13246 free(cwd);
13247 free(id_str);
13248 free(uuidstr);
13249 return error;