Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.h"
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
845 /*
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
849 */
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s\n", git_url);
1699 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1700 server_path, verbosity);
1701 if (error)
1702 goto done;
1704 if (!list_refs_only) {
1705 error = got_repo_init(repo_path, NULL);
1706 if (error)
1707 goto done;
1708 error = got_repo_pack_fds_open(&pack_fds);
1709 if (error != NULL)
1710 goto done;
1711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1712 if (error)
1713 goto done;
1716 fpa.last_scaled_size[0] = '\0';
1717 fpa.last_p_indexed = -1;
1718 fpa.last_p_resolved = -1;
1719 fpa.verbosity = verbosity;
1720 fpa.create_configs = 1;
1721 fpa.configs_created = 0;
1722 fpa.repo = repo;
1723 fpa.config_info.symrefs = &symrefs;
1724 fpa.config_info.wanted_branches = &wanted_branches;
1725 fpa.config_info.wanted_refs = &wanted_refs;
1726 fpa.config_info.proto = proto;
1727 fpa.config_info.host = host;
1728 fpa.config_info.port = port;
1729 fpa.config_info.remote_repo_path = server_path;
1730 fpa.config_info.git_url = git_url;
1731 fpa.config_info.fetch_all_branches = fetch_all_branches;
1732 fpa.config_info.mirror_references = mirror_references;
1733 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1734 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1735 fetch_all_branches, &wanted_branches, &wanted_refs,
1736 list_refs_only, verbosity, fetchfd, repo,
1737 fetch_progress, &fpa);
1738 if (error)
1739 goto done;
1741 if (list_refs_only) {
1742 error = list_remote_refs(&symrefs, &refs);
1743 goto done;
1746 if (pack_hash == NULL) {
1747 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1748 "server sent an empty pack file");
1749 goto done;
1751 error = got_object_id_str(&id_str, pack_hash);
1752 if (error)
1753 goto done;
1754 if (verbosity >= 0)
1755 printf("\nFetched %s.pack\n", id_str);
1756 free(id_str);
1758 /* Set up references provided with the pack file. */
1759 TAILQ_FOREACH(pe, &refs, entry) {
1760 const char *refname = pe->path;
1761 struct got_object_id *id = pe->data;
1762 char *remote_refname;
1764 if (is_wanted_ref(&wanted_refs, refname) &&
1765 !mirror_references) {
1766 error = create_wanted_ref(refname, id,
1767 GOT_FETCH_DEFAULT_REMOTE_NAME,
1768 verbosity - 1, repo);
1769 if (error)
1770 goto done;
1771 continue;
1774 error = create_ref(refname, id, verbosity - 1, repo);
1775 if (error)
1776 goto done;
1778 if (mirror_references)
1779 continue;
1781 if (strncmp("refs/heads/", refname, 11) != 0)
1782 continue;
1784 if (asprintf(&remote_refname,
1785 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1786 refname + 11) == -1) {
1787 error = got_error_from_errno("asprintf");
1788 goto done;
1790 error = create_ref(remote_refname, id, verbosity - 1, repo);
1791 free(remote_refname);
1792 if (error)
1793 goto done;
1796 /* Set the HEAD reference if the server provided one. */
1797 TAILQ_FOREACH(pe, &symrefs, entry) {
1798 struct got_reference *target_ref;
1799 const char *refname = pe->path;
1800 const char *target = pe->data;
1801 char *remote_refname = NULL, *remote_target = NULL;
1803 if (strcmp(refname, GOT_REF_HEAD) != 0)
1804 continue;
1806 error = got_ref_open(&target_ref, repo, target, 0);
1807 if (error) {
1808 if (error->code == GOT_ERR_NOT_REF) {
1809 error = NULL;
1810 continue;
1812 goto done;
1815 error = create_symref(refname, target_ref, verbosity, repo);
1816 got_ref_close(target_ref);
1817 if (error)
1818 goto done;
1820 if (mirror_references)
1821 continue;
1823 if (strncmp("refs/heads/", target, 11) != 0)
1824 continue;
1826 if (asprintf(&remote_refname,
1827 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1828 refname) == -1) {
1829 error = got_error_from_errno("asprintf");
1830 goto done;
1832 if (asprintf(&remote_target,
1833 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1834 target + 11) == -1) {
1835 error = got_error_from_errno("asprintf");
1836 free(remote_refname);
1837 goto done;
1839 error = got_ref_open(&target_ref, repo, remote_target, 0);
1840 if (error) {
1841 free(remote_refname);
1842 free(remote_target);
1843 if (error->code == GOT_ERR_NOT_REF) {
1844 error = NULL;
1845 continue;
1847 goto done;
1849 error = create_symref(remote_refname, target_ref,
1850 verbosity - 1, repo);
1851 free(remote_refname);
1852 free(remote_target);
1853 got_ref_close(target_ref);
1854 if (error)
1855 goto done;
1857 if (pe == NULL) {
1859 * We failed to set the HEAD reference. If we asked for
1860 * a set of wanted branches use the first of one of those
1861 * which could be fetched instead.
1863 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1864 const char *target = pe->path;
1865 struct got_reference *target_ref;
1867 error = got_ref_open(&target_ref, repo, target, 0);
1868 if (error) {
1869 if (error->code == GOT_ERR_NOT_REF) {
1870 error = NULL;
1871 continue;
1873 goto done;
1876 error = create_symref(GOT_REF_HEAD, target_ref,
1877 verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1881 break;
1884 if (!fpa.configs_created && pe != NULL) {
1885 error = create_config_files(fpa.config_info.proto,
1886 fpa.config_info.host, fpa.config_info.port,
1887 fpa.config_info.remote_repo_path,
1888 fpa.config_info.git_url,
1889 fpa.config_info.fetch_all_branches,
1890 fpa.config_info.mirror_references,
1891 fpa.config_info.symrefs,
1892 fpa.config_info.wanted_branches,
1893 fpa.config_info.wanted_refs, fpa.repo);
1894 if (error)
1895 goto done;
1899 if (verbosity >= 0)
1900 printf("Created %s repository '%s'\n",
1901 mirror_references ? "mirrored" : "cloned", repo_path);
1902 done:
1903 if (pack_fds) {
1904 const struct got_error *pack_err =
1905 got_repo_pack_fds_close(pack_fds);
1906 if (error == NULL)
1907 error = pack_err;
1909 if (fetchpid > 0) {
1910 if (kill(fetchpid, SIGTERM) == -1)
1911 error = got_error_from_errno("kill");
1912 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1913 error = got_error_from_errno("waitpid");
1915 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1916 error = got_error_from_errno("close");
1917 if (repo) {
1918 const struct got_error *close_err = got_repo_close(repo);
1919 if (error == NULL)
1920 error = close_err;
1922 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 committer_time = got_object_commit_get_committer_time(commit);
4206 datestr = get_datestr(&committer_time, datebuf);
4207 if (datestr)
4208 printf("date: %s UTC\n", datestr);
4209 author = got_object_commit_get_author(commit);
4210 committer = got_object_commit_get_committer(commit);
4211 if (strcmp(author, committer) != 0)
4212 printf("via: %s\n", committer);
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 [-bPpRs] [-C number] [-c commit] [-l N] "
4453 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4454 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 'd':
4517 show_diffstat = 1;
4518 break;
4519 case 'c':
4520 start_commit = optarg;
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_commit_object *commit = NULL;
10158 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10159 int histedit_in_progress = 0, merge_in_progress = 0;
10160 int create_backup = 1, list_backups = 0, delete_backups = 0;
10161 struct got_object_id_queue commits;
10162 struct got_pathlist_head merged_paths;
10163 const struct got_object_id_queue *parent_ids;
10164 struct got_object_qid *qid, *pid;
10165 struct got_update_progress_arg upa;
10166 int *pack_fds = NULL;
10168 STAILQ_INIT(&commits);
10169 TAILQ_INIT(&merged_paths);
10170 memset(&upa, 0, sizeof(upa));
10172 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10173 switch (ch) {
10174 case 'a':
10175 abort_rebase = 1;
10176 break;
10177 case 'c':
10178 continue_rebase = 1;
10179 break;
10180 case 'l':
10181 list_backups = 1;
10182 break;
10183 case 'X':
10184 delete_backups = 1;
10185 break;
10186 default:
10187 usage_rebase();
10188 /* NOTREACHED */
10192 argc -= optind;
10193 argv += optind;
10195 #ifndef PROFILE
10196 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10197 "unveil", NULL) == -1)
10198 err(1, "pledge");
10199 #endif
10200 if (list_backups) {
10201 if (abort_rebase)
10202 option_conflict('l', 'a');
10203 if (continue_rebase)
10204 option_conflict('l', 'c');
10205 if (delete_backups)
10206 option_conflict('l', 'X');
10207 if (argc != 0 && argc != 1)
10208 usage_rebase();
10209 } else if (delete_backups) {
10210 if (abort_rebase)
10211 option_conflict('X', 'a');
10212 if (continue_rebase)
10213 option_conflict('X', 'c');
10214 if (list_backups)
10215 option_conflict('l', 'X');
10216 if (argc != 0 && argc != 1)
10217 usage_rebase();
10218 } else {
10219 if (abort_rebase && continue_rebase)
10220 usage_rebase();
10221 else if (abort_rebase || continue_rebase) {
10222 if (argc != 0)
10223 usage_rebase();
10224 } else if (argc != 1)
10225 usage_rebase();
10228 cwd = getcwd(NULL, 0);
10229 if (cwd == NULL) {
10230 error = got_error_from_errno("getcwd");
10231 goto done;
10234 error = got_repo_pack_fds_open(&pack_fds);
10235 if (error != NULL)
10236 goto done;
10238 error = got_worktree_open(&worktree, cwd);
10239 if (error) {
10240 if (list_backups || delete_backups) {
10241 if (error->code != GOT_ERR_NOT_WORKTREE)
10242 goto done;
10243 } else {
10244 if (error->code == GOT_ERR_NOT_WORKTREE)
10245 error = wrap_not_worktree_error(error,
10246 "rebase", cwd);
10247 goto done;
10251 error = get_gitconfig_path(&gitconfig_path);
10252 if (error)
10253 goto done;
10254 error = got_repo_open(&repo,
10255 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10256 gitconfig_path, pack_fds);
10257 if (error != NULL)
10258 goto done;
10260 error = get_author(&committer, repo, worktree);
10261 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10262 goto done;
10264 error = apply_unveil(got_repo_get_path(repo), 0,
10265 worktree ? got_worktree_get_root_path(worktree) : NULL);
10266 if (error)
10267 goto done;
10269 if (list_backups || delete_backups) {
10270 error = process_backup_refs(
10271 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10272 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10273 goto done; /* nothing else to do */
10276 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10277 worktree);
10278 if (error)
10279 goto done;
10280 if (histedit_in_progress) {
10281 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10282 goto done;
10285 error = got_worktree_merge_in_progress(&merge_in_progress,
10286 worktree, repo);
10287 if (error)
10288 goto done;
10289 if (merge_in_progress) {
10290 error = got_error(GOT_ERR_MERGE_BUSY);
10291 goto done;
10294 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10295 if (error)
10296 goto done;
10298 if (abort_rebase) {
10299 if (!rebase_in_progress) {
10300 error = got_error(GOT_ERR_NOT_REBASING);
10301 goto done;
10303 error = got_worktree_rebase_continue(&resume_commit_id,
10304 &new_base_branch, &tmp_branch, &branch, &fileindex,
10305 worktree, repo);
10306 if (error)
10307 goto done;
10308 printf("Switching work tree to %s\n",
10309 got_ref_get_symref_target(new_base_branch));
10310 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10311 new_base_branch, abort_progress, &upa);
10312 if (error)
10313 goto done;
10314 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10315 print_merge_progress_stats(&upa);
10316 goto done; /* nothing else to do */
10319 if (continue_rebase) {
10320 if (!rebase_in_progress) {
10321 error = got_error(GOT_ERR_NOT_REBASING);
10322 goto done;
10324 error = got_worktree_rebase_continue(&resume_commit_id,
10325 &new_base_branch, &tmp_branch, &branch, &fileindex,
10326 worktree, repo);
10327 if (error)
10328 goto done;
10330 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10331 committer, resume_commit_id, repo);
10332 if (error)
10333 goto done;
10335 yca_id = got_object_id_dup(resume_commit_id);
10336 if (yca_id == NULL) {
10337 error = got_error_from_errno("got_object_id_dup");
10338 goto done;
10340 } else {
10341 error = got_ref_open(&branch, repo, argv[0], 0);
10342 if (error != NULL)
10343 goto done;
10344 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10345 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10346 "will not rebase a branch which lives outside "
10347 "the \"refs/heads/\" reference namespace");
10348 goto done;
10352 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10353 if (error)
10354 goto done;
10356 if (!continue_rebase) {
10357 struct got_object_id *base_commit_id;
10359 base_commit_id = got_worktree_get_base_commit_id(worktree);
10360 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10361 base_commit_id, branch_head_commit_id, 1, repo,
10362 check_cancelled, NULL);
10363 if (error)
10364 goto done;
10365 if (yca_id == NULL) {
10366 error = got_error_msg(GOT_ERR_ANCESTRY,
10367 "specified branch shares no common ancestry "
10368 "with work tree's branch");
10369 goto done;
10372 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10373 if (error) {
10374 if (error->code != GOT_ERR_ANCESTRY)
10375 goto done;
10376 error = NULL;
10377 } else {
10378 struct got_pathlist_head paths;
10379 printf("%s is already based on %s\n",
10380 got_ref_get_name(branch),
10381 got_worktree_get_head_ref_name(worktree));
10382 error = switch_head_ref(branch, branch_head_commit_id,
10383 worktree, repo);
10384 if (error)
10385 goto done;
10386 error = got_worktree_set_base_commit_id(worktree, repo,
10387 branch_head_commit_id);
10388 if (error)
10389 goto done;
10390 TAILQ_INIT(&paths);
10391 error = got_pathlist_append(&paths, "", NULL);
10392 if (error)
10393 goto done;
10394 error = got_worktree_checkout_files(worktree,
10395 &paths, repo, update_progress, &upa,
10396 check_cancelled, NULL);
10397 got_pathlist_free(&paths);
10398 if (error)
10399 goto done;
10400 if (upa.did_something) {
10401 char *id_str;
10402 error = got_object_id_str(&id_str,
10403 branch_head_commit_id);
10404 if (error)
10405 goto done;
10406 printf("Updated to %s: %s\n",
10407 got_worktree_get_head_ref_name(worktree),
10408 id_str);
10409 free(id_str);
10410 } else
10411 printf("Already up-to-date\n");
10412 print_update_progress_stats(&upa);
10413 goto done;
10417 commit_id = branch_head_commit_id;
10418 error = got_object_open_as_commit(&commit, repo, commit_id);
10419 if (error)
10420 goto done;
10422 parent_ids = got_object_commit_get_parent_ids(commit);
10423 pid = STAILQ_FIRST(parent_ids);
10424 if (pid == NULL) {
10425 error = got_error(GOT_ERR_EMPTY_REBASE);
10426 goto done;
10428 error = collect_commits(&commits, commit_id, &pid->id,
10429 yca_id, got_worktree_get_path_prefix(worktree),
10430 GOT_ERR_REBASE_PATH, repo);
10431 got_object_commit_close(commit);
10432 commit = NULL;
10433 if (error)
10434 goto done;
10436 if (!continue_rebase) {
10437 error = got_worktree_rebase_prepare(&new_base_branch,
10438 &tmp_branch, &fileindex, worktree, branch, repo);
10439 if (error)
10440 goto done;
10443 if (STAILQ_EMPTY(&commits)) {
10444 if (continue_rebase) {
10445 error = rebase_complete(worktree, fileindex,
10446 branch, new_base_branch, tmp_branch, repo,
10447 create_backup);
10448 goto done;
10449 } else {
10450 /* Fast-forward the reference of the branch. */
10451 struct got_object_id *new_head_commit_id;
10452 char *id_str;
10453 error = got_ref_resolve(&new_head_commit_id, repo,
10454 new_base_branch);
10455 if (error)
10456 goto done;
10457 error = got_object_id_str(&id_str, new_head_commit_id);
10458 if (error)
10459 goto done;
10460 printf("Forwarding %s to commit %s\n",
10461 got_ref_get_name(branch), id_str);
10462 free(id_str);
10463 error = got_ref_change_ref(branch,
10464 new_head_commit_id);
10465 if (error)
10466 goto done;
10467 /* No backup needed since objects did not change. */
10468 create_backup = 0;
10472 pid = NULL;
10473 STAILQ_FOREACH(qid, &commits, entry) {
10475 commit_id = &qid->id;
10476 parent_id = pid ? &pid->id : yca_id;
10477 pid = qid;
10479 memset(&upa, 0, sizeof(upa));
10480 error = got_worktree_rebase_merge_files(&merged_paths,
10481 worktree, fileindex, parent_id, commit_id, repo,
10482 update_progress, &upa, check_cancelled, NULL);
10483 if (error)
10484 goto done;
10486 print_merge_progress_stats(&upa);
10487 if (upa.conflicts > 0 || upa.missing > 0 ||
10488 upa.not_deleted > 0 || upa.unversioned > 0) {
10489 if (upa.conflicts > 0) {
10490 error = show_rebase_merge_conflict(&qid->id,
10491 repo);
10492 if (error)
10493 goto done;
10495 got_worktree_rebase_pathlist_free(&merged_paths);
10496 break;
10499 error = rebase_commit(&merged_paths, worktree, fileindex,
10500 tmp_branch, committer, commit_id, repo);
10501 got_worktree_rebase_pathlist_free(&merged_paths);
10502 if (error)
10503 goto done;
10506 if (upa.conflicts > 0 || upa.missing > 0 ||
10507 upa.not_deleted > 0 || upa.unversioned > 0) {
10508 error = got_worktree_rebase_postpone(worktree, fileindex);
10509 if (error)
10510 goto done;
10511 if (upa.conflicts > 0 && upa.missing == 0 &&
10512 upa.not_deleted == 0 && upa.unversioned == 0) {
10513 error = got_error_msg(GOT_ERR_CONFLICTS,
10514 "conflicts must be resolved before rebasing "
10515 "can continue");
10516 } else if (upa.conflicts > 0) {
10517 error = got_error_msg(GOT_ERR_CONFLICTS,
10518 "conflicts must be resolved before rebasing "
10519 "can continue; changes destined for some "
10520 "files were not yet merged and should be "
10521 "merged manually if required before the "
10522 "rebase operation is continued");
10523 } else {
10524 error = got_error_msg(GOT_ERR_CONFLICTS,
10525 "changes destined for some files were not "
10526 "yet merged and should be merged manually "
10527 "if required before the rebase operation "
10528 "is continued");
10530 } else
10531 error = rebase_complete(worktree, fileindex, branch,
10532 new_base_branch, tmp_branch, repo, create_backup);
10533 done:
10534 free(cwd);
10535 free(committer);
10536 free(gitconfig_path);
10537 got_object_id_queue_free(&commits);
10538 free(branch_head_commit_id);
10539 free(resume_commit_id);
10540 free(yca_id);
10541 if (commit)
10542 got_object_commit_close(commit);
10543 if (branch)
10544 got_ref_close(branch);
10545 if (new_base_branch)
10546 got_ref_close(new_base_branch);
10547 if (tmp_branch)
10548 got_ref_close(tmp_branch);
10549 if (worktree)
10550 got_worktree_close(worktree);
10551 if (repo) {
10552 const struct got_error *close_err = got_repo_close(repo);
10553 if (error == NULL)
10554 error = close_err;
10556 if (pack_fds) {
10557 const struct got_error *pack_err =
10558 got_repo_pack_fds_close(pack_fds);
10559 if (error == NULL)
10560 error = pack_err;
10562 return error;
10565 __dead static void
10566 usage_histedit(void)
10568 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10569 "[branch]\n", getprogname());
10570 exit(1);
10573 #define GOT_HISTEDIT_PICK 'p'
10574 #define GOT_HISTEDIT_EDIT 'e'
10575 #define GOT_HISTEDIT_FOLD 'f'
10576 #define GOT_HISTEDIT_DROP 'd'
10577 #define GOT_HISTEDIT_MESG 'm'
10579 static const struct got_histedit_cmd {
10580 unsigned char code;
10581 const char *name;
10582 const char *desc;
10583 } got_histedit_cmds[] = {
10584 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10585 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10586 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10587 "be used" },
10588 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10589 { GOT_HISTEDIT_MESG, "mesg",
10590 "single-line log message for commit above (open editor if empty)" },
10593 struct got_histedit_list_entry {
10594 TAILQ_ENTRY(got_histedit_list_entry) entry;
10595 struct got_object_id *commit_id;
10596 const struct got_histedit_cmd *cmd;
10597 char *logmsg;
10599 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10601 static const struct got_error *
10602 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10603 FILE *f, struct got_repository *repo)
10605 const struct got_error *err = NULL;
10606 char *logmsg = NULL, *id_str = NULL;
10607 struct got_commit_object *commit = NULL;
10608 int n;
10610 err = got_object_open_as_commit(&commit, repo, commit_id);
10611 if (err)
10612 goto done;
10614 err = get_short_logmsg(&logmsg, 34, commit);
10615 if (err)
10616 goto done;
10618 err = got_object_id_str(&id_str, commit_id);
10619 if (err)
10620 goto done;
10622 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10623 if (n < 0)
10624 err = got_ferror(f, GOT_ERR_IO);
10625 done:
10626 if (commit)
10627 got_object_commit_close(commit);
10628 free(id_str);
10629 free(logmsg);
10630 return err;
10633 static const struct got_error *
10634 histedit_write_commit_list(struct got_object_id_queue *commits,
10635 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10636 struct got_repository *repo)
10638 const struct got_error *err = NULL;
10639 struct got_object_qid *qid;
10640 const char *histedit_cmd = NULL;
10642 if (STAILQ_EMPTY(commits))
10643 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10645 STAILQ_FOREACH(qid, commits, entry) {
10646 histedit_cmd = got_histedit_cmds[0].name;
10647 if (edit_only)
10648 histedit_cmd = "edit";
10649 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10650 histedit_cmd = "fold";
10651 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10652 if (err)
10653 break;
10654 if (edit_logmsg_only) {
10655 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10656 if (n < 0) {
10657 err = got_ferror(f, GOT_ERR_IO);
10658 break;
10663 return err;
10666 static const struct got_error *
10667 write_cmd_list(FILE *f, const char *branch_name,
10668 struct got_object_id_queue *commits)
10670 const struct got_error *err = NULL;
10671 size_t i;
10672 int n;
10673 char *id_str;
10674 struct got_object_qid *qid;
10676 qid = STAILQ_FIRST(commits);
10677 err = got_object_id_str(&id_str, &qid->id);
10678 if (err)
10679 return err;
10681 n = fprintf(f,
10682 "# Editing the history of branch '%s' starting at\n"
10683 "# commit %s\n"
10684 "# Commits will be processed in order from top to "
10685 "bottom of this file.\n", branch_name, id_str);
10686 if (n < 0) {
10687 err = got_ferror(f, GOT_ERR_IO);
10688 goto done;
10691 n = fprintf(f, "# Available histedit commands:\n");
10692 if (n < 0) {
10693 err = got_ferror(f, GOT_ERR_IO);
10694 goto done;
10697 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10698 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10699 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10700 cmd->desc);
10701 if (n < 0) {
10702 err = got_ferror(f, GOT_ERR_IO);
10703 break;
10706 done:
10707 free(id_str);
10708 return err;
10711 static const struct got_error *
10712 histedit_syntax_error(int lineno)
10714 static char msg[42];
10715 int ret;
10717 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10718 lineno);
10719 if (ret < 0 || (size_t)ret >= sizeof(msg))
10720 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10722 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10725 static const struct got_error *
10726 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10727 char *logmsg, struct got_repository *repo)
10729 const struct got_error *err;
10730 struct got_commit_object *folded_commit = NULL;
10731 char *id_str, *folded_logmsg = NULL;
10733 err = got_object_id_str(&id_str, hle->commit_id);
10734 if (err)
10735 return err;
10737 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10738 if (err)
10739 goto done;
10741 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10742 if (err)
10743 goto done;
10744 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10745 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10746 folded_logmsg) == -1) {
10747 err = got_error_from_errno("asprintf");
10749 done:
10750 if (folded_commit)
10751 got_object_commit_close(folded_commit);
10752 free(id_str);
10753 free(folded_logmsg);
10754 return err;
10757 static struct got_histedit_list_entry *
10758 get_folded_commits(struct got_histedit_list_entry *hle)
10760 struct got_histedit_list_entry *prev, *folded = NULL;
10762 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10763 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10764 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10765 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10766 folded = prev;
10767 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10770 return folded;
10773 static const struct got_error *
10774 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10775 struct got_repository *repo)
10777 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10778 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10779 const struct got_error *err = NULL;
10780 struct got_commit_object *commit = NULL;
10781 int logmsg_len;
10782 int fd;
10783 struct got_histedit_list_entry *folded = NULL;
10785 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10786 if (err)
10787 return err;
10789 folded = get_folded_commits(hle);
10790 if (folded) {
10791 while (folded != hle) {
10792 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10793 folded = TAILQ_NEXT(folded, entry);
10794 continue;
10796 err = append_folded_commit_msg(&new_msg, folded,
10797 logmsg, repo);
10798 if (err)
10799 goto done;
10800 free(logmsg);
10801 logmsg = new_msg;
10802 folded = TAILQ_NEXT(folded, entry);
10806 err = got_object_id_str(&id_str, hle->commit_id);
10807 if (err)
10808 goto done;
10809 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10810 if (err)
10811 goto done;
10812 logmsg_len = asprintf(&new_msg,
10813 "%s\n# original log message of commit %s: %s",
10814 logmsg ? logmsg : "", id_str, orig_logmsg);
10815 if (logmsg_len == -1) {
10816 err = got_error_from_errno("asprintf");
10817 goto done;
10819 free(logmsg);
10820 logmsg = new_msg;
10822 err = got_object_id_str(&id_str, hle->commit_id);
10823 if (err)
10824 goto done;
10826 err = got_opentemp_named_fd(&logmsg_path, &fd,
10827 GOT_TMPDIR_STR "/got-logmsg", "");
10828 if (err)
10829 goto done;
10831 write(fd, logmsg, logmsg_len);
10832 close(fd);
10834 err = get_editor(&editor);
10835 if (err)
10836 goto done;
10838 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10839 logmsg_len, 0);
10840 if (err) {
10841 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10842 goto done;
10843 err = NULL;
10844 hle->logmsg = strdup(new_msg);
10845 if (hle->logmsg == NULL)
10846 err = got_error_from_errno("strdup");
10848 done:
10849 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10850 err = got_error_from_errno2("unlink", logmsg_path);
10851 free(logmsg_path);
10852 free(logmsg);
10853 free(orig_logmsg);
10854 free(editor);
10855 if (commit)
10856 got_object_commit_close(commit);
10857 return err;
10860 static const struct got_error *
10861 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10862 FILE *f, struct got_repository *repo)
10864 const struct got_error *err = NULL;
10865 char *line = NULL, *p, *end;
10866 size_t i, size;
10867 ssize_t len;
10868 int lineno = 0, lastcmd = -1;
10869 const struct got_histedit_cmd *cmd;
10870 struct got_object_id *commit_id = NULL;
10871 struct got_histedit_list_entry *hle = NULL;
10873 for (;;) {
10874 len = getline(&line, &size, f);
10875 if (len == -1) {
10876 const struct got_error *getline_err;
10877 if (feof(f))
10878 break;
10879 getline_err = got_error_from_errno("getline");
10880 err = got_ferror(f, getline_err->code);
10881 break;
10883 lineno++;
10884 p = line;
10885 while (isspace((unsigned char)p[0]))
10886 p++;
10887 if (p[0] == '#' || p[0] == '\0') {
10888 free(line);
10889 line = NULL;
10890 continue;
10892 cmd = NULL;
10893 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10894 cmd = &got_histedit_cmds[i];
10895 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10896 isspace((unsigned char)p[strlen(cmd->name)])) {
10897 p += strlen(cmd->name);
10898 break;
10900 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10901 p++;
10902 break;
10905 if (i == nitems(got_histedit_cmds)) {
10906 err = histedit_syntax_error(lineno);
10907 break;
10909 while (isspace((unsigned char)p[0]))
10910 p++;
10911 if (cmd->code == GOT_HISTEDIT_MESG) {
10912 if (lastcmd != GOT_HISTEDIT_PICK &&
10913 lastcmd != GOT_HISTEDIT_EDIT) {
10914 err = got_error(GOT_ERR_HISTEDIT_CMD);
10915 break;
10917 if (p[0] == '\0') {
10918 err = histedit_edit_logmsg(hle, repo);
10919 if (err)
10920 break;
10921 } else {
10922 hle->logmsg = strdup(p);
10923 if (hle->logmsg == NULL) {
10924 err = got_error_from_errno("strdup");
10925 break;
10928 free(line);
10929 line = NULL;
10930 lastcmd = cmd->code;
10931 continue;
10932 } else {
10933 end = p;
10934 while (end[0] && !isspace((unsigned char)end[0]))
10935 end++;
10936 *end = '\0';
10938 err = got_object_resolve_id_str(&commit_id, repo, p);
10939 if (err) {
10940 /* override error code */
10941 err = histedit_syntax_error(lineno);
10942 break;
10945 hle = malloc(sizeof(*hle));
10946 if (hle == NULL) {
10947 err = got_error_from_errno("malloc");
10948 break;
10950 hle->cmd = cmd;
10951 hle->commit_id = commit_id;
10952 hle->logmsg = NULL;
10953 commit_id = NULL;
10954 free(line);
10955 line = NULL;
10956 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10957 lastcmd = cmd->code;
10960 free(line);
10961 free(commit_id);
10962 return err;
10965 static const struct got_error *
10966 histedit_check_script(struct got_histedit_list *histedit_cmds,
10967 struct got_object_id_queue *commits, struct got_repository *repo)
10969 const struct got_error *err = NULL;
10970 struct got_object_qid *qid;
10971 struct got_histedit_list_entry *hle;
10972 static char msg[92];
10973 char *id_str;
10975 if (TAILQ_EMPTY(histedit_cmds))
10976 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10977 "histedit script contains no commands");
10978 if (STAILQ_EMPTY(commits))
10979 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10981 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10982 struct got_histedit_list_entry *hle2;
10983 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10984 if (hle == hle2)
10985 continue;
10986 if (got_object_id_cmp(hle->commit_id,
10987 hle2->commit_id) != 0)
10988 continue;
10989 err = got_object_id_str(&id_str, hle->commit_id);
10990 if (err)
10991 return err;
10992 snprintf(msg, sizeof(msg), "commit %s is listed "
10993 "more than once in histedit script", id_str);
10994 free(id_str);
10995 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10999 STAILQ_FOREACH(qid, commits, entry) {
11000 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11001 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11002 break;
11004 if (hle == NULL) {
11005 err = got_object_id_str(&id_str, &qid->id);
11006 if (err)
11007 return err;
11008 snprintf(msg, sizeof(msg),
11009 "commit %s missing from histedit script", id_str);
11010 free(id_str);
11011 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11015 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11016 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11017 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11018 "last commit in histedit script cannot be folded");
11020 return NULL;
11023 static const struct got_error *
11024 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11025 const char *path, struct got_object_id_queue *commits,
11026 struct got_repository *repo)
11028 const struct got_error *err = NULL;
11029 char *editor;
11030 FILE *f = NULL;
11032 err = get_editor(&editor);
11033 if (err)
11034 return err;
11036 if (spawn_editor(editor, path) == -1) {
11037 err = got_error_from_errno("failed spawning editor");
11038 goto done;
11041 f = fopen(path, "re");
11042 if (f == NULL) {
11043 err = got_error_from_errno("fopen");
11044 goto done;
11046 err = histedit_parse_list(histedit_cmds, f, repo);
11047 if (err)
11048 goto done;
11050 err = histedit_check_script(histedit_cmds, commits, repo);
11051 done:
11052 if (f && fclose(f) == EOF && err == NULL)
11053 err = got_error_from_errno("fclose");
11054 free(editor);
11055 return err;
11058 static const struct got_error *
11059 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11060 struct got_object_id_queue *, const char *, const char *,
11061 struct got_repository *);
11063 static const struct got_error *
11064 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11065 struct got_object_id_queue *commits, const char *branch_name,
11066 int edit_logmsg_only, int fold_only, int edit_only,
11067 struct got_repository *repo)
11069 const struct got_error *err;
11070 FILE *f = NULL;
11071 char *path = NULL;
11073 err = got_opentemp_named(&path, &f, "got-histedit", "");
11074 if (err)
11075 return err;
11077 err = write_cmd_list(f, branch_name, commits);
11078 if (err)
11079 goto done;
11081 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11082 fold_only, edit_only, repo);
11083 if (err)
11084 goto done;
11086 if (edit_logmsg_only || fold_only || edit_only) {
11087 rewind(f);
11088 err = histedit_parse_list(histedit_cmds, f, repo);
11089 } else {
11090 if (fclose(f) == EOF) {
11091 err = got_error_from_errno("fclose");
11092 goto done;
11094 f = NULL;
11095 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11096 if (err) {
11097 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11098 err->code != GOT_ERR_HISTEDIT_CMD)
11099 goto done;
11100 err = histedit_edit_list_retry(histedit_cmds, err,
11101 commits, path, branch_name, repo);
11104 done:
11105 if (f && fclose(f) == EOF && err == NULL)
11106 err = got_error_from_errno("fclose");
11107 if (path && unlink(path) != 0 && err == NULL)
11108 err = got_error_from_errno2("unlink", path);
11109 free(path);
11110 return err;
11113 static const struct got_error *
11114 histedit_save_list(struct got_histedit_list *histedit_cmds,
11115 struct got_worktree *worktree, struct got_repository *repo)
11117 const struct got_error *err = NULL;
11118 char *path = NULL;
11119 FILE *f = NULL;
11120 struct got_histedit_list_entry *hle;
11121 struct got_commit_object *commit = NULL;
11123 err = got_worktree_get_histedit_script_path(&path, worktree);
11124 if (err)
11125 return err;
11127 f = fopen(path, "we");
11128 if (f == NULL) {
11129 err = got_error_from_errno2("fopen", path);
11130 goto done;
11132 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11133 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11134 repo);
11135 if (err)
11136 break;
11138 if (hle->logmsg) {
11139 int n = fprintf(f, "%c %s\n",
11140 GOT_HISTEDIT_MESG, hle->logmsg);
11141 if (n < 0) {
11142 err = got_ferror(f, GOT_ERR_IO);
11143 break;
11147 done:
11148 if (f && fclose(f) == EOF && err == NULL)
11149 err = got_error_from_errno("fclose");
11150 free(path);
11151 if (commit)
11152 got_object_commit_close(commit);
11153 return err;
11156 static void
11157 histedit_free_list(struct got_histedit_list *histedit_cmds)
11159 struct got_histedit_list_entry *hle;
11161 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11162 TAILQ_REMOVE(histedit_cmds, hle, entry);
11163 free(hle);
11167 static const struct got_error *
11168 histedit_load_list(struct got_histedit_list *histedit_cmds,
11169 const char *path, struct got_repository *repo)
11171 const struct got_error *err = NULL;
11172 FILE *f = NULL;
11174 f = fopen(path, "re");
11175 if (f == NULL) {
11176 err = got_error_from_errno2("fopen", path);
11177 goto done;
11180 err = histedit_parse_list(histedit_cmds, f, repo);
11181 done:
11182 if (f && fclose(f) == EOF && err == NULL)
11183 err = got_error_from_errno("fclose");
11184 return err;
11187 static const struct got_error *
11188 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11189 const struct got_error *edit_err, struct got_object_id_queue *commits,
11190 const char *path, const char *branch_name, struct got_repository *repo)
11192 const struct got_error *err = NULL, *prev_err = edit_err;
11193 int resp = ' ';
11195 while (resp != 'c' && resp != 'r' && resp != 'a') {
11196 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11197 "or (a)bort: ", getprogname(), prev_err->msg);
11198 resp = getchar();
11199 if (resp == '\n')
11200 resp = getchar();
11201 if (resp == 'c') {
11202 histedit_free_list(histedit_cmds);
11203 err = histedit_run_editor(histedit_cmds, path, commits,
11204 repo);
11205 if (err) {
11206 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11207 err->code != GOT_ERR_HISTEDIT_CMD)
11208 break;
11209 prev_err = err;
11210 resp = ' ';
11211 continue;
11213 break;
11214 } else if (resp == 'r') {
11215 histedit_free_list(histedit_cmds);
11216 err = histedit_edit_script(histedit_cmds,
11217 commits, branch_name, 0, 0, 0, repo);
11218 if (err) {
11219 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11220 err->code != GOT_ERR_HISTEDIT_CMD)
11221 break;
11222 prev_err = err;
11223 resp = ' ';
11224 continue;
11226 break;
11227 } else if (resp == 'a') {
11228 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11229 break;
11230 } else
11231 printf("invalid response '%c'\n", resp);
11234 return err;
11237 static const struct got_error *
11238 histedit_complete(struct got_worktree *worktree,
11239 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11240 struct got_reference *branch, struct got_repository *repo)
11242 printf("Switching work tree to %s\n",
11243 got_ref_get_symref_target(branch));
11244 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11245 branch, repo);
11248 static const struct got_error *
11249 show_histedit_progress(struct got_commit_object *commit,
11250 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11252 const struct got_error *err;
11253 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11255 err = got_object_id_str(&old_id_str, hle->commit_id);
11256 if (err)
11257 goto done;
11259 if (new_id) {
11260 err = got_object_id_str(&new_id_str, new_id);
11261 if (err)
11262 goto done;
11265 old_id_str[12] = '\0';
11266 if (new_id_str)
11267 new_id_str[12] = '\0';
11269 if (hle->logmsg) {
11270 logmsg = strdup(hle->logmsg);
11271 if (logmsg == NULL) {
11272 err = got_error_from_errno("strdup");
11273 goto done;
11275 trim_logmsg(logmsg, 42);
11276 } else {
11277 err = get_short_logmsg(&logmsg, 42, commit);
11278 if (err)
11279 goto done;
11282 switch (hle->cmd->code) {
11283 case GOT_HISTEDIT_PICK:
11284 case GOT_HISTEDIT_EDIT:
11285 printf("%s -> %s: %s\n", old_id_str,
11286 new_id_str ? new_id_str : "no-op change", logmsg);
11287 break;
11288 case GOT_HISTEDIT_DROP:
11289 case GOT_HISTEDIT_FOLD:
11290 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11291 logmsg);
11292 break;
11293 default:
11294 break;
11296 done:
11297 free(old_id_str);
11298 free(new_id_str);
11299 return err;
11302 static const struct got_error *
11303 histedit_commit(struct got_pathlist_head *merged_paths,
11304 struct got_worktree *worktree, struct got_fileindex *fileindex,
11305 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11306 const char *committer, struct got_repository *repo)
11308 const struct got_error *err;
11309 struct got_commit_object *commit;
11310 struct got_object_id *new_commit_id;
11312 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11313 && hle->logmsg == NULL) {
11314 err = histedit_edit_logmsg(hle, repo);
11315 if (err)
11316 return err;
11319 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11320 if (err)
11321 return err;
11323 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11324 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11325 hle->logmsg, repo);
11326 if (err) {
11327 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11328 goto done;
11329 err = show_histedit_progress(commit, hle, NULL);
11330 } else {
11331 err = show_histedit_progress(commit, hle, new_commit_id);
11332 free(new_commit_id);
11334 done:
11335 got_object_commit_close(commit);
11336 return err;
11339 static const struct got_error *
11340 histedit_skip_commit(struct got_histedit_list_entry *hle,
11341 struct got_worktree *worktree, struct got_repository *repo)
11343 const struct got_error *error;
11344 struct got_commit_object *commit;
11346 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11347 repo);
11348 if (error)
11349 return error;
11351 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11352 if (error)
11353 return error;
11355 error = show_histedit_progress(commit, hle, NULL);
11356 got_object_commit_close(commit);
11357 return error;
11360 static const struct got_error *
11361 check_local_changes(void *arg, unsigned char status,
11362 unsigned char staged_status, const char *path,
11363 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11364 struct got_object_id *commit_id, int dirfd, const char *de_name)
11366 int *have_local_changes = arg;
11368 switch (status) {
11369 case GOT_STATUS_ADD:
11370 case GOT_STATUS_DELETE:
11371 case GOT_STATUS_MODIFY:
11372 case GOT_STATUS_CONFLICT:
11373 *have_local_changes = 1;
11374 return got_error(GOT_ERR_CANCELLED);
11375 default:
11376 break;
11379 switch (staged_status) {
11380 case GOT_STATUS_ADD:
11381 case GOT_STATUS_DELETE:
11382 case GOT_STATUS_MODIFY:
11383 *have_local_changes = 1;
11384 return got_error(GOT_ERR_CANCELLED);
11385 default:
11386 break;
11389 return NULL;
11392 static const struct got_error *
11393 cmd_histedit(int argc, char *argv[])
11395 const struct got_error *error = NULL;
11396 struct got_worktree *worktree = NULL;
11397 struct got_fileindex *fileindex = NULL;
11398 struct got_repository *repo = NULL;
11399 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11400 struct got_reference *branch = NULL;
11401 struct got_reference *tmp_branch = NULL;
11402 struct got_object_id *resume_commit_id = NULL;
11403 struct got_object_id *base_commit_id = NULL;
11404 struct got_object_id *head_commit_id = NULL;
11405 struct got_commit_object *commit = NULL;
11406 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11407 struct got_update_progress_arg upa;
11408 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11409 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11410 int list_backups = 0, delete_backups = 0;
11411 const char *edit_script_path = NULL;
11412 struct got_object_id_queue commits;
11413 struct got_pathlist_head merged_paths;
11414 const struct got_object_id_queue *parent_ids;
11415 struct got_object_qid *pid;
11416 struct got_histedit_list histedit_cmds;
11417 struct got_histedit_list_entry *hle;
11418 int *pack_fds = NULL;
11420 STAILQ_INIT(&commits);
11421 TAILQ_INIT(&histedit_cmds);
11422 TAILQ_INIT(&merged_paths);
11423 memset(&upa, 0, sizeof(upa));
11425 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11426 switch (ch) {
11427 case 'a':
11428 abort_edit = 1;
11429 break;
11430 case 'c':
11431 continue_edit = 1;
11432 break;
11433 case 'e':
11434 edit_only = 1;
11435 break;
11436 case 'F':
11437 edit_script_path = optarg;
11438 break;
11439 case 'f':
11440 fold_only = 1;
11441 break;
11442 case 'l':
11443 list_backups = 1;
11444 break;
11445 case 'm':
11446 edit_logmsg_only = 1;
11447 break;
11448 case 'X':
11449 delete_backups = 1;
11450 break;
11451 default:
11452 usage_histedit();
11453 /* NOTREACHED */
11457 argc -= optind;
11458 argv += optind;
11460 #ifndef PROFILE
11461 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11462 "unveil", NULL) == -1)
11463 err(1, "pledge");
11464 #endif
11465 if (abort_edit && continue_edit)
11466 option_conflict('a', 'c');
11467 if (edit_script_path && edit_logmsg_only)
11468 option_conflict('F', 'm');
11469 if (abort_edit && edit_logmsg_only)
11470 option_conflict('a', 'm');
11471 if (continue_edit && edit_logmsg_only)
11472 option_conflict('c', 'm');
11473 if (abort_edit && fold_only)
11474 option_conflict('a', 'f');
11475 if (continue_edit && fold_only)
11476 option_conflict('c', 'f');
11477 if (fold_only && edit_logmsg_only)
11478 option_conflict('f', 'm');
11479 if (edit_script_path && fold_only)
11480 option_conflict('F', 'f');
11481 if (abort_edit && edit_only)
11482 option_conflict('a', 'e');
11483 if (continue_edit && edit_only)
11484 option_conflict('c', 'e');
11485 if (edit_only && edit_logmsg_only)
11486 option_conflict('e', 'm');
11487 if (edit_script_path && edit_only)
11488 option_conflict('F', 'e');
11489 if (list_backups) {
11490 if (abort_edit)
11491 option_conflict('l', 'a');
11492 if (continue_edit)
11493 option_conflict('l', 'c');
11494 if (edit_script_path)
11495 option_conflict('l', 'F');
11496 if (edit_logmsg_only)
11497 option_conflict('l', 'm');
11498 if (fold_only)
11499 option_conflict('l', 'f');
11500 if (edit_only)
11501 option_conflict('l', 'e');
11502 if (delete_backups)
11503 option_conflict('l', 'X');
11504 if (argc != 0 && argc != 1)
11505 usage_histedit();
11506 } else if (delete_backups) {
11507 if (abort_edit)
11508 option_conflict('X', 'a');
11509 if (continue_edit)
11510 option_conflict('X', 'c');
11511 if (edit_script_path)
11512 option_conflict('X', 'F');
11513 if (edit_logmsg_only)
11514 option_conflict('X', 'm');
11515 if (fold_only)
11516 option_conflict('X', 'f');
11517 if (edit_only)
11518 option_conflict('X', 'e');
11519 if (list_backups)
11520 option_conflict('X', 'l');
11521 if (argc != 0 && argc != 1)
11522 usage_histedit();
11523 } else if (argc != 0)
11524 usage_histedit();
11527 * This command cannot apply unveil(2) in all cases because the
11528 * user may choose to run an editor to edit the histedit script
11529 * and to edit individual commit log messages.
11530 * unveil(2) traverses exec(2); if an editor is used we have to
11531 * apply unveil after edit script and log messages have been written.
11532 * XXX TODO: Make use of unveil(2) where possible.
11535 cwd = getcwd(NULL, 0);
11536 if (cwd == NULL) {
11537 error = got_error_from_errno("getcwd");
11538 goto done;
11541 error = got_repo_pack_fds_open(&pack_fds);
11542 if (error != NULL)
11543 goto done;
11545 error = got_worktree_open(&worktree, cwd);
11546 if (error) {
11547 if (list_backups || delete_backups) {
11548 if (error->code != GOT_ERR_NOT_WORKTREE)
11549 goto done;
11550 } else {
11551 if (error->code == GOT_ERR_NOT_WORKTREE)
11552 error = wrap_not_worktree_error(error,
11553 "histedit", cwd);
11554 goto done;
11558 if (list_backups || delete_backups) {
11559 error = got_repo_open(&repo,
11560 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11561 NULL, pack_fds);
11562 if (error != NULL)
11563 goto done;
11564 error = apply_unveil(got_repo_get_path(repo), 0,
11565 worktree ? got_worktree_get_root_path(worktree) : NULL);
11566 if (error)
11567 goto done;
11568 error = process_backup_refs(
11569 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11570 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11571 goto done; /* nothing else to do */
11574 error = get_gitconfig_path(&gitconfig_path);
11575 if (error)
11576 goto done;
11577 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11578 gitconfig_path, pack_fds);
11579 if (error != NULL)
11580 goto done;
11582 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11583 if (error)
11584 goto done;
11585 if (rebase_in_progress) {
11586 error = got_error(GOT_ERR_REBASING);
11587 goto done;
11590 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11591 repo);
11592 if (error)
11593 goto done;
11594 if (merge_in_progress) {
11595 error = got_error(GOT_ERR_MERGE_BUSY);
11596 goto done;
11599 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11600 if (error)
11601 goto done;
11603 if (edit_in_progress && edit_logmsg_only) {
11604 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11605 "histedit operation is in progress in this "
11606 "work tree and must be continued or aborted "
11607 "before the -m option can be used");
11608 goto done;
11610 if (edit_in_progress && fold_only) {
11611 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11612 "histedit operation is in progress in this "
11613 "work tree and must be continued or aborted "
11614 "before the -f option can be used");
11615 goto done;
11617 if (edit_in_progress && edit_only) {
11618 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11619 "histedit operation is in progress in this "
11620 "work tree and must be continued or aborted "
11621 "before the -e option can be used");
11622 goto done;
11625 if (edit_in_progress && abort_edit) {
11626 error = got_worktree_histedit_continue(&resume_commit_id,
11627 &tmp_branch, &branch, &base_commit_id, &fileindex,
11628 worktree, repo);
11629 if (error)
11630 goto done;
11631 printf("Switching work tree to %s\n",
11632 got_ref_get_symref_target(branch));
11633 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11634 branch, base_commit_id, abort_progress, &upa);
11635 if (error)
11636 goto done;
11637 printf("Histedit of %s aborted\n",
11638 got_ref_get_symref_target(branch));
11639 print_merge_progress_stats(&upa);
11640 goto done; /* nothing else to do */
11641 } else if (abort_edit) {
11642 error = got_error(GOT_ERR_NOT_HISTEDIT);
11643 goto done;
11646 error = get_author(&committer, repo, worktree);
11647 if (error)
11648 goto done;
11650 if (continue_edit) {
11651 char *path;
11653 if (!edit_in_progress) {
11654 error = got_error(GOT_ERR_NOT_HISTEDIT);
11655 goto done;
11658 error = got_worktree_get_histedit_script_path(&path, worktree);
11659 if (error)
11660 goto done;
11662 error = histedit_load_list(&histedit_cmds, path, repo);
11663 free(path);
11664 if (error)
11665 goto done;
11667 error = got_worktree_histedit_continue(&resume_commit_id,
11668 &tmp_branch, &branch, &base_commit_id, &fileindex,
11669 worktree, repo);
11670 if (error)
11671 goto done;
11673 error = got_ref_resolve(&head_commit_id, repo, branch);
11674 if (error)
11675 goto done;
11677 error = got_object_open_as_commit(&commit, repo,
11678 head_commit_id);
11679 if (error)
11680 goto done;
11681 parent_ids = got_object_commit_get_parent_ids(commit);
11682 pid = STAILQ_FIRST(parent_ids);
11683 if (pid == NULL) {
11684 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11685 goto done;
11687 error = collect_commits(&commits, head_commit_id, &pid->id,
11688 base_commit_id, got_worktree_get_path_prefix(worktree),
11689 GOT_ERR_HISTEDIT_PATH, repo);
11690 got_object_commit_close(commit);
11691 commit = NULL;
11692 if (error)
11693 goto done;
11694 } else {
11695 if (edit_in_progress) {
11696 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11697 goto done;
11700 error = got_ref_open(&branch, repo,
11701 got_worktree_get_head_ref_name(worktree), 0);
11702 if (error != NULL)
11703 goto done;
11705 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11706 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11707 "will not edit commit history of a branch outside "
11708 "the \"refs/heads/\" reference namespace");
11709 goto done;
11712 error = got_ref_resolve(&head_commit_id, repo, branch);
11713 got_ref_close(branch);
11714 branch = NULL;
11715 if (error)
11716 goto done;
11718 error = got_object_open_as_commit(&commit, repo,
11719 head_commit_id);
11720 if (error)
11721 goto done;
11722 parent_ids = got_object_commit_get_parent_ids(commit);
11723 pid = STAILQ_FIRST(parent_ids);
11724 if (pid == NULL) {
11725 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11726 goto done;
11728 error = collect_commits(&commits, head_commit_id, &pid->id,
11729 got_worktree_get_base_commit_id(worktree),
11730 got_worktree_get_path_prefix(worktree),
11731 GOT_ERR_HISTEDIT_PATH, repo);
11732 got_object_commit_close(commit);
11733 commit = NULL;
11734 if (error)
11735 goto done;
11737 if (STAILQ_EMPTY(&commits)) {
11738 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11739 goto done;
11742 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11743 &base_commit_id, &fileindex, worktree, repo);
11744 if (error)
11745 goto done;
11747 if (edit_script_path) {
11748 error = histedit_load_list(&histedit_cmds,
11749 edit_script_path, repo);
11750 if (error) {
11751 got_worktree_histedit_abort(worktree, fileindex,
11752 repo, branch, base_commit_id,
11753 abort_progress, &upa);
11754 print_merge_progress_stats(&upa);
11755 goto done;
11757 } else {
11758 const char *branch_name;
11759 branch_name = got_ref_get_symref_target(branch);
11760 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11761 branch_name += 11;
11762 error = histedit_edit_script(&histedit_cmds, &commits,
11763 branch_name, edit_logmsg_only, fold_only,
11764 edit_only, repo);
11765 if (error) {
11766 got_worktree_histedit_abort(worktree, fileindex,
11767 repo, branch, base_commit_id,
11768 abort_progress, &upa);
11769 print_merge_progress_stats(&upa);
11770 goto done;
11775 error = histedit_save_list(&histedit_cmds, worktree,
11776 repo);
11777 if (error) {
11778 got_worktree_histedit_abort(worktree, fileindex,
11779 repo, branch, base_commit_id,
11780 abort_progress, &upa);
11781 print_merge_progress_stats(&upa);
11782 goto done;
11787 error = histedit_check_script(&histedit_cmds, &commits, repo);
11788 if (error)
11789 goto done;
11791 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11792 if (resume_commit_id) {
11793 if (got_object_id_cmp(hle->commit_id,
11794 resume_commit_id) != 0)
11795 continue;
11797 resume_commit_id = NULL;
11798 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11799 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11800 error = histedit_skip_commit(hle, worktree,
11801 repo);
11802 if (error)
11803 goto done;
11804 } else {
11805 struct got_pathlist_head paths;
11806 int have_changes = 0;
11808 TAILQ_INIT(&paths);
11809 error = got_pathlist_append(&paths, "", NULL);
11810 if (error)
11811 goto done;
11812 error = got_worktree_status(worktree, &paths,
11813 repo, 0, check_local_changes, &have_changes,
11814 check_cancelled, NULL);
11815 got_pathlist_free(&paths);
11816 if (error) {
11817 if (error->code != GOT_ERR_CANCELLED)
11818 goto done;
11819 if (sigint_received || sigpipe_received)
11820 goto done;
11822 if (have_changes) {
11823 error = histedit_commit(NULL, worktree,
11824 fileindex, tmp_branch, hle,
11825 committer, repo);
11826 if (error)
11827 goto done;
11828 } else {
11829 error = got_object_open_as_commit(
11830 &commit, repo, hle->commit_id);
11831 if (error)
11832 goto done;
11833 error = show_histedit_progress(commit,
11834 hle, NULL);
11835 got_object_commit_close(commit);
11836 commit = NULL;
11837 if (error)
11838 goto done;
11841 continue;
11844 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11845 error = histedit_skip_commit(hle, worktree, repo);
11846 if (error)
11847 goto done;
11848 continue;
11851 error = got_object_open_as_commit(&commit, repo,
11852 hle->commit_id);
11853 if (error)
11854 goto done;
11855 parent_ids = got_object_commit_get_parent_ids(commit);
11856 pid = STAILQ_FIRST(parent_ids);
11858 error = got_worktree_histedit_merge_files(&merged_paths,
11859 worktree, fileindex, &pid->id, hle->commit_id, repo,
11860 update_progress, &upa, check_cancelled, NULL);
11861 if (error)
11862 goto done;
11863 got_object_commit_close(commit);
11864 commit = NULL;
11866 print_merge_progress_stats(&upa);
11867 if (upa.conflicts > 0 || upa.missing > 0 ||
11868 upa.not_deleted > 0 || upa.unversioned > 0) {
11869 if (upa.conflicts > 0) {
11870 error = show_rebase_merge_conflict(
11871 hle->commit_id, repo);
11872 if (error)
11873 goto done;
11875 got_worktree_rebase_pathlist_free(&merged_paths);
11876 break;
11879 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11880 char *id_str;
11881 error = got_object_id_str(&id_str, hle->commit_id);
11882 if (error)
11883 goto done;
11884 printf("Stopping histedit for amending commit %s\n",
11885 id_str);
11886 free(id_str);
11887 got_worktree_rebase_pathlist_free(&merged_paths);
11888 error = got_worktree_histedit_postpone(worktree,
11889 fileindex);
11890 goto done;
11893 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11894 error = histedit_skip_commit(hle, worktree, repo);
11895 if (error)
11896 goto done;
11897 continue;
11900 error = histedit_commit(&merged_paths, worktree, fileindex,
11901 tmp_branch, hle, committer, repo);
11902 got_worktree_rebase_pathlist_free(&merged_paths);
11903 if (error)
11904 goto done;
11907 if (upa.conflicts > 0 || upa.missing > 0 ||
11908 upa.not_deleted > 0 || upa.unversioned > 0) {
11909 error = got_worktree_histedit_postpone(worktree, fileindex);
11910 if (error)
11911 goto done;
11912 if (upa.conflicts > 0 && upa.missing == 0 &&
11913 upa.not_deleted == 0 && upa.unversioned == 0) {
11914 error = got_error_msg(GOT_ERR_CONFLICTS,
11915 "conflicts must be resolved before histedit "
11916 "can continue");
11917 } else if (upa.conflicts > 0) {
11918 error = got_error_msg(GOT_ERR_CONFLICTS,
11919 "conflicts must be resolved before histedit "
11920 "can continue; changes destined for some "
11921 "files were not yet merged and should be "
11922 "merged manually if required before the "
11923 "histedit operation is continued");
11924 } else {
11925 error = got_error_msg(GOT_ERR_CONFLICTS,
11926 "changes destined for some files were not "
11927 "yet merged and should be merged manually "
11928 "if required before the histedit operation "
11929 "is continued");
11931 } else
11932 error = histedit_complete(worktree, fileindex, tmp_branch,
11933 branch, repo);
11934 done:
11935 free(cwd);
11936 free(committer);
11937 free(gitconfig_path);
11938 got_object_id_queue_free(&commits);
11939 histedit_free_list(&histedit_cmds);
11940 free(head_commit_id);
11941 free(base_commit_id);
11942 free(resume_commit_id);
11943 if (commit)
11944 got_object_commit_close(commit);
11945 if (branch)
11946 got_ref_close(branch);
11947 if (tmp_branch)
11948 got_ref_close(tmp_branch);
11949 if (worktree)
11950 got_worktree_close(worktree);
11951 if (repo) {
11952 const struct got_error *close_err = got_repo_close(repo);
11953 if (error == NULL)
11954 error = close_err;
11956 if (pack_fds) {
11957 const struct got_error *pack_err =
11958 got_repo_pack_fds_close(pack_fds);
11959 if (error == NULL)
11960 error = pack_err;
11962 return error;
11965 __dead static void
11966 usage_integrate(void)
11968 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11969 exit(1);
11972 static const struct got_error *
11973 cmd_integrate(int argc, char *argv[])
11975 const struct got_error *error = NULL;
11976 struct got_repository *repo = NULL;
11977 struct got_worktree *worktree = NULL;
11978 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11979 const char *branch_arg = NULL;
11980 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11981 struct got_fileindex *fileindex = NULL;
11982 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11983 int ch;
11984 struct got_update_progress_arg upa;
11985 int *pack_fds = NULL;
11987 while ((ch = getopt(argc, argv, "")) != -1) {
11988 switch (ch) {
11989 default:
11990 usage_integrate();
11991 /* NOTREACHED */
11995 argc -= optind;
11996 argv += optind;
11998 if (argc != 1)
11999 usage_integrate();
12000 branch_arg = argv[0];
12001 #ifndef PROFILE
12002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12003 "unveil", NULL) == -1)
12004 err(1, "pledge");
12005 #endif
12006 cwd = getcwd(NULL, 0);
12007 if (cwd == NULL) {
12008 error = got_error_from_errno("getcwd");
12009 goto done;
12012 error = got_repo_pack_fds_open(&pack_fds);
12013 if (error != NULL)
12014 goto done;
12016 error = got_worktree_open(&worktree, cwd);
12017 if (error) {
12018 if (error->code == GOT_ERR_NOT_WORKTREE)
12019 error = wrap_not_worktree_error(error, "integrate",
12020 cwd);
12021 goto done;
12024 error = check_rebase_or_histedit_in_progress(worktree);
12025 if (error)
12026 goto done;
12028 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12029 NULL, pack_fds);
12030 if (error != NULL)
12031 goto done;
12033 error = apply_unveil(got_repo_get_path(repo), 0,
12034 got_worktree_get_root_path(worktree));
12035 if (error)
12036 goto done;
12038 error = check_merge_in_progress(worktree, repo);
12039 if (error)
12040 goto done;
12042 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12043 error = got_error_from_errno("asprintf");
12044 goto done;
12047 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12048 &base_branch_ref, worktree, refname, repo);
12049 if (error)
12050 goto done;
12052 refname = strdup(got_ref_get_name(branch_ref));
12053 if (refname == NULL) {
12054 error = got_error_from_errno("strdup");
12055 got_worktree_integrate_abort(worktree, fileindex, repo,
12056 branch_ref, base_branch_ref);
12057 goto done;
12059 base_refname = strdup(got_ref_get_name(base_branch_ref));
12060 if (base_refname == NULL) {
12061 error = got_error_from_errno("strdup");
12062 got_worktree_integrate_abort(worktree, fileindex, repo,
12063 branch_ref, base_branch_ref);
12064 goto done;
12066 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12067 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12068 got_worktree_integrate_abort(worktree, fileindex, repo,
12069 branch_ref, base_branch_ref);
12070 goto done;
12073 error = got_ref_resolve(&commit_id, repo, branch_ref);
12074 if (error)
12075 goto done;
12077 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12078 if (error)
12079 goto done;
12081 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12082 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12083 "specified branch has already been integrated");
12084 got_worktree_integrate_abort(worktree, fileindex, repo,
12085 branch_ref, base_branch_ref);
12086 goto done;
12089 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12090 if (error) {
12091 if (error->code == GOT_ERR_ANCESTRY)
12092 error = got_error(GOT_ERR_REBASE_REQUIRED);
12093 got_worktree_integrate_abort(worktree, fileindex, repo,
12094 branch_ref, base_branch_ref);
12095 goto done;
12098 memset(&upa, 0, sizeof(upa));
12099 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12100 branch_ref, base_branch_ref, update_progress, &upa,
12101 check_cancelled, NULL);
12102 if (error)
12103 goto done;
12105 printf("Integrated %s into %s\n", refname, base_refname);
12106 print_update_progress_stats(&upa);
12107 done:
12108 if (repo) {
12109 const struct got_error *close_err = got_repo_close(repo);
12110 if (error == NULL)
12111 error = close_err;
12113 if (worktree)
12114 got_worktree_close(worktree);
12115 if (pack_fds) {
12116 const struct got_error *pack_err =
12117 got_repo_pack_fds_close(pack_fds);
12118 if (error == NULL)
12119 error = pack_err;
12121 free(cwd);
12122 free(base_commit_id);
12123 free(commit_id);
12124 free(refname);
12125 free(base_refname);
12126 return error;
12129 __dead static void
12130 usage_merge(void)
12132 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12133 exit(1);
12136 static const struct got_error *
12137 cmd_merge(int argc, char *argv[])
12139 const struct got_error *error = NULL;
12140 struct got_worktree *worktree = NULL;
12141 struct got_repository *repo = NULL;
12142 struct got_fileindex *fileindex = NULL;
12143 char *cwd = NULL, *id_str = NULL, *author = NULL;
12144 struct got_reference *branch = NULL, *wt_branch = NULL;
12145 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12146 struct got_object_id *wt_branch_tip = NULL;
12147 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12148 int interrupt_merge = 0;
12149 struct got_update_progress_arg upa;
12150 struct got_object_id *merge_commit_id = NULL;
12151 char *branch_name = NULL;
12152 int *pack_fds = NULL;
12154 memset(&upa, 0, sizeof(upa));
12156 while ((ch = getopt(argc, argv, "acn")) != -1) {
12157 switch (ch) {
12158 case 'a':
12159 abort_merge = 1;
12160 break;
12161 case 'c':
12162 continue_merge = 1;
12163 break;
12164 case 'n':
12165 interrupt_merge = 1;
12166 break;
12167 default:
12168 usage_rebase();
12169 /* NOTREACHED */
12173 argc -= optind;
12174 argv += optind;
12176 #ifndef PROFILE
12177 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12178 "unveil", NULL) == -1)
12179 err(1, "pledge");
12180 #endif
12182 if (abort_merge && continue_merge)
12183 option_conflict('a', 'c');
12184 if (abort_merge || continue_merge) {
12185 if (argc != 0)
12186 usage_merge();
12187 } else if (argc != 1)
12188 usage_merge();
12190 cwd = getcwd(NULL, 0);
12191 if (cwd == NULL) {
12192 error = got_error_from_errno("getcwd");
12193 goto done;
12196 error = got_repo_pack_fds_open(&pack_fds);
12197 if (error != NULL)
12198 goto done;
12200 error = got_worktree_open(&worktree, cwd);
12201 if (error) {
12202 if (error->code == GOT_ERR_NOT_WORKTREE)
12203 error = wrap_not_worktree_error(error,
12204 "merge", cwd);
12205 goto done;
12208 error = got_repo_open(&repo,
12209 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12210 pack_fds);
12211 if (error != NULL)
12212 goto done;
12214 error = apply_unveil(got_repo_get_path(repo), 0,
12215 worktree ? got_worktree_get_root_path(worktree) : NULL);
12216 if (error)
12217 goto done;
12219 error = check_rebase_or_histedit_in_progress(worktree);
12220 if (error)
12221 goto done;
12223 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12224 repo);
12225 if (error)
12226 goto done;
12228 if (abort_merge) {
12229 if (!merge_in_progress) {
12230 error = got_error(GOT_ERR_NOT_MERGING);
12231 goto done;
12233 error = got_worktree_merge_continue(&branch_name,
12234 &branch_tip, &fileindex, worktree, repo);
12235 if (error)
12236 goto done;
12237 error = got_worktree_merge_abort(worktree, fileindex, repo,
12238 abort_progress, &upa);
12239 if (error)
12240 goto done;
12241 printf("Merge of %s aborted\n", branch_name);
12242 goto done; /* nothing else to do */
12245 error = get_author(&author, repo, worktree);
12246 if (error)
12247 goto done;
12249 if (continue_merge) {
12250 if (!merge_in_progress) {
12251 error = got_error(GOT_ERR_NOT_MERGING);
12252 goto done;
12254 error = got_worktree_merge_continue(&branch_name,
12255 &branch_tip, &fileindex, worktree, repo);
12256 if (error)
12257 goto done;
12258 } else {
12259 error = got_ref_open(&branch, repo, argv[0], 0);
12260 if (error != NULL)
12261 goto done;
12262 branch_name = strdup(got_ref_get_name(branch));
12263 if (branch_name == NULL) {
12264 error = got_error_from_errno("strdup");
12265 goto done;
12267 error = got_ref_resolve(&branch_tip, repo, branch);
12268 if (error)
12269 goto done;
12272 error = got_ref_open(&wt_branch, repo,
12273 got_worktree_get_head_ref_name(worktree), 0);
12274 if (error)
12275 goto done;
12276 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12277 if (error)
12278 goto done;
12279 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12280 wt_branch_tip, branch_tip, 0, repo,
12281 check_cancelled, NULL);
12282 if (error && error->code != GOT_ERR_ANCESTRY)
12283 goto done;
12285 if (!continue_merge) {
12286 error = check_path_prefix(wt_branch_tip, branch_tip,
12287 got_worktree_get_path_prefix(worktree),
12288 GOT_ERR_MERGE_PATH, repo);
12289 if (error)
12290 goto done;
12291 if (yca_id) {
12292 error = check_same_branch(wt_branch_tip, branch,
12293 yca_id, repo);
12294 if (error) {
12295 if (error->code != GOT_ERR_ANCESTRY)
12296 goto done;
12297 error = NULL;
12298 } else {
12299 static char msg[512];
12300 snprintf(msg, sizeof(msg),
12301 "cannot create a merge commit because "
12302 "%s is based on %s; %s can be integrated "
12303 "with 'got integrate' instead", branch_name,
12304 got_worktree_get_head_ref_name(worktree),
12305 branch_name);
12306 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12307 goto done;
12310 error = got_worktree_merge_prepare(&fileindex, worktree,
12311 branch, repo);
12312 if (error)
12313 goto done;
12315 error = got_worktree_merge_branch(worktree, fileindex,
12316 yca_id, branch_tip, repo, update_progress, &upa,
12317 check_cancelled, NULL);
12318 if (error)
12319 goto done;
12320 print_merge_progress_stats(&upa);
12321 if (!upa.did_something) {
12322 error = got_worktree_merge_abort(worktree, fileindex,
12323 repo, abort_progress, &upa);
12324 if (error)
12325 goto done;
12326 printf("Already up-to-date\n");
12327 goto done;
12331 if (interrupt_merge) {
12332 error = got_worktree_merge_postpone(worktree, fileindex);
12333 if (error)
12334 goto done;
12335 printf("Merge of %s interrupted on request\n", branch_name);
12336 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12337 upa.not_deleted > 0 || upa.unversioned > 0) {
12338 error = got_worktree_merge_postpone(worktree, fileindex);
12339 if (error)
12340 goto done;
12341 if (upa.conflicts > 0 && upa.missing == 0 &&
12342 upa.not_deleted == 0 && upa.unversioned == 0) {
12343 error = got_error_msg(GOT_ERR_CONFLICTS,
12344 "conflicts must be resolved before merging "
12345 "can continue");
12346 } else if (upa.conflicts > 0) {
12347 error = got_error_msg(GOT_ERR_CONFLICTS,
12348 "conflicts must be resolved before merging "
12349 "can continue; changes destined for some "
12350 "files were not yet merged and "
12351 "should be merged manually if required before the "
12352 "merge operation is continued");
12353 } else {
12354 error = got_error_msg(GOT_ERR_CONFLICTS,
12355 "changes destined for some "
12356 "files were not yet merged and should be "
12357 "merged manually if required before the "
12358 "merge operation is continued");
12360 goto done;
12361 } else {
12362 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12363 fileindex, author, NULL, 1, branch_tip, branch_name,
12364 repo, continue_merge ? print_status : NULL, NULL);
12365 if (error)
12366 goto done;
12367 error = got_worktree_merge_complete(worktree, fileindex, repo);
12368 if (error)
12369 goto done;
12370 error = got_object_id_str(&id_str, merge_commit_id);
12371 if (error)
12372 goto done;
12373 printf("Merged %s into %s: %s\n", branch_name,
12374 got_worktree_get_head_ref_name(worktree),
12375 id_str);
12378 done:
12379 free(id_str);
12380 free(merge_commit_id);
12381 free(author);
12382 free(branch_tip);
12383 free(branch_name);
12384 free(yca_id);
12385 if (branch)
12386 got_ref_close(branch);
12387 if (wt_branch)
12388 got_ref_close(wt_branch);
12389 if (worktree)
12390 got_worktree_close(worktree);
12391 if (repo) {
12392 const struct got_error *close_err = got_repo_close(repo);
12393 if (error == NULL)
12394 error = close_err;
12396 if (pack_fds) {
12397 const struct got_error *pack_err =
12398 got_repo_pack_fds_close(pack_fds);
12399 if (error == NULL)
12400 error = pack_err;
12402 return error;
12405 __dead static void
12406 usage_stage(void)
12408 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12409 "[path ...]\n", getprogname());
12410 exit(1);
12413 static const struct got_error *
12414 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12415 const char *path, struct got_object_id *blob_id,
12416 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12417 int dirfd, const char *de_name)
12419 const struct got_error *err = NULL;
12420 char *id_str = NULL;
12422 if (staged_status != GOT_STATUS_ADD &&
12423 staged_status != GOT_STATUS_MODIFY &&
12424 staged_status != GOT_STATUS_DELETE)
12425 return NULL;
12427 if (staged_status == GOT_STATUS_ADD ||
12428 staged_status == GOT_STATUS_MODIFY)
12429 err = got_object_id_str(&id_str, staged_blob_id);
12430 else
12431 err = got_object_id_str(&id_str, blob_id);
12432 if (err)
12433 return err;
12435 printf("%s %c %s\n", id_str, staged_status, path);
12436 free(id_str);
12437 return NULL;
12440 static const struct got_error *
12441 cmd_stage(int argc, char *argv[])
12443 const struct got_error *error = NULL;
12444 struct got_repository *repo = NULL;
12445 struct got_worktree *worktree = NULL;
12446 char *cwd = NULL;
12447 struct got_pathlist_head paths;
12448 struct got_pathlist_entry *pe;
12449 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12450 FILE *patch_script_file = NULL;
12451 const char *patch_script_path = NULL;
12452 struct choose_patch_arg cpa;
12453 int *pack_fds = NULL;
12455 TAILQ_INIT(&paths);
12457 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12458 switch (ch) {
12459 case 'F':
12460 patch_script_path = optarg;
12461 break;
12462 case 'l':
12463 list_stage = 1;
12464 break;
12465 case 'p':
12466 pflag = 1;
12467 break;
12468 case 'S':
12469 allow_bad_symlinks = 1;
12470 break;
12471 default:
12472 usage_stage();
12473 /* NOTREACHED */
12477 argc -= optind;
12478 argv += optind;
12480 #ifndef PROFILE
12481 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12482 "unveil", NULL) == -1)
12483 err(1, "pledge");
12484 #endif
12485 if (list_stage && (pflag || patch_script_path))
12486 errx(1, "-l option cannot be used with other options");
12487 if (patch_script_path && !pflag)
12488 errx(1, "-F option can only be used together with -p option");
12490 cwd = getcwd(NULL, 0);
12491 if (cwd == NULL) {
12492 error = got_error_from_errno("getcwd");
12493 goto done;
12496 error = got_repo_pack_fds_open(&pack_fds);
12497 if (error != NULL)
12498 goto done;
12500 error = got_worktree_open(&worktree, cwd);
12501 if (error) {
12502 if (error->code == GOT_ERR_NOT_WORKTREE)
12503 error = wrap_not_worktree_error(error, "stage", cwd);
12504 goto done;
12507 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12508 NULL, pack_fds);
12509 if (error != NULL)
12510 goto done;
12512 if (patch_script_path) {
12513 patch_script_file = fopen(patch_script_path, "re");
12514 if (patch_script_file == NULL) {
12515 error = got_error_from_errno2("fopen",
12516 patch_script_path);
12517 goto done;
12520 error = apply_unveil(got_repo_get_path(repo), 0,
12521 got_worktree_get_root_path(worktree));
12522 if (error)
12523 goto done;
12525 error = check_merge_in_progress(worktree, repo);
12526 if (error)
12527 goto done;
12529 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12530 if (error)
12531 goto done;
12533 if (list_stage)
12534 error = got_worktree_status(worktree, &paths, repo, 0,
12535 print_stage, NULL, check_cancelled, NULL);
12536 else {
12537 cpa.patch_script_file = patch_script_file;
12538 cpa.action = "stage";
12539 error = got_worktree_stage(worktree, &paths,
12540 pflag ? NULL : print_status, NULL,
12541 pflag ? choose_patch : NULL, &cpa,
12542 allow_bad_symlinks, repo);
12544 done:
12545 if (patch_script_file && fclose(patch_script_file) == EOF &&
12546 error == NULL)
12547 error = got_error_from_errno2("fclose", patch_script_path);
12548 if (repo) {
12549 const struct got_error *close_err = got_repo_close(repo);
12550 if (error == NULL)
12551 error = close_err;
12553 if (worktree)
12554 got_worktree_close(worktree);
12555 if (pack_fds) {
12556 const struct got_error *pack_err =
12557 got_repo_pack_fds_close(pack_fds);
12558 if (error == NULL)
12559 error = pack_err;
12561 TAILQ_FOREACH(pe, &paths, entry)
12562 free((char *)pe->path);
12563 got_pathlist_free(&paths);
12564 free(cwd);
12565 return error;
12568 __dead static void
12569 usage_unstage(void)
12571 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12572 "[path ...]\n", getprogname());
12573 exit(1);
12577 static const struct got_error *
12578 cmd_unstage(int argc, char *argv[])
12580 const struct got_error *error = NULL;
12581 struct got_repository *repo = NULL;
12582 struct got_worktree *worktree = NULL;
12583 char *cwd = NULL;
12584 struct got_pathlist_head paths;
12585 struct got_pathlist_entry *pe;
12586 int ch, pflag = 0;
12587 struct got_update_progress_arg upa;
12588 FILE *patch_script_file = NULL;
12589 const char *patch_script_path = NULL;
12590 struct choose_patch_arg cpa;
12591 int *pack_fds = NULL;
12593 TAILQ_INIT(&paths);
12595 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12596 switch (ch) {
12597 case 'F':
12598 patch_script_path = optarg;
12599 break;
12600 case 'p':
12601 pflag = 1;
12602 break;
12603 default:
12604 usage_unstage();
12605 /* NOTREACHED */
12609 argc -= optind;
12610 argv += optind;
12612 #ifndef PROFILE
12613 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12614 "unveil", NULL) == -1)
12615 err(1, "pledge");
12616 #endif
12617 if (patch_script_path && !pflag)
12618 errx(1, "-F option can only be used together with -p option");
12620 cwd = getcwd(NULL, 0);
12621 if (cwd == NULL) {
12622 error = got_error_from_errno("getcwd");
12623 goto done;
12626 error = got_repo_pack_fds_open(&pack_fds);
12627 if (error != NULL)
12628 goto done;
12630 error = got_worktree_open(&worktree, cwd);
12631 if (error) {
12632 if (error->code == GOT_ERR_NOT_WORKTREE)
12633 error = wrap_not_worktree_error(error, "unstage", cwd);
12634 goto done;
12637 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12638 NULL, pack_fds);
12639 if (error != NULL)
12640 goto done;
12642 if (patch_script_path) {
12643 patch_script_file = fopen(patch_script_path, "re");
12644 if (patch_script_file == NULL) {
12645 error = got_error_from_errno2("fopen",
12646 patch_script_path);
12647 goto done;
12651 error = apply_unveil(got_repo_get_path(repo), 0,
12652 got_worktree_get_root_path(worktree));
12653 if (error)
12654 goto done;
12656 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12657 if (error)
12658 goto done;
12660 cpa.patch_script_file = patch_script_file;
12661 cpa.action = "unstage";
12662 memset(&upa, 0, sizeof(upa));
12663 error = got_worktree_unstage(worktree, &paths, update_progress,
12664 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12665 if (!error)
12666 print_merge_progress_stats(&upa);
12667 done:
12668 if (patch_script_file && fclose(patch_script_file) == EOF &&
12669 error == NULL)
12670 error = got_error_from_errno2("fclose", patch_script_path);
12671 if (repo) {
12672 const struct got_error *close_err = got_repo_close(repo);
12673 if (error == NULL)
12674 error = close_err;
12676 if (worktree)
12677 got_worktree_close(worktree);
12678 if (pack_fds) {
12679 const struct got_error *pack_err =
12680 got_repo_pack_fds_close(pack_fds);
12681 if (error == NULL)
12682 error = pack_err;
12684 TAILQ_FOREACH(pe, &paths, entry)
12685 free((char *)pe->path);
12686 got_pathlist_free(&paths);
12687 free(cwd);
12688 return error;
12691 __dead static void
12692 usage_cat(void)
12694 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12695 "arg ...\n", getprogname());
12696 exit(1);
12699 static const struct got_error *
12700 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12702 const struct got_error *err;
12703 struct got_blob_object *blob;
12704 int fd = -1;
12706 fd = got_opentempfd();
12707 if (fd == -1)
12708 return got_error_from_errno("got_opentempfd");
12710 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12711 if (err)
12712 goto done;
12714 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12715 done:
12716 if (fd != -1 && close(fd) == -1 && err == NULL)
12717 err = got_error_from_errno("close");
12718 if (blob)
12719 got_object_blob_close(blob);
12720 return err;
12723 static const struct got_error *
12724 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12726 const struct got_error *err;
12727 struct got_tree_object *tree;
12728 int nentries, i;
12730 err = got_object_open_as_tree(&tree, repo, id);
12731 if (err)
12732 return err;
12734 nentries = got_object_tree_get_nentries(tree);
12735 for (i = 0; i < nentries; i++) {
12736 struct got_tree_entry *te;
12737 char *id_str;
12738 if (sigint_received || sigpipe_received)
12739 break;
12740 te = got_object_tree_get_entry(tree, i);
12741 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12742 if (err)
12743 break;
12744 fprintf(outfile, "%s %.7o %s\n", id_str,
12745 got_tree_entry_get_mode(te),
12746 got_tree_entry_get_name(te));
12747 free(id_str);
12750 got_object_tree_close(tree);
12751 return err;
12754 static const struct got_error *
12755 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12757 const struct got_error *err;
12758 struct got_commit_object *commit;
12759 const struct got_object_id_queue *parent_ids;
12760 struct got_object_qid *pid;
12761 char *id_str = NULL;
12762 const char *logmsg = NULL;
12763 char gmtoff[6];
12765 err = got_object_open_as_commit(&commit, repo, id);
12766 if (err)
12767 return err;
12769 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12770 if (err)
12771 goto done;
12773 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12774 parent_ids = got_object_commit_get_parent_ids(commit);
12775 fprintf(outfile, "numparents %d\n",
12776 got_object_commit_get_nparents(commit));
12777 STAILQ_FOREACH(pid, parent_ids, entry) {
12778 char *pid_str;
12779 err = got_object_id_str(&pid_str, &pid->id);
12780 if (err)
12781 goto done;
12782 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12783 free(pid_str);
12785 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12786 got_object_commit_get_author_gmtoff(commit));
12787 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12788 got_object_commit_get_author(commit),
12789 (long long)got_object_commit_get_author_time(commit),
12790 gmtoff);
12792 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12793 got_object_commit_get_committer_gmtoff(commit));
12794 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12795 got_object_commit_get_committer(commit),
12796 (long long)got_object_commit_get_committer_time(commit),
12797 gmtoff);
12799 logmsg = got_object_commit_get_logmsg_raw(commit);
12800 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12801 fprintf(outfile, "%s", logmsg);
12802 done:
12803 free(id_str);
12804 got_object_commit_close(commit);
12805 return err;
12808 static const struct got_error *
12809 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12811 const struct got_error *err;
12812 struct got_tag_object *tag;
12813 char *id_str = NULL;
12814 const char *tagmsg = NULL;
12815 char gmtoff[6];
12817 err = got_object_open_as_tag(&tag, repo, id);
12818 if (err)
12819 return err;
12821 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12822 if (err)
12823 goto done;
12825 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12827 switch (got_object_tag_get_object_type(tag)) {
12828 case GOT_OBJ_TYPE_BLOB:
12829 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12830 GOT_OBJ_LABEL_BLOB);
12831 break;
12832 case GOT_OBJ_TYPE_TREE:
12833 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12834 GOT_OBJ_LABEL_TREE);
12835 break;
12836 case GOT_OBJ_TYPE_COMMIT:
12837 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12838 GOT_OBJ_LABEL_COMMIT);
12839 break;
12840 case GOT_OBJ_TYPE_TAG:
12841 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12842 GOT_OBJ_LABEL_TAG);
12843 break;
12844 default:
12845 break;
12848 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12849 got_object_tag_get_name(tag));
12851 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12852 got_object_tag_get_tagger_gmtoff(tag));
12853 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12854 got_object_tag_get_tagger(tag),
12855 (long long)got_object_tag_get_tagger_time(tag),
12856 gmtoff);
12858 tagmsg = got_object_tag_get_message(tag);
12859 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12860 fprintf(outfile, "%s", tagmsg);
12861 done:
12862 free(id_str);
12863 got_object_tag_close(tag);
12864 return err;
12867 static const struct got_error *
12868 cmd_cat(int argc, char *argv[])
12870 const struct got_error *error;
12871 struct got_repository *repo = NULL;
12872 struct got_worktree *worktree = NULL;
12873 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12874 const char *commit_id_str = NULL;
12875 struct got_object_id *id = NULL, *commit_id = NULL;
12876 struct got_commit_object *commit = NULL;
12877 int ch, obj_type, i, force_path = 0;
12878 struct got_reflist_head refs;
12879 int *pack_fds = NULL;
12881 TAILQ_INIT(&refs);
12883 #ifndef PROFILE
12884 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12885 NULL) == -1)
12886 err(1, "pledge");
12887 #endif
12889 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12890 switch (ch) {
12891 case 'c':
12892 commit_id_str = optarg;
12893 break;
12894 case 'P':
12895 force_path = 1;
12896 break;
12897 case 'r':
12898 repo_path = realpath(optarg, NULL);
12899 if (repo_path == NULL)
12900 return got_error_from_errno2("realpath",
12901 optarg);
12902 got_path_strip_trailing_slashes(repo_path);
12903 break;
12904 default:
12905 usage_cat();
12906 /* NOTREACHED */
12910 argc -= optind;
12911 argv += optind;
12913 cwd = getcwd(NULL, 0);
12914 if (cwd == NULL) {
12915 error = got_error_from_errno("getcwd");
12916 goto done;
12919 error = got_repo_pack_fds_open(&pack_fds);
12920 if (error != NULL)
12921 goto done;
12923 if (repo_path == NULL) {
12924 error = got_worktree_open(&worktree, cwd);
12925 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12926 goto done;
12927 if (worktree) {
12928 repo_path = strdup(
12929 got_worktree_get_repo_path(worktree));
12930 if (repo_path == NULL) {
12931 error = got_error_from_errno("strdup");
12932 goto done;
12935 /* Release work tree lock. */
12936 got_worktree_close(worktree);
12937 worktree = NULL;
12941 if (repo_path == NULL) {
12942 repo_path = strdup(cwd);
12943 if (repo_path == NULL)
12944 return got_error_from_errno("strdup");
12947 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12948 free(repo_path);
12949 if (error != NULL)
12950 goto done;
12952 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12953 if (error)
12954 goto done;
12956 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12957 if (error)
12958 goto done;
12960 if (commit_id_str == NULL)
12961 commit_id_str = GOT_REF_HEAD;
12962 error = got_repo_match_object_id(&commit_id, NULL,
12963 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12964 if (error)
12965 goto done;
12967 error = got_object_open_as_commit(&commit, repo, commit_id);
12968 if (error)
12969 goto done;
12971 for (i = 0; i < argc; i++) {
12972 if (force_path) {
12973 error = got_object_id_by_path(&id, repo, commit,
12974 argv[i]);
12975 if (error)
12976 break;
12977 } else {
12978 error = got_repo_match_object_id(&id, &label, argv[i],
12979 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12980 repo);
12981 if (error) {
12982 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12983 error->code != GOT_ERR_NOT_REF)
12984 break;
12985 error = got_object_id_by_path(&id, repo,
12986 commit, argv[i]);
12987 if (error)
12988 break;
12992 error = got_object_get_type(&obj_type, repo, id);
12993 if (error)
12994 break;
12996 switch (obj_type) {
12997 case GOT_OBJ_TYPE_BLOB:
12998 error = cat_blob(id, repo, stdout);
12999 break;
13000 case GOT_OBJ_TYPE_TREE:
13001 error = cat_tree(id, repo, stdout);
13002 break;
13003 case GOT_OBJ_TYPE_COMMIT:
13004 error = cat_commit(id, repo, stdout);
13005 break;
13006 case GOT_OBJ_TYPE_TAG:
13007 error = cat_tag(id, repo, stdout);
13008 break;
13009 default:
13010 error = got_error(GOT_ERR_OBJ_TYPE);
13011 break;
13013 if (error)
13014 break;
13015 free(label);
13016 label = NULL;
13017 free(id);
13018 id = NULL;
13020 done:
13021 free(label);
13022 free(id);
13023 free(commit_id);
13024 if (commit)
13025 got_object_commit_close(commit);
13026 if (worktree)
13027 got_worktree_close(worktree);
13028 if (repo) {
13029 const struct got_error *close_err = got_repo_close(repo);
13030 if (error == NULL)
13031 error = close_err;
13033 if (pack_fds) {
13034 const struct got_error *pack_err =
13035 got_repo_pack_fds_close(pack_fds);
13036 if (error == NULL)
13037 error = pack_err;
13040 got_ref_list_free(&refs);
13041 return error;
13044 __dead static void
13045 usage_info(void)
13047 fprintf(stderr, "usage: %s info [path ...]\n",
13048 getprogname());
13049 exit(1);
13052 static const struct got_error *
13053 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13054 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13055 struct got_object_id *commit_id)
13057 const struct got_error *err = NULL;
13058 char *id_str = NULL;
13059 char datebuf[128];
13060 struct tm mytm, *tm;
13061 struct got_pathlist_head *paths = arg;
13062 struct got_pathlist_entry *pe;
13065 * Clear error indication from any of the path arguments which
13066 * would cause this file index entry to be displayed.
13068 TAILQ_FOREACH(pe, paths, entry) {
13069 if (got_path_cmp(path, pe->path, strlen(path),
13070 pe->path_len) == 0 ||
13071 got_path_is_child(path, pe->path, pe->path_len))
13072 pe->data = NULL; /* no error */
13075 printf(GOT_COMMIT_SEP_STR);
13076 if (S_ISLNK(mode))
13077 printf("symlink: %s\n", path);
13078 else if (S_ISREG(mode)) {
13079 printf("file: %s\n", path);
13080 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13081 } else if (S_ISDIR(mode))
13082 printf("directory: %s\n", path);
13083 else
13084 printf("something: %s\n", path);
13086 tm = localtime_r(&mtime, &mytm);
13087 if (tm == NULL)
13088 return NULL;
13089 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13090 return got_error(GOT_ERR_NO_SPACE);
13091 printf("timestamp: %s\n", datebuf);
13093 if (blob_id) {
13094 err = got_object_id_str(&id_str, blob_id);
13095 if (err)
13096 return err;
13097 printf("based on blob: %s\n", id_str);
13098 free(id_str);
13101 if (staged_blob_id) {
13102 err = got_object_id_str(&id_str, staged_blob_id);
13103 if (err)
13104 return err;
13105 printf("based on staged blob: %s\n", id_str);
13106 free(id_str);
13109 if (commit_id) {
13110 err = got_object_id_str(&id_str, commit_id);
13111 if (err)
13112 return err;
13113 printf("based on commit: %s\n", id_str);
13114 free(id_str);
13117 return NULL;
13120 static const struct got_error *
13121 cmd_info(int argc, char *argv[])
13123 const struct got_error *error = NULL;
13124 struct got_worktree *worktree = NULL;
13125 char *cwd = NULL, *id_str = NULL;
13126 struct got_pathlist_head paths;
13127 struct got_pathlist_entry *pe;
13128 char *uuidstr = NULL;
13129 int ch, show_files = 0;
13131 TAILQ_INIT(&paths);
13133 while ((ch = getopt(argc, argv, "")) != -1) {
13134 switch (ch) {
13135 default:
13136 usage_info();
13137 /* NOTREACHED */
13141 argc -= optind;
13142 argv += optind;
13144 #ifndef PROFILE
13145 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13146 NULL) == -1)
13147 err(1, "pledge");
13148 #endif
13149 cwd = getcwd(NULL, 0);
13150 if (cwd == NULL) {
13151 error = got_error_from_errno("getcwd");
13152 goto done;
13155 error = got_worktree_open(&worktree, cwd);
13156 if (error) {
13157 if (error->code == GOT_ERR_NOT_WORKTREE)
13158 error = wrap_not_worktree_error(error, "info", cwd);
13159 goto done;
13162 #ifndef PROFILE
13163 /* Remove "wpath cpath proc exec sendfd" promises. */
13164 if (pledge("stdio rpath flock unveil", NULL) == -1)
13165 err(1, "pledge");
13166 #endif
13167 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13168 if (error)
13169 goto done;
13171 if (argc >= 1) {
13172 error = get_worktree_paths_from_argv(&paths, argc, argv,
13173 worktree);
13174 if (error)
13175 goto done;
13176 show_files = 1;
13179 error = got_object_id_str(&id_str,
13180 got_worktree_get_base_commit_id(worktree));
13181 if (error)
13182 goto done;
13184 error = got_worktree_get_uuid(&uuidstr, worktree);
13185 if (error)
13186 goto done;
13188 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13189 printf("work tree base commit: %s\n", id_str);
13190 printf("work tree path prefix: %s\n",
13191 got_worktree_get_path_prefix(worktree));
13192 printf("work tree branch reference: %s\n",
13193 got_worktree_get_head_ref_name(worktree));
13194 printf("work tree UUID: %s\n", uuidstr);
13195 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13197 if (show_files) {
13198 struct got_pathlist_entry *pe;
13199 TAILQ_FOREACH(pe, &paths, entry) {
13200 if (pe->path_len == 0)
13201 continue;
13203 * Assume this path will fail. This will be corrected
13204 * in print_path_info() in case the path does suceeed.
13206 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13208 error = got_worktree_path_info(worktree, &paths,
13209 print_path_info, &paths, check_cancelled, NULL);
13210 if (error)
13211 goto done;
13212 TAILQ_FOREACH(pe, &paths, entry) {
13213 if (pe->data != NULL) {
13214 const struct got_error *perr;
13216 perr = pe->data;
13217 error = got_error_fmt(perr->code, "%s",
13218 pe->path);
13219 break;
13223 done:
13224 if (worktree)
13225 got_worktree_close(worktree);
13226 TAILQ_FOREACH(pe, &paths, entry)
13227 free((char *)pe->path);
13228 got_pathlist_free(&paths);
13229 free(cwd);
13230 free(id_str);
13231 free(uuidstr);
13232 return error;