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/time.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
41 #include "got_compat.h"
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
61 #include "got_sigs.h"
62 #include "got_date.h"
64 #ifndef nitems
65 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
66 #endif
68 static volatile sig_atomic_t sigint_received;
69 static volatile sig_atomic_t sigpipe_received;
71 static void
72 catch_sigint(int signo)
73 {
74 sigint_received = 1;
75 }
77 static void
78 catch_sigpipe(int signo)
79 {
80 sigpipe_received = 1;
81 }
84 struct got_cmd {
85 const char *cmd_name;
86 const struct got_error *(*cmd_main)(int, char *[]);
87 void (*cmd_usage)(void);
88 const char *cmd_alias;
89 };
91 __dead static void usage(int, int);
92 __dead static void usage_import(void);
93 __dead static void usage_clone(void);
94 __dead static void usage_fetch(void);
95 __dead static void usage_checkout(void);
96 __dead static void usage_update(void);
97 __dead static void usage_log(void);
98 __dead static void usage_diff(void);
99 __dead static void usage_blame(void);
100 __dead static void usage_tree(void);
101 __dead static void usage_status(void);
102 __dead static void usage_ref(void);
103 __dead static void usage_branch(void);
104 __dead static void usage_tag(void);
105 __dead static void usage_add(void);
106 __dead static void usage_remove(void);
107 __dead static void usage_patch(void);
108 __dead static void usage_revert(void);
109 __dead static void usage_commit(void);
110 __dead static void usage_send(void);
111 __dead static void usage_cherrypick(void);
112 __dead static void usage_backout(void);
113 __dead static void usage_rebase(void);
114 __dead static void usage_histedit(void);
115 __dead static void usage_integrate(void);
116 __dead static void usage_merge(void);
117 __dead static void usage_stage(void);
118 __dead static void usage_unstage(void);
119 __dead static void usage_cat(void);
120 __dead static void usage_info(void);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_import(void)
349 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
350 "[-r repository-path] [-I pattern] path\n", getprogname());
351 exit(1);
354 static int
355 spawn_editor(const char *editor, const char *file)
357 pid_t pid;
358 sig_t sighup, sigint, sigquit;
359 int st = -1;
361 sighup = signal(SIGHUP, SIG_IGN);
362 sigint = signal(SIGINT, SIG_IGN);
363 sigquit = signal(SIGQUIT, SIG_IGN);
365 switch (pid = fork()) {
366 case -1:
367 goto doneediting;
368 case 0:
369 execl(editor, editor, file, (char *)NULL);
370 _exit(127);
373 while (waitpid(pid, &st, 0) == -1)
374 if (errno != EINTR)
375 break;
377 doneediting:
378 (void)signal(SIGHUP, sighup);
379 (void)signal(SIGINT, sigint);
380 (void)signal(SIGQUIT, sigquit);
382 if (!WIFEXITED(st)) {
383 errno = EINTR;
384 return -1;
387 return WEXITSTATUS(st);
390 static const struct got_error *
391 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
392 const char *initial_content, size_t initial_content_len,
393 int require_modification)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
398 ssize_t linelen;
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 ((linelen = 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 int
551 valid_author(const char *author)
553 /*
554 * Really dumb email address check; we're only doing this to
555 * avoid git's object parser breaking on commits we create.
556 */
557 while (*author && *author != '<')
558 author++;
559 if (*author != '<')
560 return 0;
561 while (*author && *author != '@')
562 author++;
563 if (*author != '@')
564 return 0;
565 while (*author && *author != '>')
566 author++;
567 return *author == '>';
570 static const struct got_error *
571 get_author(char **author, struct got_repository *repo,
572 struct got_worktree *worktree)
574 const struct got_error *err = NULL;
575 const char *got_author = NULL, *name, *email;
576 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
578 *author = NULL;
580 if (worktree)
581 worktree_conf = got_worktree_get_gotconfig(worktree);
582 repo_conf = got_repo_get_gotconfig(repo);
584 /*
585 * Priority of potential author information sources, from most
586 * significant to least significant:
587 * 1) work tree's .got/got.conf file
588 * 2) repository's got.conf file
589 * 3) repository's git config file
590 * 4) environment variables
591 * 5) global git config files (in user's home directory or /etc)
592 */
594 if (worktree_conf)
595 got_author = got_gotconfig_get_author(worktree_conf);
596 if (got_author == NULL)
597 got_author = got_gotconfig_get_author(repo_conf);
598 if (got_author == NULL) {
599 name = got_repo_get_gitconfig_author_name(repo);
600 email = got_repo_get_gitconfig_author_email(repo);
601 if (name && email) {
602 if (asprintf(author, "%s <%s>", name, email) == -1)
603 return got_error_from_errno("asprintf");
604 return NULL;
607 got_author = getenv("GOT_AUTHOR");
608 if (got_author == NULL) {
609 name = got_repo_get_global_gitconfig_author_name(repo);
610 email = got_repo_get_global_gitconfig_author_email(
611 repo);
612 if (name && email) {
613 if (asprintf(author, "%s <%s>", name, email)
614 == -1)
615 return got_error_from_errno("asprintf");
616 return NULL;
618 /* TODO: Look up user in password database? */
619 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
623 *author = strdup(got_author);
624 if (*author == NULL)
625 return got_error_from_errno("strdup");
627 if (!valid_author(*author)) {
628 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
629 free(*author);
630 *author = NULL;
632 return err;
635 static const struct got_error *
636 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
637 struct got_worktree *worktree)
639 const char *got_allowed_signers = NULL;
640 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
642 *allowed_signers = NULL;
644 if (worktree)
645 worktree_conf = got_worktree_get_gotconfig(worktree);
646 repo_conf = got_repo_get_gotconfig(repo);
648 /*
649 * Priority of potential author information sources, from most
650 * significant to least significant:
651 * 1) work tree's .got/got.conf file
652 * 2) repository's got.conf file
653 */
655 if (worktree_conf)
656 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
657 worktree_conf);
658 if (got_allowed_signers == NULL)
659 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
660 repo_conf);
662 if (got_allowed_signers) {
663 *allowed_signers = strdup(got_allowed_signers);
664 if (*allowed_signers == NULL)
665 return got_error_from_errno("strdup");
667 return NULL;
670 static const struct got_error *
671 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
672 struct got_worktree *worktree)
674 const char *got_revoked_signers = NULL;
675 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
677 *revoked_signers = NULL;
679 if (worktree)
680 worktree_conf = got_worktree_get_gotconfig(worktree);
681 repo_conf = got_repo_get_gotconfig(repo);
683 /*
684 * Priority of potential author information sources, from most
685 * significant to least significant:
686 * 1) work tree's .got/got.conf file
687 * 2) repository's got.conf file
688 */
690 if (worktree_conf)
691 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
692 worktree_conf);
693 if (got_revoked_signers == NULL)
694 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
695 repo_conf);
697 if (got_revoked_signers) {
698 *revoked_signers = strdup(got_revoked_signers);
699 if (*revoked_signers == NULL)
700 return got_error_from_errno("strdup");
702 return NULL;
705 static const struct got_error *
706 get_gitconfig_path(char **gitconfig_path)
708 const char *homedir = getenv("HOME");
710 *gitconfig_path = NULL;
711 if (homedir) {
712 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
713 return got_error_from_errno("asprintf");
716 return NULL;
719 static const struct got_error *
720 cmd_import(int argc, char *argv[])
722 const struct got_error *error = NULL;
723 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
724 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
725 const char *branch_name = "main";
726 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
727 struct got_repository *repo = NULL;
728 struct got_reference *branch_ref = NULL, *head_ref = NULL;
729 struct got_object_id *new_commit_id = NULL;
730 int ch;
731 struct got_pathlist_head ignores;
732 struct got_pathlist_entry *pe;
733 int preserve_logmsg = 0;
734 int *pack_fds = NULL;
736 TAILQ_INIT(&ignores);
738 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
739 switch (ch) {
740 case 'b':
741 branch_name = optarg;
742 break;
743 case 'm':
744 logmsg = strdup(optarg);
745 if (logmsg == NULL) {
746 error = got_error_from_errno("strdup");
747 goto done;
749 break;
750 case 'r':
751 repo_path = realpath(optarg, NULL);
752 if (repo_path == NULL) {
753 error = got_error_from_errno2("realpath",
754 optarg);
755 goto done;
757 break;
758 case 'I':
759 if (optarg[0] == '\0')
760 break;
761 error = got_pathlist_insert(&pe, &ignores, optarg,
762 NULL);
763 if (error)
764 goto done;
765 break;
766 default:
767 usage_import();
768 /* NOTREACHED */
772 argc -= optind;
773 argv += optind;
775 #ifndef PROFILE
776 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
777 "unveil",
778 NULL) == -1)
779 err(1, "pledge");
780 #endif
781 if (argc != 1)
782 usage_import();
784 if (repo_path == NULL) {
785 repo_path = getcwd(NULL, 0);
786 if (repo_path == NULL)
787 return got_error_from_errno("getcwd");
789 got_path_strip_trailing_slashes(repo_path);
790 error = get_gitconfig_path(&gitconfig_path);
791 if (error)
792 goto done;
793 error = got_repo_pack_fds_open(&pack_fds);
794 if (error != NULL)
795 goto done;
796 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
797 if (error)
798 goto done;
800 error = get_author(&author, repo, NULL);
801 if (error)
802 return error;
804 /*
805 * Don't let the user create a branch name with a leading '-'.
806 * While technically a valid reference name, this case is usually
807 * an unintended typo.
808 */
809 if (branch_name[0] == '-')
810 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
812 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
813 error = got_error_from_errno("asprintf");
814 goto done;
817 error = got_ref_open(&branch_ref, repo, refname, 0);
818 if (error) {
819 if (error->code != GOT_ERR_NOT_REF)
820 goto done;
821 } else {
822 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
823 "import target branch already exists");
824 goto done;
827 path_dir = realpath(argv[0], NULL);
828 if (path_dir == NULL) {
829 error = got_error_from_errno2("realpath", argv[0]);
830 goto done;
832 got_path_strip_trailing_slashes(path_dir);
834 /*
835 * unveil(2) traverses exec(2); if an editor is used we have
836 * to apply unveil after the log message has been written.
837 */
838 if (logmsg == NULL || strlen(logmsg) == 0) {
839 error = get_editor(&editor);
840 if (error)
841 goto done;
842 free(logmsg);
843 error = collect_import_msg(&logmsg, &logmsg_path, editor,
844 path_dir, refname);
845 if (error) {
846 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
847 logmsg_path != NULL)
848 preserve_logmsg = 1;
849 goto done;
853 if (unveil(path_dir, "r") != 0) {
854 error = got_error_from_errno2("unveil", path_dir);
855 if (logmsg_path)
856 preserve_logmsg = 1;
857 goto done;
860 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
861 if (error) {
862 if (logmsg_path)
863 preserve_logmsg = 1;
864 goto done;
867 error = got_repo_import(&new_commit_id, path_dir, logmsg,
868 author, &ignores, repo, import_progress, NULL);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
876 if (error) {
877 if (logmsg_path)
878 preserve_logmsg = 1;
879 goto done;
882 error = got_ref_write(branch_ref, repo);
883 if (error) {
884 if (logmsg_path)
885 preserve_logmsg = 1;
886 goto done;
889 error = got_object_id_str(&id_str, new_commit_id);
890 if (error) {
891 if (logmsg_path)
892 preserve_logmsg = 1;
893 goto done;
896 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
897 if (error) {
898 if (error->code != GOT_ERR_NOT_REF) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
905 branch_ref);
906 if (error) {
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = got_ref_write(head_ref, repo);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
920 printf("Created branch %s with commit %s\n",
921 got_ref_get_name(branch_ref), id_str);
922 done:
923 if (pack_fds) {
924 const struct got_error *pack_err =
925 got_repo_pack_fds_close(pack_fds);
926 if (error == NULL)
927 error = pack_err;
929 if (preserve_logmsg) {
930 fprintf(stderr, "%s: log message preserved in %s\n",
931 getprogname(), logmsg_path);
932 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
933 error = got_error_from_errno2("unlink", logmsg_path);
934 free(logmsg);
935 free(logmsg_path);
936 free(repo_path);
937 free(editor);
938 free(refname);
939 free(new_commit_id);
940 free(id_str);
941 free(author);
942 free(gitconfig_path);
943 if (branch_ref)
944 got_ref_close(branch_ref);
945 if (head_ref)
946 got_ref_close(head_ref);
947 return error;
950 __dead static void
951 usage_clone(void)
953 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
954 "[-R reference] repository-url [directory]\n", getprogname());
955 exit(1);
958 struct got_fetch_progress_arg {
959 char last_scaled_size[FMT_SCALED_STRSIZE];
960 int last_p_indexed;
961 int last_p_resolved;
962 int verbosity;
964 struct got_repository *repo;
966 int create_configs;
967 int configs_created;
968 struct {
969 struct got_pathlist_head *symrefs;
970 struct got_pathlist_head *wanted_branches;
971 struct got_pathlist_head *wanted_refs;
972 const char *proto;
973 const char *host;
974 const char *port;
975 const char *remote_repo_path;
976 const char *git_url;
977 int fetch_all_branches;
978 int mirror_references;
979 } config_info;
980 };
982 /* XXX forward declaration */
983 static const struct got_error *
984 create_config_files(const char *proto, const char *host, const char *port,
985 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
986 int mirror_references, struct got_pathlist_head *symrefs,
987 struct got_pathlist_head *wanted_branches,
988 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
990 static const struct got_error *
991 fetch_progress(void *arg, const char *message, off_t packfile_size,
992 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
994 const struct got_error *err = NULL;
995 struct got_fetch_progress_arg *a = arg;
996 char scaled_size[FMT_SCALED_STRSIZE];
997 int p_indexed, p_resolved;
998 int print_size = 0, print_indexed = 0, print_resolved = 0;
1001 * In order to allow a failed clone to be resumed with 'got fetch'
1002 * we try to create configuration files as soon as possible.
1003 * Once the server has sent information about its default branch
1004 * we have all required information.
1006 if (a->create_configs && !a->configs_created &&
1007 !TAILQ_EMPTY(a->config_info.symrefs)) {
1008 err = create_config_files(a->config_info.proto,
1009 a->config_info.host, a->config_info.port,
1010 a->config_info.remote_repo_path,
1011 a->config_info.git_url,
1012 a->config_info.fetch_all_branches,
1013 a->config_info.mirror_references,
1014 a->config_info.symrefs,
1015 a->config_info.wanted_branches,
1016 a->config_info.wanted_refs, a->repo);
1017 if (err)
1018 return err;
1019 a->configs_created = 1;
1022 if (a->verbosity < 0)
1023 return NULL;
1025 if (message && message[0] != '\0') {
1026 printf("\rserver: %s", message);
1027 fflush(stdout);
1028 return NULL;
1031 if (packfile_size > 0 || nobj_indexed > 0) {
1032 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1033 (a->last_scaled_size[0] == '\0' ||
1034 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1035 print_size = 1;
1036 if (strlcpy(a->last_scaled_size, scaled_size,
1037 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1038 return got_error(GOT_ERR_NO_SPACE);
1040 if (nobj_indexed > 0) {
1041 p_indexed = (nobj_indexed * 100) / nobj_total;
1042 if (p_indexed != a->last_p_indexed) {
1043 a->last_p_indexed = p_indexed;
1044 print_indexed = 1;
1045 print_size = 1;
1048 if (nobj_resolved > 0) {
1049 p_resolved = (nobj_resolved * 100) /
1050 (nobj_total - nobj_loose);
1051 if (p_resolved != a->last_p_resolved) {
1052 a->last_p_resolved = p_resolved;
1053 print_resolved = 1;
1054 print_indexed = 1;
1055 print_size = 1;
1060 if (print_size || print_indexed || print_resolved)
1061 printf("\r");
1062 if (print_size)
1063 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1064 if (print_indexed)
1065 printf("; indexing %d%%", p_indexed);
1066 if (print_resolved)
1067 printf("; resolving deltas %d%%", p_resolved);
1068 if (print_size || print_indexed || print_resolved)
1069 fflush(stdout);
1071 return NULL;
1074 static const struct got_error *
1075 create_symref(const char *refname, struct got_reference *target_ref,
1076 int verbosity, struct got_repository *repo)
1078 const struct got_error *err;
1079 struct got_reference *head_symref;
1081 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1082 if (err)
1083 return err;
1085 err = got_ref_write(head_symref, repo);
1086 if (err == NULL && verbosity > 0) {
1087 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1088 got_ref_get_name(target_ref));
1090 got_ref_close(head_symref);
1091 return err;
1094 static const struct got_error *
1095 list_remote_refs(struct got_pathlist_head *symrefs,
1096 struct got_pathlist_head *refs)
1098 const struct got_error *err;
1099 struct got_pathlist_entry *pe;
1101 TAILQ_FOREACH(pe, symrefs, entry) {
1102 const char *refname = pe->path;
1103 const char *targetref = pe->data;
1105 printf("%s: %s\n", refname, targetref);
1108 TAILQ_FOREACH(pe, refs, entry) {
1109 const char *refname = pe->path;
1110 struct got_object_id *id = pe->data;
1111 char *id_str;
1113 err = got_object_id_str(&id_str, id);
1114 if (err)
1115 return err;
1116 printf("%s: %s\n", refname, id_str);
1117 free(id_str);
1120 return NULL;
1123 static const struct got_error *
1124 create_ref(const char *refname, struct got_object_id *id,
1125 int verbosity, struct got_repository *repo)
1127 const struct got_error *err = NULL;
1128 struct got_reference *ref;
1129 char *id_str;
1131 err = got_object_id_str(&id_str, id);
1132 if (err)
1133 return err;
1135 err = got_ref_alloc(&ref, refname, id);
1136 if (err)
1137 goto done;
1139 err = got_ref_write(ref, repo);
1140 got_ref_close(ref);
1142 if (err == NULL && verbosity >= 0)
1143 printf("Created reference %s: %s\n", refname, id_str);
1144 done:
1145 free(id_str);
1146 return err;
1149 static int
1150 match_wanted_ref(const char *refname, const char *wanted_ref)
1152 if (strncmp(refname, "refs/", 5) != 0)
1153 return 0;
1154 refname += 5;
1157 * Prevent fetching of references that won't make any
1158 * sense outside of the remote repository's context.
1160 if (strncmp(refname, "got/", 4) == 0)
1161 return 0;
1162 if (strncmp(refname, "remotes/", 8) == 0)
1163 return 0;
1165 if (strncmp(wanted_ref, "refs/", 5) == 0)
1166 wanted_ref += 5;
1168 /* Allow prefix match. */
1169 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1170 return 1;
1172 /* Allow exact match. */
1173 return (strcmp(refname, wanted_ref) == 0);
1176 static int
1177 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1179 struct got_pathlist_entry *pe;
1181 TAILQ_FOREACH(pe, wanted_refs, entry) {
1182 if (match_wanted_ref(refname, pe->path))
1183 return 1;
1186 return 0;
1189 static const struct got_error *
1190 create_wanted_ref(const char *refname, struct got_object_id *id,
1191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1193 const struct got_error *err;
1194 char *remote_refname;
1196 if (strncmp("refs/", refname, 5) == 0)
1197 refname += 5;
1199 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1200 remote_repo_name, refname) == -1)
1201 return got_error_from_errno("asprintf");
1203 err = create_ref(remote_refname, id, verbosity, repo);
1204 free(remote_refname);
1205 return err;
1208 static const struct got_error *
1209 create_gotconfig(const char *proto, const char *host, const char *port,
1210 const char *remote_repo_path, const char *default_branch,
1211 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1212 struct got_pathlist_head *wanted_refs, int mirror_references,
1213 struct got_repository *repo)
1215 const struct got_error *err = NULL;
1216 char *gotconfig_path = NULL;
1217 char *gotconfig = NULL;
1218 FILE *gotconfig_file = NULL;
1219 const char *branchname = NULL;
1220 char *branches = NULL, *refs = NULL;
1221 ssize_t n;
1223 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1224 struct got_pathlist_entry *pe;
1225 TAILQ_FOREACH(pe, wanted_branches, entry) {
1226 char *s;
1227 branchname = pe->path;
1228 if (strncmp(branchname, "refs/heads/", 11) == 0)
1229 branchname += 11;
1230 if (asprintf(&s, "%s\"%s\" ",
1231 branches ? branches : "", branchname) == -1) {
1232 err = got_error_from_errno("asprintf");
1233 goto done;
1235 free(branches);
1236 branches = s;
1238 } else if (!fetch_all_branches && default_branch) {
1239 branchname = default_branch;
1240 if (strncmp(branchname, "refs/heads/", 11) == 0)
1241 branchname += 11;
1242 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1243 err = got_error_from_errno("asprintf");
1244 goto done;
1247 if (!TAILQ_EMPTY(wanted_refs)) {
1248 struct got_pathlist_entry *pe;
1249 TAILQ_FOREACH(pe, wanted_refs, entry) {
1250 char *s;
1251 const char *refname = pe->path;
1252 if (strncmp(refname, "refs/", 5) == 0)
1253 branchname += 5;
1254 if (asprintf(&s, "%s\"%s\" ",
1255 refs ? refs : "", refname) == -1) {
1256 err = got_error_from_errno("asprintf");
1257 goto done;
1259 free(refs);
1260 refs = s;
1264 /* Create got.conf(5). */
1265 gotconfig_path = got_repo_get_path_gotconfig(repo);
1266 if (gotconfig_path == NULL) {
1267 err = got_error_from_errno("got_repo_get_path_gotconfig");
1268 goto done;
1270 gotconfig_file = fopen(gotconfig_path, "ae");
1271 if (gotconfig_file == NULL) {
1272 err = got_error_from_errno2("fopen", gotconfig_path);
1273 goto done;
1275 if (asprintf(&gotconfig,
1276 "remote \"%s\" {\n"
1277 "\tserver %s\n"
1278 "\tprotocol %s\n"
1279 "%s%s%s"
1280 "\trepository \"%s\"\n"
1281 "%s%s%s"
1282 "%s%s%s"
1283 "%s"
1284 "%s"
1285 "}\n",
1286 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1287 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1288 remote_repo_path, branches ? "\tbranch { " : "",
1289 branches ? branches : "", branches ? "}\n" : "",
1290 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1291 mirror_references ? "\tmirror_references yes\n" : "",
1292 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1293 err = got_error_from_errno("asprintf");
1294 goto done;
1296 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1297 if (n != strlen(gotconfig)) {
1298 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1299 goto done;
1302 done:
1303 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1304 err = got_error_from_errno2("fclose", gotconfig_path);
1305 free(gotconfig_path);
1306 free(branches);
1307 return err;
1310 static const struct got_error *
1311 create_gitconfig(const char *git_url, const char *default_branch,
1312 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1313 struct got_pathlist_head *wanted_refs, int mirror_references,
1314 struct got_repository *repo)
1316 const struct got_error *err = NULL;
1317 char *gitconfig_path = NULL;
1318 char *gitconfig = NULL;
1319 FILE *gitconfig_file = NULL;
1320 char *branches = NULL, *refs = NULL;
1321 const char *branchname;
1322 ssize_t n;
1324 /* Create a config file Git can understand. */
1325 gitconfig_path = got_repo_get_path_gitconfig(repo);
1326 if (gitconfig_path == NULL) {
1327 err = got_error_from_errno("got_repo_get_path_gitconfig");
1328 goto done;
1330 gitconfig_file = fopen(gitconfig_path, "ae");
1331 if (gitconfig_file == NULL) {
1332 err = got_error_from_errno2("fopen", gitconfig_path);
1333 goto done;
1335 if (fetch_all_branches) {
1336 if (mirror_references) {
1337 if (asprintf(&branches,
1338 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1339 err = got_error_from_errno("asprintf");
1340 goto done;
1342 } else if (asprintf(&branches,
1343 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1344 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1345 err = got_error_from_errno("asprintf");
1346 goto done;
1348 } else if (!TAILQ_EMPTY(wanted_branches)) {
1349 struct got_pathlist_entry *pe;
1350 TAILQ_FOREACH(pe, wanted_branches, entry) {
1351 char *s;
1352 branchname = pe->path;
1353 if (strncmp(branchname, "refs/heads/", 11) == 0)
1354 branchname += 11;
1355 if (mirror_references) {
1356 if (asprintf(&s,
1357 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1358 branches ? branches : "",
1359 branchname, branchname) == -1) {
1360 err = got_error_from_errno("asprintf");
1361 goto done;
1363 } else if (asprintf(&s,
1364 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1365 branches ? branches : "",
1366 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1367 branchname) == -1) {
1368 err = got_error_from_errno("asprintf");
1369 goto done;
1371 free(branches);
1372 branches = s;
1374 } else {
1376 * If the server specified a default branch, use just that one.
1377 * Otherwise fall back to fetching all branches on next fetch.
1379 if (default_branch) {
1380 branchname = default_branch;
1381 if (strncmp(branchname, "refs/heads/", 11) == 0)
1382 branchname += 11;
1383 } else
1384 branchname = "*"; /* fall back to all branches */
1385 if (mirror_references) {
1386 if (asprintf(&branches,
1387 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1388 branchname, branchname) == -1) {
1389 err = got_error_from_errno("asprintf");
1390 goto done;
1392 } else if (asprintf(&branches,
1393 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1394 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1395 branchname) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1400 if (!TAILQ_EMPTY(wanted_refs)) {
1401 struct got_pathlist_entry *pe;
1402 TAILQ_FOREACH(pe, wanted_refs, entry) {
1403 char *s;
1404 const char *refname = pe->path;
1405 if (strncmp(refname, "refs/", 5) == 0)
1406 refname += 5;
1407 if (mirror_references) {
1408 if (asprintf(&s,
1409 "%s\tfetch = refs/%s:refs/%s\n",
1410 refs ? refs : "", refname, refname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1416 refs ? refs : "",
1417 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 refname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(refs);
1423 refs = s;
1427 if (asprintf(&gitconfig,
1428 "[remote \"%s\"]\n"
1429 "\turl = %s\n"
1430 "%s"
1431 "%s"
1432 "\tfetch = refs/tags/*:refs/tags/*\n",
1433 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1434 refs ? refs : "") == -1) {
1435 err = got_error_from_errno("asprintf");
1436 goto done;
1438 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1439 if (n != strlen(gitconfig)) {
1440 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1441 goto done;
1443 done:
1444 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1445 err = got_error_from_errno2("fclose", gitconfig_path);
1446 free(gitconfig_path);
1447 free(branches);
1448 return err;
1451 static const struct got_error *
1452 create_config_files(const char *proto, const char *host, const char *port,
1453 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1454 int mirror_references, struct got_pathlist_head *symrefs,
1455 struct got_pathlist_head *wanted_branches,
1456 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1458 const struct got_error *err = NULL;
1459 const char *default_branch = NULL;
1460 struct got_pathlist_entry *pe;
1463 * If we asked for a set of wanted branches then use the first
1464 * one of those.
1466 if (!TAILQ_EMPTY(wanted_branches)) {
1467 pe = TAILQ_FIRST(wanted_branches);
1468 default_branch = pe->path;
1469 } else {
1470 /* First HEAD ref listed by server is the default branch. */
1471 TAILQ_FOREACH(pe, symrefs, entry) {
1472 const char *refname = pe->path;
1473 const char *target = pe->data;
1475 if (strcmp(refname, GOT_REF_HEAD) != 0)
1476 continue;
1478 default_branch = target;
1479 break;
1483 /* Create got.conf(5). */
1484 err = create_gotconfig(proto, host, port, remote_repo_path,
1485 default_branch, fetch_all_branches, wanted_branches,
1486 wanted_refs, mirror_references, repo);
1487 if (err)
1488 return err;
1490 /* Create a config file Git can understand. */
1491 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1492 wanted_branches, wanted_refs, mirror_references, repo);
1495 static const struct got_error *
1496 cmd_clone(int argc, char *argv[])
1498 const struct got_error *error = NULL;
1499 const char *uri, *dirname;
1500 char *proto, *host, *port, *repo_name, *server_path;
1501 char *default_destdir = NULL, *id_str = NULL;
1502 const char *repo_path;
1503 struct got_repository *repo = NULL;
1504 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1505 struct got_pathlist_entry *pe;
1506 struct got_object_id *pack_hash = NULL;
1507 int ch, fetchfd = -1, fetchstatus;
1508 pid_t fetchpid = -1;
1509 struct got_fetch_progress_arg fpa;
1510 char *git_url = NULL;
1511 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1512 int list_refs_only = 0;
1513 int *pack_fds = NULL;
1515 TAILQ_INIT(&refs);
1516 TAILQ_INIT(&symrefs);
1517 TAILQ_INIT(&wanted_branches);
1518 TAILQ_INIT(&wanted_refs);
1520 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1521 switch (ch) {
1522 case 'a':
1523 fetch_all_branches = 1;
1524 break;
1525 case 'b':
1526 error = got_pathlist_append(&wanted_branches,
1527 optarg, NULL);
1528 if (error)
1529 return error;
1530 break;
1531 case 'l':
1532 list_refs_only = 1;
1533 break;
1534 case 'm':
1535 mirror_references = 1;
1536 break;
1537 case 'v':
1538 if (verbosity < 0)
1539 verbosity = 0;
1540 else if (verbosity < 3)
1541 verbosity++;
1542 break;
1543 case 'q':
1544 verbosity = -1;
1545 break;
1546 case 'R':
1547 error = got_pathlist_append(&wanted_refs,
1548 optarg, NULL);
1549 if (error)
1550 return error;
1551 break;
1552 default:
1553 usage_clone();
1554 break;
1557 argc -= optind;
1558 argv += optind;
1560 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1561 option_conflict('a', 'b');
1562 if (list_refs_only) {
1563 if (!TAILQ_EMPTY(&wanted_branches))
1564 option_conflict('l', 'b');
1565 if (fetch_all_branches)
1566 option_conflict('l', 'a');
1567 if (mirror_references)
1568 option_conflict('l', 'm');
1569 if (!TAILQ_EMPTY(&wanted_refs))
1570 option_conflict('l', 'R');
1573 uri = argv[0];
1575 if (argc == 1)
1576 dirname = NULL;
1577 else if (argc == 2)
1578 dirname = argv[1];
1579 else
1580 usage_clone();
1582 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1583 &repo_name, uri);
1584 if (error)
1585 goto done;
1587 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1588 host, port ? ":" : "", port ? port : "",
1589 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1590 error = got_error_from_errno("asprintf");
1591 goto done;
1594 if (strcmp(proto, "git") == 0) {
1595 #ifndef PROFILE
1596 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1597 "sendfd dns inet unveil", NULL) == -1)
1598 err(1, "pledge");
1599 #endif
1600 } else if (strcmp(proto, "git+ssh") == 0 ||
1601 strcmp(proto, "ssh") == 0) {
1602 #ifndef PROFILE
1603 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1604 "sendfd unveil", NULL) == -1)
1605 err(1, "pledge");
1606 #endif
1607 } else if (strcmp(proto, "http") == 0 ||
1608 strcmp(proto, "git+http") == 0) {
1609 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1610 goto done;
1611 } else {
1612 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1613 goto done;
1615 if (dirname == NULL) {
1616 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1617 error = got_error_from_errno("asprintf");
1618 goto done;
1620 repo_path = default_destdir;
1621 } else
1622 repo_path = dirname;
1624 if (!list_refs_only) {
1625 error = got_path_mkdir(repo_path);
1626 if (error &&
1627 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1628 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1629 goto done;
1630 if (!got_path_dir_is_empty(repo_path)) {
1631 error = got_error_path(repo_path,
1632 GOT_ERR_DIR_NOT_EMPTY);
1633 goto done;
1637 error = got_dial_apply_unveil(proto);
1638 if (error)
1639 goto done;
1641 error = apply_unveil(repo_path, 0, NULL);
1642 if (error)
1643 goto done;
1645 if (verbosity >= 0)
1646 printf("Connecting to %s%s%s\n", host,
1647 port ? ":" : "", port ? port : "");
1649 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1650 server_path, verbosity);
1651 if (error)
1652 goto done;
1654 if (!list_refs_only) {
1655 error = got_repo_init(repo_path);
1656 if (error)
1657 goto done;
1658 error = got_repo_pack_fds_open(&pack_fds);
1659 if (error != NULL)
1660 goto done;
1661 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1662 if (error)
1663 goto done;
1666 fpa.last_scaled_size[0] = '\0';
1667 fpa.last_p_indexed = -1;
1668 fpa.last_p_resolved = -1;
1669 fpa.verbosity = verbosity;
1670 fpa.create_configs = 1;
1671 fpa.configs_created = 0;
1672 fpa.repo = repo;
1673 fpa.config_info.symrefs = &symrefs;
1674 fpa.config_info.wanted_branches = &wanted_branches;
1675 fpa.config_info.wanted_refs = &wanted_refs;
1676 fpa.config_info.proto = proto;
1677 fpa.config_info.host = host;
1678 fpa.config_info.port = port;
1679 fpa.config_info.remote_repo_path = server_path;
1680 fpa.config_info.git_url = git_url;
1681 fpa.config_info.fetch_all_branches = fetch_all_branches;
1682 fpa.config_info.mirror_references = mirror_references;
1683 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1684 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1685 fetch_all_branches, &wanted_branches, &wanted_refs,
1686 list_refs_only, verbosity, fetchfd, repo,
1687 fetch_progress, &fpa);
1688 if (error)
1689 goto done;
1691 if (list_refs_only) {
1692 error = list_remote_refs(&symrefs, &refs);
1693 goto done;
1696 if (pack_hash == NULL) {
1697 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1698 "server sent an empty pack file");
1699 goto done;
1701 error = got_object_id_str(&id_str, pack_hash);
1702 if (error)
1703 goto done;
1704 if (verbosity >= 0)
1705 printf("\nFetched %s.pack\n", id_str);
1706 free(id_str);
1708 /* Set up references provided with the pack file. */
1709 TAILQ_FOREACH(pe, &refs, entry) {
1710 const char *refname = pe->path;
1711 struct got_object_id *id = pe->data;
1712 char *remote_refname;
1714 if (is_wanted_ref(&wanted_refs, refname) &&
1715 !mirror_references) {
1716 error = create_wanted_ref(refname, id,
1717 GOT_FETCH_DEFAULT_REMOTE_NAME,
1718 verbosity - 1, repo);
1719 if (error)
1720 goto done;
1721 continue;
1724 error = create_ref(refname, id, verbosity - 1, repo);
1725 if (error)
1726 goto done;
1728 if (mirror_references)
1729 continue;
1731 if (strncmp("refs/heads/", refname, 11) != 0)
1732 continue;
1734 if (asprintf(&remote_refname,
1735 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1736 refname + 11) == -1) {
1737 error = got_error_from_errno("asprintf");
1738 goto done;
1740 error = create_ref(remote_refname, id, verbosity - 1, repo);
1741 free(remote_refname);
1742 if (error)
1743 goto done;
1746 /* Set the HEAD reference if the server provided one. */
1747 TAILQ_FOREACH(pe, &symrefs, entry) {
1748 struct got_reference *target_ref;
1749 const char *refname = pe->path;
1750 const char *target = pe->data;
1751 char *remote_refname = NULL, *remote_target = NULL;
1753 if (strcmp(refname, GOT_REF_HEAD) != 0)
1754 continue;
1756 error = got_ref_open(&target_ref, repo, target, 0);
1757 if (error) {
1758 if (error->code == GOT_ERR_NOT_REF) {
1759 error = NULL;
1760 continue;
1762 goto done;
1765 error = create_symref(refname, target_ref, verbosity, repo);
1766 got_ref_close(target_ref);
1767 if (error)
1768 goto done;
1770 if (mirror_references)
1771 continue;
1773 if (strncmp("refs/heads/", target, 11) != 0)
1774 continue;
1776 if (asprintf(&remote_refname,
1777 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1778 refname) == -1) {
1779 error = got_error_from_errno("asprintf");
1780 goto done;
1782 if (asprintf(&remote_target,
1783 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1784 target + 11) == -1) {
1785 error = got_error_from_errno("asprintf");
1786 free(remote_refname);
1787 goto done;
1789 error = got_ref_open(&target_ref, repo, remote_target, 0);
1790 if (error) {
1791 free(remote_refname);
1792 free(remote_target);
1793 if (error->code == GOT_ERR_NOT_REF) {
1794 error = NULL;
1795 continue;
1797 goto done;
1799 error = create_symref(remote_refname, target_ref,
1800 verbosity - 1, repo);
1801 free(remote_refname);
1802 free(remote_target);
1803 got_ref_close(target_ref);
1804 if (error)
1805 goto done;
1807 if (pe == NULL) {
1809 * We failed to set the HEAD reference. If we asked for
1810 * a set of wanted branches use the first of one of those
1811 * which could be fetched instead.
1813 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1814 const char *target = pe->path;
1815 struct got_reference *target_ref;
1817 error = got_ref_open(&target_ref, repo, target, 0);
1818 if (error) {
1819 if (error->code == GOT_ERR_NOT_REF) {
1820 error = NULL;
1821 continue;
1823 goto done;
1826 error = create_symref(GOT_REF_HEAD, target_ref,
1827 verbosity, repo);
1828 got_ref_close(target_ref);
1829 if (error)
1830 goto done;
1831 break;
1835 if (verbosity >= 0)
1836 printf("Created %s repository '%s'\n",
1837 mirror_references ? "mirrored" : "cloned", repo_path);
1838 done:
1839 if (pack_fds) {
1840 const struct got_error *pack_err =
1841 got_repo_pack_fds_close(pack_fds);
1842 if (error == NULL)
1843 error = pack_err;
1845 if (fetchpid > 0) {
1846 if (kill(fetchpid, SIGTERM) == -1)
1847 error = got_error_from_errno("kill");
1848 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1849 error = got_error_from_errno("waitpid");
1851 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1852 error = got_error_from_errno("close");
1853 if (repo) {
1854 const struct got_error *close_err = got_repo_close(repo);
1855 if (error == NULL)
1856 error = close_err;
1858 TAILQ_FOREACH(pe, &refs, entry) {
1859 free((void *)pe->path);
1860 free(pe->data);
1862 got_pathlist_free(&refs);
1863 TAILQ_FOREACH(pe, &symrefs, entry) {
1864 free((void *)pe->path);
1865 free(pe->data);
1867 got_pathlist_free(&symrefs);
1868 got_pathlist_free(&wanted_branches);
1869 got_pathlist_free(&wanted_refs);
1870 free(pack_hash);
1871 free(proto);
1872 free(host);
1873 free(port);
1874 free(server_path);
1875 free(repo_name);
1876 free(default_destdir);
1877 free(git_url);
1878 return error;
1881 static const struct got_error *
1882 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1883 int replace_tags, int verbosity, struct got_repository *repo)
1885 const struct got_error *err = NULL;
1886 char *new_id_str = NULL;
1887 struct got_object_id *old_id = NULL;
1889 err = got_object_id_str(&new_id_str, new_id);
1890 if (err)
1891 goto done;
1893 if (!replace_tags &&
1894 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1895 err = got_ref_resolve(&old_id, repo, ref);
1896 if (err)
1897 goto done;
1898 if (got_object_id_cmp(old_id, new_id) == 0)
1899 goto done;
1900 if (verbosity >= 0) {
1901 printf("Rejecting update of existing tag %s: %s\n",
1902 got_ref_get_name(ref), new_id_str);
1904 goto done;
1907 if (got_ref_is_symbolic(ref)) {
1908 if (verbosity >= 0) {
1909 printf("Replacing reference %s: %s\n",
1910 got_ref_get_name(ref),
1911 got_ref_get_symref_target(ref));
1913 err = got_ref_change_symref_to_ref(ref, new_id);
1914 if (err)
1915 goto done;
1916 err = got_ref_write(ref, repo);
1917 if (err)
1918 goto done;
1919 } else {
1920 err = got_ref_resolve(&old_id, repo, ref);
1921 if (err)
1922 goto done;
1923 if (got_object_id_cmp(old_id, new_id) == 0)
1924 goto done;
1926 err = got_ref_change_ref(ref, new_id);
1927 if (err)
1928 goto done;
1929 err = got_ref_write(ref, repo);
1930 if (err)
1931 goto done;
1934 if (verbosity >= 0)
1935 printf("Updated %s: %s\n", got_ref_get_name(ref),
1936 new_id_str);
1937 done:
1938 free(old_id);
1939 free(new_id_str);
1940 return err;
1943 static const struct got_error *
1944 update_symref(const char *refname, struct got_reference *target_ref,
1945 int verbosity, struct got_repository *repo)
1947 const struct got_error *err = NULL, *unlock_err;
1948 struct got_reference *symref;
1949 int symref_is_locked = 0;
1951 err = got_ref_open(&symref, repo, refname, 1);
1952 if (err) {
1953 if (err->code != GOT_ERR_NOT_REF)
1954 return err;
1955 err = got_ref_alloc_symref(&symref, refname, target_ref);
1956 if (err)
1957 goto done;
1959 err = got_ref_write(symref, repo);
1960 if (err)
1961 goto done;
1963 if (verbosity >= 0)
1964 printf("Created reference %s: %s\n",
1965 got_ref_get_name(symref),
1966 got_ref_get_symref_target(symref));
1967 } else {
1968 symref_is_locked = 1;
1970 if (strcmp(got_ref_get_symref_target(symref),
1971 got_ref_get_name(target_ref)) == 0)
1972 goto done;
1974 err = got_ref_change_symref(symref,
1975 got_ref_get_name(target_ref));
1976 if (err)
1977 goto done;
1979 err = got_ref_write(symref, repo);
1980 if (err)
1981 goto done;
1983 if (verbosity >= 0)
1984 printf("Updated %s: %s\n", got_ref_get_name(symref),
1985 got_ref_get_symref_target(symref));
1988 done:
1989 if (symref_is_locked) {
1990 unlock_err = got_ref_unlock(symref);
1991 if (unlock_err && err == NULL)
1992 err = unlock_err;
1994 got_ref_close(symref);
1995 return err;
1998 __dead static void
1999 usage_fetch(void)
2001 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2002 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2003 "[remote-repository-name]\n",
2004 getprogname());
2005 exit(1);
2008 static const struct got_error *
2009 delete_missing_ref(struct got_reference *ref,
2010 int verbosity, struct got_repository *repo)
2012 const struct got_error *err = NULL;
2013 struct got_object_id *id = NULL;
2014 char *id_str = NULL;
2016 if (got_ref_is_symbolic(ref)) {
2017 err = got_ref_delete(ref, repo);
2018 if (err)
2019 return err;
2020 if (verbosity >= 0) {
2021 printf("Deleted %s: %s\n",
2022 got_ref_get_name(ref),
2023 got_ref_get_symref_target(ref));
2025 } else {
2026 err = got_ref_resolve(&id, repo, ref);
2027 if (err)
2028 return err;
2029 err = got_object_id_str(&id_str, id);
2030 if (err)
2031 goto done;
2033 err = got_ref_delete(ref, repo);
2034 if (err)
2035 goto done;
2036 if (verbosity >= 0) {
2037 printf("Deleted %s: %s\n",
2038 got_ref_get_name(ref), id_str);
2041 done:
2042 free(id);
2043 free(id_str);
2044 return NULL;
2047 static const struct got_error *
2048 delete_missing_refs(struct got_pathlist_head *their_refs,
2049 struct got_pathlist_head *their_symrefs,
2050 const struct got_remote_repo *remote,
2051 int verbosity, struct got_repository *repo)
2053 const struct got_error *err = NULL, *unlock_err;
2054 struct got_reflist_head my_refs;
2055 struct got_reflist_entry *re;
2056 struct got_pathlist_entry *pe;
2057 char *remote_namespace = NULL;
2058 char *local_refname = NULL;
2060 TAILQ_INIT(&my_refs);
2062 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2063 == -1)
2064 return got_error_from_errno("asprintf");
2066 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2067 if (err)
2068 goto done;
2070 TAILQ_FOREACH(re, &my_refs, entry) {
2071 const char *refname = got_ref_get_name(re->ref);
2072 const char *their_refname;
2074 if (remote->mirror_references) {
2075 their_refname = refname;
2076 } else {
2077 if (strncmp(refname, remote_namespace,
2078 strlen(remote_namespace)) == 0) {
2079 if (strcmp(refname + strlen(remote_namespace),
2080 GOT_REF_HEAD) == 0)
2081 continue;
2082 if (asprintf(&local_refname, "refs/heads/%s",
2083 refname + strlen(remote_namespace)) == -1) {
2084 err = got_error_from_errno("asprintf");
2085 goto done;
2087 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2088 continue;
2090 their_refname = local_refname;
2093 TAILQ_FOREACH(pe, their_refs, entry) {
2094 if (strcmp(their_refname, pe->path) == 0)
2095 break;
2097 if (pe != NULL)
2098 continue;
2100 TAILQ_FOREACH(pe, their_symrefs, entry) {
2101 if (strcmp(their_refname, pe->path) == 0)
2102 break;
2104 if (pe != NULL)
2105 continue;
2107 err = delete_missing_ref(re->ref, verbosity, repo);
2108 if (err)
2109 break;
2111 if (local_refname) {
2112 struct got_reference *ref;
2113 err = got_ref_open(&ref, repo, local_refname, 1);
2114 if (err) {
2115 if (err->code != GOT_ERR_NOT_REF)
2116 break;
2117 free(local_refname);
2118 local_refname = NULL;
2119 continue;
2121 err = delete_missing_ref(ref, verbosity, repo);
2122 if (err)
2123 break;
2124 unlock_err = got_ref_unlock(ref);
2125 got_ref_close(ref);
2126 if (unlock_err && err == NULL) {
2127 err = unlock_err;
2128 break;
2131 free(local_refname);
2132 local_refname = NULL;
2135 done:
2136 free(remote_namespace);
2137 free(local_refname);
2138 return err;
2141 static const struct got_error *
2142 update_wanted_ref(const char *refname, struct got_object_id *id,
2143 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2145 const struct got_error *err, *unlock_err;
2146 char *remote_refname;
2147 struct got_reference *ref;
2149 if (strncmp("refs/", refname, 5) == 0)
2150 refname += 5;
2152 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2153 remote_repo_name, refname) == -1)
2154 return got_error_from_errno("asprintf");
2156 err = got_ref_open(&ref, repo, remote_refname, 1);
2157 if (err) {
2158 if (err->code != GOT_ERR_NOT_REF)
2159 goto done;
2160 err = create_ref(remote_refname, id, verbosity, repo);
2161 } else {
2162 err = update_ref(ref, id, 0, verbosity, repo);
2163 unlock_err = got_ref_unlock(ref);
2164 if (unlock_err && err == NULL)
2165 err = unlock_err;
2166 got_ref_close(ref);
2168 done:
2169 free(remote_refname);
2170 return err;
2173 static const struct got_error *
2174 delete_ref(struct got_repository *repo, struct got_reference *ref)
2176 const struct got_error *err = NULL;
2177 struct got_object_id *id = NULL;
2178 char *id_str = NULL;
2179 const char *target;
2181 if (got_ref_is_symbolic(ref)) {
2182 target = got_ref_get_symref_target(ref);
2183 } else {
2184 err = got_ref_resolve(&id, repo, ref);
2185 if (err)
2186 goto done;
2187 err = got_object_id_str(&id_str, id);
2188 if (err)
2189 goto done;
2190 target = id_str;
2193 err = got_ref_delete(ref, repo);
2194 if (err)
2195 goto done;
2197 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2198 done:
2199 free(id);
2200 free(id_str);
2201 return err;
2204 static const struct got_error *
2205 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2207 const struct got_error *err = NULL;
2208 struct got_reflist_head refs;
2209 struct got_reflist_entry *re;
2210 char *prefix;
2212 TAILQ_INIT(&refs);
2214 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2215 err = got_error_from_errno("asprintf");
2216 goto done;
2218 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2219 if (err)
2220 goto done;
2222 TAILQ_FOREACH(re, &refs, entry)
2223 delete_ref(repo, re->ref);
2224 done:
2225 got_ref_list_free(&refs);
2226 return err;
2229 static const struct got_error *
2230 cmd_fetch(int argc, char *argv[])
2232 const struct got_error *error = NULL, *unlock_err;
2233 char *cwd = NULL, *repo_path = NULL;
2234 const char *remote_name;
2235 char *proto = NULL, *host = NULL, *port = NULL;
2236 char *repo_name = NULL, *server_path = NULL;
2237 const struct got_remote_repo *remotes, *remote = NULL;
2238 int nremotes;
2239 char *id_str = NULL;
2240 struct got_repository *repo = NULL;
2241 struct got_worktree *worktree = NULL;
2242 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2243 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2244 struct got_pathlist_entry *pe;
2245 struct got_object_id *pack_hash = NULL;
2246 int i, ch, fetchfd = -1, fetchstatus;
2247 pid_t fetchpid = -1;
2248 struct got_fetch_progress_arg fpa;
2249 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2250 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2251 int *pack_fds = NULL;
2253 TAILQ_INIT(&refs);
2254 TAILQ_INIT(&symrefs);
2255 TAILQ_INIT(&wanted_branches);
2256 TAILQ_INIT(&wanted_refs);
2258 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2259 switch (ch) {
2260 case 'a':
2261 fetch_all_branches = 1;
2262 break;
2263 case 'b':
2264 error = got_pathlist_append(&wanted_branches,
2265 optarg, NULL);
2266 if (error)
2267 return error;
2268 break;
2269 case 'd':
2270 delete_refs = 1;
2271 break;
2272 case 'l':
2273 list_refs_only = 1;
2274 break;
2275 case 'r':
2276 repo_path = realpath(optarg, NULL);
2277 if (repo_path == NULL)
2278 return got_error_from_errno2("realpath",
2279 optarg);
2280 got_path_strip_trailing_slashes(repo_path);
2281 break;
2282 case 't':
2283 replace_tags = 1;
2284 break;
2285 case 'v':
2286 if (verbosity < 0)
2287 verbosity = 0;
2288 else if (verbosity < 3)
2289 verbosity++;
2290 break;
2291 case 'q':
2292 verbosity = -1;
2293 break;
2294 case 'R':
2295 error = got_pathlist_append(&wanted_refs,
2296 optarg, NULL);
2297 if (error)
2298 return error;
2299 break;
2300 case 'X':
2301 delete_remote = 1;
2302 break;
2303 default:
2304 usage_fetch();
2305 break;
2308 argc -= optind;
2309 argv += optind;
2311 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2312 option_conflict('a', 'b');
2313 if (list_refs_only) {
2314 if (!TAILQ_EMPTY(&wanted_branches))
2315 option_conflict('l', 'b');
2316 if (fetch_all_branches)
2317 option_conflict('l', 'a');
2318 if (delete_refs)
2319 option_conflict('l', 'd');
2320 if (delete_remote)
2321 option_conflict('l', 'X');
2323 if (delete_remote) {
2324 if (fetch_all_branches)
2325 option_conflict('X', 'a');
2326 if (!TAILQ_EMPTY(&wanted_branches))
2327 option_conflict('X', 'b');
2328 if (delete_refs)
2329 option_conflict('X', 'd');
2330 if (replace_tags)
2331 option_conflict('X', 't');
2332 if (!TAILQ_EMPTY(&wanted_refs))
2333 option_conflict('X', 'R');
2336 if (argc == 0) {
2337 if (delete_remote)
2338 errx(1, "-X option requires a remote name");
2339 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2340 } else if (argc == 1)
2341 remote_name = argv[0];
2342 else
2343 usage_fetch();
2345 cwd = getcwd(NULL, 0);
2346 if (cwd == NULL) {
2347 error = got_error_from_errno("getcwd");
2348 goto done;
2351 error = got_repo_pack_fds_open(&pack_fds);
2352 if (error != NULL)
2353 goto done;
2355 if (repo_path == NULL) {
2356 error = got_worktree_open(&worktree, cwd);
2357 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2358 goto done;
2359 else
2360 error = NULL;
2361 if (worktree) {
2362 repo_path =
2363 strdup(got_worktree_get_repo_path(worktree));
2364 if (repo_path == NULL)
2365 error = got_error_from_errno("strdup");
2366 if (error)
2367 goto done;
2368 } else {
2369 repo_path = strdup(cwd);
2370 if (repo_path == NULL) {
2371 error = got_error_from_errno("strdup");
2372 goto done;
2377 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2378 if (error)
2379 goto done;
2381 if (delete_remote) {
2382 error = delete_refs_for_remote(repo, remote_name);
2383 goto done; /* nothing else to do */
2386 if (worktree) {
2387 worktree_conf = got_worktree_get_gotconfig(worktree);
2388 if (worktree_conf) {
2389 got_gotconfig_get_remotes(&nremotes, &remotes,
2390 worktree_conf);
2391 for (i = 0; i < nremotes; i++) {
2392 if (strcmp(remotes[i].name, remote_name) == 0) {
2393 remote = &remotes[i];
2394 break;
2399 if (remote == NULL) {
2400 repo_conf = got_repo_get_gotconfig(repo);
2401 if (repo_conf) {
2402 got_gotconfig_get_remotes(&nremotes, &remotes,
2403 repo_conf);
2404 for (i = 0; i < nremotes; i++) {
2405 if (strcmp(remotes[i].name, remote_name) == 0) {
2406 remote = &remotes[i];
2407 break;
2412 if (remote == NULL) {
2413 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2414 for (i = 0; i < nremotes; i++) {
2415 if (strcmp(remotes[i].name, remote_name) == 0) {
2416 remote = &remotes[i];
2417 break;
2421 if (remote == NULL) {
2422 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2423 goto done;
2426 if (TAILQ_EMPTY(&wanted_branches)) {
2427 if (!fetch_all_branches)
2428 fetch_all_branches = remote->fetch_all_branches;
2429 for (i = 0; i < remote->nfetch_branches; i++) {
2430 got_pathlist_append(&wanted_branches,
2431 remote->fetch_branches[i], NULL);
2434 if (TAILQ_EMPTY(&wanted_refs)) {
2435 for (i = 0; i < remote->nfetch_refs; i++) {
2436 got_pathlist_append(&wanted_refs,
2437 remote->fetch_refs[i], NULL);
2441 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2442 &repo_name, remote->fetch_url);
2443 if (error)
2444 goto done;
2446 if (strcmp(proto, "git") == 0) {
2447 #ifndef PROFILE
2448 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2449 "sendfd dns inet unveil", NULL) == -1)
2450 err(1, "pledge");
2451 #endif
2452 } else if (strcmp(proto, "git+ssh") == 0 ||
2453 strcmp(proto, "ssh") == 0) {
2454 #ifndef PROFILE
2455 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2456 "sendfd unveil", NULL) == -1)
2457 err(1, "pledge");
2458 #endif
2459 } else if (strcmp(proto, "http") == 0 ||
2460 strcmp(proto, "git+http") == 0) {
2461 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2462 goto done;
2463 } else {
2464 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2465 goto done;
2468 error = got_dial_apply_unveil(proto);
2469 if (error)
2470 goto done;
2472 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2473 if (error)
2474 goto done;
2476 if (verbosity >= 0)
2477 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2478 port ? ":" : "", port ? port : "");
2480 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2481 server_path, verbosity);
2482 if (error)
2483 goto done;
2485 fpa.last_scaled_size[0] = '\0';
2486 fpa.last_p_indexed = -1;
2487 fpa.last_p_resolved = -1;
2488 fpa.verbosity = verbosity;
2489 fpa.repo = repo;
2490 fpa.create_configs = 0;
2491 fpa.configs_created = 0;
2492 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2493 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2494 remote->mirror_references, fetch_all_branches, &wanted_branches,
2495 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2496 fetch_progress, &fpa);
2497 if (error)
2498 goto done;
2500 if (list_refs_only) {
2501 error = list_remote_refs(&symrefs, &refs);
2502 goto done;
2505 if (pack_hash == NULL) {
2506 if (verbosity >= 0)
2507 printf("Already up-to-date\n");
2508 } else if (verbosity >= 0) {
2509 error = got_object_id_str(&id_str, pack_hash);
2510 if (error)
2511 goto done;
2512 printf("\nFetched %s.pack\n", id_str);
2513 free(id_str);
2514 id_str = NULL;
2517 /* Update references provided with the pack file. */
2518 TAILQ_FOREACH(pe, &refs, entry) {
2519 const char *refname = pe->path;
2520 struct got_object_id *id = pe->data;
2521 struct got_reference *ref;
2522 char *remote_refname;
2524 if (is_wanted_ref(&wanted_refs, refname) &&
2525 !remote->mirror_references) {
2526 error = update_wanted_ref(refname, id,
2527 remote->name, verbosity, repo);
2528 if (error)
2529 goto done;
2530 continue;
2533 if (remote->mirror_references ||
2534 strncmp("refs/tags/", refname, 10) == 0) {
2535 error = got_ref_open(&ref, repo, refname, 1);
2536 if (error) {
2537 if (error->code != GOT_ERR_NOT_REF)
2538 goto done;
2539 error = create_ref(refname, id, verbosity,
2540 repo);
2541 if (error)
2542 goto done;
2543 } else {
2544 error = update_ref(ref, id, replace_tags,
2545 verbosity, repo);
2546 unlock_err = got_ref_unlock(ref);
2547 if (unlock_err && error == NULL)
2548 error = unlock_err;
2549 got_ref_close(ref);
2550 if (error)
2551 goto done;
2553 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2554 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2555 remote_name, refname + 11) == -1) {
2556 error = got_error_from_errno("asprintf");
2557 goto done;
2560 error = got_ref_open(&ref, repo, remote_refname, 1);
2561 if (error) {
2562 if (error->code != GOT_ERR_NOT_REF)
2563 goto done;
2564 error = create_ref(remote_refname, id,
2565 verbosity, repo);
2566 if (error)
2567 goto done;
2568 } else {
2569 error = update_ref(ref, id, replace_tags,
2570 verbosity, repo);
2571 unlock_err = got_ref_unlock(ref);
2572 if (unlock_err && error == NULL)
2573 error = unlock_err;
2574 got_ref_close(ref);
2575 if (error)
2576 goto done;
2579 /* Also create a local branch if none exists yet. */
2580 error = got_ref_open(&ref, repo, refname, 1);
2581 if (error) {
2582 if (error->code != GOT_ERR_NOT_REF)
2583 goto done;
2584 error = create_ref(refname, id, verbosity,
2585 repo);
2586 if (error)
2587 goto done;
2588 } else {
2589 unlock_err = got_ref_unlock(ref);
2590 if (unlock_err && error == NULL)
2591 error = unlock_err;
2592 got_ref_close(ref);
2596 if (delete_refs) {
2597 error = delete_missing_refs(&refs, &symrefs, remote,
2598 verbosity, repo);
2599 if (error)
2600 goto done;
2603 if (!remote->mirror_references) {
2604 /* Update remote HEAD reference if the server provided one. */
2605 TAILQ_FOREACH(pe, &symrefs, entry) {
2606 struct got_reference *target_ref;
2607 const char *refname = pe->path;
2608 const char *target = pe->data;
2609 char *remote_refname = NULL, *remote_target = NULL;
2611 if (strcmp(refname, GOT_REF_HEAD) != 0)
2612 continue;
2614 if (strncmp("refs/heads/", target, 11) != 0)
2615 continue;
2617 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2618 remote->name, refname) == -1) {
2619 error = got_error_from_errno("asprintf");
2620 goto done;
2622 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2623 remote->name, target + 11) == -1) {
2624 error = got_error_from_errno("asprintf");
2625 free(remote_refname);
2626 goto done;
2629 error = got_ref_open(&target_ref, repo, remote_target,
2630 0);
2631 if (error) {
2632 free(remote_refname);
2633 free(remote_target);
2634 if (error->code == GOT_ERR_NOT_REF) {
2635 error = NULL;
2636 continue;
2638 goto done;
2640 error = update_symref(remote_refname, target_ref,
2641 verbosity, repo);
2642 free(remote_refname);
2643 free(remote_target);
2644 got_ref_close(target_ref);
2645 if (error)
2646 goto done;
2649 done:
2650 if (fetchpid > 0) {
2651 if (kill(fetchpid, SIGTERM) == -1)
2652 error = got_error_from_errno("kill");
2653 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2654 error = got_error_from_errno("waitpid");
2656 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2657 error = got_error_from_errno("close");
2658 if (repo) {
2659 const struct got_error *close_err = got_repo_close(repo);
2660 if (error == NULL)
2661 error = close_err;
2663 if (worktree)
2664 got_worktree_close(worktree);
2665 if (pack_fds) {
2666 const struct got_error *pack_err =
2667 got_repo_pack_fds_close(pack_fds);
2668 if (error == NULL)
2669 error = pack_err;
2671 TAILQ_FOREACH(pe, &refs, entry) {
2672 free((void *)pe->path);
2673 free(pe->data);
2675 got_pathlist_free(&refs);
2676 TAILQ_FOREACH(pe, &symrefs, entry) {
2677 free((void *)pe->path);
2678 free(pe->data);
2680 got_pathlist_free(&symrefs);
2681 got_pathlist_free(&wanted_branches);
2682 got_pathlist_free(&wanted_refs);
2683 free(id_str);
2684 free(cwd);
2685 free(repo_path);
2686 free(pack_hash);
2687 free(proto);
2688 free(host);
2689 free(port);
2690 free(server_path);
2691 free(repo_name);
2692 return error;
2696 __dead static void
2697 usage_checkout(void)
2699 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2700 "[-p prefix] [-q] repository-path [worktree-path]\n",
2701 getprogname());
2702 exit(1);
2705 static void
2706 show_worktree_base_ref_warning(void)
2708 fprintf(stderr, "%s: warning: could not create a reference "
2709 "to the work tree's base commit; the commit could be "
2710 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2711 "repository writable and running 'got update' will prevent this\n",
2712 getprogname());
2715 struct got_checkout_progress_arg {
2716 const char *worktree_path;
2717 int had_base_commit_ref_error;
2718 int verbosity;
2721 static const struct got_error *
2722 checkout_progress(void *arg, unsigned char status, const char *path)
2724 struct got_checkout_progress_arg *a = arg;
2726 /* Base commit bump happens silently. */
2727 if (status == GOT_STATUS_BUMP_BASE)
2728 return NULL;
2730 if (status == GOT_STATUS_BASE_REF_ERR) {
2731 a->had_base_commit_ref_error = 1;
2732 return NULL;
2735 while (path[0] == '/')
2736 path++;
2738 if (a->verbosity >= 0)
2739 printf("%c %s/%s\n", status, a->worktree_path, path);
2741 return NULL;
2744 static const struct got_error *
2745 check_cancelled(void *arg)
2747 if (sigint_received || sigpipe_received)
2748 return got_error(GOT_ERR_CANCELLED);
2749 return NULL;
2752 static const struct got_error *
2753 check_linear_ancestry(struct got_object_id *commit_id,
2754 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2755 struct got_repository *repo)
2757 const struct got_error *err = NULL;
2758 struct got_object_id *yca_id;
2760 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2761 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2762 if (err)
2763 return err;
2765 if (yca_id == NULL)
2766 return got_error(GOT_ERR_ANCESTRY);
2769 * Require a straight line of history between the target commit
2770 * and the work tree's base commit.
2772 * Non-linear situations such as this require a rebase:
2774 * (commit) D F (base_commit)
2775 * \ /
2776 * C E
2777 * \ /
2778 * B (yca)
2779 * |
2780 * A
2782 * 'got update' only handles linear cases:
2783 * Update forwards in time: A (base/yca) - B - C - D (commit)
2784 * Update backwards in time: D (base) - C - B - A (commit/yca)
2786 if (allow_forwards_in_time_only) {
2787 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2788 return got_error(GOT_ERR_ANCESTRY);
2789 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2790 got_object_id_cmp(base_commit_id, yca_id) != 0)
2791 return got_error(GOT_ERR_ANCESTRY);
2793 free(yca_id);
2794 return NULL;
2797 static const struct got_error *
2798 check_same_branch(struct got_object_id *commit_id,
2799 struct got_reference *head_ref, struct got_object_id *yca_id,
2800 struct got_repository *repo)
2802 const struct got_error *err = NULL;
2803 struct got_commit_graph *graph = NULL;
2804 struct got_object_id *head_commit_id = NULL;
2805 int is_same_branch = 0;
2807 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2808 if (err)
2809 goto done;
2811 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2812 is_same_branch = 1;
2813 goto done;
2815 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2816 is_same_branch = 1;
2817 goto done;
2820 err = got_commit_graph_open(&graph, "/", 1);
2821 if (err)
2822 goto done;
2824 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2825 check_cancelled, NULL);
2826 if (err)
2827 goto done;
2829 for (;;) {
2830 struct got_object_id *id;
2831 err = got_commit_graph_iter_next(&id, graph, repo,
2832 check_cancelled, NULL);
2833 if (err) {
2834 if (err->code == GOT_ERR_ITER_COMPLETED)
2835 err = NULL;
2836 break;
2839 if (id) {
2840 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2841 break;
2842 if (got_object_id_cmp(id, commit_id) == 0) {
2843 is_same_branch = 1;
2844 break;
2848 done:
2849 if (graph)
2850 got_commit_graph_close(graph);
2851 free(head_commit_id);
2852 if (!err && !is_same_branch)
2853 err = got_error(GOT_ERR_ANCESTRY);
2854 return err;
2857 static const struct got_error *
2858 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2860 static char msg[512];
2861 const char *branch_name;
2863 if (got_ref_is_symbolic(ref))
2864 branch_name = got_ref_get_symref_target(ref);
2865 else
2866 branch_name = got_ref_get_name(ref);
2868 if (strncmp("refs/heads/", branch_name, 11) == 0)
2869 branch_name += 11;
2871 snprintf(msg, sizeof(msg),
2872 "target commit is not contained in branch '%s'; "
2873 "the branch to use must be specified with -b; "
2874 "if necessary a new branch can be created for "
2875 "this commit with 'got branch -c %s BRANCH_NAME'",
2876 branch_name, commit_id_str);
2878 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2881 static const struct got_error *
2882 cmd_checkout(int argc, char *argv[])
2884 const struct got_error *error = NULL;
2885 struct got_repository *repo = NULL;
2886 struct got_reference *head_ref = NULL, *ref = NULL;
2887 struct got_worktree *worktree = NULL;
2888 char *repo_path = NULL;
2889 char *worktree_path = NULL;
2890 const char *path_prefix = "";
2891 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2892 char *commit_id_str = NULL;
2893 struct got_object_id *commit_id = NULL;
2894 char *cwd = NULL;
2895 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2896 struct got_pathlist_head paths;
2897 struct got_checkout_progress_arg cpa;
2898 int *pack_fds = NULL;
2900 TAILQ_INIT(&paths);
2902 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2903 switch (ch) {
2904 case 'b':
2905 branch_name = optarg;
2906 break;
2907 case 'c':
2908 commit_id_str = strdup(optarg);
2909 if (commit_id_str == NULL)
2910 return got_error_from_errno("strdup");
2911 break;
2912 case 'E':
2913 allow_nonempty = 1;
2914 break;
2915 case 'p':
2916 path_prefix = optarg;
2917 break;
2918 case 'q':
2919 verbosity = -1;
2920 break;
2921 default:
2922 usage_checkout();
2923 /* NOTREACHED */
2927 argc -= optind;
2928 argv += optind;
2930 #ifndef PROFILE
2931 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2932 "unveil", NULL) == -1)
2933 err(1, "pledge");
2934 #endif
2935 if (argc == 1) {
2936 char *base, *dotgit;
2937 const char *path;
2938 repo_path = realpath(argv[0], NULL);
2939 if (repo_path == NULL)
2940 return got_error_from_errno2("realpath", argv[0]);
2941 cwd = getcwd(NULL, 0);
2942 if (cwd == NULL) {
2943 error = got_error_from_errno("getcwd");
2944 goto done;
2946 if (path_prefix[0])
2947 path = path_prefix;
2948 else
2949 path = repo_path;
2950 error = got_path_basename(&base, path);
2951 if (error)
2952 goto done;
2953 dotgit = strstr(base, ".git");
2954 if (dotgit)
2955 *dotgit = '\0';
2956 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2957 error = got_error_from_errno("asprintf");
2958 free(base);
2959 goto done;
2961 free(base);
2962 } else if (argc == 2) {
2963 repo_path = realpath(argv[0], NULL);
2964 if (repo_path == NULL) {
2965 error = got_error_from_errno2("realpath", argv[0]);
2966 goto done;
2968 worktree_path = realpath(argv[1], NULL);
2969 if (worktree_path == NULL) {
2970 if (errno != ENOENT) {
2971 error = got_error_from_errno2("realpath",
2972 argv[1]);
2973 goto done;
2975 worktree_path = strdup(argv[1]);
2976 if (worktree_path == NULL) {
2977 error = got_error_from_errno("strdup");
2978 goto done;
2981 } else
2982 usage_checkout();
2984 got_path_strip_trailing_slashes(repo_path);
2985 got_path_strip_trailing_slashes(worktree_path);
2987 error = got_repo_pack_fds_open(&pack_fds);
2988 if (error != NULL)
2989 goto done;
2991 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2992 if (error != NULL)
2993 goto done;
2995 /* Pre-create work tree path for unveil(2) */
2996 error = got_path_mkdir(worktree_path);
2997 if (error) {
2998 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2999 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3000 goto done;
3001 if (!allow_nonempty &&
3002 !got_path_dir_is_empty(worktree_path)) {
3003 error = got_error_path(worktree_path,
3004 GOT_ERR_DIR_NOT_EMPTY);
3005 goto done;
3009 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3010 if (error)
3011 goto done;
3013 error = got_ref_open(&head_ref, repo, branch_name, 0);
3014 if (error != NULL)
3015 goto done;
3017 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3018 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3019 goto done;
3021 error = got_worktree_open(&worktree, worktree_path);
3022 if (error != NULL)
3023 goto done;
3025 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3026 path_prefix);
3027 if (error != NULL)
3028 goto done;
3029 if (!same_path_prefix) {
3030 error = got_error(GOT_ERR_PATH_PREFIX);
3031 goto done;
3034 if (commit_id_str) {
3035 struct got_reflist_head refs;
3036 TAILQ_INIT(&refs);
3037 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3038 NULL);
3039 if (error)
3040 goto done;
3041 error = got_repo_match_object_id(&commit_id, NULL,
3042 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3043 got_ref_list_free(&refs);
3044 if (error)
3045 goto done;
3046 error = check_linear_ancestry(commit_id,
3047 got_worktree_get_base_commit_id(worktree), 0, repo);
3048 if (error != NULL) {
3049 if (error->code == GOT_ERR_ANCESTRY) {
3050 error = checkout_ancestry_error(
3051 head_ref, commit_id_str);
3053 goto done;
3055 error = check_same_branch(commit_id, head_ref, NULL, repo);
3056 if (error) {
3057 if (error->code == GOT_ERR_ANCESTRY) {
3058 error = checkout_ancestry_error(
3059 head_ref, commit_id_str);
3061 goto done;
3063 error = got_worktree_set_base_commit_id(worktree, repo,
3064 commit_id);
3065 if (error)
3066 goto done;
3067 /* Expand potentially abbreviated commit ID string. */
3068 free(commit_id_str);
3069 error = got_object_id_str(&commit_id_str, commit_id);
3070 if (error)
3071 goto done;
3072 } else {
3073 commit_id = got_object_id_dup(
3074 got_worktree_get_base_commit_id(worktree));
3075 if (commit_id == NULL) {
3076 error = got_error_from_errno("got_object_id_dup");
3077 goto done;
3079 error = got_object_id_str(&commit_id_str, commit_id);
3080 if (error)
3081 goto done;
3084 error = got_pathlist_append(&paths, "", NULL);
3085 if (error)
3086 goto done;
3087 cpa.worktree_path = worktree_path;
3088 cpa.had_base_commit_ref_error = 0;
3089 cpa.verbosity = verbosity;
3090 error = got_worktree_checkout_files(worktree, &paths, repo,
3091 checkout_progress, &cpa, check_cancelled, NULL);
3092 if (error != NULL)
3093 goto done;
3095 if (got_ref_is_symbolic(head_ref)) {
3096 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3097 if (error)
3098 goto done;
3099 refname = got_ref_get_name(ref);
3100 } else
3101 refname = got_ref_get_name(head_ref);
3102 printf("Checked out %s: %s\n", refname, commit_id_str);
3103 printf("Now shut up and hack\n");
3104 if (cpa.had_base_commit_ref_error)
3105 show_worktree_base_ref_warning();
3106 done:
3107 if (pack_fds) {
3108 const struct got_error *pack_err =
3109 got_repo_pack_fds_close(pack_fds);
3110 if (error == NULL)
3111 error = pack_err;
3113 if (head_ref)
3114 got_ref_close(head_ref);
3115 if (ref)
3116 got_ref_close(ref);
3117 got_pathlist_free(&paths);
3118 free(commit_id_str);
3119 free(commit_id);
3120 free(repo_path);
3121 free(worktree_path);
3122 free(cwd);
3123 return error;
3126 struct got_update_progress_arg {
3127 int did_something;
3128 int conflicts;
3129 int obstructed;
3130 int not_updated;
3131 int missing;
3132 int not_deleted;
3133 int unversioned;
3134 int verbosity;
3137 static void
3138 print_update_progress_stats(struct got_update_progress_arg *upa)
3140 if (!upa->did_something)
3141 return;
3143 if (upa->conflicts > 0)
3144 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3145 if (upa->obstructed > 0)
3146 printf("File paths obstructed by a non-regular file: %d\n",
3147 upa->obstructed);
3148 if (upa->not_updated > 0)
3149 printf("Files not updated because of existing merge "
3150 "conflicts: %d\n", upa->not_updated);
3154 * The meaning of some status codes differs between merge-style operations and
3155 * update operations. For example, the ! status code means "file was missing"
3156 * if changes were merged into the work tree, and "missing file was restored"
3157 * if the work tree was updated. This function should be used by any operation
3158 * which merges changes into the work tree without updating the work tree.
3160 static void
3161 print_merge_progress_stats(struct got_update_progress_arg *upa)
3163 if (!upa->did_something)
3164 return;
3166 if (upa->conflicts > 0)
3167 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3168 if (upa->obstructed > 0)
3169 printf("File paths obstructed by a non-regular file: %d\n",
3170 upa->obstructed);
3171 if (upa->missing > 0)
3172 printf("Files which had incoming changes but could not be "
3173 "found in the work tree: %d\n", upa->missing);
3174 if (upa->not_deleted > 0)
3175 printf("Files not deleted due to differences in deleted "
3176 "content: %d\n", upa->not_deleted);
3177 if (upa->unversioned > 0)
3178 printf("Files not merged because an unversioned file was "
3179 "found in the work tree: %d\n", upa->unversioned);
3182 __dead static void
3183 usage_update(void)
3185 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3186 "[path ...]\n",
3187 getprogname());
3188 exit(1);
3191 static const struct got_error *
3192 update_progress(void *arg, unsigned char status, const char *path)
3194 struct got_update_progress_arg *upa = arg;
3196 if (status == GOT_STATUS_EXISTS ||
3197 status == GOT_STATUS_BASE_REF_ERR)
3198 return NULL;
3200 upa->did_something = 1;
3202 /* Base commit bump happens silently. */
3203 if (status == GOT_STATUS_BUMP_BASE)
3204 return NULL;
3206 if (status == GOT_STATUS_CONFLICT)
3207 upa->conflicts++;
3208 if (status == GOT_STATUS_OBSTRUCTED)
3209 upa->obstructed++;
3210 if (status == GOT_STATUS_CANNOT_UPDATE)
3211 upa->not_updated++;
3212 if (status == GOT_STATUS_MISSING)
3213 upa->missing++;
3214 if (status == GOT_STATUS_CANNOT_DELETE)
3215 upa->not_deleted++;
3216 if (status == GOT_STATUS_UNVERSIONED)
3217 upa->unversioned++;
3219 while (path[0] == '/')
3220 path++;
3221 if (upa->verbosity >= 0)
3222 printf("%c %s\n", status, path);
3224 return NULL;
3227 static const struct got_error *
3228 switch_head_ref(struct got_reference *head_ref,
3229 struct got_object_id *commit_id, struct got_worktree *worktree,
3230 struct got_repository *repo)
3232 const struct got_error *err = NULL;
3233 char *base_id_str;
3234 int ref_has_moved = 0;
3236 /* Trivial case: switching between two different references. */
3237 if (strcmp(got_ref_get_name(head_ref),
3238 got_worktree_get_head_ref_name(worktree)) != 0) {
3239 printf("Switching work tree from %s to %s\n",
3240 got_worktree_get_head_ref_name(worktree),
3241 got_ref_get_name(head_ref));
3242 return got_worktree_set_head_ref(worktree, head_ref);
3245 err = check_linear_ancestry(commit_id,
3246 got_worktree_get_base_commit_id(worktree), 0, repo);
3247 if (err) {
3248 if (err->code != GOT_ERR_ANCESTRY)
3249 return err;
3250 ref_has_moved = 1;
3252 if (!ref_has_moved)
3253 return NULL;
3255 /* Switching to a rebased branch with the same reference name. */
3256 err = got_object_id_str(&base_id_str,
3257 got_worktree_get_base_commit_id(worktree));
3258 if (err)
3259 return err;
3260 printf("Reference %s now points at a different branch\n",
3261 got_worktree_get_head_ref_name(worktree));
3262 printf("Switching work tree from %s to %s\n", base_id_str,
3263 got_worktree_get_head_ref_name(worktree));
3264 return NULL;
3267 static const struct got_error *
3268 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3270 const struct got_error *err;
3271 int in_progress;
3273 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3274 if (err)
3275 return err;
3276 if (in_progress)
3277 return got_error(GOT_ERR_REBASING);
3279 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3280 if (err)
3281 return err;
3282 if (in_progress)
3283 return got_error(GOT_ERR_HISTEDIT_BUSY);
3285 return NULL;
3288 static const struct got_error *
3289 check_merge_in_progress(struct got_worktree *worktree,
3290 struct got_repository *repo)
3292 const struct got_error *err;
3293 int in_progress;
3295 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3296 if (err)
3297 return err;
3298 if (in_progress)
3299 return got_error(GOT_ERR_MERGE_BUSY);
3301 return NULL;
3304 static const struct got_error *
3305 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3306 char *argv[], struct got_worktree *worktree)
3308 const struct got_error *err = NULL;
3309 char *path;
3310 struct got_pathlist_entry *new;
3311 int i;
3313 if (argc == 0) {
3314 path = strdup("");
3315 if (path == NULL)
3316 return got_error_from_errno("strdup");
3317 return got_pathlist_append(paths, path, NULL);
3320 for (i = 0; i < argc; i++) {
3321 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3322 if (err)
3323 break;
3324 err = got_pathlist_insert(&new, paths, path, NULL);
3325 if (err || new == NULL /* duplicate */) {
3326 free(path);
3327 if (err)
3328 break;
3332 return err;
3335 static const struct got_error *
3336 wrap_not_worktree_error(const struct got_error *orig_err,
3337 const char *cmdname, const char *path)
3339 const struct got_error *err;
3340 struct got_repository *repo;
3341 static char msg[512];
3342 int *pack_fds = NULL;
3344 err = got_repo_pack_fds_open(&pack_fds);
3345 if (err)
3346 return err;
3348 err = got_repo_open(&repo, path, NULL, pack_fds);
3349 if (err)
3350 return orig_err;
3352 snprintf(msg, sizeof(msg),
3353 "'got %s' needs a work tree in addition to a git repository\n"
3354 "Work trees can be checked out from this Git repository with "
3355 "'got checkout'.\n"
3356 "The got(1) manual page contains more information.", cmdname);
3357 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3358 got_repo_close(repo);
3359 if (pack_fds) {
3360 const struct got_error *pack_err =
3361 got_repo_pack_fds_close(pack_fds);
3362 if (err == NULL)
3363 err = pack_err;
3365 return err;
3368 static const struct got_error *
3369 cmd_update(int argc, char *argv[])
3371 const struct got_error *error = NULL;
3372 struct got_repository *repo = NULL;
3373 struct got_worktree *worktree = NULL;
3374 char *worktree_path = NULL;
3375 struct got_object_id *commit_id = NULL;
3376 char *commit_id_str = NULL;
3377 const char *branch_name = NULL;
3378 struct got_reference *head_ref = NULL;
3379 struct got_pathlist_head paths;
3380 struct got_pathlist_entry *pe;
3381 int ch, verbosity = 0;
3382 struct got_update_progress_arg upa;
3383 int *pack_fds = NULL;
3385 TAILQ_INIT(&paths);
3387 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3388 switch (ch) {
3389 case 'b':
3390 branch_name = optarg;
3391 break;
3392 case 'c':
3393 commit_id_str = strdup(optarg);
3394 if (commit_id_str == NULL)
3395 return got_error_from_errno("strdup");
3396 break;
3397 case 'q':
3398 verbosity = -1;
3399 break;
3400 default:
3401 usage_update();
3402 /* NOTREACHED */
3406 argc -= optind;
3407 argv += optind;
3409 #ifndef PROFILE
3410 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3411 "unveil", NULL) == -1)
3412 err(1, "pledge");
3413 #endif
3414 worktree_path = getcwd(NULL, 0);
3415 if (worktree_path == NULL) {
3416 error = got_error_from_errno("getcwd");
3417 goto done;
3420 error = got_repo_pack_fds_open(&pack_fds);
3421 if (error != NULL)
3422 goto done;
3424 error = got_worktree_open(&worktree, worktree_path);
3425 if (error) {
3426 if (error->code == GOT_ERR_NOT_WORKTREE)
3427 error = wrap_not_worktree_error(error, "update",
3428 worktree_path);
3429 goto done;
3432 error = check_rebase_or_histedit_in_progress(worktree);
3433 if (error)
3434 goto done;
3436 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3437 NULL, pack_fds);
3438 if (error != NULL)
3439 goto done;
3441 error = apply_unveil(got_repo_get_path(repo), 0,
3442 got_worktree_get_root_path(worktree));
3443 if (error)
3444 goto done;
3446 error = check_merge_in_progress(worktree, repo);
3447 if (error)
3448 goto done;
3450 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3451 if (error)
3452 goto done;
3454 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3455 got_worktree_get_head_ref_name(worktree), 0);
3456 if (error != NULL)
3457 goto done;
3458 if (commit_id_str == NULL) {
3459 error = got_ref_resolve(&commit_id, repo, head_ref);
3460 if (error != NULL)
3461 goto done;
3462 error = got_object_id_str(&commit_id_str, commit_id);
3463 if (error != NULL)
3464 goto done;
3465 } else {
3466 struct got_reflist_head refs;
3467 TAILQ_INIT(&refs);
3468 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3469 NULL);
3470 if (error)
3471 goto done;
3472 error = got_repo_match_object_id(&commit_id, NULL,
3473 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3474 got_ref_list_free(&refs);
3475 free(commit_id_str);
3476 commit_id_str = NULL;
3477 if (error)
3478 goto done;
3479 error = got_object_id_str(&commit_id_str, commit_id);
3480 if (error)
3481 goto done;
3484 if (branch_name) {
3485 struct got_object_id *head_commit_id;
3486 TAILQ_FOREACH(pe, &paths, entry) {
3487 if (pe->path_len == 0)
3488 continue;
3489 error = got_error_msg(GOT_ERR_BAD_PATH,
3490 "switching between branches requires that "
3491 "the entire work tree gets updated");
3492 goto done;
3494 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3495 if (error)
3496 goto done;
3497 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3498 repo);
3499 free(head_commit_id);
3500 if (error != NULL)
3501 goto done;
3502 error = check_same_branch(commit_id, head_ref, NULL, repo);
3503 if (error)
3504 goto done;
3505 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3506 if (error)
3507 goto done;
3508 } else {
3509 error = check_linear_ancestry(commit_id,
3510 got_worktree_get_base_commit_id(worktree), 0, repo);
3511 if (error != NULL) {
3512 if (error->code == GOT_ERR_ANCESTRY)
3513 error = got_error(GOT_ERR_BRANCH_MOVED);
3514 goto done;
3516 error = check_same_branch(commit_id, head_ref, NULL, repo);
3517 if (error)
3518 goto done;
3521 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3522 commit_id) != 0) {
3523 error = got_worktree_set_base_commit_id(worktree, repo,
3524 commit_id);
3525 if (error)
3526 goto done;
3529 memset(&upa, 0, sizeof(upa));
3530 upa.verbosity = verbosity;
3531 error = got_worktree_checkout_files(worktree, &paths, repo,
3532 update_progress, &upa, check_cancelled, NULL);
3533 if (error != NULL)
3534 goto done;
3536 if (upa.did_something) {
3537 printf("Updated to %s: %s\n",
3538 got_worktree_get_head_ref_name(worktree), commit_id_str);
3539 } else
3540 printf("Already up-to-date\n");
3542 print_update_progress_stats(&upa);
3543 done:
3544 if (pack_fds) {
3545 const struct got_error *pack_err =
3546 got_repo_pack_fds_close(pack_fds);
3547 if (error == NULL)
3548 error = pack_err;
3550 free(worktree_path);
3551 TAILQ_FOREACH(pe, &paths, entry)
3552 free((char *)pe->path);
3553 got_pathlist_free(&paths);
3554 free(commit_id);
3555 free(commit_id_str);
3556 return error;
3559 static const struct got_error *
3560 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3561 const char *path, int diff_context, int ignore_whitespace,
3562 int force_text_diff, struct got_repository *repo, FILE *outfile)
3564 const struct got_error *err = NULL;
3565 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3566 FILE *f1 = NULL, *f2 = NULL;
3567 int fd1 = -1, fd2 = -1;
3569 fd1 = got_opentempfd();
3570 if (fd1 == -1)
3571 return got_error_from_errno("got_opentempfd");
3572 fd2 = got_opentempfd();
3573 if (fd2 == -1) {
3574 err = got_error_from_errno("got_opentempfd");
3575 goto done;
3578 if (blob_id1) {
3579 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3580 fd1);
3581 if (err)
3582 goto done;
3585 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3586 if (err)
3587 goto done;
3589 f1 = got_opentemp();
3590 if (f1 == NULL) {
3591 err = got_error_from_errno("got_opentemp");
3592 goto done;
3594 f2 = got_opentemp();
3595 if (f2 == NULL) {
3596 err = got_error_from_errno("got_opentemp");
3597 goto done;
3600 while (path[0] == '/')
3601 path++;
3602 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3603 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3604 force_text_diff, outfile);
3605 done:
3606 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3607 err = got_error_from_errno("close");
3608 if (blob1)
3609 got_object_blob_close(blob1);
3610 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3611 err = got_error_from_errno("close");
3612 got_object_blob_close(blob2);
3613 if (f1 && fclose(f1) == EOF && err == NULL)
3614 err = got_error_from_errno("fclose");
3615 if (f2 && fclose(f2) == EOF && err == NULL)
3616 err = got_error_from_errno("fclose");
3617 return err;
3620 static const struct got_error *
3621 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3622 const char *path, int diff_context, int ignore_whitespace,
3623 int force_text_diff, struct got_repository *repo, FILE *outfile)
3625 const struct got_error *err = NULL;
3626 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3627 struct got_diff_blob_output_unidiff_arg arg;
3628 FILE *f1 = NULL, *f2 = NULL;
3629 int fd1 = -1, fd2 = -1;
3631 if (tree_id1) {
3632 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3633 if (err)
3634 goto done;
3635 fd1 = got_opentempfd();
3636 if (fd1 == -1) {
3637 err = got_error_from_errno("got_opentempfd");
3638 goto done;
3642 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3643 if (err)
3644 goto done;
3646 f1 = got_opentemp();
3647 if (f1 == NULL) {
3648 err = got_error_from_errno("got_opentemp");
3649 goto done;
3652 f2 = got_opentemp();
3653 if (f2 == NULL) {
3654 err = got_error_from_errno("got_opentemp");
3655 goto done;
3657 fd2 = got_opentempfd();
3658 if (fd2 == -1) {
3659 err = got_error_from_errno("got_opentempfd");
3660 goto done;
3662 arg.diff_context = diff_context;
3663 arg.ignore_whitespace = ignore_whitespace;
3664 arg.force_text_diff = force_text_diff;
3665 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3666 arg.outfile = outfile;
3667 arg.line_offsets = NULL;
3668 arg.nlines = 0;
3669 while (path[0] == '/')
3670 path++;
3671 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3672 got_diff_blob_output_unidiff, &arg, 1);
3673 done:
3674 if (tree1)
3675 got_object_tree_close(tree1);
3676 if (tree2)
3677 got_object_tree_close(tree2);
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 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3683 err = got_error_from_errno("close");
3684 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3685 err = got_error_from_errno("close");
3686 return err;
3689 static const struct got_error *
3690 get_changed_paths(struct got_pathlist_head *paths,
3691 struct got_commit_object *commit, struct got_repository *repo)
3693 const struct got_error *err = NULL;
3694 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3695 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3696 struct got_object_qid *qid;
3698 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3699 if (qid != NULL) {
3700 struct got_commit_object *pcommit;
3701 err = got_object_open_as_commit(&pcommit, repo,
3702 &qid->id);
3703 if (err)
3704 return err;
3706 tree_id1 = got_object_id_dup(
3707 got_object_commit_get_tree_id(pcommit));
3708 if (tree_id1 == NULL) {
3709 got_object_commit_close(pcommit);
3710 return got_error_from_errno("got_object_id_dup");
3712 got_object_commit_close(pcommit);
3716 if (tree_id1) {
3717 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3718 if (err)
3719 goto done;
3722 tree_id2 = got_object_commit_get_tree_id(commit);
3723 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3724 if (err)
3725 goto done;
3727 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3728 got_diff_tree_collect_changed_paths, paths, 0);
3729 done:
3730 if (tree1)
3731 got_object_tree_close(tree1);
3732 if (tree2)
3733 got_object_tree_close(tree2);
3734 free(tree_id1);
3735 return err;
3738 static const struct got_error *
3739 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3740 const char *path, int diff_context, struct got_repository *repo,
3741 FILE *outfile)
3743 const struct got_error *err = NULL;
3744 struct got_commit_object *pcommit = NULL;
3745 char *id_str1 = NULL, *id_str2 = NULL;
3746 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3747 struct got_object_qid *qid;
3749 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3750 if (qid != NULL) {
3751 err = got_object_open_as_commit(&pcommit, repo,
3752 &qid->id);
3753 if (err)
3754 return err;
3755 err = got_object_id_str(&id_str1, &qid->id);
3756 if (err)
3757 goto done;
3760 err = got_object_id_str(&id_str2, id);
3761 if (err)
3762 goto done;
3764 if (path && path[0] != '\0') {
3765 int obj_type;
3766 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3767 if (err)
3768 goto done;
3769 if (pcommit) {
3770 err = got_object_id_by_path(&obj_id1, repo,
3771 pcommit, path);
3772 if (err) {
3773 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3774 free(obj_id2);
3775 goto done;
3779 err = got_object_get_type(&obj_type, repo, obj_id2);
3780 if (err) {
3781 free(obj_id2);
3782 goto done;
3784 fprintf(outfile,
3785 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3786 fprintf(outfile, "commit - %s\n",
3787 id_str1 ? id_str1 : "/dev/null");
3788 fprintf(outfile, "commit + %s\n", id_str2);
3789 switch (obj_type) {
3790 case GOT_OBJ_TYPE_BLOB:
3791 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3792 0, 0, repo, outfile);
3793 break;
3794 case GOT_OBJ_TYPE_TREE:
3795 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3796 0, 0, repo, outfile);
3797 break;
3798 default:
3799 err = got_error(GOT_ERR_OBJ_TYPE);
3800 break;
3802 free(obj_id1);
3803 free(obj_id2);
3804 } else {
3805 obj_id2 = got_object_commit_get_tree_id(commit);
3806 if (pcommit)
3807 obj_id1 = got_object_commit_get_tree_id(pcommit);
3808 fprintf(outfile,
3809 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3810 fprintf(outfile, "commit - %s\n",
3811 id_str1 ? id_str1 : "/dev/null");
3812 fprintf(outfile, "commit + %s\n", id_str2);
3813 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3814 repo, outfile);
3816 done:
3817 free(id_str1);
3818 free(id_str2);
3819 if (pcommit)
3820 got_object_commit_close(pcommit);
3821 return err;
3824 static char *
3825 get_datestr(time_t *time, char *datebuf)
3827 struct tm mytm, *tm;
3828 char *p, *s;
3830 tm = gmtime_r(time, &mytm);
3831 if (tm == NULL)
3832 return NULL;
3833 s = asctime_r(tm, datebuf);
3834 if (s == NULL)
3835 return NULL;
3836 p = strchr(s, '\n');
3837 if (p)
3838 *p = '\0';
3839 return s;
3842 static const struct got_error *
3843 match_commit(int *have_match, struct got_object_id *id,
3844 struct got_commit_object *commit, regex_t *regex)
3846 const struct got_error *err = NULL;
3847 regmatch_t regmatch;
3848 char *id_str = NULL, *logmsg = NULL;
3850 *have_match = 0;
3852 err = got_object_id_str(&id_str, id);
3853 if (err)
3854 return err;
3856 err = got_object_commit_get_logmsg(&logmsg, commit);
3857 if (err)
3858 goto done;
3860 if (regexec(regex, got_object_commit_get_author(commit), 1,
3861 &regmatch, 0) == 0 ||
3862 regexec(regex, got_object_commit_get_committer(commit), 1,
3863 &regmatch, 0) == 0 ||
3864 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3865 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3866 *have_match = 1;
3867 done:
3868 free(id_str);
3869 free(logmsg);
3870 return err;
3873 static void
3874 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3875 regex_t *regex)
3877 regmatch_t regmatch;
3878 struct got_pathlist_entry *pe;
3880 *have_match = 0;
3882 TAILQ_FOREACH(pe, changed_paths, entry) {
3883 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3884 *have_match = 1;
3885 break;
3890 static const struct got_error *
3891 match_patch(int *have_match, struct got_commit_object *commit,
3892 struct got_object_id *id, const char *path, int diff_context,
3893 struct got_repository *repo, regex_t *regex, FILE *f)
3895 const struct got_error *err = NULL;
3896 char *line = NULL;
3897 size_t linesize = 0;
3898 ssize_t linelen;
3899 regmatch_t regmatch;
3901 *have_match = 0;
3903 err = got_opentemp_truncate(f);
3904 if (err)
3905 return err;
3907 err = print_patch(commit, id, path, diff_context, repo, f);
3908 if (err)
3909 goto done;
3911 if (fseeko(f, 0L, SEEK_SET) == -1) {
3912 err = got_error_from_errno("fseeko");
3913 goto done;
3916 while ((linelen = getline(&line, &linesize, f)) != -1) {
3917 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3918 *have_match = 1;
3919 break;
3922 done:
3923 free(line);
3924 return err;
3927 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3929 static const struct got_error*
3930 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3931 struct got_object_id *id, struct got_repository *repo,
3932 int local_only)
3934 static const struct got_error *err = NULL;
3935 struct got_reflist_entry *re;
3936 char *s;
3937 const char *name;
3939 *refs_str = NULL;
3941 TAILQ_FOREACH(re, refs, entry) {
3942 struct got_tag_object *tag = NULL;
3943 struct got_object_id *ref_id;
3944 int cmp;
3946 name = got_ref_get_name(re->ref);
3947 if (strcmp(name, GOT_REF_HEAD) == 0)
3948 continue;
3949 if (strncmp(name, "refs/", 5) == 0)
3950 name += 5;
3951 if (strncmp(name, "got/", 4) == 0)
3952 continue;
3953 if (strncmp(name, "heads/", 6) == 0)
3954 name += 6;
3955 if (strncmp(name, "remotes/", 8) == 0) {
3956 if (local_only)
3957 continue;
3958 name += 8;
3959 s = strstr(name, "/" GOT_REF_HEAD);
3960 if (s != NULL && s[strlen(s)] == '\0')
3961 continue;
3963 err = got_ref_resolve(&ref_id, repo, re->ref);
3964 if (err)
3965 break;
3966 if (strncmp(name, "tags/", 5) == 0) {
3967 err = got_object_open_as_tag(&tag, repo, ref_id);
3968 if (err) {
3969 if (err->code != GOT_ERR_OBJ_TYPE) {
3970 free(ref_id);
3971 break;
3973 /* Ref points at something other than a tag. */
3974 err = NULL;
3975 tag = NULL;
3978 cmp = got_object_id_cmp(tag ?
3979 got_object_tag_get_object_id(tag) : ref_id, id);
3980 free(ref_id);
3981 if (tag)
3982 got_object_tag_close(tag);
3983 if (cmp != 0)
3984 continue;
3985 s = *refs_str;
3986 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3987 s ? ", " : "", name) == -1) {
3988 err = got_error_from_errno("asprintf");
3989 free(s);
3990 *refs_str = NULL;
3991 break;
3993 free(s);
3996 return err;
3999 static const struct got_error *
4000 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4001 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4003 const struct got_error *err = NULL;
4004 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4005 char *comma, *s, *nl;
4006 struct got_reflist_head *refs;
4007 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4008 struct tm tm;
4009 time_t committer_time;
4011 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4012 if (refs) {
4013 err = build_refs_str(&ref_str, refs, id, repo, 1);
4014 if (err)
4015 return err;
4017 /* Display the first matching ref only. */
4018 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4019 *comma = '\0';
4022 if (ref_str == NULL) {
4023 err = got_object_id_str(&id_str, id);
4024 if (err)
4025 return err;
4028 committer_time = got_object_commit_get_committer_time(commit);
4029 if (gmtime_r(&committer_time, &tm) == NULL) {
4030 err = got_error_from_errno("gmtime_r");
4031 goto done;
4033 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4034 err = got_error(GOT_ERR_NO_SPACE);
4035 goto done;
4038 err = got_object_commit_get_logmsg(&logmsg0, commit);
4039 if (err)
4040 goto done;
4042 s = logmsg0;
4043 while (isspace((unsigned char)s[0]))
4044 s++;
4046 nl = strchr(s, '\n');
4047 if (nl) {
4048 *nl = '\0';
4051 if (ref_str)
4052 printf("%s%-7s %s\n", datebuf, ref_str, s);
4053 else
4054 printf("%s%.7s %s\n", datebuf, id_str, s);
4056 if (fflush(stdout) != 0 && err == NULL)
4057 err = got_error_from_errno("fflush");
4058 done:
4059 free(id_str);
4060 free(ref_str);
4061 free(logmsg0);
4062 return err;
4065 static const struct got_error *
4066 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4067 struct got_repository *repo, const char *path,
4068 struct got_pathlist_head *changed_paths, int show_patch,
4069 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4070 const char *custom_refs_str)
4072 const struct got_error *err = NULL;
4073 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4074 char datebuf[26];
4075 time_t committer_time;
4076 const char *author, *committer;
4077 char *refs_str = NULL;
4079 err = got_object_id_str(&id_str, id);
4080 if (err)
4081 return err;
4083 if (custom_refs_str == NULL) {
4084 struct got_reflist_head *refs;
4085 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4086 if (refs) {
4087 err = build_refs_str(&refs_str, refs, id, repo, 0);
4088 if (err)
4089 goto done;
4093 printf(GOT_COMMIT_SEP_STR);
4094 if (custom_refs_str)
4095 printf("commit %s (%s)\n", id_str, custom_refs_str);
4096 else
4097 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4098 refs_str ? refs_str : "", refs_str ? ")" : "");
4099 free(id_str);
4100 id_str = NULL;
4101 free(refs_str);
4102 refs_str = NULL;
4103 printf("from: %s\n", got_object_commit_get_author(commit));
4104 committer_time = got_object_commit_get_committer_time(commit);
4105 datestr = get_datestr(&committer_time, datebuf);
4106 if (datestr)
4107 printf("date: %s UTC\n", datestr);
4108 author = got_object_commit_get_author(commit);
4109 committer = got_object_commit_get_committer(commit);
4110 if (strcmp(author, committer) != 0)
4111 printf("via: %s\n", committer);
4112 if (got_object_commit_get_nparents(commit) > 1) {
4113 const struct got_object_id_queue *parent_ids;
4114 struct got_object_qid *qid;
4115 int n = 1;
4116 parent_ids = got_object_commit_get_parent_ids(commit);
4117 STAILQ_FOREACH(qid, parent_ids, entry) {
4118 err = got_object_id_str(&id_str, &qid->id);
4119 if (err)
4120 goto done;
4121 printf("parent %d: %s\n", n++, id_str);
4122 free(id_str);
4123 id_str = NULL;
4127 err = got_object_commit_get_logmsg(&logmsg0, commit);
4128 if (err)
4129 goto done;
4131 logmsg = logmsg0;
4132 do {
4133 line = strsep(&logmsg, "\n");
4134 if (line)
4135 printf(" %s\n", line);
4136 } while (line);
4137 free(logmsg0);
4139 if (changed_paths) {
4140 struct got_pathlist_entry *pe;
4141 TAILQ_FOREACH(pe, changed_paths, entry) {
4142 struct got_diff_changed_path *cp = pe->data;
4143 printf(" %c %s\n", cp->status, pe->path);
4145 printf("\n");
4147 if (show_patch) {
4148 err = print_patch(commit, id, path, diff_context, repo, stdout);
4149 if (err == 0)
4150 printf("\n");
4153 if (fflush(stdout) != 0 && err == NULL)
4154 err = got_error_from_errno("fflush");
4155 done:
4156 free(id_str);
4157 free(refs_str);
4158 return err;
4161 static const struct got_error *
4162 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4163 struct got_repository *repo, const char *path, int show_changed_paths,
4164 int show_patch, const char *search_pattern, int diff_context, int limit,
4165 int log_branches, int reverse_display_order,
4166 struct got_reflist_object_id_map *refs_idmap, int one_line,
4167 FILE *tmpfile)
4169 const struct got_error *err;
4170 struct got_commit_graph *graph;
4171 regex_t regex;
4172 int have_match;
4173 struct got_object_id_queue reversed_commits;
4174 struct got_object_qid *qid;
4175 struct got_commit_object *commit;
4176 struct got_pathlist_head changed_paths;
4177 struct got_pathlist_entry *pe;
4179 STAILQ_INIT(&reversed_commits);
4180 TAILQ_INIT(&changed_paths);
4182 if (search_pattern && regcomp(&regex, search_pattern,
4183 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4184 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4186 err = got_commit_graph_open(&graph, path, !log_branches);
4187 if (err)
4188 return err;
4189 err = got_commit_graph_iter_start(graph, root_id, repo,
4190 check_cancelled, NULL);
4191 if (err)
4192 goto done;
4193 for (;;) {
4194 struct got_object_id *id;
4196 if (sigint_received || sigpipe_received)
4197 break;
4199 err = got_commit_graph_iter_next(&id, graph, repo,
4200 check_cancelled, NULL);
4201 if (err) {
4202 if (err->code == GOT_ERR_ITER_COMPLETED)
4203 err = NULL;
4204 break;
4206 if (id == NULL)
4207 break;
4209 err = got_object_open_as_commit(&commit, repo, id);
4210 if (err)
4211 break;
4213 if (show_changed_paths && !reverse_display_order) {
4214 err = get_changed_paths(&changed_paths, commit, repo);
4215 if (err)
4216 break;
4219 if (search_pattern) {
4220 err = match_commit(&have_match, id, commit, &regex);
4221 if (err) {
4222 got_object_commit_close(commit);
4223 break;
4225 if (have_match == 0 && show_changed_paths)
4226 match_changed_paths(&have_match,
4227 &changed_paths, &regex);
4228 if (have_match == 0 && show_patch) {
4229 err = match_patch(&have_match, commit, id,
4230 path, diff_context, repo, &regex,
4231 tmpfile);
4232 if (err)
4233 break;
4235 if (have_match == 0) {
4236 got_object_commit_close(commit);
4237 TAILQ_FOREACH(pe, &changed_paths, entry) {
4238 free((char *)pe->path);
4239 free(pe->data);
4241 got_pathlist_free(&changed_paths);
4242 continue;
4246 if (reverse_display_order) {
4247 err = got_object_qid_alloc(&qid, id);
4248 if (err)
4249 break;
4250 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4251 got_object_commit_close(commit);
4252 } else {
4253 if (one_line)
4254 err = print_commit_oneline(commit, id,
4255 repo, refs_idmap);
4256 else
4257 err = print_commit(commit, id, repo, path,
4258 show_changed_paths ? &changed_paths : NULL,
4259 show_patch, diff_context, refs_idmap, NULL);
4260 got_object_commit_close(commit);
4261 if (err)
4262 break;
4264 if ((limit && --limit == 0) ||
4265 (end_id && got_object_id_cmp(id, end_id) == 0))
4266 break;
4268 TAILQ_FOREACH(pe, &changed_paths, entry) {
4269 free((char *)pe->path);
4270 free(pe->data);
4272 got_pathlist_free(&changed_paths);
4274 if (reverse_display_order) {
4275 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4276 err = got_object_open_as_commit(&commit, repo,
4277 &qid->id);
4278 if (err)
4279 break;
4280 if (show_changed_paths) {
4281 err = get_changed_paths(&changed_paths,
4282 commit, repo);
4283 if (err)
4284 break;
4286 if (one_line)
4287 err = print_commit_oneline(commit, &qid->id,
4288 repo, refs_idmap);
4289 else
4290 err = print_commit(commit, &qid->id, repo, path,
4291 show_changed_paths ? &changed_paths : NULL,
4292 show_patch, diff_context, refs_idmap, NULL);
4293 got_object_commit_close(commit);
4294 if (err)
4295 break;
4296 TAILQ_FOREACH(pe, &changed_paths, entry) {
4297 free((char *)pe->path);
4298 free(pe->data);
4300 got_pathlist_free(&changed_paths);
4303 done:
4304 while (!STAILQ_EMPTY(&reversed_commits)) {
4305 qid = STAILQ_FIRST(&reversed_commits);
4306 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4307 got_object_qid_free(qid);
4309 TAILQ_FOREACH(pe, &changed_paths, entry) {
4310 free((char *)pe->path);
4311 free(pe->data);
4313 got_pathlist_free(&changed_paths);
4314 if (search_pattern)
4315 regfree(&regex);
4316 got_commit_graph_close(graph);
4317 return err;
4320 __dead static void
4321 usage_log(void)
4323 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4324 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4325 "[-r repository-path] [-R] [path]\n", getprogname());
4326 exit(1);
4329 static int
4330 get_default_log_limit(void)
4332 const char *got_default_log_limit;
4333 long long n;
4334 const char *errstr;
4336 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4337 if (got_default_log_limit == NULL)
4338 return 0;
4339 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4340 if (errstr != NULL)
4341 return 0;
4342 return n;
4345 static const struct got_error *
4346 cmd_log(int argc, char *argv[])
4348 const struct got_error *error;
4349 struct got_repository *repo = NULL;
4350 struct got_worktree *worktree = NULL;
4351 struct got_object_id *start_id = NULL, *end_id = NULL;
4352 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4353 const char *start_commit = NULL, *end_commit = NULL;
4354 const char *search_pattern = NULL;
4355 int diff_context = -1, ch;
4356 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4357 int reverse_display_order = 0, one_line = 0;
4358 const char *errstr;
4359 struct got_reflist_head refs;
4360 struct got_reflist_object_id_map *refs_idmap = NULL;
4361 FILE *tmpfile = NULL;
4362 int *pack_fds = NULL;
4364 TAILQ_INIT(&refs);
4366 #ifndef PROFILE
4367 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4368 NULL)
4369 == -1)
4370 err(1, "pledge");
4371 #endif
4373 limit = get_default_log_limit();
4375 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4376 switch (ch) {
4377 case 'p':
4378 show_patch = 1;
4379 break;
4380 case 'P':
4381 show_changed_paths = 1;
4382 break;
4383 case 'c':
4384 start_commit = optarg;
4385 break;
4386 case 'C':
4387 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4388 &errstr);
4389 if (errstr != NULL)
4390 errx(1, "number of context lines is %s: %s",
4391 errstr, optarg);
4392 break;
4393 case 'l':
4394 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4395 if (errstr != NULL)
4396 errx(1, "number of commits is %s: %s",
4397 errstr, optarg);
4398 break;
4399 case 'b':
4400 log_branches = 1;
4401 break;
4402 case 'r':
4403 repo_path = realpath(optarg, NULL);
4404 if (repo_path == NULL)
4405 return got_error_from_errno2("realpath",
4406 optarg);
4407 got_path_strip_trailing_slashes(repo_path);
4408 break;
4409 case 'R':
4410 reverse_display_order = 1;
4411 break;
4412 case 's':
4413 one_line = 1;
4414 break;
4415 case 'S':
4416 search_pattern = optarg;
4417 break;
4418 case 'x':
4419 end_commit = optarg;
4420 break;
4421 default:
4422 usage_log();
4423 /* NOTREACHED */
4427 argc -= optind;
4428 argv += optind;
4430 if (diff_context == -1)
4431 diff_context = 3;
4432 else if (!show_patch)
4433 errx(1, "-C requires -p");
4435 if (one_line && (show_patch || show_changed_paths))
4436 errx(1, "cannot use -s with -p or -P");
4438 cwd = getcwd(NULL, 0);
4439 if (cwd == NULL) {
4440 error = got_error_from_errno("getcwd");
4441 goto done;
4444 error = got_repo_pack_fds_open(&pack_fds);
4445 if (error != NULL)
4446 goto done;
4448 if (repo_path == NULL) {
4449 error = got_worktree_open(&worktree, cwd);
4450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4451 goto done;
4452 error = NULL;
4455 if (argc == 1) {
4456 if (worktree) {
4457 error = got_worktree_resolve_path(&path, worktree,
4458 argv[0]);
4459 if (error)
4460 goto done;
4461 } else {
4462 path = strdup(argv[0]);
4463 if (path == NULL) {
4464 error = got_error_from_errno("strdup");
4465 goto done;
4468 } else if (argc != 0)
4469 usage_log();
4471 if (repo_path == NULL) {
4472 repo_path = worktree ?
4473 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4475 if (repo_path == NULL) {
4476 error = got_error_from_errno("strdup");
4477 goto done;
4480 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4481 if (error != NULL)
4482 goto done;
4484 error = apply_unveil(got_repo_get_path(repo), 1,
4485 worktree ? got_worktree_get_root_path(worktree) : NULL);
4486 if (error)
4487 goto done;
4489 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4490 if (error)
4491 goto done;
4493 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4494 if (error)
4495 goto done;
4497 if (start_commit == NULL) {
4498 struct got_reference *head_ref;
4499 struct got_commit_object *commit = NULL;
4500 error = got_ref_open(&head_ref, repo,
4501 worktree ? got_worktree_get_head_ref_name(worktree)
4502 : GOT_REF_HEAD, 0);
4503 if (error != NULL)
4504 goto done;
4505 error = got_ref_resolve(&start_id, repo, head_ref);
4506 got_ref_close(head_ref);
4507 if (error != NULL)
4508 goto done;
4509 error = got_object_open_as_commit(&commit, repo,
4510 start_id);
4511 if (error != NULL)
4512 goto done;
4513 got_object_commit_close(commit);
4514 } else {
4515 error = got_repo_match_object_id(&start_id, NULL,
4516 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4517 if (error != NULL)
4518 goto done;
4520 if (end_commit != NULL) {
4521 error = got_repo_match_object_id(&end_id, NULL,
4522 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4523 if (error != NULL)
4524 goto done;
4527 if (worktree) {
4529 * If a path was specified on the command line it was resolved
4530 * to a path in the work tree above. Prepend the work tree's
4531 * path prefix to obtain the corresponding in-repository path.
4533 if (path) {
4534 const char *prefix;
4535 prefix = got_worktree_get_path_prefix(worktree);
4536 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4537 (path[0] != '\0') ? "/" : "", path) == -1) {
4538 error = got_error_from_errno("asprintf");
4539 goto done;
4542 } else
4543 error = got_repo_map_path(&in_repo_path, repo,
4544 path ? path : "");
4545 if (error != NULL)
4546 goto done;
4547 if (in_repo_path) {
4548 free(path);
4549 path = in_repo_path;
4552 if (worktree) {
4553 /* Release work tree lock. */
4554 got_worktree_close(worktree);
4555 worktree = NULL;
4558 if (search_pattern && show_patch) {
4559 tmpfile = got_opentemp();
4560 if (tmpfile == NULL) {
4561 error = got_error_from_errno("got_opentemp");
4562 goto done;
4566 error = print_commits(start_id, end_id, repo, path ? path : "",
4567 show_changed_paths, show_patch, search_pattern, diff_context,
4568 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4569 tmpfile);
4570 done:
4571 free(path);
4572 free(repo_path);
4573 free(cwd);
4574 if (worktree)
4575 got_worktree_close(worktree);
4576 if (repo) {
4577 const struct got_error *close_err = got_repo_close(repo);
4578 if (error == NULL)
4579 error = close_err;
4581 if (pack_fds) {
4582 const struct got_error *pack_err =
4583 got_repo_pack_fds_close(pack_fds);
4584 if (error == NULL)
4585 error = pack_err;
4587 if (refs_idmap)
4588 got_reflist_object_id_map_free(refs_idmap);
4589 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4590 error = got_error_from_errno("fclose");
4591 got_ref_list_free(&refs);
4592 return error;
4595 __dead static void
4596 usage_diff(void)
4598 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4599 "[-r repository-path] [-s] [-w] [-P] "
4600 "[object1 object2 | path ...]\n", getprogname());
4601 exit(1);
4604 struct print_diff_arg {
4605 struct got_repository *repo;
4606 struct got_worktree *worktree;
4607 int diff_context;
4608 const char *id_str;
4609 int header_shown;
4610 int diff_staged;
4611 enum got_diff_algorithm diff_algo;
4612 int ignore_whitespace;
4613 int force_text_diff;
4614 FILE *f1;
4615 FILE *f2;
4619 * Create a file which contains the target path of a symlink so we can feed
4620 * it as content to the diff engine.
4622 static const struct got_error *
4623 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4624 const char *abspath)
4626 const struct got_error *err = NULL;
4627 char target_path[PATH_MAX];
4628 ssize_t target_len, outlen;
4630 *fd = -1;
4632 if (dirfd != -1) {
4633 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4634 if (target_len == -1)
4635 return got_error_from_errno2("readlinkat", abspath);
4636 } else {
4637 target_len = readlink(abspath, target_path, PATH_MAX);
4638 if (target_len == -1)
4639 return got_error_from_errno2("readlink", abspath);
4642 *fd = got_opentempfd();
4643 if (*fd == -1)
4644 return got_error_from_errno("got_opentempfd");
4646 outlen = write(*fd, target_path, target_len);
4647 if (outlen == -1) {
4648 err = got_error_from_errno("got_opentempfd");
4649 goto done;
4652 if (lseek(*fd, 0, SEEK_SET) == -1) {
4653 err = got_error_from_errno2("lseek", abspath);
4654 goto done;
4656 done:
4657 if (err) {
4658 close(*fd);
4659 *fd = -1;
4661 return err;
4664 static const struct got_error *
4665 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4666 const char *path, struct got_object_id *blob_id,
4667 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4668 int dirfd, const char *de_name)
4670 struct print_diff_arg *a = arg;
4671 const struct got_error *err = NULL;
4672 struct got_blob_object *blob1 = NULL;
4673 int fd = -1, fd1 = -1, fd2 = -1;
4674 FILE *f2 = NULL;
4675 char *abspath = NULL, *label1 = NULL;
4676 struct stat sb;
4677 off_t size1 = 0;
4678 int f2_exists = 1;
4680 if (a->diff_staged) {
4681 if (staged_status != GOT_STATUS_MODIFY &&
4682 staged_status != GOT_STATUS_ADD &&
4683 staged_status != GOT_STATUS_DELETE)
4684 return NULL;
4685 } else {
4686 if (staged_status == GOT_STATUS_DELETE)
4687 return NULL;
4688 if (status == GOT_STATUS_NONEXISTENT)
4689 return got_error_set_errno(ENOENT, path);
4690 if (status != GOT_STATUS_MODIFY &&
4691 status != GOT_STATUS_ADD &&
4692 status != GOT_STATUS_DELETE &&
4693 status != GOT_STATUS_CONFLICT)
4694 return NULL;
4697 err = got_opentemp_truncate(a->f1);
4698 if (err)
4699 return got_error_from_errno("got_opentemp_truncate");
4700 err = got_opentemp_truncate(a->f2);
4701 if (err)
4702 return got_error_from_errno("got_opentemp_truncate");
4704 if (!a->header_shown) {
4705 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4706 got_worktree_get_root_path(a->worktree));
4707 printf("commit - %s\n", a->id_str);
4708 printf("path + %s%s\n",
4709 got_worktree_get_root_path(a->worktree),
4710 a->diff_staged ? " (staged changes)" : "");
4711 a->header_shown = 1;
4714 if (a->diff_staged) {
4715 const char *label1 = NULL, *label2 = NULL;
4716 switch (staged_status) {
4717 case GOT_STATUS_MODIFY:
4718 label1 = path;
4719 label2 = path;
4720 break;
4721 case GOT_STATUS_ADD:
4722 label2 = path;
4723 break;
4724 case GOT_STATUS_DELETE:
4725 label1 = path;
4726 break;
4727 default:
4728 return got_error(GOT_ERR_FILE_STATUS);
4730 fd1 = got_opentempfd();
4731 if (fd1 == -1) {
4732 err = got_error_from_errno("got_opentempfd");
4733 goto done;
4735 fd2 = got_opentempfd();
4736 if (fd2 == -1) {
4737 err = got_error_from_errno("got_opentempfd");
4738 goto done;
4740 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4741 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4742 a->diff_algo, a->diff_context, a->ignore_whitespace,
4743 a->force_text_diff, a->repo, stdout);
4744 goto done;
4747 fd1 = got_opentempfd();
4748 if (fd1 == -1) {
4749 err = got_error_from_errno("got_opentempfd");
4750 goto done;
4753 if (staged_status == GOT_STATUS_ADD ||
4754 staged_status == GOT_STATUS_MODIFY) {
4755 char *id_str;
4756 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4757 8192, fd1);
4758 if (err)
4759 goto done;
4760 err = got_object_id_str(&id_str, staged_blob_id);
4761 if (err)
4762 goto done;
4763 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4764 err = got_error_from_errno("asprintf");
4765 free(id_str);
4766 goto done;
4768 free(id_str);
4769 } else if (status != GOT_STATUS_ADD) {
4770 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4771 fd1);
4772 if (err)
4773 goto done;
4776 if (status != GOT_STATUS_DELETE) {
4777 if (asprintf(&abspath, "%s/%s",
4778 got_worktree_get_root_path(a->worktree), path) == -1) {
4779 err = got_error_from_errno("asprintf");
4780 goto done;
4783 if (dirfd != -1) {
4784 fd = openat(dirfd, de_name,
4785 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4786 if (fd == -1) {
4787 if (!got_err_open_nofollow_on_symlink()) {
4788 err = got_error_from_errno2("openat",
4789 abspath);
4790 goto done;
4792 err = get_symlink_target_file(&fd, dirfd,
4793 de_name, abspath);
4794 if (err)
4795 goto done;
4797 } else {
4798 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4799 if (fd == -1) {
4800 if (!got_err_open_nofollow_on_symlink()) {
4801 err = got_error_from_errno2("open",
4802 abspath);
4803 goto done;
4805 err = get_symlink_target_file(&fd, dirfd,
4806 de_name, abspath);
4807 if (err)
4808 goto done;
4811 if (fstat(fd, &sb) == -1) {
4812 err = got_error_from_errno2("fstat", abspath);
4813 goto done;
4815 f2 = fdopen(fd, "r");
4816 if (f2 == NULL) {
4817 err = got_error_from_errno2("fdopen", abspath);
4818 goto done;
4820 fd = -1;
4821 } else {
4822 sb.st_size = 0;
4823 f2_exists = 0;
4826 if (blob1) {
4827 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4828 a->f1, blob1);
4829 if (err)
4830 goto done;
4833 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4834 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4835 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4836 done:
4837 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4838 err = got_error_from_errno("close");
4839 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4840 err = got_error_from_errno("close");
4841 if (blob1)
4842 got_object_blob_close(blob1);
4843 if (fd != -1 && close(fd) == -1 && err == NULL)
4844 err = got_error_from_errno("close");
4845 if (f2 && fclose(f2) == EOF && err == NULL)
4846 err = got_error_from_errno("fclose");
4847 free(abspath);
4848 return err;
4851 static const struct got_error *
4852 cmd_diff(int argc, char *argv[])
4854 const struct got_error *error;
4855 struct got_repository *repo = NULL;
4856 struct got_worktree *worktree = NULL;
4857 char *cwd = NULL, *repo_path = NULL;
4858 const char *commit_args[2] = { NULL, NULL };
4859 int ncommit_args = 0;
4860 struct got_object_id *ids[2] = { NULL, NULL };
4861 char *labels[2] = { NULL, NULL };
4862 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4863 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4864 int force_text_diff = 0, force_path = 0, rflag = 0;
4865 const char *errstr;
4866 struct got_reflist_head refs;
4867 struct got_pathlist_head paths;
4868 struct got_pathlist_entry *pe;
4869 FILE *f1 = NULL, *f2 = NULL;
4870 int fd1 = -1, fd2 = -1;
4871 int *pack_fds = NULL;
4873 TAILQ_INIT(&refs);
4874 TAILQ_INIT(&paths);
4876 #ifndef PROFILE
4877 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4878 NULL) == -1)
4879 err(1, "pledge");
4880 #endif
4882 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4883 switch (ch) {
4884 case 'a':
4885 force_text_diff = 1;
4886 break;
4887 case 'c':
4888 if (ncommit_args >= 2)
4889 errx(1, "too many -c options used");
4890 commit_args[ncommit_args++] = optarg;
4891 break;
4892 case 'C':
4893 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4894 &errstr);
4895 if (errstr != NULL)
4896 errx(1, "number of context lines is %s: %s",
4897 errstr, optarg);
4898 break;
4899 case 'r':
4900 repo_path = realpath(optarg, NULL);
4901 if (repo_path == NULL)
4902 return got_error_from_errno2("realpath",
4903 optarg);
4904 got_path_strip_trailing_slashes(repo_path);
4905 rflag = 1;
4906 break;
4907 case 's':
4908 diff_staged = 1;
4909 break;
4910 case 'w':
4911 ignore_whitespace = 1;
4912 break;
4913 case 'P':
4914 force_path = 1;
4915 break;
4916 default:
4917 usage_diff();
4918 /* NOTREACHED */
4922 argc -= optind;
4923 argv += optind;
4925 cwd = getcwd(NULL, 0);
4926 if (cwd == NULL) {
4927 error = got_error_from_errno("getcwd");
4928 goto done;
4931 error = got_repo_pack_fds_open(&pack_fds);
4932 if (error != NULL)
4933 goto done;
4935 if (repo_path == NULL) {
4936 error = got_worktree_open(&worktree, cwd);
4937 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4938 goto done;
4939 else
4940 error = NULL;
4941 if (worktree) {
4942 repo_path =
4943 strdup(got_worktree_get_repo_path(worktree));
4944 if (repo_path == NULL) {
4945 error = got_error_from_errno("strdup");
4946 goto done;
4948 } else {
4949 repo_path = strdup(cwd);
4950 if (repo_path == NULL) {
4951 error = got_error_from_errno("strdup");
4952 goto done;
4957 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4958 free(repo_path);
4959 if (error != NULL)
4960 goto done;
4962 if (rflag || worktree == NULL || ncommit_args > 0) {
4963 if (force_path) {
4964 error = got_error_msg(GOT_ERR_NOT_IMPL,
4965 "-P option can only be used when diffing "
4966 "a work tree");
4967 goto done;
4969 if (diff_staged) {
4970 error = got_error_msg(GOT_ERR_NOT_IMPL,
4971 "-s option can only be used when diffing "
4972 "a work tree");
4973 goto done;
4977 error = apply_unveil(got_repo_get_path(repo), 1,
4978 worktree ? got_worktree_get_root_path(worktree) : NULL);
4979 if (error)
4980 goto done;
4982 if ((!force_path && argc == 2) || ncommit_args > 0) {
4983 int obj_type = (ncommit_args > 0 ?
4984 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4985 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4986 NULL);
4987 if (error)
4988 goto done;
4989 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4990 const char *arg;
4991 if (ncommit_args > 0)
4992 arg = commit_args[i];
4993 else
4994 arg = argv[i];
4995 error = got_repo_match_object_id(&ids[i], &labels[i],
4996 arg, obj_type, &refs, repo);
4997 if (error) {
4998 if (error->code != GOT_ERR_NOT_REF &&
4999 error->code != GOT_ERR_NO_OBJ)
5000 goto done;
5001 if (ncommit_args > 0)
5002 goto done;
5003 error = NULL;
5004 break;
5009 f1 = got_opentemp();
5010 if (f1 == NULL) {
5011 error = got_error_from_errno("got_opentemp");
5012 goto done;
5015 f2 = got_opentemp();
5016 if (f2 == NULL) {
5017 error = got_error_from_errno("got_opentemp");
5018 goto done;
5021 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5022 struct print_diff_arg arg;
5023 char *id_str;
5025 if (worktree == NULL) {
5026 if (argc == 2 && ids[0] == NULL) {
5027 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5028 goto done;
5029 } else if (argc == 2 && ids[1] == NULL) {
5030 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5031 goto done;
5032 } else if (argc > 0) {
5033 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5034 "%s", "specified paths cannot be resolved");
5035 goto done;
5036 } else {
5037 error = got_error(GOT_ERR_NOT_WORKTREE);
5038 goto done;
5042 error = get_worktree_paths_from_argv(&paths, argc, argv,
5043 worktree);
5044 if (error)
5045 goto done;
5047 error = got_object_id_str(&id_str,
5048 got_worktree_get_base_commit_id(worktree));
5049 if (error)
5050 goto done;
5051 arg.repo = repo;
5052 arg.worktree = worktree;
5053 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5054 arg.diff_context = diff_context;
5055 arg.id_str = id_str;
5056 arg.header_shown = 0;
5057 arg.diff_staged = diff_staged;
5058 arg.ignore_whitespace = ignore_whitespace;
5059 arg.force_text_diff = force_text_diff;
5060 arg.f1 = f1;
5061 arg.f2 = f2;
5063 error = got_worktree_status(worktree, &paths, repo, 0,
5064 print_diff, &arg, check_cancelled, NULL);
5065 free(id_str);
5066 goto done;
5069 if (ncommit_args == 1) {
5070 struct got_commit_object *commit;
5071 error = got_object_open_as_commit(&commit, repo, ids[0]);
5072 if (error)
5073 goto done;
5075 labels[1] = labels[0];
5076 ids[1] = ids[0];
5077 if (got_object_commit_get_nparents(commit) > 0) {
5078 const struct got_object_id_queue *pids;
5079 struct got_object_qid *pid;
5080 pids = got_object_commit_get_parent_ids(commit);
5081 pid = STAILQ_FIRST(pids);
5082 ids[0] = got_object_id_dup(&pid->id);
5083 if (ids[0] == NULL) {
5084 error = got_error_from_errno(
5085 "got_object_id_dup");
5086 got_object_commit_close(commit);
5087 goto done;
5089 error = got_object_id_str(&labels[0], ids[0]);
5090 if (error) {
5091 got_object_commit_close(commit);
5092 goto done;
5094 } else {
5095 ids[0] = NULL;
5096 labels[0] = strdup("/dev/null");
5097 if (labels[0] == NULL) {
5098 error = got_error_from_errno("strdup");
5099 got_object_commit_close(commit);
5100 goto done;
5104 got_object_commit_close(commit);
5107 if (ncommit_args == 0 && argc > 2) {
5108 error = got_error_msg(GOT_ERR_BAD_PATH,
5109 "path arguments cannot be used when diffing two objects");
5110 goto done;
5113 if (ids[0]) {
5114 error = got_object_get_type(&type1, repo, ids[0]);
5115 if (error)
5116 goto done;
5119 error = got_object_get_type(&type2, repo, ids[1]);
5120 if (error)
5121 goto done;
5122 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5123 error = got_error(GOT_ERR_OBJ_TYPE);
5124 goto done;
5126 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5127 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5128 "path arguments cannot be used when diffing blobs");
5129 goto done;
5132 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5133 char *in_repo_path;
5134 struct got_pathlist_entry *new;
5135 if (worktree) {
5136 const char *prefix;
5137 char *p;
5138 error = got_worktree_resolve_path(&p, worktree,
5139 argv[i]);
5140 if (error)
5141 goto done;
5142 prefix = got_worktree_get_path_prefix(worktree);
5143 while (prefix[0] == '/')
5144 prefix++;
5145 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5146 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5147 p) == -1) {
5148 error = got_error_from_errno("asprintf");
5149 free(p);
5150 goto done;
5152 free(p);
5153 } else {
5154 char *mapped_path, *s;
5155 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5156 if (error)
5157 goto done;
5158 s = mapped_path;
5159 while (s[0] == '/')
5160 s++;
5161 in_repo_path = strdup(s);
5162 if (in_repo_path == NULL) {
5163 error = got_error_from_errno("asprintf");
5164 free(mapped_path);
5165 goto done;
5167 free(mapped_path);
5170 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5171 if (error || new == NULL /* duplicate */)
5172 free(in_repo_path);
5173 if (error)
5174 goto done;
5177 if (worktree) {
5178 /* Release work tree lock. */
5179 got_worktree_close(worktree);
5180 worktree = NULL;
5183 fd1 = got_opentempfd();
5184 if (fd1 == -1) {
5185 error = got_error_from_errno("got_opentempfd");
5186 goto done;
5189 fd2 = got_opentempfd();
5190 if (fd2 == -1) {
5191 error = got_error_from_errno("got_opentempfd");
5192 goto done;
5195 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5196 case GOT_OBJ_TYPE_BLOB:
5197 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5198 fd1, fd2, ids[0], ids[1], NULL, NULL,
5199 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5200 ignore_whitespace, force_text_diff, repo, stdout);
5201 break;
5202 case GOT_OBJ_TYPE_TREE:
5203 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5204 ids[0], ids[1], &paths, "", "",
5205 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5206 ignore_whitespace, force_text_diff, repo, stdout);
5207 break;
5208 case GOT_OBJ_TYPE_COMMIT:
5209 printf("diff %s %s\n", labels[0], labels[1]);
5210 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5211 fd1, fd2, ids[0], ids[1], &paths,
5212 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5213 ignore_whitespace, force_text_diff, repo, stdout);
5214 break;
5215 default:
5216 error = got_error(GOT_ERR_OBJ_TYPE);
5218 done:
5219 free(labels[0]);
5220 free(labels[1]);
5221 free(ids[0]);
5222 free(ids[1]);
5223 if (worktree)
5224 got_worktree_close(worktree);
5225 if (repo) {
5226 const struct got_error *close_err = got_repo_close(repo);
5227 if (error == NULL)
5228 error = close_err;
5230 if (pack_fds) {
5231 const struct got_error *pack_err =
5232 got_repo_pack_fds_close(pack_fds);
5233 if (error == NULL)
5234 error = pack_err;
5236 TAILQ_FOREACH(pe, &paths, entry)
5237 free((char *)pe->path);
5238 got_pathlist_free(&paths);
5239 got_ref_list_free(&refs);
5240 if (f1 && fclose(f1) == EOF && error == NULL)
5241 error = got_error_from_errno("fclose");
5242 if (f2 && fclose(f2) == EOF && error == NULL)
5243 error = got_error_from_errno("fclose");
5244 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5245 error = got_error_from_errno("close");
5246 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5247 error = got_error_from_errno("close");
5248 return error;
5251 __dead static void
5252 usage_blame(void)
5254 fprintf(stderr,
5255 "usage: %s blame [-c commit] [-r repository-path] path\n",
5256 getprogname());
5257 exit(1);
5260 struct blame_line {
5261 int annotated;
5262 char *id_str;
5263 char *committer;
5264 char datebuf[11]; /* YYYY-MM-DD + NUL */
5267 struct blame_cb_args {
5268 struct blame_line *lines;
5269 int nlines;
5270 int nlines_prec;
5271 int lineno_cur;
5272 off_t *line_offsets;
5273 FILE *f;
5274 struct got_repository *repo;
5277 static const struct got_error *
5278 blame_cb(void *arg, int nlines, int lineno,
5279 struct got_commit_object *commit, struct got_object_id *id)
5281 const struct got_error *err = NULL;
5282 struct blame_cb_args *a = arg;
5283 struct blame_line *bline;
5284 char *line = NULL;
5285 size_t linesize = 0;
5286 off_t offset;
5287 struct tm tm;
5288 time_t committer_time;
5290 if (nlines != a->nlines ||
5291 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5292 return got_error(GOT_ERR_RANGE);
5294 if (sigint_received)
5295 return got_error(GOT_ERR_ITER_COMPLETED);
5297 if (lineno == -1)
5298 return NULL; /* no change in this commit */
5300 /* Annotate this line. */
5301 bline = &a->lines[lineno - 1];
5302 if (bline->annotated)
5303 return NULL;
5304 err = got_object_id_str(&bline->id_str, id);
5305 if (err)
5306 return err;
5308 bline->committer = strdup(got_object_commit_get_committer(commit));
5309 if (bline->committer == NULL) {
5310 err = got_error_from_errno("strdup");
5311 goto done;
5314 committer_time = got_object_commit_get_committer_time(commit);
5315 if (gmtime_r(&committer_time, &tm) == NULL)
5316 return got_error_from_errno("gmtime_r");
5317 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5318 &tm) == 0) {
5319 err = got_error(GOT_ERR_NO_SPACE);
5320 goto done;
5322 bline->annotated = 1;
5324 /* Print lines annotated so far. */
5325 bline = &a->lines[a->lineno_cur - 1];
5326 if (!bline->annotated)
5327 goto done;
5329 offset = a->line_offsets[a->lineno_cur - 1];
5330 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5331 err = got_error_from_errno("fseeko");
5332 goto done;
5335 while (bline->annotated) {
5336 char *smallerthan, *at, *nl, *committer;
5337 size_t len;
5339 if (getline(&line, &linesize, a->f) == -1) {
5340 if (ferror(a->f))
5341 err = got_error_from_errno("getline");
5342 break;
5345 committer = bline->committer;
5346 smallerthan = strchr(committer, '<');
5347 if (smallerthan && smallerthan[1] != '\0')
5348 committer = smallerthan + 1;
5349 at = strchr(committer, '@');
5350 if (at)
5351 *at = '\0';
5352 len = strlen(committer);
5353 if (len >= 9)
5354 committer[8] = '\0';
5356 nl = strchr(line, '\n');
5357 if (nl)
5358 *nl = '\0';
5359 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5360 bline->id_str, bline->datebuf, committer, line);
5362 a->lineno_cur++;
5363 bline = &a->lines[a->lineno_cur - 1];
5365 done:
5366 free(line);
5367 return err;
5370 static const struct got_error *
5371 cmd_blame(int argc, char *argv[])
5373 const struct got_error *error;
5374 struct got_repository *repo = NULL;
5375 struct got_worktree *worktree = NULL;
5376 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5377 char *link_target = NULL;
5378 struct got_object_id *obj_id = NULL;
5379 struct got_object_id *commit_id = NULL;
5380 struct got_commit_object *commit = NULL;
5381 struct got_blob_object *blob = NULL;
5382 char *commit_id_str = NULL;
5383 struct blame_cb_args bca;
5384 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5385 off_t filesize;
5386 int *pack_fds = NULL;
5387 FILE *f1 = NULL, *f2 = NULL;
5389 fd1 = got_opentempfd();
5390 if (fd1 == -1)
5391 return got_error_from_errno("got_opentempfd");
5393 memset(&bca, 0, sizeof(bca));
5395 #ifndef PROFILE
5396 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5397 NULL) == -1)
5398 err(1, "pledge");
5399 #endif
5401 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5402 switch (ch) {
5403 case 'c':
5404 commit_id_str = optarg;
5405 break;
5406 case 'r':
5407 repo_path = realpath(optarg, NULL);
5408 if (repo_path == NULL)
5409 return got_error_from_errno2("realpath",
5410 optarg);
5411 got_path_strip_trailing_slashes(repo_path);
5412 break;
5413 default:
5414 usage_blame();
5415 /* NOTREACHED */
5419 argc -= optind;
5420 argv += optind;
5422 if (argc == 1)
5423 path = argv[0];
5424 else
5425 usage_blame();
5427 cwd = getcwd(NULL, 0);
5428 if (cwd == NULL) {
5429 error = got_error_from_errno("getcwd");
5430 goto done;
5433 error = got_repo_pack_fds_open(&pack_fds);
5434 if (error != NULL)
5435 goto done;
5437 if (repo_path == NULL) {
5438 error = got_worktree_open(&worktree, cwd);
5439 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5440 goto done;
5441 else
5442 error = NULL;
5443 if (worktree) {
5444 repo_path =
5445 strdup(got_worktree_get_repo_path(worktree));
5446 if (repo_path == NULL) {
5447 error = got_error_from_errno("strdup");
5448 if (error)
5449 goto done;
5451 } else {
5452 repo_path = strdup(cwd);
5453 if (repo_path == NULL) {
5454 error = got_error_from_errno("strdup");
5455 goto done;
5460 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5461 if (error != NULL)
5462 goto done;
5464 if (worktree) {
5465 const char *prefix = got_worktree_get_path_prefix(worktree);
5466 char *p;
5468 error = got_worktree_resolve_path(&p, worktree, path);
5469 if (error)
5470 goto done;
5471 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5472 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5473 p) == -1) {
5474 error = got_error_from_errno("asprintf");
5475 free(p);
5476 goto done;
5478 free(p);
5479 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5480 } else {
5481 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5482 if (error)
5483 goto done;
5484 error = got_repo_map_path(&in_repo_path, repo, path);
5486 if (error)
5487 goto done;
5489 if (commit_id_str == NULL) {
5490 struct got_reference *head_ref;
5491 error = got_ref_open(&head_ref, repo, worktree ?
5492 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5493 if (error != NULL)
5494 goto done;
5495 error = got_ref_resolve(&commit_id, repo, head_ref);
5496 got_ref_close(head_ref);
5497 if (error != NULL)
5498 goto done;
5499 } else {
5500 struct got_reflist_head refs;
5501 TAILQ_INIT(&refs);
5502 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5503 NULL);
5504 if (error)
5505 goto done;
5506 error = got_repo_match_object_id(&commit_id, NULL,
5507 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5508 got_ref_list_free(&refs);
5509 if (error)
5510 goto done;
5513 if (worktree) {
5514 /* Release work tree lock. */
5515 got_worktree_close(worktree);
5516 worktree = NULL;
5519 error = got_object_open_as_commit(&commit, repo, commit_id);
5520 if (error)
5521 goto done;
5523 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5524 commit, repo);
5525 if (error)
5526 goto done;
5528 error = got_object_id_by_path(&obj_id, repo, commit,
5529 link_target ? link_target : in_repo_path);
5530 if (error)
5531 goto done;
5533 error = got_object_get_type(&obj_type, repo, obj_id);
5534 if (error)
5535 goto done;
5537 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5538 error = got_error_path(link_target ? link_target : in_repo_path,
5539 GOT_ERR_OBJ_TYPE);
5540 goto done;
5543 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5544 if (error)
5545 goto done;
5546 bca.f = got_opentemp();
5547 if (bca.f == NULL) {
5548 error = got_error_from_errno("got_opentemp");
5549 goto done;
5551 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5552 &bca.line_offsets, bca.f, blob);
5553 if (error || bca.nlines == 0)
5554 goto done;
5556 /* Don't include \n at EOF in the blame line count. */
5557 if (bca.line_offsets[bca.nlines - 1] == filesize)
5558 bca.nlines--;
5560 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5561 if (bca.lines == NULL) {
5562 error = got_error_from_errno("calloc");
5563 goto done;
5565 bca.lineno_cur = 1;
5566 bca.nlines_prec = 0;
5567 i = bca.nlines;
5568 while (i > 0) {
5569 i /= 10;
5570 bca.nlines_prec++;
5572 bca.repo = repo;
5574 fd2 = got_opentempfd();
5575 if (fd2 == -1) {
5576 error = got_error_from_errno("got_opentempfd");
5577 goto done;
5579 fd3 = got_opentempfd();
5580 if (fd3 == -1) {
5581 error = got_error_from_errno("got_opentempfd");
5582 goto done;
5584 f1 = got_opentemp();
5585 if (f1 == NULL) {
5586 error = got_error_from_errno("got_opentemp");
5587 goto done;
5589 f2 = got_opentemp();
5590 if (f2 == NULL) {
5591 error = got_error_from_errno("got_opentemp");
5592 goto done;
5594 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5595 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5596 check_cancelled, NULL, fd2, fd3, f1, f2);
5597 done:
5598 free(in_repo_path);
5599 free(link_target);
5600 free(repo_path);
5601 free(cwd);
5602 free(commit_id);
5603 free(obj_id);
5604 if (commit)
5605 got_object_commit_close(commit);
5607 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5608 error = got_error_from_errno("close");
5609 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5610 error = got_error_from_errno("close");
5611 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5612 error = got_error_from_errno("close");
5613 if (f1 && fclose(f1) == EOF && error == NULL)
5614 error = got_error_from_errno("fclose");
5615 if (f2 && fclose(f2) == EOF && error == NULL)
5616 error = got_error_from_errno("fclose");
5618 if (blob)
5619 got_object_blob_close(blob);
5620 if (worktree)
5621 got_worktree_close(worktree);
5622 if (repo) {
5623 const struct got_error *close_err = got_repo_close(repo);
5624 if (error == NULL)
5625 error = close_err;
5627 if (pack_fds) {
5628 const struct got_error *pack_err =
5629 got_repo_pack_fds_close(pack_fds);
5630 if (error == NULL)
5631 error = pack_err;
5633 if (bca.lines) {
5634 for (i = 0; i < bca.nlines; i++) {
5635 struct blame_line *bline = &bca.lines[i];
5636 free(bline->id_str);
5637 free(bline->committer);
5639 free(bca.lines);
5641 free(bca.line_offsets);
5642 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5643 error = got_error_from_errno("fclose");
5644 return error;
5647 __dead static void
5648 usage_tree(void)
5650 fprintf(stderr,
5651 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5652 getprogname());
5653 exit(1);
5656 static const struct got_error *
5657 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5658 const char *root_path, struct got_repository *repo)
5660 const struct got_error *err = NULL;
5661 int is_root_path = (strcmp(path, root_path) == 0);
5662 const char *modestr = "";
5663 mode_t mode = got_tree_entry_get_mode(te);
5664 char *link_target = NULL;
5666 path += strlen(root_path);
5667 while (path[0] == '/')
5668 path++;
5670 if (got_object_tree_entry_is_submodule(te))
5671 modestr = "$";
5672 else if (S_ISLNK(mode)) {
5673 int i;
5675 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5676 if (err)
5677 return err;
5678 for (i = 0; i < strlen(link_target); i++) {
5679 if (!isprint((unsigned char)link_target[i]))
5680 link_target[i] = '?';
5683 modestr = "@";
5685 else if (S_ISDIR(mode))
5686 modestr = "/";
5687 else if (mode & S_IXUSR)
5688 modestr = "*";
5690 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5691 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5692 link_target ? " -> ": "", link_target ? link_target : "");
5694 free(link_target);
5695 return NULL;
5698 static const struct got_error *
5699 print_tree(const char *path, struct got_commit_object *commit,
5700 int show_ids, int recurse, const char *root_path,
5701 struct got_repository *repo)
5703 const struct got_error *err = NULL;
5704 struct got_object_id *tree_id = NULL;
5705 struct got_tree_object *tree = NULL;
5706 int nentries, i;
5708 err = got_object_id_by_path(&tree_id, repo, commit, path);
5709 if (err)
5710 goto done;
5712 err = got_object_open_as_tree(&tree, repo, tree_id);
5713 if (err)
5714 goto done;
5715 nentries = got_object_tree_get_nentries(tree);
5716 for (i = 0; i < nentries; i++) {
5717 struct got_tree_entry *te;
5718 char *id = NULL;
5720 if (sigint_received || sigpipe_received)
5721 break;
5723 te = got_object_tree_get_entry(tree, i);
5724 if (show_ids) {
5725 char *id_str;
5726 err = got_object_id_str(&id_str,
5727 got_tree_entry_get_id(te));
5728 if (err)
5729 goto done;
5730 if (asprintf(&id, "%s ", id_str) == -1) {
5731 err = got_error_from_errno("asprintf");
5732 free(id_str);
5733 goto done;
5735 free(id_str);
5737 err = print_entry(te, id, path, root_path, repo);
5738 free(id);
5739 if (err)
5740 goto done;
5742 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5743 char *child_path;
5744 if (asprintf(&child_path, "%s%s%s", path,
5745 path[0] == '/' && path[1] == '\0' ? "" : "/",
5746 got_tree_entry_get_name(te)) == -1) {
5747 err = got_error_from_errno("asprintf");
5748 goto done;
5750 err = print_tree(child_path, commit, show_ids, 1,
5751 root_path, repo);
5752 free(child_path);
5753 if (err)
5754 goto done;
5757 done:
5758 if (tree)
5759 got_object_tree_close(tree);
5760 free(tree_id);
5761 return err;
5764 static const struct got_error *
5765 cmd_tree(int argc, char *argv[])
5767 const struct got_error *error;
5768 struct got_repository *repo = NULL;
5769 struct got_worktree *worktree = NULL;
5770 const char *path, *refname = NULL;
5771 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5772 struct got_object_id *commit_id = NULL;
5773 struct got_commit_object *commit = NULL;
5774 char *commit_id_str = NULL;
5775 int show_ids = 0, recurse = 0;
5776 int ch;
5777 int *pack_fds = NULL;
5779 #ifndef PROFILE
5780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5781 NULL) == -1)
5782 err(1, "pledge");
5783 #endif
5785 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5786 switch (ch) {
5787 case 'c':
5788 commit_id_str = optarg;
5789 break;
5790 case 'r':
5791 repo_path = realpath(optarg, NULL);
5792 if (repo_path == NULL)
5793 return got_error_from_errno2("realpath",
5794 optarg);
5795 got_path_strip_trailing_slashes(repo_path);
5796 break;
5797 case 'i':
5798 show_ids = 1;
5799 break;
5800 case 'R':
5801 recurse = 1;
5802 break;
5803 default:
5804 usage_tree();
5805 /* NOTREACHED */
5809 argc -= optind;
5810 argv += optind;
5812 if (argc == 1)
5813 path = argv[0];
5814 else if (argc > 1)
5815 usage_tree();
5816 else
5817 path = NULL;
5819 cwd = getcwd(NULL, 0);
5820 if (cwd == NULL) {
5821 error = got_error_from_errno("getcwd");
5822 goto done;
5825 error = got_repo_pack_fds_open(&pack_fds);
5826 if (error != NULL)
5827 goto done;
5829 if (repo_path == NULL) {
5830 error = got_worktree_open(&worktree, cwd);
5831 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5832 goto done;
5833 else
5834 error = NULL;
5835 if (worktree) {
5836 repo_path =
5837 strdup(got_worktree_get_repo_path(worktree));
5838 if (repo_path == NULL)
5839 error = got_error_from_errno("strdup");
5840 if (error)
5841 goto done;
5842 } else {
5843 repo_path = strdup(cwd);
5844 if (repo_path == NULL) {
5845 error = got_error_from_errno("strdup");
5846 goto done;
5851 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5852 if (error != NULL)
5853 goto done;
5855 if (worktree) {
5856 const char *prefix = got_worktree_get_path_prefix(worktree);
5857 char *p;
5859 if (path == NULL)
5860 path = "";
5861 error = got_worktree_resolve_path(&p, worktree, path);
5862 if (error)
5863 goto done;
5864 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5865 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5866 p) == -1) {
5867 error = got_error_from_errno("asprintf");
5868 free(p);
5869 goto done;
5871 free(p);
5872 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5873 if (error)
5874 goto done;
5875 } else {
5876 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5877 if (error)
5878 goto done;
5879 if (path == NULL)
5880 path = "/";
5881 error = got_repo_map_path(&in_repo_path, repo, path);
5882 if (error != NULL)
5883 goto done;
5886 if (commit_id_str == NULL) {
5887 struct got_reference *head_ref;
5888 if (worktree)
5889 refname = got_worktree_get_head_ref_name(worktree);
5890 else
5891 refname = GOT_REF_HEAD;
5892 error = got_ref_open(&head_ref, repo, refname, 0);
5893 if (error != NULL)
5894 goto done;
5895 error = got_ref_resolve(&commit_id, repo, head_ref);
5896 got_ref_close(head_ref);
5897 if (error != NULL)
5898 goto done;
5899 } else {
5900 struct got_reflist_head refs;
5901 TAILQ_INIT(&refs);
5902 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5903 NULL);
5904 if (error)
5905 goto done;
5906 error = got_repo_match_object_id(&commit_id, NULL,
5907 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5908 got_ref_list_free(&refs);
5909 if (error)
5910 goto done;
5913 if (worktree) {
5914 /* Release work tree lock. */
5915 got_worktree_close(worktree);
5916 worktree = NULL;
5919 error = got_object_open_as_commit(&commit, repo, commit_id);
5920 if (error)
5921 goto done;
5923 error = print_tree(in_repo_path, commit, show_ids, recurse,
5924 in_repo_path, repo);
5925 done:
5926 free(in_repo_path);
5927 free(repo_path);
5928 free(cwd);
5929 free(commit_id);
5930 if (commit)
5931 got_object_commit_close(commit);
5932 if (worktree)
5933 got_worktree_close(worktree);
5934 if (repo) {
5935 const struct got_error *close_err = got_repo_close(repo);
5936 if (error == NULL)
5937 error = close_err;
5939 if (pack_fds) {
5940 const struct got_error *pack_err =
5941 got_repo_pack_fds_close(pack_fds);
5942 if (error == NULL)
5943 error = pack_err;
5945 return error;
5948 __dead static void
5949 usage_status(void)
5951 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5952 "[-S status-codes] [path ...]\n", getprogname());
5953 exit(1);
5956 struct got_status_arg {
5957 char *status_codes;
5958 int suppress;
5961 static const struct got_error *
5962 print_status(void *arg, unsigned char status, unsigned char staged_status,
5963 const char *path, struct got_object_id *blob_id,
5964 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5965 int dirfd, const char *de_name)
5967 struct got_status_arg *st = arg;
5969 if (status == staged_status && (status == GOT_STATUS_DELETE))
5970 status = GOT_STATUS_NO_CHANGE;
5971 if (st != NULL && st->status_codes) {
5972 size_t ncodes = strlen(st->status_codes);
5973 int i, j = 0;
5975 for (i = 0; i < ncodes ; i++) {
5976 if (st->suppress) {
5977 if (status == st->status_codes[i] ||
5978 staged_status == st->status_codes[i]) {
5979 j++;
5980 continue;
5982 } else {
5983 if (status == st->status_codes[i] ||
5984 staged_status == st->status_codes[i])
5985 break;
5989 if (st->suppress && j == 0)
5990 goto print;
5992 if (i == ncodes)
5993 return NULL;
5995 print:
5996 printf("%c%c %s\n", status, staged_status, path);
5997 return NULL;
6000 static const struct got_error *
6001 cmd_status(int argc, char *argv[])
6003 const struct got_error *error = NULL;
6004 struct got_repository *repo = NULL;
6005 struct got_worktree *worktree = NULL;
6006 struct got_status_arg st;
6007 char *cwd = NULL;
6008 struct got_pathlist_head paths;
6009 struct got_pathlist_entry *pe;
6010 int ch, i, no_ignores = 0;
6011 int *pack_fds = NULL;
6013 TAILQ_INIT(&paths);
6015 memset(&st, 0, sizeof(st));
6016 st.status_codes = NULL;
6017 st.suppress = 0;
6019 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6020 switch (ch) {
6021 case 'I':
6022 no_ignores = 1;
6023 break;
6024 case 'S':
6025 if (st.status_codes != NULL && st.suppress == 0)
6026 option_conflict('S', 's');
6027 st.suppress = 1;
6028 /* fallthrough */
6029 case 's':
6030 for (i = 0; i < strlen(optarg); i++) {
6031 switch (optarg[i]) {
6032 case GOT_STATUS_MODIFY:
6033 case GOT_STATUS_ADD:
6034 case GOT_STATUS_DELETE:
6035 case GOT_STATUS_CONFLICT:
6036 case GOT_STATUS_MISSING:
6037 case GOT_STATUS_OBSTRUCTED:
6038 case GOT_STATUS_UNVERSIONED:
6039 case GOT_STATUS_MODE_CHANGE:
6040 case GOT_STATUS_NONEXISTENT:
6041 break;
6042 default:
6043 errx(1, "invalid status code '%c'",
6044 optarg[i]);
6047 if (ch == 's' && st.suppress)
6048 option_conflict('s', 'S');
6049 st.status_codes = optarg;
6050 break;
6051 default:
6052 usage_status();
6053 /* NOTREACHED */
6057 argc -= optind;
6058 argv += optind;
6060 #ifndef PROFILE
6061 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6062 NULL) == -1)
6063 err(1, "pledge");
6064 #endif
6065 cwd = getcwd(NULL, 0);
6066 if (cwd == NULL) {
6067 error = got_error_from_errno("getcwd");
6068 goto done;
6071 error = got_repo_pack_fds_open(&pack_fds);
6072 if (error != NULL)
6073 goto done;
6075 error = got_worktree_open(&worktree, cwd);
6076 if (error) {
6077 if (error->code == GOT_ERR_NOT_WORKTREE)
6078 error = wrap_not_worktree_error(error, "status", cwd);
6079 goto done;
6082 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6083 NULL, pack_fds);
6084 if (error != NULL)
6085 goto done;
6087 error = apply_unveil(got_repo_get_path(repo), 1,
6088 got_worktree_get_root_path(worktree));
6089 if (error)
6090 goto done;
6092 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6093 if (error)
6094 goto done;
6096 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6097 print_status, &st, check_cancelled, NULL);
6098 done:
6099 if (pack_fds) {
6100 const struct got_error *pack_err =
6101 got_repo_pack_fds_close(pack_fds);
6102 if (error == NULL)
6103 error = pack_err;
6106 TAILQ_FOREACH(pe, &paths, entry)
6107 free((char *)pe->path);
6108 got_pathlist_free(&paths);
6109 free(cwd);
6110 return error;
6113 __dead static void
6114 usage_ref(void)
6116 fprintf(stderr,
6117 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6118 "[-s reference] [-d] [name]\n",
6119 getprogname());
6120 exit(1);
6123 static const struct got_error *
6124 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6126 static const struct got_error *err = NULL;
6127 struct got_reflist_head refs;
6128 struct got_reflist_entry *re;
6130 TAILQ_INIT(&refs);
6131 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6132 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6133 repo);
6134 if (err)
6135 return err;
6137 TAILQ_FOREACH(re, &refs, entry) {
6138 char *refstr;
6139 refstr = got_ref_to_str(re->ref);
6140 if (refstr == NULL) {
6141 err = got_error_from_errno("got_ref_to_str");
6142 break;
6144 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6145 free(refstr);
6148 got_ref_list_free(&refs);
6149 return err;
6152 static const struct got_error *
6153 delete_ref_by_name(struct got_repository *repo, const char *refname)
6155 const struct got_error *err;
6156 struct got_reference *ref;
6158 err = got_ref_open(&ref, repo, refname, 0);
6159 if (err)
6160 return err;
6162 err = delete_ref(repo, ref);
6163 got_ref_close(ref);
6164 return err;
6167 static const struct got_error *
6168 add_ref(struct got_repository *repo, const char *refname, const char *target)
6170 const struct got_error *err = NULL;
6171 struct got_object_id *id = NULL;
6172 struct got_reference *ref = NULL;
6173 struct got_reflist_head refs;
6176 * Don't let the user create a reference name with a leading '-'.
6177 * While technically a valid reference name, this case is usually
6178 * an unintended typo.
6180 if (refname[0] == '-')
6181 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6183 TAILQ_INIT(&refs);
6184 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6185 if (err)
6186 goto done;
6187 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6188 &refs, repo);
6189 got_ref_list_free(&refs);
6190 if (err)
6191 goto done;
6193 err = got_ref_alloc(&ref, refname, id);
6194 if (err)
6195 goto done;
6197 err = got_ref_write(ref, repo);
6198 done:
6199 if (ref)
6200 got_ref_close(ref);
6201 free(id);
6202 return err;
6205 static const struct got_error *
6206 add_symref(struct got_repository *repo, const char *refname, const char *target)
6208 const struct got_error *err = NULL;
6209 struct got_reference *ref = NULL;
6210 struct got_reference *target_ref = NULL;
6213 * Don't let the user create a reference name with a leading '-'.
6214 * While technically a valid reference name, this case is usually
6215 * an unintended typo.
6217 if (refname[0] == '-')
6218 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6220 err = got_ref_open(&target_ref, repo, target, 0);
6221 if (err)
6222 return err;
6224 err = got_ref_alloc_symref(&ref, refname, target_ref);
6225 if (err)
6226 goto done;
6228 err = got_ref_write(ref, repo);
6229 done:
6230 if (target_ref)
6231 got_ref_close(target_ref);
6232 if (ref)
6233 got_ref_close(ref);
6234 return err;
6237 static const struct got_error *
6238 cmd_ref(int argc, char *argv[])
6240 const struct got_error *error = NULL;
6241 struct got_repository *repo = NULL;
6242 struct got_worktree *worktree = NULL;
6243 char *cwd = NULL, *repo_path = NULL;
6244 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6245 const char *obj_arg = NULL, *symref_target= NULL;
6246 char *refname = NULL;
6247 int *pack_fds = NULL;
6249 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6250 switch (ch) {
6251 case 'c':
6252 obj_arg = optarg;
6253 break;
6254 case 'd':
6255 do_delete = 1;
6256 break;
6257 case 'r':
6258 repo_path = realpath(optarg, NULL);
6259 if (repo_path == NULL)
6260 return got_error_from_errno2("realpath",
6261 optarg);
6262 got_path_strip_trailing_slashes(repo_path);
6263 break;
6264 case 'l':
6265 do_list = 1;
6266 break;
6267 case 's':
6268 symref_target = optarg;
6269 break;
6270 case 't':
6271 sort_by_time = 1;
6272 break;
6273 default:
6274 usage_ref();
6275 /* NOTREACHED */
6279 if (obj_arg && do_list)
6280 option_conflict('c', 'l');
6281 if (obj_arg && do_delete)
6282 option_conflict('c', 'd');
6283 if (obj_arg && symref_target)
6284 option_conflict('c', 's');
6285 if (symref_target && do_delete)
6286 option_conflict('s', 'd');
6287 if (symref_target && do_list)
6288 option_conflict('s', 'l');
6289 if (do_delete && do_list)
6290 option_conflict('d', 'l');
6291 if (sort_by_time && !do_list)
6292 errx(1, "-t option requires -l option");
6294 argc -= optind;
6295 argv += optind;
6297 if (do_list) {
6298 if (argc != 0 && argc != 1)
6299 usage_ref();
6300 if (argc == 1) {
6301 refname = strdup(argv[0]);
6302 if (refname == NULL) {
6303 error = got_error_from_errno("strdup");
6304 goto done;
6307 } else {
6308 if (argc != 1)
6309 usage_ref();
6310 refname = strdup(argv[0]);
6311 if (refname == NULL) {
6312 error = got_error_from_errno("strdup");
6313 goto done;
6317 if (refname)
6318 got_path_strip_trailing_slashes(refname);
6320 #ifndef PROFILE
6321 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6322 "sendfd unveil", NULL) == -1)
6323 err(1, "pledge");
6324 #endif
6325 cwd = getcwd(NULL, 0);
6326 if (cwd == NULL) {
6327 error = got_error_from_errno("getcwd");
6328 goto done;
6331 error = got_repo_pack_fds_open(&pack_fds);
6332 if (error != NULL)
6333 goto done;
6335 if (repo_path == NULL) {
6336 error = got_worktree_open(&worktree, cwd);
6337 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6338 goto done;
6339 else
6340 error = NULL;
6341 if (worktree) {
6342 repo_path =
6343 strdup(got_worktree_get_repo_path(worktree));
6344 if (repo_path == NULL)
6345 error = got_error_from_errno("strdup");
6346 if (error)
6347 goto done;
6348 } else {
6349 repo_path = strdup(cwd);
6350 if (repo_path == NULL) {
6351 error = got_error_from_errno("strdup");
6352 goto done;
6357 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6358 if (error != NULL)
6359 goto done;
6361 #ifndef PROFILE
6362 if (do_list) {
6363 /* Remove "cpath" promise. */
6364 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6365 NULL) == -1)
6366 err(1, "pledge");
6368 #endif
6370 error = apply_unveil(got_repo_get_path(repo), do_list,
6371 worktree ? got_worktree_get_root_path(worktree) : NULL);
6372 if (error)
6373 goto done;
6375 if (do_list)
6376 error = list_refs(repo, refname, sort_by_time);
6377 else if (do_delete)
6378 error = delete_ref_by_name(repo, refname);
6379 else if (symref_target)
6380 error = add_symref(repo, refname, symref_target);
6381 else {
6382 if (obj_arg == NULL)
6383 usage_ref();
6384 error = add_ref(repo, refname, obj_arg);
6386 done:
6387 free(refname);
6388 if (repo) {
6389 const struct got_error *close_err = got_repo_close(repo);
6390 if (error == NULL)
6391 error = close_err;
6393 if (worktree)
6394 got_worktree_close(worktree);
6395 if (pack_fds) {
6396 const struct got_error *pack_err =
6397 got_repo_pack_fds_close(pack_fds);
6398 if (error == NULL)
6399 error = pack_err;
6401 free(cwd);
6402 free(repo_path);
6403 return error;
6406 __dead static void
6407 usage_branch(void)
6409 fprintf(stderr,
6410 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6411 "[-n] [name]\n", getprogname());
6412 exit(1);
6415 static const struct got_error *
6416 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6417 struct got_reference *ref)
6419 const struct got_error *err = NULL;
6420 const char *refname, *marker = " ";
6421 char *refstr;
6423 refname = got_ref_get_name(ref);
6424 if (worktree && strcmp(refname,
6425 got_worktree_get_head_ref_name(worktree)) == 0) {
6426 struct got_object_id *id = NULL;
6428 err = got_ref_resolve(&id, repo, ref);
6429 if (err)
6430 return err;
6431 if (got_object_id_cmp(id,
6432 got_worktree_get_base_commit_id(worktree)) == 0)
6433 marker = "* ";
6434 else
6435 marker = "~ ";
6436 free(id);
6439 if (strncmp(refname, "refs/heads/", 11) == 0)
6440 refname += 11;
6441 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6442 refname += 18;
6443 if (strncmp(refname, "refs/remotes/", 13) == 0)
6444 refname += 13;
6446 refstr = got_ref_to_str(ref);
6447 if (refstr == NULL)
6448 return got_error_from_errno("got_ref_to_str");
6450 printf("%s%s: %s\n", marker, refname, refstr);
6451 free(refstr);
6452 return NULL;
6455 static const struct got_error *
6456 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6458 const char *refname;
6460 if (worktree == NULL)
6461 return got_error(GOT_ERR_NOT_WORKTREE);
6463 refname = got_worktree_get_head_ref_name(worktree);
6465 if (strncmp(refname, "refs/heads/", 11) == 0)
6466 refname += 11;
6467 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6468 refname += 18;
6470 printf("%s\n", refname);
6472 return NULL;
6475 static const struct got_error *
6476 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6477 int sort_by_time)
6479 static const struct got_error *err = NULL;
6480 struct got_reflist_head refs;
6481 struct got_reflist_entry *re;
6482 struct got_reference *temp_ref = NULL;
6483 int rebase_in_progress, histedit_in_progress;
6485 TAILQ_INIT(&refs);
6487 if (worktree) {
6488 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6489 worktree);
6490 if (err)
6491 return err;
6493 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6494 worktree);
6495 if (err)
6496 return err;
6498 if (rebase_in_progress || histedit_in_progress) {
6499 err = got_ref_open(&temp_ref, repo,
6500 got_worktree_get_head_ref_name(worktree), 0);
6501 if (err)
6502 return err;
6503 list_branch(repo, worktree, temp_ref);
6504 got_ref_close(temp_ref);
6508 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6509 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6510 repo);
6511 if (err)
6512 return err;
6514 TAILQ_FOREACH(re, &refs, entry)
6515 list_branch(repo, worktree, re->ref);
6517 got_ref_list_free(&refs);
6519 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6520 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6521 repo);
6522 if (err)
6523 return err;
6525 TAILQ_FOREACH(re, &refs, entry)
6526 list_branch(repo, worktree, re->ref);
6528 got_ref_list_free(&refs);
6530 return NULL;
6533 static const struct got_error *
6534 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6535 const char *branch_name)
6537 const struct got_error *err = NULL;
6538 struct got_reference *ref = NULL;
6539 char *refname, *remote_refname = NULL;
6541 if (strncmp(branch_name, "refs/", 5) == 0)
6542 branch_name += 5;
6543 if (strncmp(branch_name, "heads/", 6) == 0)
6544 branch_name += 6;
6545 else if (strncmp(branch_name, "remotes/", 8) == 0)
6546 branch_name += 8;
6548 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6549 return got_error_from_errno("asprintf");
6551 if (asprintf(&remote_refname, "refs/remotes/%s",
6552 branch_name) == -1) {
6553 err = got_error_from_errno("asprintf");
6554 goto done;
6557 err = got_ref_open(&ref, repo, refname, 0);
6558 if (err) {
6559 const struct got_error *err2;
6560 if (err->code != GOT_ERR_NOT_REF)
6561 goto done;
6563 * Keep 'err' intact such that if neither branch exists
6564 * we report "refs/heads" rather than "refs/remotes" in
6565 * our error message.
6567 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6568 if (err2)
6569 goto done;
6570 err = NULL;
6573 if (worktree &&
6574 strcmp(got_worktree_get_head_ref_name(worktree),
6575 got_ref_get_name(ref)) == 0) {
6576 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6577 "will not delete this work tree's current branch");
6578 goto done;
6581 err = delete_ref(repo, ref);
6582 done:
6583 if (ref)
6584 got_ref_close(ref);
6585 free(refname);
6586 free(remote_refname);
6587 return err;
6590 static const struct got_error *
6591 add_branch(struct got_repository *repo, const char *branch_name,
6592 struct got_object_id *base_commit_id)
6594 const struct got_error *err = NULL;
6595 struct got_reference *ref = NULL;
6596 char *base_refname = NULL, *refname = NULL;
6599 * Don't let the user create a branch name with a leading '-'.
6600 * While technically a valid reference name, this case is usually
6601 * an unintended typo.
6603 if (branch_name[0] == '-')
6604 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6606 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6607 branch_name += 11;
6609 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6610 err = got_error_from_errno("asprintf");
6611 goto done;
6614 err = got_ref_open(&ref, repo, refname, 0);
6615 if (err == NULL) {
6616 err = got_error(GOT_ERR_BRANCH_EXISTS);
6617 goto done;
6618 } else if (err->code != GOT_ERR_NOT_REF)
6619 goto done;
6621 err = got_ref_alloc(&ref, refname, base_commit_id);
6622 if (err)
6623 goto done;
6625 err = got_ref_write(ref, repo);
6626 done:
6627 if (ref)
6628 got_ref_close(ref);
6629 free(base_refname);
6630 free(refname);
6631 return err;
6634 static const struct got_error *
6635 cmd_branch(int argc, char *argv[])
6637 const struct got_error *error = NULL;
6638 struct got_repository *repo = NULL;
6639 struct got_worktree *worktree = NULL;
6640 char *cwd = NULL, *repo_path = NULL;
6641 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6642 const char *delref = NULL, *commit_id_arg = NULL;
6643 struct got_reference *ref = NULL;
6644 struct got_pathlist_head paths;
6645 struct got_pathlist_entry *pe;
6646 struct got_object_id *commit_id = NULL;
6647 char *commit_id_str = NULL;
6648 int *pack_fds = NULL;
6650 TAILQ_INIT(&paths);
6652 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6653 switch (ch) {
6654 case 'c':
6655 commit_id_arg = optarg;
6656 break;
6657 case 'd':
6658 delref = optarg;
6659 break;
6660 case 'r':
6661 repo_path = realpath(optarg, NULL);
6662 if (repo_path == NULL)
6663 return got_error_from_errno2("realpath",
6664 optarg);
6665 got_path_strip_trailing_slashes(repo_path);
6666 break;
6667 case 'l':
6668 do_list = 1;
6669 break;
6670 case 'n':
6671 do_update = 0;
6672 break;
6673 case 't':
6674 sort_by_time = 1;
6675 break;
6676 default:
6677 usage_branch();
6678 /* NOTREACHED */
6682 if (do_list && delref)
6683 option_conflict('l', 'd');
6684 if (sort_by_time && !do_list)
6685 errx(1, "-t option requires -l option");
6687 argc -= optind;
6688 argv += optind;
6690 if (!do_list && !delref && argc == 0)
6691 do_show = 1;
6693 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6694 errx(1, "-c option can only be used when creating a branch");
6696 if (do_list || delref) {
6697 if (argc > 0)
6698 usage_branch();
6699 } else if (!do_show && argc != 1)
6700 usage_branch();
6702 #ifndef PROFILE
6703 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6704 "sendfd unveil", NULL) == -1)
6705 err(1, "pledge");
6706 #endif
6707 cwd = getcwd(NULL, 0);
6708 if (cwd == NULL) {
6709 error = got_error_from_errno("getcwd");
6710 goto done;
6713 error = got_repo_pack_fds_open(&pack_fds);
6714 if (error != NULL)
6715 goto done;
6717 if (repo_path == NULL) {
6718 error = got_worktree_open(&worktree, cwd);
6719 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6720 goto done;
6721 else
6722 error = NULL;
6723 if (worktree) {
6724 repo_path =
6725 strdup(got_worktree_get_repo_path(worktree));
6726 if (repo_path == NULL)
6727 error = got_error_from_errno("strdup");
6728 if (error)
6729 goto done;
6730 } else {
6731 repo_path = strdup(cwd);
6732 if (repo_path == NULL) {
6733 error = got_error_from_errno("strdup");
6734 goto done;
6739 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6740 if (error != NULL)
6741 goto done;
6743 #ifndef PROFILE
6744 if (do_list || do_show) {
6745 /* Remove "cpath" promise. */
6746 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6747 NULL) == -1)
6748 err(1, "pledge");
6750 #endif
6752 error = apply_unveil(got_repo_get_path(repo), do_list,
6753 worktree ? got_worktree_get_root_path(worktree) : NULL);
6754 if (error)
6755 goto done;
6757 if (do_show)
6758 error = show_current_branch(repo, worktree);
6759 else if (do_list)
6760 error = list_branches(repo, worktree, sort_by_time);
6761 else if (delref)
6762 error = delete_branch(repo, worktree, delref);
6763 else {
6764 struct got_reflist_head refs;
6765 TAILQ_INIT(&refs);
6766 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6767 NULL);
6768 if (error)
6769 goto done;
6770 if (commit_id_arg == NULL)
6771 commit_id_arg = worktree ?
6772 got_worktree_get_head_ref_name(worktree) :
6773 GOT_REF_HEAD;
6774 error = got_repo_match_object_id(&commit_id, NULL,
6775 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6776 got_ref_list_free(&refs);
6777 if (error)
6778 goto done;
6779 error = add_branch(repo, argv[0], commit_id);
6780 if (error)
6781 goto done;
6782 if (worktree && do_update) {
6783 struct got_update_progress_arg upa;
6784 char *branch_refname = NULL;
6786 error = got_object_id_str(&commit_id_str, commit_id);
6787 if (error)
6788 goto done;
6789 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6790 worktree);
6791 if (error)
6792 goto done;
6793 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6794 == -1) {
6795 error = got_error_from_errno("asprintf");
6796 goto done;
6798 error = got_ref_open(&ref, repo, branch_refname, 0);
6799 free(branch_refname);
6800 if (error)
6801 goto done;
6802 error = switch_head_ref(ref, commit_id, worktree,
6803 repo);
6804 if (error)
6805 goto done;
6806 error = got_worktree_set_base_commit_id(worktree, repo,
6807 commit_id);
6808 if (error)
6809 goto done;
6810 memset(&upa, 0, sizeof(upa));
6811 error = got_worktree_checkout_files(worktree, &paths,
6812 repo, update_progress, &upa, check_cancelled,
6813 NULL);
6814 if (error)
6815 goto done;
6816 if (upa.did_something) {
6817 printf("Updated to %s: %s\n",
6818 got_worktree_get_head_ref_name(worktree),
6819 commit_id_str);
6821 print_update_progress_stats(&upa);
6824 done:
6825 if (ref)
6826 got_ref_close(ref);
6827 if (repo) {
6828 const struct got_error *close_err = got_repo_close(repo);
6829 if (error == NULL)
6830 error = close_err;
6832 if (worktree)
6833 got_worktree_close(worktree);
6834 if (pack_fds) {
6835 const struct got_error *pack_err =
6836 got_repo_pack_fds_close(pack_fds);
6837 if (error == NULL)
6838 error = pack_err;
6840 free(cwd);
6841 free(repo_path);
6842 free(commit_id);
6843 free(commit_id_str);
6844 TAILQ_FOREACH(pe, &paths, entry)
6845 free((char *)pe->path);
6846 got_pathlist_free(&paths);
6847 return error;
6851 __dead static void
6852 usage_tag(void)
6854 fprintf(stderr,
6855 "usage: %s tag [-c commit] [-r repository] [-l] "
6856 "[-m message] [-s signer-id] [-V] name\n",
6857 getprogname());
6858 exit(1);
6861 #if 0
6862 static const struct got_error *
6863 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6865 const struct got_error *err = NULL;
6866 struct got_reflist_entry *re, *se, *new;
6867 struct got_object_id *re_id, *se_id;
6868 struct got_tag_object *re_tag, *se_tag;
6869 time_t re_time, se_time;
6871 STAILQ_FOREACH(re, tags, entry) {
6872 se = STAILQ_FIRST(sorted);
6873 if (se == NULL) {
6874 err = got_reflist_entry_dup(&new, re);
6875 if (err)
6876 return err;
6877 STAILQ_INSERT_HEAD(sorted, new, entry);
6878 continue;
6879 } else {
6880 err = got_ref_resolve(&re_id, repo, re->ref);
6881 if (err)
6882 break;
6883 err = got_object_open_as_tag(&re_tag, repo, re_id);
6884 free(re_id);
6885 if (err)
6886 break;
6887 re_time = got_object_tag_get_tagger_time(re_tag);
6888 got_object_tag_close(re_tag);
6891 while (se) {
6892 err = got_ref_resolve(&se_id, repo, re->ref);
6893 if (err)
6894 break;
6895 err = got_object_open_as_tag(&se_tag, repo, se_id);
6896 free(se_id);
6897 if (err)
6898 break;
6899 se_time = got_object_tag_get_tagger_time(se_tag);
6900 got_object_tag_close(se_tag);
6902 if (se_time > re_time) {
6903 err = got_reflist_entry_dup(&new, re);
6904 if (err)
6905 return err;
6906 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6907 break;
6909 se = STAILQ_NEXT(se, entry);
6910 continue;
6913 done:
6914 return err;
6916 #endif
6918 static const struct got_error *
6919 get_tag_refname(char **refname, const char *tag_name)
6921 const struct got_error *err;
6923 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6924 *refname = strdup(tag_name);
6925 if (*refname == NULL)
6926 return got_error_from_errno("strdup");
6927 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6928 err = got_error_from_errno("asprintf");
6929 *refname = NULL;
6930 return err;
6933 return NULL;
6936 static const struct got_error *
6937 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6938 const char *allowed_signers, const char *revoked_signers, int verbosity)
6940 static const struct got_error *err = NULL;
6941 struct got_reflist_head refs;
6942 struct got_reflist_entry *re;
6943 char *wanted_refname = NULL;
6944 int bad_sigs = 0;
6946 TAILQ_INIT(&refs);
6948 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6949 if (err)
6950 return err;
6952 if (tag_name) {
6953 struct got_reference *ref;
6954 err = get_tag_refname(&wanted_refname, tag_name);
6955 if (err)
6956 goto done;
6957 /* Wanted tag reference should exist. */
6958 err = got_ref_open(&ref, repo, wanted_refname, 0);
6959 if (err)
6960 goto done;
6961 got_ref_close(ref);
6964 TAILQ_FOREACH(re, &refs, entry) {
6965 const char *refname;
6966 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6967 char datebuf[26];
6968 const char *tagger, *ssh_sig = NULL;
6969 char *sig_msg = NULL;
6970 time_t tagger_time;
6971 struct got_object_id *id;
6972 struct got_tag_object *tag;
6973 struct got_commit_object *commit = NULL;
6975 refname = got_ref_get_name(re->ref);
6976 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6977 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6978 continue;
6979 refname += 10;
6980 refstr = got_ref_to_str(re->ref);
6981 if (refstr == NULL) {
6982 err = got_error_from_errno("got_ref_to_str");
6983 break;
6986 err = got_ref_resolve(&id, repo, re->ref);
6987 if (err)
6988 break;
6989 err = got_object_open_as_tag(&tag, repo, id);
6990 if (err) {
6991 if (err->code != GOT_ERR_OBJ_TYPE) {
6992 free(id);
6993 break;
6995 /* "lightweight" tag */
6996 err = got_object_open_as_commit(&commit, repo, id);
6997 if (err) {
6998 free(id);
6999 break;
7001 tagger = got_object_commit_get_committer(commit);
7002 tagger_time =
7003 got_object_commit_get_committer_time(commit);
7004 err = got_object_id_str(&id_str, id);
7005 free(id);
7006 if (err)
7007 break;
7008 } else {
7009 free(id);
7010 tagger = got_object_tag_get_tagger(tag);
7011 tagger_time = got_object_tag_get_tagger_time(tag);
7012 err = got_object_id_str(&id_str,
7013 got_object_tag_get_object_id(tag));
7014 if (err)
7015 break;
7018 if (verify_tags) {
7019 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7020 got_object_tag_get_message(tag));
7021 if (ssh_sig && allowed_signers == NULL) {
7022 err = got_error_msg(
7023 GOT_ERR_VERIFY_TAG_SIGNATURE,
7024 "SSH signature verification requires "
7025 "setting allowed_signers in "
7026 "got.conf(5)");
7027 break;
7031 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7032 free(refstr);
7033 printf("from: %s\n", tagger);
7034 datestr = get_datestr(&tagger_time, datebuf);
7035 if (datestr)
7036 printf("date: %s UTC\n", datestr);
7037 if (commit)
7038 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7039 else {
7040 switch (got_object_tag_get_object_type(tag)) {
7041 case GOT_OBJ_TYPE_BLOB:
7042 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7043 id_str);
7044 break;
7045 case GOT_OBJ_TYPE_TREE:
7046 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7047 id_str);
7048 break;
7049 case GOT_OBJ_TYPE_COMMIT:
7050 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7051 id_str);
7052 break;
7053 case GOT_OBJ_TYPE_TAG:
7054 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7055 id_str);
7056 break;
7057 default:
7058 break;
7061 free(id_str);
7063 if (ssh_sig) {
7064 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7065 allowed_signers, revoked_signers, verbosity);
7066 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7067 bad_sigs = 1;
7068 else if (err)
7069 break;
7070 printf("signature: %s", sig_msg);
7071 free(sig_msg);
7072 sig_msg = NULL;
7075 if (commit) {
7076 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7077 if (err)
7078 break;
7079 got_object_commit_close(commit);
7080 } else {
7081 tagmsg0 = strdup(got_object_tag_get_message(tag));
7082 got_object_tag_close(tag);
7083 if (tagmsg0 == NULL) {
7084 err = got_error_from_errno("strdup");
7085 break;
7089 tagmsg = tagmsg0;
7090 do {
7091 line = strsep(&tagmsg, "\n");
7092 if (line)
7093 printf(" %s\n", line);
7094 } while (line);
7095 free(tagmsg0);
7097 done:
7098 got_ref_list_free(&refs);
7099 free(wanted_refname);
7101 if (err == NULL && bad_sigs)
7102 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7103 return err;
7106 static const struct got_error *
7107 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7108 const char *tag_name, const char *repo_path)
7110 const struct got_error *err = NULL;
7111 char *template = NULL, *initial_content = NULL;
7112 char *editor = NULL;
7113 int initial_content_len;
7114 int fd = -1;
7116 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7117 err = got_error_from_errno("asprintf");
7118 goto done;
7121 initial_content_len = asprintf(&initial_content,
7122 "\n# tagging commit %s as %s\n",
7123 commit_id_str, tag_name);
7124 if (initial_content_len == -1) {
7125 err = got_error_from_errno("asprintf");
7126 goto done;
7129 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7130 if (err)
7131 goto done;
7133 if (write(fd, initial_content, initial_content_len) == -1) {
7134 err = got_error_from_errno2("write", *tagmsg_path);
7135 goto done;
7138 err = get_editor(&editor);
7139 if (err)
7140 goto done;
7141 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7142 initial_content_len, 1);
7143 done:
7144 free(initial_content);
7145 free(template);
7146 free(editor);
7148 if (fd != -1 && close(fd) == -1 && err == NULL)
7149 err = got_error_from_errno2("close", *tagmsg_path);
7151 if (err) {
7152 free(*tagmsg);
7153 *tagmsg = NULL;
7155 return err;
7158 static const struct got_error *
7159 add_tag(struct got_repository *repo, const char *tagger,
7160 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7161 const char *signer_id, int verbosity)
7163 const struct got_error *err = NULL;
7164 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7165 char *label = NULL, *commit_id_str = NULL;
7166 struct got_reference *ref = NULL;
7167 char *refname = NULL, *tagmsg = NULL;
7168 char *tagmsg_path = NULL, *tag_id_str = NULL;
7169 int preserve_tagmsg = 0;
7170 struct got_reflist_head refs;
7172 TAILQ_INIT(&refs);
7175 * Don't let the user create a tag name with a leading '-'.
7176 * While technically a valid reference name, this case is usually
7177 * an unintended typo.
7179 if (tag_name[0] == '-')
7180 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7182 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7183 if (err)
7184 goto done;
7186 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7187 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7188 if (err)
7189 goto done;
7191 err = got_object_id_str(&commit_id_str, commit_id);
7192 if (err)
7193 goto done;
7195 err = get_tag_refname(&refname, tag_name);
7196 if (err)
7197 goto done;
7198 if (strncmp("refs/tags/", tag_name, 10) == 0)
7199 tag_name += 10;
7201 err = got_ref_open(&ref, repo, refname, 0);
7202 if (err == NULL) {
7203 err = got_error(GOT_ERR_TAG_EXISTS);
7204 goto done;
7205 } else if (err->code != GOT_ERR_NOT_REF)
7206 goto done;
7208 if (tagmsg_arg == NULL) {
7209 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7210 tag_name, got_repo_get_path(repo));
7211 if (err) {
7212 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7213 tagmsg_path != NULL)
7214 preserve_tagmsg = 1;
7215 goto done;
7217 /* Editor is done; we can now apply unveil(2) */
7218 err = got_sigs_apply_unveil();
7219 if (err)
7220 goto done;
7221 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7222 if (err)
7223 goto done;
7226 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7227 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7228 verbosity);
7229 if (err) {
7230 if (tagmsg_path)
7231 preserve_tagmsg = 1;
7232 goto done;
7235 err = got_ref_alloc(&ref, refname, tag_id);
7236 if (err) {
7237 if (tagmsg_path)
7238 preserve_tagmsg = 1;
7239 goto done;
7242 err = got_ref_write(ref, repo);
7243 if (err) {
7244 if (tagmsg_path)
7245 preserve_tagmsg = 1;
7246 goto done;
7249 err = got_object_id_str(&tag_id_str, tag_id);
7250 if (err) {
7251 if (tagmsg_path)
7252 preserve_tagmsg = 1;
7253 goto done;
7255 printf("Created tag %s\n", tag_id_str);
7256 done:
7257 if (preserve_tagmsg) {
7258 fprintf(stderr, "%s: tag message preserved in %s\n",
7259 getprogname(), tagmsg_path);
7260 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7261 err = got_error_from_errno2("unlink", tagmsg_path);
7262 free(tag_id_str);
7263 if (ref)
7264 got_ref_close(ref);
7265 free(commit_id);
7266 free(commit_id_str);
7267 free(refname);
7268 free(tagmsg);
7269 free(tagmsg_path);
7270 got_ref_list_free(&refs);
7271 return err;
7274 static const struct got_error *
7275 cmd_tag(int argc, char *argv[])
7277 const struct got_error *error = NULL;
7278 struct got_repository *repo = NULL;
7279 struct got_worktree *worktree = NULL;
7280 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7281 char *gitconfig_path = NULL, *tagger = NULL;
7282 char *allowed_signers = NULL, *revoked_signers = NULL;
7283 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7284 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7285 const char *signer_id = NULL;
7286 int *pack_fds = NULL;
7288 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7289 switch (ch) {
7290 case 'c':
7291 commit_id_arg = optarg;
7292 break;
7293 case 'm':
7294 tagmsg = optarg;
7295 break;
7296 case 'r':
7297 repo_path = realpath(optarg, NULL);
7298 if (repo_path == NULL)
7299 return got_error_from_errno2("realpath",
7300 optarg);
7301 got_path_strip_trailing_slashes(repo_path);
7302 break;
7303 case 'l':
7304 do_list = 1;
7305 break;
7306 case 's':
7307 signer_id = optarg;
7308 break;
7309 case 'V':
7310 verify_tags = 1;
7311 break;
7312 case 'v':
7313 if (verbosity < 0)
7314 verbosity = 0;
7315 else if (verbosity < 3)
7316 verbosity++;
7317 break;
7318 default:
7319 usage_tag();
7320 /* NOTREACHED */
7324 argc -= optind;
7325 argv += optind;
7327 if (do_list || verify_tags) {
7328 if (commit_id_arg != NULL)
7329 errx(1,
7330 "-c option can only be used when creating a tag");
7331 if (tagmsg)
7332 option_conflict('l', 'm');
7333 if (signer_id)
7334 option_conflict('l', 's');
7335 if (verify_tags)
7336 option_conflict('l', 'V');
7337 if (argc > 1)
7338 usage_tag();
7339 } else if (argc != 1)
7340 usage_tag();
7342 if (verify_tags) {
7343 if (commit_id_arg != NULL)
7344 errx(1,
7345 "-c option can only be used when creating a tag");
7346 if (tagmsg)
7347 option_conflict('V', 'm');
7348 if (signer_id)
7349 option_conflict('V', 's');
7350 if (do_list)
7351 option_conflict('V', 'l');
7354 if (argc == 1)
7355 tag_name = argv[0];
7357 #ifndef PROFILE
7358 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7359 "sendfd unveil", NULL) == -1)
7360 err(1, "pledge");
7361 #endif
7362 cwd = getcwd(NULL, 0);
7363 if (cwd == NULL) {
7364 error = got_error_from_errno("getcwd");
7365 goto done;
7368 error = got_repo_pack_fds_open(&pack_fds);
7369 if (error != NULL)
7370 goto done;
7372 if (repo_path == NULL) {
7373 error = got_worktree_open(&worktree, cwd);
7374 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7375 goto done;
7376 else
7377 error = NULL;
7378 if (worktree) {
7379 repo_path =
7380 strdup(got_worktree_get_repo_path(worktree));
7381 if (repo_path == NULL)
7382 error = got_error_from_errno("strdup");
7383 if (error)
7384 goto done;
7385 } else {
7386 repo_path = strdup(cwd);
7387 if (repo_path == NULL) {
7388 error = got_error_from_errno("strdup");
7389 goto done;
7394 if (do_list || verify_tags) {
7395 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7396 if (error != NULL)
7397 goto done;
7398 error = get_allowed_signers(&allowed_signers, repo, worktree);
7399 if (error)
7400 goto done;
7401 error = get_revoked_signers(&revoked_signers, repo, worktree);
7402 if (error)
7403 goto done;
7404 if (worktree) {
7405 /* Release work tree lock. */
7406 got_worktree_close(worktree);
7407 worktree = NULL;
7411 * Remove "cpath" promise unless needed for signature tmpfile
7412 * creation.
7414 if (verify_tags)
7415 got_sigs_apply_unveil();
7416 else {
7417 #ifndef PROFILE
7418 if (pledge("stdio rpath wpath flock proc exec sendfd "
7419 "unveil", NULL) == -1)
7420 err(1, "pledge");
7421 #endif
7423 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7424 if (error)
7425 goto done;
7426 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7427 revoked_signers, verbosity);
7428 } else {
7429 error = get_gitconfig_path(&gitconfig_path);
7430 if (error)
7431 goto done;
7432 error = got_repo_open(&repo, repo_path, gitconfig_path,
7433 pack_fds);
7434 if (error != NULL)
7435 goto done;
7437 error = get_author(&tagger, repo, worktree);
7438 if (error)
7439 goto done;
7440 if (worktree) {
7441 /* Release work tree lock. */
7442 got_worktree_close(worktree);
7443 worktree = NULL;
7446 if (tagmsg) {
7447 if (signer_id) {
7448 error = got_sigs_apply_unveil();
7449 if (error)
7450 goto done;
7452 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7453 if (error)
7454 goto done;
7457 if (commit_id_arg == NULL) {
7458 struct got_reference *head_ref;
7459 struct got_object_id *commit_id;
7460 error = got_ref_open(&head_ref, repo,
7461 worktree ? got_worktree_get_head_ref_name(worktree)
7462 : GOT_REF_HEAD, 0);
7463 if (error)
7464 goto done;
7465 error = got_ref_resolve(&commit_id, repo, head_ref);
7466 got_ref_close(head_ref);
7467 if (error)
7468 goto done;
7469 error = got_object_id_str(&commit_id_str, commit_id);
7470 free(commit_id);
7471 if (error)
7472 goto done;
7475 error = add_tag(repo, tagger, tag_name,
7476 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7477 signer_id, verbosity);
7479 done:
7480 if (repo) {
7481 const struct got_error *close_err = got_repo_close(repo);
7482 if (error == NULL)
7483 error = close_err;
7485 if (worktree)
7486 got_worktree_close(worktree);
7487 if (pack_fds) {
7488 const struct got_error *pack_err =
7489 got_repo_pack_fds_close(pack_fds);
7490 if (error == NULL)
7491 error = pack_err;
7493 free(cwd);
7494 free(repo_path);
7495 free(gitconfig_path);
7496 free(commit_id_str);
7497 free(tagger);
7498 free(allowed_signers);
7499 free(revoked_signers);
7500 return error;
7503 __dead static void
7504 usage_add(void)
7506 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7507 getprogname());
7508 exit(1);
7511 static const struct got_error *
7512 add_progress(void *arg, unsigned char status, const char *path)
7514 while (path[0] == '/')
7515 path++;
7516 printf("%c %s\n", status, path);
7517 return NULL;
7520 static const struct got_error *
7521 cmd_add(int argc, char *argv[])
7523 const struct got_error *error = NULL;
7524 struct got_repository *repo = NULL;
7525 struct got_worktree *worktree = NULL;
7526 char *cwd = NULL;
7527 struct got_pathlist_head paths;
7528 struct got_pathlist_entry *pe;
7529 int ch, can_recurse = 0, no_ignores = 0;
7530 int *pack_fds = NULL;
7532 TAILQ_INIT(&paths);
7534 while ((ch = getopt(argc, argv, "IR")) != -1) {
7535 switch (ch) {
7536 case 'I':
7537 no_ignores = 1;
7538 break;
7539 case 'R':
7540 can_recurse = 1;
7541 break;
7542 default:
7543 usage_add();
7544 /* NOTREACHED */
7548 argc -= optind;
7549 argv += optind;
7551 #ifndef PROFILE
7552 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7553 NULL) == -1)
7554 err(1, "pledge");
7555 #endif
7556 if (argc < 1)
7557 usage_add();
7559 cwd = getcwd(NULL, 0);
7560 if (cwd == NULL) {
7561 error = got_error_from_errno("getcwd");
7562 goto done;
7565 error = got_repo_pack_fds_open(&pack_fds);
7566 if (error != NULL)
7567 goto done;
7569 error = got_worktree_open(&worktree, cwd);
7570 if (error) {
7571 if (error->code == GOT_ERR_NOT_WORKTREE)
7572 error = wrap_not_worktree_error(error, "add", cwd);
7573 goto done;
7576 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7577 NULL, pack_fds);
7578 if (error != NULL)
7579 goto done;
7581 error = apply_unveil(got_repo_get_path(repo), 1,
7582 got_worktree_get_root_path(worktree));
7583 if (error)
7584 goto done;
7586 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7587 if (error)
7588 goto done;
7590 if (!can_recurse) {
7591 char *ondisk_path;
7592 struct stat sb;
7593 TAILQ_FOREACH(pe, &paths, entry) {
7594 if (asprintf(&ondisk_path, "%s/%s",
7595 got_worktree_get_root_path(worktree),
7596 pe->path) == -1) {
7597 error = got_error_from_errno("asprintf");
7598 goto done;
7600 if (lstat(ondisk_path, &sb) == -1) {
7601 if (errno == ENOENT) {
7602 free(ondisk_path);
7603 continue;
7605 error = got_error_from_errno2("lstat",
7606 ondisk_path);
7607 free(ondisk_path);
7608 goto done;
7610 free(ondisk_path);
7611 if (S_ISDIR(sb.st_mode)) {
7612 error = got_error_msg(GOT_ERR_BAD_PATH,
7613 "adding directories requires -R option");
7614 goto done;
7619 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7620 NULL, repo, no_ignores);
7621 done:
7622 if (repo) {
7623 const struct got_error *close_err = got_repo_close(repo);
7624 if (error == NULL)
7625 error = close_err;
7627 if (worktree)
7628 got_worktree_close(worktree);
7629 if (pack_fds) {
7630 const struct got_error *pack_err =
7631 got_repo_pack_fds_close(pack_fds);
7632 if (error == NULL)
7633 error = pack_err;
7635 TAILQ_FOREACH(pe, &paths, entry)
7636 free((char *)pe->path);
7637 got_pathlist_free(&paths);
7638 free(cwd);
7639 return error;
7642 __dead static void
7643 usage_remove(void)
7645 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7646 "path ...\n", getprogname());
7647 exit(1);
7650 static const struct got_error *
7651 print_remove_status(void *arg, unsigned char status,
7652 unsigned char staged_status, const char *path)
7654 while (path[0] == '/')
7655 path++;
7656 if (status == GOT_STATUS_NONEXISTENT)
7657 return NULL;
7658 if (status == staged_status && (status == GOT_STATUS_DELETE))
7659 status = GOT_STATUS_NO_CHANGE;
7660 printf("%c%c %s\n", status, staged_status, path);
7661 return NULL;
7664 static const struct got_error *
7665 cmd_remove(int argc, char *argv[])
7667 const struct got_error *error = NULL;
7668 struct got_worktree *worktree = NULL;
7669 struct got_repository *repo = NULL;
7670 const char *status_codes = NULL;
7671 char *cwd = NULL;
7672 struct got_pathlist_head paths;
7673 struct got_pathlist_entry *pe;
7674 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7675 int ignore_missing_paths = 0;
7676 int *pack_fds = NULL;
7678 TAILQ_INIT(&paths);
7680 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7681 switch (ch) {
7682 case 'f':
7683 delete_local_mods = 1;
7684 ignore_missing_paths = 1;
7685 break;
7686 case 'k':
7687 keep_on_disk = 1;
7688 break;
7689 case 'R':
7690 can_recurse = 1;
7691 break;
7692 case 's':
7693 for (i = 0; i < strlen(optarg); i++) {
7694 switch (optarg[i]) {
7695 case GOT_STATUS_MODIFY:
7696 delete_local_mods = 1;
7697 break;
7698 case GOT_STATUS_MISSING:
7699 ignore_missing_paths = 1;
7700 break;
7701 default:
7702 errx(1, "invalid status code '%c'",
7703 optarg[i]);
7706 status_codes = optarg;
7707 break;
7708 default:
7709 usage_remove();
7710 /* NOTREACHED */
7714 argc -= optind;
7715 argv += optind;
7717 #ifndef PROFILE
7718 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7719 NULL) == -1)
7720 err(1, "pledge");
7721 #endif
7722 if (argc < 1)
7723 usage_remove();
7725 cwd = getcwd(NULL, 0);
7726 if (cwd == NULL) {
7727 error = got_error_from_errno("getcwd");
7728 goto done;
7731 error = got_repo_pack_fds_open(&pack_fds);
7732 if (error != NULL)
7733 goto done;
7735 error = got_worktree_open(&worktree, cwd);
7736 if (error) {
7737 if (error->code == GOT_ERR_NOT_WORKTREE)
7738 error = wrap_not_worktree_error(error, "remove", cwd);
7739 goto done;
7742 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7743 NULL, pack_fds);
7744 if (error)
7745 goto done;
7747 error = apply_unveil(got_repo_get_path(repo), 1,
7748 got_worktree_get_root_path(worktree));
7749 if (error)
7750 goto done;
7752 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7753 if (error)
7754 goto done;
7756 if (!can_recurse) {
7757 char *ondisk_path;
7758 struct stat sb;
7759 TAILQ_FOREACH(pe, &paths, entry) {
7760 if (asprintf(&ondisk_path, "%s/%s",
7761 got_worktree_get_root_path(worktree),
7762 pe->path) == -1) {
7763 error = got_error_from_errno("asprintf");
7764 goto done;
7766 if (lstat(ondisk_path, &sb) == -1) {
7767 if (errno == ENOENT) {
7768 free(ondisk_path);
7769 continue;
7771 error = got_error_from_errno2("lstat",
7772 ondisk_path);
7773 free(ondisk_path);
7774 goto done;
7776 free(ondisk_path);
7777 if (S_ISDIR(sb.st_mode)) {
7778 error = got_error_msg(GOT_ERR_BAD_PATH,
7779 "removing directories requires -R option");
7780 goto done;
7785 error = got_worktree_schedule_delete(worktree, &paths,
7786 delete_local_mods, status_codes, print_remove_status, NULL,
7787 repo, keep_on_disk, ignore_missing_paths);
7788 done:
7789 if (repo) {
7790 const struct got_error *close_err = got_repo_close(repo);
7791 if (error == NULL)
7792 error = close_err;
7794 if (worktree)
7795 got_worktree_close(worktree);
7796 if (pack_fds) {
7797 const struct got_error *pack_err =
7798 got_repo_pack_fds_close(pack_fds);
7799 if (error == NULL)
7800 error = pack_err;
7802 TAILQ_FOREACH(pe, &paths, entry)
7803 free((char *)pe->path);
7804 got_pathlist_free(&paths);
7805 free(cwd);
7806 return error;
7809 __dead static void
7810 usage_patch(void)
7812 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7813 "[-R] [patchfile]\n", getprogname());
7814 exit(1);
7817 static const struct got_error *
7818 patch_from_stdin(int *patchfd)
7820 const struct got_error *err = NULL;
7821 ssize_t r;
7822 char *path, buf[BUFSIZ];
7823 sig_t sighup, sigint, sigquit;
7825 err = got_opentemp_named_fd(&path, patchfd,
7826 GOT_TMPDIR_STR "/got-patch");
7827 if (err)
7828 return err;
7829 unlink(path);
7830 free(path);
7832 sighup = signal(SIGHUP, SIG_DFL);
7833 sigint = signal(SIGINT, SIG_DFL);
7834 sigquit = signal(SIGQUIT, SIG_DFL);
7836 for (;;) {
7837 r = read(0, buf, sizeof(buf));
7838 if (r == -1) {
7839 err = got_error_from_errno("read");
7840 break;
7842 if (r == 0)
7843 break;
7844 if (write(*patchfd, buf, r) == -1) {
7845 err = got_error_from_errno("write");
7846 break;
7850 signal(SIGHUP, sighup);
7851 signal(SIGINT, sigint);
7852 signal(SIGQUIT, sigquit);
7854 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7855 err = got_error_from_errno("lseek");
7857 if (err != NULL) {
7858 close(*patchfd);
7859 *patchfd = -1;
7862 return err;
7865 static const struct got_error *
7866 patch_progress(void *arg, const char *old, const char *new,
7867 unsigned char status, const struct got_error *error, int old_from,
7868 int old_lines, int new_from, int new_lines, int offset,
7869 int ws_mangled, const struct got_error *hunk_err)
7871 const char *path = new == NULL ? old : new;
7873 while (*path == '/')
7874 path++;
7876 if (status != 0)
7877 printf("%c %s\n", status, path);
7879 if (error != NULL)
7880 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7882 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7883 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7884 old_lines, new_from, new_lines);
7885 if (hunk_err != NULL)
7886 printf("%s\n", hunk_err->msg);
7887 else if (offset != 0)
7888 printf("applied with offset %d\n", offset);
7889 else
7890 printf("hunk contains mangled whitespace\n");
7893 return NULL;
7896 static const struct got_error *
7897 cmd_patch(int argc, char *argv[])
7899 const struct got_error *error = NULL, *close_error = NULL;
7900 struct got_worktree *worktree = NULL;
7901 struct got_repository *repo = NULL;
7902 const char *errstr;
7903 char *cwd = NULL;
7904 int ch, nop = 0, strip = -1, reverse = 0;
7905 int patchfd;
7906 int *pack_fds = NULL;
7908 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7909 switch (ch) {
7910 case 'n':
7911 nop = 1;
7912 break;
7913 case 'p':
7914 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7915 if (errstr != NULL)
7916 errx(1, "pathname strip count is %s: %s",
7917 errstr, optarg);
7918 break;
7919 case 'R':
7920 reverse = 1;
7921 break;
7922 default:
7923 usage_patch();
7924 /* NOTREACHED */
7928 argc -= optind;
7929 argv += optind;
7931 if (argc == 0) {
7932 error = patch_from_stdin(&patchfd);
7933 if (error)
7934 return error;
7935 } else if (argc == 1) {
7936 patchfd = open(argv[0], O_RDONLY);
7937 if (patchfd == -1) {
7938 error = got_error_from_errno2("open", argv[0]);
7939 return error;
7941 } else
7942 usage_patch();
7944 if ((cwd = getcwd(NULL, 0)) == NULL) {
7945 error = got_error_from_errno("getcwd");
7946 goto done;
7949 error = got_repo_pack_fds_open(&pack_fds);
7950 if (error != NULL)
7951 goto done;
7953 error = got_worktree_open(&worktree, cwd);
7954 if (error != NULL)
7955 goto done;
7957 const char *repo_path = got_worktree_get_repo_path(worktree);
7958 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7959 if (error != NULL)
7960 goto done;
7962 error = apply_unveil(got_repo_get_path(repo), 0,
7963 got_worktree_get_root_path(worktree));
7964 if (error != NULL)
7965 goto done;
7967 #ifndef PROFILE
7968 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7969 NULL) == -1)
7970 err(1, "pledge");
7971 #endif
7973 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7974 &patch_progress, NULL, check_cancelled, NULL);
7976 done:
7977 if (repo) {
7978 close_error = got_repo_close(repo);
7979 if (error == NULL)
7980 error = close_error;
7982 if (worktree != NULL) {
7983 close_error = got_worktree_close(worktree);
7984 if (error == NULL)
7985 error = close_error;
7987 if (pack_fds) {
7988 const struct got_error *pack_err =
7989 got_repo_pack_fds_close(pack_fds);
7990 if (error == NULL)
7991 error = pack_err;
7993 free(cwd);
7994 return error;
7997 __dead static void
7998 usage_revert(void)
8000 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
8001 "path ...\n", getprogname());
8002 exit(1);
8005 static const struct got_error *
8006 revert_progress(void *arg, unsigned char status, const char *path)
8008 if (status == GOT_STATUS_UNVERSIONED)
8009 return NULL;
8011 while (path[0] == '/')
8012 path++;
8013 printf("%c %s\n", status, path);
8014 return NULL;
8017 struct choose_patch_arg {
8018 FILE *patch_script_file;
8019 const char *action;
8022 static const struct got_error *
8023 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8024 int nchanges, const char *action)
8026 const struct got_error *err;
8027 char *line = NULL;
8028 size_t linesize = 0;
8029 ssize_t linelen;
8031 switch (status) {
8032 case GOT_STATUS_ADD:
8033 printf("A %s\n%s this addition? [y/n] ", path, action);
8034 break;
8035 case GOT_STATUS_DELETE:
8036 printf("D %s\n%s this deletion? [y/n] ", path, action);
8037 break;
8038 case GOT_STATUS_MODIFY:
8039 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8040 return got_error_from_errno("fseek");
8041 printf(GOT_COMMIT_SEP_STR);
8042 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8043 printf("%s", line);
8044 if (linelen == -1 && ferror(patch_file)) {
8045 err = got_error_from_errno("getline");
8046 free(line);
8047 return err;
8049 free(line);
8050 printf(GOT_COMMIT_SEP_STR);
8051 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8052 path, n, nchanges, action);
8053 break;
8054 default:
8055 return got_error_path(path, GOT_ERR_FILE_STATUS);
8058 return NULL;
8061 static const struct got_error *
8062 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8063 FILE *patch_file, int n, int nchanges)
8065 const struct got_error *err = NULL;
8066 char *line = NULL;
8067 size_t linesize = 0;
8068 ssize_t linelen;
8069 int resp = ' ';
8070 struct choose_patch_arg *a = arg;
8072 *choice = GOT_PATCH_CHOICE_NONE;
8074 if (a->patch_script_file) {
8075 char *nl;
8076 err = show_change(status, path, patch_file, n, nchanges,
8077 a->action);
8078 if (err)
8079 return err;
8080 linelen = getline(&line, &linesize, a->patch_script_file);
8081 if (linelen == -1) {
8082 if (ferror(a->patch_script_file))
8083 return got_error_from_errno("getline");
8084 return NULL;
8086 nl = strchr(line, '\n');
8087 if (nl)
8088 *nl = '\0';
8089 if (strcmp(line, "y") == 0) {
8090 *choice = GOT_PATCH_CHOICE_YES;
8091 printf("y\n");
8092 } else if (strcmp(line, "n") == 0) {
8093 *choice = GOT_PATCH_CHOICE_NO;
8094 printf("n\n");
8095 } else if (strcmp(line, "q") == 0 &&
8096 status == GOT_STATUS_MODIFY) {
8097 *choice = GOT_PATCH_CHOICE_QUIT;
8098 printf("q\n");
8099 } else
8100 printf("invalid response '%s'\n", line);
8101 free(line);
8102 return NULL;
8105 while (resp != 'y' && resp != 'n' && resp != 'q') {
8106 err = show_change(status, path, patch_file, n, nchanges,
8107 a->action);
8108 if (err)
8109 return err;
8110 resp = getchar();
8111 if (resp == '\n')
8112 resp = getchar();
8113 if (status == GOT_STATUS_MODIFY) {
8114 if (resp != 'y' && resp != 'n' && resp != 'q') {
8115 printf("invalid response '%c'\n", resp);
8116 resp = ' ';
8118 } else if (resp != 'y' && resp != 'n') {
8119 printf("invalid response '%c'\n", resp);
8120 resp = ' ';
8124 if (resp == 'y')
8125 *choice = GOT_PATCH_CHOICE_YES;
8126 else if (resp == 'n')
8127 *choice = GOT_PATCH_CHOICE_NO;
8128 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8129 *choice = GOT_PATCH_CHOICE_QUIT;
8131 return NULL;
8134 static const struct got_error *
8135 cmd_revert(int argc, char *argv[])
8137 const struct got_error *error = NULL;
8138 struct got_worktree *worktree = NULL;
8139 struct got_repository *repo = NULL;
8140 char *cwd = NULL, *path = NULL;
8141 struct got_pathlist_head paths;
8142 struct got_pathlist_entry *pe;
8143 int ch, can_recurse = 0, pflag = 0;
8144 FILE *patch_script_file = NULL;
8145 const char *patch_script_path = NULL;
8146 struct choose_patch_arg cpa;
8147 int *pack_fds = NULL;
8149 TAILQ_INIT(&paths);
8151 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8152 switch (ch) {
8153 case 'p':
8154 pflag = 1;
8155 break;
8156 case 'F':
8157 patch_script_path = optarg;
8158 break;
8159 case 'R':
8160 can_recurse = 1;
8161 break;
8162 default:
8163 usage_revert();
8164 /* NOTREACHED */
8168 argc -= optind;
8169 argv += optind;
8171 #ifndef PROFILE
8172 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8173 "unveil", NULL) == -1)
8174 err(1, "pledge");
8175 #endif
8176 if (argc < 1)
8177 usage_revert();
8178 if (patch_script_path && !pflag)
8179 errx(1, "-F option can only be used together with -p option");
8181 cwd = getcwd(NULL, 0);
8182 if (cwd == NULL) {
8183 error = got_error_from_errno("getcwd");
8184 goto done;
8187 error = got_repo_pack_fds_open(&pack_fds);
8188 if (error != NULL)
8189 goto done;
8191 error = got_worktree_open(&worktree, cwd);
8192 if (error) {
8193 if (error->code == GOT_ERR_NOT_WORKTREE)
8194 error = wrap_not_worktree_error(error, "revert", cwd);
8195 goto done;
8198 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8199 NULL, pack_fds);
8200 if (error != NULL)
8201 goto done;
8203 if (patch_script_path) {
8204 patch_script_file = fopen(patch_script_path, "re");
8205 if (patch_script_file == NULL) {
8206 error = got_error_from_errno2("fopen",
8207 patch_script_path);
8208 goto done;
8211 error = apply_unveil(got_repo_get_path(repo), 1,
8212 got_worktree_get_root_path(worktree));
8213 if (error)
8214 goto done;
8216 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8217 if (error)
8218 goto done;
8220 if (!can_recurse) {
8221 char *ondisk_path;
8222 struct stat sb;
8223 TAILQ_FOREACH(pe, &paths, entry) {
8224 if (asprintf(&ondisk_path, "%s/%s",
8225 got_worktree_get_root_path(worktree),
8226 pe->path) == -1) {
8227 error = got_error_from_errno("asprintf");
8228 goto done;
8230 if (lstat(ondisk_path, &sb) == -1) {
8231 if (errno == ENOENT) {
8232 free(ondisk_path);
8233 continue;
8235 error = got_error_from_errno2("lstat",
8236 ondisk_path);
8237 free(ondisk_path);
8238 goto done;
8240 free(ondisk_path);
8241 if (S_ISDIR(sb.st_mode)) {
8242 error = got_error_msg(GOT_ERR_BAD_PATH,
8243 "reverting directories requires -R option");
8244 goto done;
8249 cpa.patch_script_file = patch_script_file;
8250 cpa.action = "revert";
8251 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8252 pflag ? choose_patch : NULL, &cpa, repo);
8253 done:
8254 if (patch_script_file && fclose(patch_script_file) == EOF &&
8255 error == NULL)
8256 error = got_error_from_errno2("fclose", patch_script_path);
8257 if (repo) {
8258 const struct got_error *close_err = got_repo_close(repo);
8259 if (error == NULL)
8260 error = close_err;
8262 if (worktree)
8263 got_worktree_close(worktree);
8264 if (pack_fds) {
8265 const struct got_error *pack_err =
8266 got_repo_pack_fds_close(pack_fds);
8267 if (error == NULL)
8268 error = pack_err;
8270 free(path);
8271 free(cwd);
8272 return error;
8275 __dead static void
8276 usage_commit(void)
8278 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8279 "[path ...]\n", getprogname());
8280 exit(1);
8283 struct collect_commit_logmsg_arg {
8284 const char *cmdline_log;
8285 const char *prepared_log;
8286 int non_interactive;
8287 const char *editor;
8288 const char *worktree_path;
8289 const char *branch_name;
8290 const char *repo_path;
8291 char *logmsg_path;
8295 static const struct got_error *
8296 read_prepared_logmsg(char **logmsg, const char *path)
8298 const struct got_error *err = NULL;
8299 FILE *f = NULL;
8300 struct stat sb;
8301 size_t r;
8303 *logmsg = NULL;
8304 memset(&sb, 0, sizeof(sb));
8306 f = fopen(path, "re");
8307 if (f == NULL)
8308 return got_error_from_errno2("fopen", path);
8310 if (fstat(fileno(f), &sb) == -1) {
8311 err = got_error_from_errno2("fstat", path);
8312 goto done;
8314 if (sb.st_size == 0) {
8315 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8316 goto done;
8319 *logmsg = malloc(sb.st_size + 1);
8320 if (*logmsg == NULL) {
8321 err = got_error_from_errno("malloc");
8322 goto done;
8325 r = fread(*logmsg, 1, sb.st_size, f);
8326 if (r != sb.st_size) {
8327 if (ferror(f))
8328 err = got_error_from_errno2("fread", path);
8329 else
8330 err = got_error(GOT_ERR_IO);
8331 goto done;
8333 (*logmsg)[sb.st_size] = '\0';
8334 done:
8335 if (fclose(f) == EOF && err == NULL)
8336 err = got_error_from_errno2("fclose", path);
8337 if (err) {
8338 free(*logmsg);
8339 *logmsg = NULL;
8341 return err;
8345 static const struct got_error *
8346 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8347 void *arg)
8349 char *initial_content = NULL;
8350 struct got_pathlist_entry *pe;
8351 const struct got_error *err = NULL;
8352 char *template = NULL;
8353 struct collect_commit_logmsg_arg *a = arg;
8354 int initial_content_len;
8355 int fd = -1;
8356 size_t len;
8358 /* if a message was specified on the command line, just use it */
8359 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8360 len = strlen(a->cmdline_log) + 1;
8361 *logmsg = malloc(len + 1);
8362 if (*logmsg == NULL)
8363 return got_error_from_errno("malloc");
8364 strlcpy(*logmsg, a->cmdline_log, len);
8365 return NULL;
8366 } else if (a->prepared_log != NULL && a->non_interactive)
8367 return read_prepared_logmsg(logmsg, a->prepared_log);
8369 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8370 return got_error_from_errno("asprintf");
8372 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8373 if (err)
8374 goto done;
8376 if (a->prepared_log) {
8377 char *msg;
8378 err = read_prepared_logmsg(&msg, a->prepared_log);
8379 if (err)
8380 goto done;
8381 if (write(fd, msg, strlen(msg)) == -1) {
8382 err = got_error_from_errno2("write", a->logmsg_path);
8383 free(msg);
8384 goto done;
8386 free(msg);
8389 initial_content_len = asprintf(&initial_content,
8390 "\n# changes to be committed on branch %s:\n",
8391 a->branch_name);
8392 if (initial_content_len == -1) {
8393 err = got_error_from_errno("asprintf");
8394 goto done;
8397 if (write(fd, initial_content, initial_content_len) == -1) {
8398 err = got_error_from_errno2("write", a->logmsg_path);
8399 goto done;
8402 TAILQ_FOREACH(pe, commitable_paths, entry) {
8403 struct got_commitable *ct = pe->data;
8404 dprintf(fd, "# %c %s\n",
8405 got_commitable_get_status(ct),
8406 got_commitable_get_path(ct));
8409 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8410 initial_content_len, a->prepared_log ? 0 : 1);
8411 done:
8412 free(initial_content);
8413 free(template);
8415 if (fd != -1 && close(fd) == -1 && err == NULL)
8416 err = got_error_from_errno2("close", a->logmsg_path);
8418 /* Editor is done; we can now apply unveil(2) */
8419 if (err == NULL)
8420 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8421 if (err) {
8422 free(*logmsg);
8423 *logmsg = NULL;
8425 return err;
8428 static const struct got_error *
8429 cmd_commit(int argc, char *argv[])
8431 const struct got_error *error = NULL;
8432 struct got_worktree *worktree = NULL;
8433 struct got_repository *repo = NULL;
8434 char *cwd = NULL, *id_str = NULL;
8435 struct got_object_id *id = NULL;
8436 const char *logmsg = NULL;
8437 char *prepared_logmsg = NULL;
8438 struct collect_commit_logmsg_arg cl_arg;
8439 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8440 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8441 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8442 struct got_pathlist_head paths;
8443 int *pack_fds = NULL;
8445 TAILQ_INIT(&paths);
8446 cl_arg.logmsg_path = NULL;
8448 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8449 switch (ch) {
8450 case 'F':
8451 if (logmsg != NULL)
8452 option_conflict('F', 'm');
8453 prepared_logmsg = realpath(optarg, NULL);
8454 if (prepared_logmsg == NULL)
8455 return got_error_from_errno2("realpath",
8456 optarg);
8457 break;
8458 case 'm':
8459 if (prepared_logmsg)
8460 option_conflict('m', 'F');
8461 logmsg = optarg;
8462 break;
8463 case 'N':
8464 non_interactive = 1;
8465 break;
8466 case 'S':
8467 allow_bad_symlinks = 1;
8468 break;
8469 default:
8470 usage_commit();
8471 /* NOTREACHED */
8475 argc -= optind;
8476 argv += optind;
8478 #ifndef PROFILE
8479 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8480 "unveil", NULL) == -1)
8481 err(1, "pledge");
8482 #endif
8483 cwd = getcwd(NULL, 0);
8484 if (cwd == NULL) {
8485 error = got_error_from_errno("getcwd");
8486 goto done;
8489 error = got_repo_pack_fds_open(&pack_fds);
8490 if (error != NULL)
8491 goto done;
8493 error = got_worktree_open(&worktree, cwd);
8494 if (error) {
8495 if (error->code == GOT_ERR_NOT_WORKTREE)
8496 error = wrap_not_worktree_error(error, "commit", cwd);
8497 goto done;
8500 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8501 if (error)
8502 goto done;
8503 if (rebase_in_progress) {
8504 error = got_error(GOT_ERR_REBASING);
8505 goto done;
8508 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8509 worktree);
8510 if (error)
8511 goto done;
8513 error = get_gitconfig_path(&gitconfig_path);
8514 if (error)
8515 goto done;
8516 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8517 gitconfig_path, pack_fds);
8518 if (error != NULL)
8519 goto done;
8521 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8522 if (error)
8523 goto done;
8524 if (merge_in_progress) {
8525 error = got_error(GOT_ERR_MERGE_BUSY);
8526 goto done;
8529 error = get_author(&author, repo, worktree);
8530 if (error)
8531 return error;
8534 * unveil(2) traverses exec(2); if an editor is used we have
8535 * to apply unveil after the log message has been written.
8537 if (logmsg == NULL || strlen(logmsg) == 0)
8538 error = get_editor(&editor);
8539 else
8540 error = apply_unveil(got_repo_get_path(repo), 0,
8541 got_worktree_get_root_path(worktree));
8542 if (error)
8543 goto done;
8545 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8546 if (error)
8547 goto done;
8549 cl_arg.editor = editor;
8550 cl_arg.cmdline_log = logmsg;
8551 cl_arg.prepared_log = prepared_logmsg;
8552 cl_arg.non_interactive = non_interactive;
8553 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8554 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8555 if (!histedit_in_progress) {
8556 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8557 error = got_error(GOT_ERR_COMMIT_BRANCH);
8558 goto done;
8560 cl_arg.branch_name += 11;
8562 cl_arg.repo_path = got_repo_get_path(repo);
8563 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8564 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8565 print_status, NULL, repo);
8566 if (error) {
8567 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8568 cl_arg.logmsg_path != NULL)
8569 preserve_logmsg = 1;
8570 goto done;
8573 error = got_object_id_str(&id_str, id);
8574 if (error)
8575 goto done;
8576 printf("Created commit %s\n", id_str);
8577 done:
8578 if (preserve_logmsg) {
8579 fprintf(stderr, "%s: log message preserved in %s\n",
8580 getprogname(), cl_arg.logmsg_path);
8581 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8582 error == NULL)
8583 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8584 free(cl_arg.logmsg_path);
8585 if (repo) {
8586 const struct got_error *close_err = got_repo_close(repo);
8587 if (error == NULL)
8588 error = close_err;
8590 if (worktree)
8591 got_worktree_close(worktree);
8592 if (pack_fds) {
8593 const struct got_error *pack_err =
8594 got_repo_pack_fds_close(pack_fds);
8595 if (error == NULL)
8596 error = pack_err;
8598 free(cwd);
8599 free(id_str);
8600 free(gitconfig_path);
8601 free(editor);
8602 free(author);
8603 free(prepared_logmsg);
8604 return error;
8607 __dead static void
8608 usage_send(void)
8610 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8611 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8612 "[remote-repository]\n", getprogname());
8613 exit(1);
8616 static void
8617 print_load_info(int print_colored, int print_found, int print_trees,
8618 int ncolored, int nfound, int ntrees)
8620 if (print_colored) {
8621 printf("%d commit%s colored", ncolored,
8622 ncolored == 1 ? "" : "s");
8624 if (print_found) {
8625 printf("%s%d object%s found",
8626 ncolored > 0 ? "; " : "",
8627 nfound, nfound == 1 ? "" : "s");
8629 if (print_trees) {
8630 printf("; %d tree%s scanned", ntrees,
8631 ntrees == 1 ? "" : "s");
8635 struct got_send_progress_arg {
8636 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8637 int verbosity;
8638 int last_ncolored;
8639 int last_nfound;
8640 int last_ntrees;
8641 int loading_done;
8642 int last_ncommits;
8643 int last_nobj_total;
8644 int last_p_deltify;
8645 int last_p_written;
8646 int last_p_sent;
8647 int printed_something;
8648 int sent_something;
8649 struct got_pathlist_head *delete_branches;
8652 static const struct got_error *
8653 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8654 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8655 int nobj_written, off_t bytes_sent, const char *refname, int success)
8657 struct got_send_progress_arg *a = arg;
8658 char scaled_packsize[FMT_SCALED_STRSIZE];
8659 char scaled_sent[FMT_SCALED_STRSIZE];
8660 int p_deltify = 0, p_written = 0, p_sent = 0;
8661 int print_colored = 0, print_found = 0, print_trees = 0;
8662 int print_searching = 0, print_total = 0;
8663 int print_deltify = 0, print_written = 0, print_sent = 0;
8665 if (a->verbosity < 0)
8666 return NULL;
8668 if (refname) {
8669 const char *status = success ? "accepted" : "rejected";
8671 if (success) {
8672 struct got_pathlist_entry *pe;
8673 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8674 const char *branchname = pe->path;
8675 if (got_path_cmp(branchname, refname,
8676 strlen(branchname), strlen(refname)) == 0) {
8677 status = "deleted";
8678 a->sent_something = 1;
8679 break;
8684 if (a->printed_something)
8685 putchar('\n');
8686 printf("Server has %s %s", status, refname);
8687 a->printed_something = 1;
8688 return NULL;
8691 if (a->last_ncolored != ncolored) {
8692 print_colored = 1;
8693 a->last_ncolored = ncolored;
8696 if (a->last_nfound != nfound) {
8697 print_colored = 1;
8698 print_found = 1;
8699 a->last_nfound = nfound;
8702 if (a->last_ntrees != ntrees) {
8703 print_colored = 1;
8704 print_found = 1;
8705 print_trees = 1;
8706 a->last_ntrees = ntrees;
8709 if ((print_colored || print_found || print_trees) &&
8710 !a->loading_done) {
8711 printf("\r");
8712 print_load_info(print_colored, print_found, print_trees,
8713 ncolored, nfound, ntrees);
8714 a->printed_something = 1;
8715 fflush(stdout);
8716 return NULL;
8717 } else if (!a->loading_done) {
8718 printf("\r");
8719 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8720 printf("\n");
8721 a->loading_done = 1;
8724 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8725 return got_error_from_errno("fmt_scaled");
8726 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8727 return got_error_from_errno("fmt_scaled");
8729 if (a->last_ncommits != ncommits) {
8730 print_searching = 1;
8731 a->last_ncommits = ncommits;
8734 if (a->last_nobj_total != nobj_total) {
8735 print_searching = 1;
8736 print_total = 1;
8737 a->last_nobj_total = nobj_total;
8740 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8741 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8742 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8743 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8744 return got_error(GOT_ERR_NO_SPACE);
8747 if (nobj_deltify > 0 || nobj_written > 0) {
8748 if (nobj_deltify > 0) {
8749 p_deltify = (nobj_deltify * 100) / nobj_total;
8750 if (p_deltify != a->last_p_deltify) {
8751 a->last_p_deltify = p_deltify;
8752 print_searching = 1;
8753 print_total = 1;
8754 print_deltify = 1;
8757 if (nobj_written > 0) {
8758 p_written = (nobj_written * 100) / nobj_total;
8759 if (p_written != a->last_p_written) {
8760 a->last_p_written = p_written;
8761 print_searching = 1;
8762 print_total = 1;
8763 print_deltify = 1;
8764 print_written = 1;
8769 if (bytes_sent > 0) {
8770 p_sent = (bytes_sent * 100) / packfile_size;
8771 if (p_sent != a->last_p_sent) {
8772 a->last_p_sent = p_sent;
8773 print_searching = 1;
8774 print_total = 1;
8775 print_deltify = 1;
8776 print_written = 1;
8777 print_sent = 1;
8779 a->sent_something = 1;
8782 if (print_searching || print_total || print_deltify || print_written ||
8783 print_sent)
8784 printf("\r");
8785 if (print_searching)
8786 printf("packing %d reference%s", ncommits,
8787 ncommits == 1 ? "" : "s");
8788 if (print_total)
8789 printf("; %d object%s", nobj_total,
8790 nobj_total == 1 ? "" : "s");
8791 if (print_deltify)
8792 printf("; deltify: %d%%", p_deltify);
8793 if (print_sent)
8794 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8795 scaled_packsize, p_sent);
8796 else if (print_written)
8797 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8798 scaled_packsize, p_written);
8799 if (print_searching || print_total || print_deltify ||
8800 print_written || print_sent) {
8801 a->printed_something = 1;
8802 fflush(stdout);
8804 return NULL;
8807 static const struct got_error *
8808 cmd_send(int argc, char *argv[])
8810 const struct got_error *error = NULL;
8811 char *cwd = NULL, *repo_path = NULL;
8812 const char *remote_name;
8813 char *proto = NULL, *host = NULL, *port = NULL;
8814 char *repo_name = NULL, *server_path = NULL;
8815 const struct got_remote_repo *remotes, *remote = NULL;
8816 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8817 struct got_repository *repo = NULL;
8818 struct got_worktree *worktree = NULL;
8819 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8820 struct got_pathlist_head branches;
8821 struct got_pathlist_head tags;
8822 struct got_reflist_head all_branches;
8823 struct got_reflist_head all_tags;
8824 struct got_pathlist_head delete_args;
8825 struct got_pathlist_head delete_branches;
8826 struct got_reflist_entry *re;
8827 struct got_pathlist_entry *pe;
8828 int i, ch, sendfd = -1, sendstatus;
8829 pid_t sendpid = -1;
8830 struct got_send_progress_arg spa;
8831 int verbosity = 0, overwrite_refs = 0;
8832 int send_all_branches = 0, send_all_tags = 0;
8833 struct got_reference *ref = NULL;
8834 int *pack_fds = NULL;
8836 TAILQ_INIT(&branches);
8837 TAILQ_INIT(&tags);
8838 TAILQ_INIT(&all_branches);
8839 TAILQ_INIT(&all_tags);
8840 TAILQ_INIT(&delete_args);
8841 TAILQ_INIT(&delete_branches);
8843 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8844 switch (ch) {
8845 case 'a':
8846 send_all_branches = 1;
8847 break;
8848 case 'b':
8849 error = got_pathlist_append(&branches, optarg, NULL);
8850 if (error)
8851 return error;
8852 nbranches++;
8853 break;
8854 case 'd':
8855 error = got_pathlist_append(&delete_args, optarg, NULL);
8856 if (error)
8857 return error;
8858 break;
8859 case 'f':
8860 overwrite_refs = 1;
8861 break;
8862 case 'r':
8863 repo_path = realpath(optarg, NULL);
8864 if (repo_path == NULL)
8865 return got_error_from_errno2("realpath",
8866 optarg);
8867 got_path_strip_trailing_slashes(repo_path);
8868 break;
8869 case 't':
8870 error = got_pathlist_append(&tags, optarg, NULL);
8871 if (error)
8872 return error;
8873 ntags++;
8874 break;
8875 case 'T':
8876 send_all_tags = 1;
8877 break;
8878 case 'v':
8879 if (verbosity < 0)
8880 verbosity = 0;
8881 else if (verbosity < 3)
8882 verbosity++;
8883 break;
8884 case 'q':
8885 verbosity = -1;
8886 break;
8887 default:
8888 usage_send();
8889 /* NOTREACHED */
8892 argc -= optind;
8893 argv += optind;
8895 if (send_all_branches && !TAILQ_EMPTY(&branches))
8896 option_conflict('a', 'b');
8897 if (send_all_tags && !TAILQ_EMPTY(&tags))
8898 option_conflict('T', 't');
8901 if (argc == 0)
8902 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8903 else if (argc == 1)
8904 remote_name = argv[0];
8905 else
8906 usage_send();
8908 cwd = getcwd(NULL, 0);
8909 if (cwd == NULL) {
8910 error = got_error_from_errno("getcwd");
8911 goto done;
8914 error = got_repo_pack_fds_open(&pack_fds);
8915 if (error != NULL)
8916 goto done;
8918 if (repo_path == NULL) {
8919 error = got_worktree_open(&worktree, cwd);
8920 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8921 goto done;
8922 else
8923 error = NULL;
8924 if (worktree) {
8925 repo_path =
8926 strdup(got_worktree_get_repo_path(worktree));
8927 if (repo_path == NULL)
8928 error = got_error_from_errno("strdup");
8929 if (error)
8930 goto done;
8931 } else {
8932 repo_path = strdup(cwd);
8933 if (repo_path == NULL) {
8934 error = got_error_from_errno("strdup");
8935 goto done;
8940 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8941 if (error)
8942 goto done;
8944 if (worktree) {
8945 worktree_conf = got_worktree_get_gotconfig(worktree);
8946 if (worktree_conf) {
8947 got_gotconfig_get_remotes(&nremotes, &remotes,
8948 worktree_conf);
8949 for (i = 0; i < nremotes; i++) {
8950 if (strcmp(remotes[i].name, remote_name) == 0) {
8951 remote = &remotes[i];
8952 break;
8957 if (remote == NULL) {
8958 repo_conf = got_repo_get_gotconfig(repo);
8959 if (repo_conf) {
8960 got_gotconfig_get_remotes(&nremotes, &remotes,
8961 repo_conf);
8962 for (i = 0; i < nremotes; i++) {
8963 if (strcmp(remotes[i].name, remote_name) == 0) {
8964 remote = &remotes[i];
8965 break;
8970 if (remote == NULL) {
8971 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8972 for (i = 0; i < nremotes; i++) {
8973 if (strcmp(remotes[i].name, remote_name) == 0) {
8974 remote = &remotes[i];
8975 break;
8979 if (remote == NULL) {
8980 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8981 goto done;
8984 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8985 &repo_name, remote->send_url);
8986 if (error)
8987 goto done;
8989 if (strcmp(proto, "git") == 0) {
8990 #ifndef PROFILE
8991 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8992 "sendfd dns inet unveil", NULL) == -1)
8993 err(1, "pledge");
8994 #endif
8995 } else if (strcmp(proto, "git+ssh") == 0 ||
8996 strcmp(proto, "ssh") == 0) {
8997 #ifndef PROFILE
8998 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8999 "sendfd unveil", NULL) == -1)
9000 err(1, "pledge");
9001 #endif
9002 } else if (strcmp(proto, "http") == 0 ||
9003 strcmp(proto, "git+http") == 0) {
9004 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9005 goto done;
9006 } else {
9007 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9008 goto done;
9011 error = got_dial_apply_unveil(proto);
9012 if (error)
9013 goto done;
9015 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9016 if (error)
9017 goto done;
9019 if (send_all_branches) {
9020 error = got_ref_list(&all_branches, repo, "refs/heads",
9021 got_ref_cmp_by_name, NULL);
9022 if (error)
9023 goto done;
9024 TAILQ_FOREACH(re, &all_branches, entry) {
9025 const char *branchname = got_ref_get_name(re->ref);
9026 error = got_pathlist_append(&branches,
9027 branchname, NULL);
9028 if (error)
9029 goto done;
9030 nbranches++;
9032 } else if (nbranches == 0) {
9033 for (i = 0; i < remote->nsend_branches; i++) {
9034 got_pathlist_append(&branches,
9035 remote->send_branches[i], NULL);
9039 if (send_all_tags) {
9040 error = got_ref_list(&all_tags, repo, "refs/tags",
9041 got_ref_cmp_by_name, NULL);
9042 if (error)
9043 goto done;
9044 TAILQ_FOREACH(re, &all_tags, entry) {
9045 const char *tagname = got_ref_get_name(re->ref);
9046 error = got_pathlist_append(&tags,
9047 tagname, NULL);
9048 if (error)
9049 goto done;
9050 ntags++;
9055 * To prevent accidents only branches in refs/heads/ can be deleted
9056 * with 'got send -d'.
9057 * Deleting anything else requires local repository access or Git.
9059 TAILQ_FOREACH(pe, &delete_args, entry) {
9060 const char *branchname = pe->path;
9061 char *s;
9062 struct got_pathlist_entry *new;
9063 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9064 s = strdup(branchname);
9065 if (s == NULL) {
9066 error = got_error_from_errno("strdup");
9067 goto done;
9069 } else {
9070 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9071 error = got_error_from_errno("asprintf");
9072 goto done;
9075 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9076 if (error || new == NULL /* duplicate */)
9077 free(s);
9078 if (error)
9079 goto done;
9080 ndelete_branches++;
9083 if (nbranches == 0 && ndelete_branches == 0) {
9084 struct got_reference *head_ref;
9085 if (worktree)
9086 error = got_ref_open(&head_ref, repo,
9087 got_worktree_get_head_ref_name(worktree), 0);
9088 else
9089 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9090 if (error)
9091 goto done;
9092 if (got_ref_is_symbolic(head_ref)) {
9093 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9094 got_ref_close(head_ref);
9095 if (error)
9096 goto done;
9097 } else
9098 ref = head_ref;
9099 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9100 NULL);
9101 if (error)
9102 goto done;
9103 nbranches++;
9106 if (verbosity >= 0)
9107 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9108 port ? ":" : "", port ? port : "");
9110 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9111 server_path, verbosity);
9112 if (error)
9113 goto done;
9115 memset(&spa, 0, sizeof(spa));
9116 spa.last_scaled_packsize[0] = '\0';
9117 spa.last_p_deltify = -1;
9118 spa.last_p_written = -1;
9119 spa.verbosity = verbosity;
9120 spa.delete_branches = &delete_branches;
9121 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9122 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9123 check_cancelled, NULL);
9124 if (spa.printed_something)
9125 putchar('\n');
9126 if (error)
9127 goto done;
9128 if (!spa.sent_something && verbosity >= 0)
9129 printf("Already up-to-date\n");
9130 done:
9131 if (sendpid > 0) {
9132 if (kill(sendpid, SIGTERM) == -1)
9133 error = got_error_from_errno("kill");
9134 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9135 error = got_error_from_errno("waitpid");
9137 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9138 error = got_error_from_errno("close");
9139 if (repo) {
9140 const struct got_error *close_err = got_repo_close(repo);
9141 if (error == NULL)
9142 error = close_err;
9144 if (worktree)
9145 got_worktree_close(worktree);
9146 if (pack_fds) {
9147 const struct got_error *pack_err =
9148 got_repo_pack_fds_close(pack_fds);
9149 if (error == NULL)
9150 error = pack_err;
9152 if (ref)
9153 got_ref_close(ref);
9154 got_pathlist_free(&branches);
9155 got_pathlist_free(&tags);
9156 got_ref_list_free(&all_branches);
9157 got_ref_list_free(&all_tags);
9158 got_pathlist_free(&delete_args);
9159 TAILQ_FOREACH(pe, &delete_branches, entry)
9160 free((char *)pe->path);
9161 got_pathlist_free(&delete_branches);
9162 free(cwd);
9163 free(repo_path);
9164 free(proto);
9165 free(host);
9166 free(port);
9167 free(server_path);
9168 free(repo_name);
9169 return error;
9172 __dead static void
9173 usage_cherrypick(void)
9175 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9176 exit(1);
9179 static const struct got_error *
9180 cmd_cherrypick(int argc, char *argv[])
9182 const struct got_error *error = NULL;
9183 struct got_worktree *worktree = NULL;
9184 struct got_repository *repo = NULL;
9185 char *cwd = NULL, *commit_id_str = NULL;
9186 struct got_object_id *commit_id = NULL;
9187 struct got_commit_object *commit = NULL;
9188 struct got_object_qid *pid;
9189 int ch;
9190 struct got_update_progress_arg upa;
9191 int *pack_fds = NULL;
9193 while ((ch = getopt(argc, argv, "")) != -1) {
9194 switch (ch) {
9195 default:
9196 usage_cherrypick();
9197 /* NOTREACHED */
9201 argc -= optind;
9202 argv += optind;
9204 #ifndef PROFILE
9205 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9206 "unveil", NULL) == -1)
9207 err(1, "pledge");
9208 #endif
9209 if (argc != 1)
9210 usage_cherrypick();
9212 cwd = getcwd(NULL, 0);
9213 if (cwd == NULL) {
9214 error = got_error_from_errno("getcwd");
9215 goto done;
9218 error = got_repo_pack_fds_open(&pack_fds);
9219 if (error != NULL)
9220 goto done;
9222 error = got_worktree_open(&worktree, cwd);
9223 if (error) {
9224 if (error->code == GOT_ERR_NOT_WORKTREE)
9225 error = wrap_not_worktree_error(error, "cherrypick",
9226 cwd);
9227 goto done;
9230 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9231 NULL, pack_fds);
9232 if (error != NULL)
9233 goto done;
9235 error = apply_unveil(got_repo_get_path(repo), 0,
9236 got_worktree_get_root_path(worktree));
9237 if (error)
9238 goto done;
9240 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9241 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9242 if (error)
9243 goto done;
9244 error = got_object_id_str(&commit_id_str, commit_id);
9245 if (error)
9246 goto done;
9248 error = got_object_open_as_commit(&commit, repo, commit_id);
9249 if (error)
9250 goto done;
9251 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9252 memset(&upa, 0, sizeof(upa));
9253 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9254 commit_id, repo, update_progress, &upa, check_cancelled,
9255 NULL);
9256 if (error != NULL)
9257 goto done;
9259 if (upa.did_something)
9260 printf("Merged commit %s\n", commit_id_str);
9261 print_merge_progress_stats(&upa);
9262 done:
9263 if (commit)
9264 got_object_commit_close(commit);
9265 free(commit_id_str);
9266 if (worktree)
9267 got_worktree_close(worktree);
9268 if (repo) {
9269 const struct got_error *close_err = got_repo_close(repo);
9270 if (error == NULL)
9271 error = close_err;
9273 if (pack_fds) {
9274 const struct got_error *pack_err =
9275 got_repo_pack_fds_close(pack_fds);
9276 if (error == NULL)
9277 error = pack_err;
9280 return error;
9283 __dead static void
9284 usage_backout(void)
9286 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9287 exit(1);
9290 static const struct got_error *
9291 cmd_backout(int argc, char *argv[])
9293 const struct got_error *error = NULL;
9294 struct got_worktree *worktree = NULL;
9295 struct got_repository *repo = NULL;
9296 char *cwd = NULL, *commit_id_str = NULL;
9297 struct got_object_id *commit_id = NULL;
9298 struct got_commit_object *commit = NULL;
9299 struct got_object_qid *pid;
9300 int ch;
9301 struct got_update_progress_arg upa;
9302 int *pack_fds = NULL;
9304 while ((ch = getopt(argc, argv, "")) != -1) {
9305 switch (ch) {
9306 default:
9307 usage_backout();
9308 /* NOTREACHED */
9312 argc -= optind;
9313 argv += optind;
9315 #ifndef PROFILE
9316 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9317 "unveil", NULL) == -1)
9318 err(1, "pledge");
9319 #endif
9320 if (argc != 1)
9321 usage_backout();
9323 cwd = getcwd(NULL, 0);
9324 if (cwd == NULL) {
9325 error = got_error_from_errno("getcwd");
9326 goto done;
9329 error = got_repo_pack_fds_open(&pack_fds);
9330 if (error != NULL)
9331 goto done;
9333 error = got_worktree_open(&worktree, cwd);
9334 if (error) {
9335 if (error->code == GOT_ERR_NOT_WORKTREE)
9336 error = wrap_not_worktree_error(error, "backout", cwd);
9337 goto done;
9340 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9341 NULL, pack_fds);
9342 if (error != NULL)
9343 goto done;
9345 error = apply_unveil(got_repo_get_path(repo), 0,
9346 got_worktree_get_root_path(worktree));
9347 if (error)
9348 goto done;
9350 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9351 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9352 if (error)
9353 goto done;
9354 error = got_object_id_str(&commit_id_str, commit_id);
9355 if (error)
9356 goto done;
9358 error = got_object_open_as_commit(&commit, repo, commit_id);
9359 if (error)
9360 goto done;
9361 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9362 if (pid == NULL) {
9363 error = got_error(GOT_ERR_ROOT_COMMIT);
9364 goto done;
9367 memset(&upa, 0, sizeof(upa));
9368 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9369 repo, update_progress, &upa, check_cancelled, NULL);
9370 if (error != NULL)
9371 goto done;
9373 if (upa.did_something)
9374 printf("Backed out commit %s\n", commit_id_str);
9375 print_merge_progress_stats(&upa);
9376 done:
9377 if (commit)
9378 got_object_commit_close(commit);
9379 free(commit_id_str);
9380 if (worktree)
9381 got_worktree_close(worktree);
9382 if (repo) {
9383 const struct got_error *close_err = got_repo_close(repo);
9384 if (error == NULL)
9385 error = close_err;
9387 if (pack_fds) {
9388 const struct got_error *pack_err =
9389 got_repo_pack_fds_close(pack_fds);
9390 if (error == NULL)
9391 error = pack_err;
9393 return error;
9396 __dead static void
9397 usage_rebase(void)
9399 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9400 getprogname());
9401 exit(1);
9404 static void
9405 trim_logmsg(char *logmsg, int limit)
9407 char *nl;
9408 size_t len;
9410 len = strlen(logmsg);
9411 if (len > limit)
9412 len = limit;
9413 logmsg[len] = '\0';
9414 nl = strchr(logmsg, '\n');
9415 if (nl)
9416 *nl = '\0';
9419 static const struct got_error *
9420 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9422 const struct got_error *err;
9423 char *logmsg0 = NULL;
9424 const char *s;
9426 err = got_object_commit_get_logmsg(&logmsg0, commit);
9427 if (err)
9428 return err;
9430 s = logmsg0;
9431 while (isspace((unsigned char)s[0]))
9432 s++;
9434 *logmsg = strdup(s);
9435 if (*logmsg == NULL) {
9436 err = got_error_from_errno("strdup");
9437 goto done;
9440 trim_logmsg(*logmsg, limit);
9441 done:
9442 free(logmsg0);
9443 return err;
9446 static const struct got_error *
9447 show_rebase_merge_conflict(struct got_object_id *id,
9448 struct got_repository *repo)
9450 const struct got_error *err;
9451 struct got_commit_object *commit = NULL;
9452 char *id_str = NULL, *logmsg = NULL;
9454 err = got_object_open_as_commit(&commit, repo, id);
9455 if (err)
9456 return err;
9458 err = got_object_id_str(&id_str, id);
9459 if (err)
9460 goto done;
9462 id_str[12] = '\0';
9464 err = get_short_logmsg(&logmsg, 42, commit);
9465 if (err)
9466 goto done;
9468 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9469 done:
9470 free(id_str);
9471 got_object_commit_close(commit);
9472 free(logmsg);
9473 return err;
9476 static const struct got_error *
9477 show_rebase_progress(struct got_commit_object *commit,
9478 struct got_object_id *old_id, struct got_object_id *new_id)
9480 const struct got_error *err;
9481 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9483 err = got_object_id_str(&old_id_str, old_id);
9484 if (err)
9485 goto done;
9487 if (new_id) {
9488 err = got_object_id_str(&new_id_str, new_id);
9489 if (err)
9490 goto done;
9493 old_id_str[12] = '\0';
9494 if (new_id_str)
9495 new_id_str[12] = '\0';
9497 err = get_short_logmsg(&logmsg, 42, commit);
9498 if (err)
9499 goto done;
9501 printf("%s -> %s: %s\n", old_id_str,
9502 new_id_str ? new_id_str : "no-op change", logmsg);
9503 done:
9504 free(old_id_str);
9505 free(new_id_str);
9506 free(logmsg);
9507 return err;
9510 static const struct got_error *
9511 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9512 struct got_reference *branch, struct got_reference *new_base_branch,
9513 struct got_reference *tmp_branch, struct got_repository *repo,
9514 int create_backup)
9516 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9517 return got_worktree_rebase_complete(worktree, fileindex,
9518 new_base_branch, tmp_branch, branch, repo, create_backup);
9521 static const struct got_error *
9522 rebase_commit(struct got_pathlist_head *merged_paths,
9523 struct got_worktree *worktree, struct got_fileindex *fileindex,
9524 struct got_reference *tmp_branch,
9525 struct got_object_id *commit_id, struct got_repository *repo)
9527 const struct got_error *error;
9528 struct got_commit_object *commit;
9529 struct got_object_id *new_commit_id;
9531 error = got_object_open_as_commit(&commit, repo, commit_id);
9532 if (error)
9533 return error;
9535 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9536 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9537 if (error) {
9538 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9539 goto done;
9540 error = show_rebase_progress(commit, commit_id, NULL);
9541 } else {
9542 error = show_rebase_progress(commit, commit_id, new_commit_id);
9543 free(new_commit_id);
9545 done:
9546 got_object_commit_close(commit);
9547 return error;
9550 struct check_path_prefix_arg {
9551 const char *path_prefix;
9552 size_t len;
9553 int errcode;
9556 static const struct got_error *
9557 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9558 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9559 struct got_object_id *id1, struct got_object_id *id2,
9560 const char *path1, const char *path2,
9561 mode_t mode1, mode_t mode2, struct got_repository *repo)
9563 struct check_path_prefix_arg *a = arg;
9565 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9566 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9567 return got_error(a->errcode);
9569 return NULL;
9572 static const struct got_error *
9573 check_path_prefix(struct got_object_id *parent_id,
9574 struct got_object_id *commit_id, const char *path_prefix,
9575 int errcode, struct got_repository *repo)
9577 const struct got_error *err;
9578 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9579 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9580 struct check_path_prefix_arg cpp_arg;
9582 if (got_path_is_root_dir(path_prefix))
9583 return NULL;
9585 err = got_object_open_as_commit(&commit, repo, commit_id);
9586 if (err)
9587 goto done;
9589 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9590 if (err)
9591 goto done;
9593 err = got_object_open_as_tree(&tree1, repo,
9594 got_object_commit_get_tree_id(parent_commit));
9595 if (err)
9596 goto done;
9598 err = got_object_open_as_tree(&tree2, repo,
9599 got_object_commit_get_tree_id(commit));
9600 if (err)
9601 goto done;
9603 cpp_arg.path_prefix = path_prefix;
9604 while (cpp_arg.path_prefix[0] == '/')
9605 cpp_arg.path_prefix++;
9606 cpp_arg.len = strlen(cpp_arg.path_prefix);
9607 cpp_arg.errcode = errcode;
9608 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9609 check_path_prefix_in_diff, &cpp_arg, 0);
9610 done:
9611 if (tree1)
9612 got_object_tree_close(tree1);
9613 if (tree2)
9614 got_object_tree_close(tree2);
9615 if (commit)
9616 got_object_commit_close(commit);
9617 if (parent_commit)
9618 got_object_commit_close(parent_commit);
9619 return err;
9622 static const struct got_error *
9623 collect_commits(struct got_object_id_queue *commits,
9624 struct got_object_id *initial_commit_id,
9625 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9626 const char *path_prefix, int path_prefix_errcode,
9627 struct got_repository *repo)
9629 const struct got_error *err = NULL;
9630 struct got_commit_graph *graph = NULL;
9631 struct got_object_id *parent_id = NULL;
9632 struct got_object_qid *qid;
9633 struct got_object_id *commit_id = initial_commit_id;
9635 err = got_commit_graph_open(&graph, "/", 1);
9636 if (err)
9637 return err;
9639 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9640 check_cancelled, NULL);
9641 if (err)
9642 goto done;
9643 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9644 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9645 check_cancelled, NULL);
9646 if (err) {
9647 if (err->code == GOT_ERR_ITER_COMPLETED) {
9648 err = got_error_msg(GOT_ERR_ANCESTRY,
9649 "ran out of commits to rebase before "
9650 "youngest common ancestor commit has "
9651 "been reached?!?");
9653 goto done;
9654 } else {
9655 err = check_path_prefix(parent_id, commit_id,
9656 path_prefix, path_prefix_errcode, repo);
9657 if (err)
9658 goto done;
9660 err = got_object_qid_alloc(&qid, commit_id);
9661 if (err)
9662 goto done;
9663 STAILQ_INSERT_HEAD(commits, qid, entry);
9664 commit_id = parent_id;
9667 done:
9668 got_commit_graph_close(graph);
9669 return err;
9672 static const struct got_error *
9673 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9675 const struct got_error *err = NULL;
9676 time_t committer_time;
9677 struct tm tm;
9678 char datebuf[11]; /* YYYY-MM-DD + NUL */
9679 char *author0 = NULL, *author, *smallerthan;
9680 char *logmsg0 = NULL, *logmsg, *newline;
9682 committer_time = got_object_commit_get_committer_time(commit);
9683 if (gmtime_r(&committer_time, &tm) == NULL)
9684 return got_error_from_errno("gmtime_r");
9685 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9686 return got_error(GOT_ERR_NO_SPACE);
9688 author0 = strdup(got_object_commit_get_author(commit));
9689 if (author0 == NULL)
9690 return got_error_from_errno("strdup");
9691 author = author0;
9692 smallerthan = strchr(author, '<');
9693 if (smallerthan && smallerthan[1] != '\0')
9694 author = smallerthan + 1;
9695 author[strcspn(author, "@>")] = '\0';
9697 err = got_object_commit_get_logmsg(&logmsg0, commit);
9698 if (err)
9699 goto done;
9700 logmsg = logmsg0;
9701 while (*logmsg == '\n')
9702 logmsg++;
9703 newline = strchr(logmsg, '\n');
9704 if (newline)
9705 *newline = '\0';
9707 if (asprintf(brief_str, "%s %s %s",
9708 datebuf, author, logmsg) == -1)
9709 err = got_error_from_errno("asprintf");
9710 done:
9711 free(author0);
9712 free(logmsg0);
9713 return err;
9716 static const struct got_error *
9717 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9718 struct got_repository *repo)
9720 const struct got_error *err;
9721 char *id_str;
9723 err = got_object_id_str(&id_str, id);
9724 if (err)
9725 return err;
9727 err = got_ref_delete(ref, repo);
9728 if (err)
9729 goto done;
9731 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9732 done:
9733 free(id_str);
9734 return err;
9737 static const struct got_error *
9738 print_backup_ref(const char *branch_name, const char *new_id_str,
9739 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9740 struct got_reflist_object_id_map *refs_idmap,
9741 struct got_repository *repo)
9743 const struct got_error *err = NULL;
9744 struct got_reflist_head *refs;
9745 char *refs_str = NULL;
9746 struct got_object_id *new_commit_id = NULL;
9747 struct got_commit_object *new_commit = NULL;
9748 char *new_commit_brief_str = NULL;
9749 struct got_object_id *yca_id = NULL;
9750 struct got_commit_object *yca_commit = NULL;
9751 char *yca_id_str = NULL, *yca_brief_str = NULL;
9752 char *custom_refs_str;
9754 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9755 return got_error_from_errno("asprintf");
9757 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9758 0, 0, refs_idmap, custom_refs_str);
9759 if (err)
9760 goto done;
9762 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9763 if (err)
9764 goto done;
9766 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9767 if (refs) {
9768 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9769 if (err)
9770 goto done;
9773 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9774 if (err)
9775 goto done;
9777 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9778 if (err)
9779 goto done;
9781 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9782 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9783 if (err)
9784 goto done;
9786 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9787 refs_str ? " (" : "", refs_str ? refs_str : "",
9788 refs_str ? ")" : "", new_commit_brief_str);
9789 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9790 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9791 free(refs_str);
9792 refs_str = NULL;
9794 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9795 if (err)
9796 goto done;
9798 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9799 if (err)
9800 goto done;
9802 err = got_object_id_str(&yca_id_str, yca_id);
9803 if (err)
9804 goto done;
9806 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9807 if (refs) {
9808 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9809 if (err)
9810 goto done;
9812 printf("history forked at %s%s%s%s\n %s\n",
9813 yca_id_str,
9814 refs_str ? " (" : "", refs_str ? refs_str : "",
9815 refs_str ? ")" : "", yca_brief_str);
9817 done:
9818 free(custom_refs_str);
9819 free(new_commit_id);
9820 free(refs_str);
9821 free(yca_id);
9822 free(yca_id_str);
9823 free(yca_brief_str);
9824 if (new_commit)
9825 got_object_commit_close(new_commit);
9826 if (yca_commit)
9827 got_object_commit_close(yca_commit);
9829 return NULL;
9832 static const struct got_error *
9833 process_backup_refs(const char *backup_ref_prefix,
9834 const char *wanted_branch_name,
9835 int delete, struct got_repository *repo)
9837 const struct got_error *err;
9838 struct got_reflist_head refs, backup_refs;
9839 struct got_reflist_entry *re;
9840 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9841 struct got_object_id *old_commit_id = NULL;
9842 char *branch_name = NULL;
9843 struct got_commit_object *old_commit = NULL;
9844 struct got_reflist_object_id_map *refs_idmap = NULL;
9845 int wanted_branch_found = 0;
9847 TAILQ_INIT(&refs);
9848 TAILQ_INIT(&backup_refs);
9850 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9851 if (err)
9852 return err;
9854 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9855 if (err)
9856 goto done;
9858 if (wanted_branch_name) {
9859 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9860 wanted_branch_name += 11;
9863 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9864 got_ref_cmp_by_commit_timestamp_descending, repo);
9865 if (err)
9866 goto done;
9868 TAILQ_FOREACH(re, &backup_refs, entry) {
9869 const char *refname = got_ref_get_name(re->ref);
9870 char *slash;
9872 err = check_cancelled(NULL);
9873 if (err)
9874 break;
9876 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9877 if (err)
9878 break;
9880 err = got_object_open_as_commit(&old_commit, repo,
9881 old_commit_id);
9882 if (err)
9883 break;
9885 if (strncmp(backup_ref_prefix, refname,
9886 backup_ref_prefix_len) == 0)
9887 refname += backup_ref_prefix_len;
9889 while (refname[0] == '/')
9890 refname++;
9892 branch_name = strdup(refname);
9893 if (branch_name == NULL) {
9894 err = got_error_from_errno("strdup");
9895 break;
9897 slash = strrchr(branch_name, '/');
9898 if (slash) {
9899 *slash = '\0';
9900 refname += strlen(branch_name) + 1;
9903 if (wanted_branch_name == NULL ||
9904 strcmp(wanted_branch_name, branch_name) == 0) {
9905 wanted_branch_found = 1;
9906 if (delete) {
9907 err = delete_backup_ref(re->ref,
9908 old_commit_id, repo);
9909 } else {
9910 err = print_backup_ref(branch_name, refname,
9911 old_commit_id, old_commit, refs_idmap,
9912 repo);
9914 if (err)
9915 break;
9918 free(old_commit_id);
9919 old_commit_id = NULL;
9920 free(branch_name);
9921 branch_name = NULL;
9922 got_object_commit_close(old_commit);
9923 old_commit = NULL;
9926 if (wanted_branch_name && !wanted_branch_found) {
9927 err = got_error_fmt(GOT_ERR_NOT_REF,
9928 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9930 done:
9931 if (refs_idmap)
9932 got_reflist_object_id_map_free(refs_idmap);
9933 got_ref_list_free(&refs);
9934 got_ref_list_free(&backup_refs);
9935 free(old_commit_id);
9936 free(branch_name);
9937 if (old_commit)
9938 got_object_commit_close(old_commit);
9939 return err;
9942 static const struct got_error *
9943 abort_progress(void *arg, unsigned char status, const char *path)
9946 * Unversioned files should not clutter progress output when
9947 * an operation is aborted.
9949 if (status == GOT_STATUS_UNVERSIONED)
9950 return NULL;
9952 return update_progress(arg, status, path);
9955 static const struct got_error *
9956 cmd_rebase(int argc, char *argv[])
9958 const struct got_error *error = NULL;
9959 struct got_worktree *worktree = NULL;
9960 struct got_repository *repo = NULL;
9961 struct got_fileindex *fileindex = NULL;
9962 char *cwd = NULL;
9963 struct got_reference *branch = NULL;
9964 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9965 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9966 struct got_object_id *resume_commit_id = NULL;
9967 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9968 struct got_commit_object *commit = NULL;
9969 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9970 int histedit_in_progress = 0, merge_in_progress = 0;
9971 int create_backup = 1, list_backups = 0, delete_backups = 0;
9972 struct got_object_id_queue commits;
9973 struct got_pathlist_head merged_paths;
9974 const struct got_object_id_queue *parent_ids;
9975 struct got_object_qid *qid, *pid;
9976 struct got_update_progress_arg upa;
9977 int *pack_fds = NULL;
9979 STAILQ_INIT(&commits);
9980 TAILQ_INIT(&merged_paths);
9981 memset(&upa, 0, sizeof(upa));
9983 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9984 switch (ch) {
9985 case 'a':
9986 abort_rebase = 1;
9987 break;
9988 case 'c':
9989 continue_rebase = 1;
9990 break;
9991 case 'l':
9992 list_backups = 1;
9993 break;
9994 case 'X':
9995 delete_backups = 1;
9996 break;
9997 default:
9998 usage_rebase();
9999 /* NOTREACHED */
10003 argc -= optind;
10004 argv += optind;
10006 #ifndef PROFILE
10007 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10008 "unveil", NULL) == -1)
10009 err(1, "pledge");
10010 #endif
10011 if (list_backups) {
10012 if (abort_rebase)
10013 option_conflict('l', 'a');
10014 if (continue_rebase)
10015 option_conflict('l', 'c');
10016 if (delete_backups)
10017 option_conflict('l', 'X');
10018 if (argc != 0 && argc != 1)
10019 usage_rebase();
10020 } else if (delete_backups) {
10021 if (abort_rebase)
10022 option_conflict('X', 'a');
10023 if (continue_rebase)
10024 option_conflict('X', 'c');
10025 if (list_backups)
10026 option_conflict('l', 'X');
10027 if (argc != 0 && argc != 1)
10028 usage_rebase();
10029 } else {
10030 if (abort_rebase && continue_rebase)
10031 usage_rebase();
10032 else if (abort_rebase || continue_rebase) {
10033 if (argc != 0)
10034 usage_rebase();
10035 } else if (argc != 1)
10036 usage_rebase();
10039 cwd = getcwd(NULL, 0);
10040 if (cwd == NULL) {
10041 error = got_error_from_errno("getcwd");
10042 goto done;
10045 error = got_repo_pack_fds_open(&pack_fds);
10046 if (error != NULL)
10047 goto done;
10049 error = got_worktree_open(&worktree, cwd);
10050 if (error) {
10051 if (list_backups || delete_backups) {
10052 if (error->code != GOT_ERR_NOT_WORKTREE)
10053 goto done;
10054 } else {
10055 if (error->code == GOT_ERR_NOT_WORKTREE)
10056 error = wrap_not_worktree_error(error,
10057 "rebase", cwd);
10058 goto done;
10062 error = got_repo_open(&repo,
10063 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10064 pack_fds);
10065 if (error != NULL)
10066 goto done;
10068 error = apply_unveil(got_repo_get_path(repo), 0,
10069 worktree ? got_worktree_get_root_path(worktree) : NULL);
10070 if (error)
10071 goto done;
10073 if (list_backups || delete_backups) {
10074 error = process_backup_refs(
10075 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10076 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10077 goto done; /* nothing else to do */
10080 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10081 worktree);
10082 if (error)
10083 goto done;
10084 if (histedit_in_progress) {
10085 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10086 goto done;
10089 error = got_worktree_merge_in_progress(&merge_in_progress,
10090 worktree, repo);
10091 if (error)
10092 goto done;
10093 if (merge_in_progress) {
10094 error = got_error(GOT_ERR_MERGE_BUSY);
10095 goto done;
10098 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10099 if (error)
10100 goto done;
10102 if (abort_rebase) {
10103 if (!rebase_in_progress) {
10104 error = got_error(GOT_ERR_NOT_REBASING);
10105 goto done;
10107 error = got_worktree_rebase_continue(&resume_commit_id,
10108 &new_base_branch, &tmp_branch, &branch, &fileindex,
10109 worktree, repo);
10110 if (error)
10111 goto done;
10112 printf("Switching work tree to %s\n",
10113 got_ref_get_symref_target(new_base_branch));
10114 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10115 new_base_branch, abort_progress, &upa);
10116 if (error)
10117 goto done;
10118 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10119 print_merge_progress_stats(&upa);
10120 goto done; /* nothing else to do */
10123 if (continue_rebase) {
10124 if (!rebase_in_progress) {
10125 error = got_error(GOT_ERR_NOT_REBASING);
10126 goto done;
10128 error = got_worktree_rebase_continue(&resume_commit_id,
10129 &new_base_branch, &tmp_branch, &branch, &fileindex,
10130 worktree, repo);
10131 if (error)
10132 goto done;
10134 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10135 resume_commit_id, repo);
10136 if (error)
10137 goto done;
10139 yca_id = got_object_id_dup(resume_commit_id);
10140 if (yca_id == NULL) {
10141 error = got_error_from_errno("got_object_id_dup");
10142 goto done;
10144 } else {
10145 error = got_ref_open(&branch, repo, argv[0], 0);
10146 if (error != NULL)
10147 goto done;
10150 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10151 if (error)
10152 goto done;
10154 if (!continue_rebase) {
10155 struct got_object_id *base_commit_id;
10157 base_commit_id = got_worktree_get_base_commit_id(worktree);
10158 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10159 base_commit_id, branch_head_commit_id, 1, repo,
10160 check_cancelled, NULL);
10161 if (error)
10162 goto done;
10163 if (yca_id == NULL) {
10164 error = got_error_msg(GOT_ERR_ANCESTRY,
10165 "specified branch shares no common ancestry "
10166 "with work tree's branch");
10167 goto done;
10170 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10171 if (error) {
10172 if (error->code != GOT_ERR_ANCESTRY)
10173 goto done;
10174 error = NULL;
10175 } else {
10176 struct got_pathlist_head paths;
10177 printf("%s is already based on %s\n",
10178 got_ref_get_name(branch),
10179 got_worktree_get_head_ref_name(worktree));
10180 error = switch_head_ref(branch, branch_head_commit_id,
10181 worktree, repo);
10182 if (error)
10183 goto done;
10184 error = got_worktree_set_base_commit_id(worktree, repo,
10185 branch_head_commit_id);
10186 if (error)
10187 goto done;
10188 TAILQ_INIT(&paths);
10189 error = got_pathlist_append(&paths, "", NULL);
10190 if (error)
10191 goto done;
10192 error = got_worktree_checkout_files(worktree,
10193 &paths, repo, update_progress, &upa,
10194 check_cancelled, NULL);
10195 got_pathlist_free(&paths);
10196 if (error)
10197 goto done;
10198 if (upa.did_something) {
10199 char *id_str;
10200 error = got_object_id_str(&id_str,
10201 branch_head_commit_id);
10202 if (error)
10203 goto done;
10204 printf("Updated to %s: %s\n",
10205 got_worktree_get_head_ref_name(worktree),
10206 id_str);
10207 free(id_str);
10208 } else
10209 printf("Already up-to-date\n");
10210 print_update_progress_stats(&upa);
10211 goto done;
10215 commit_id = branch_head_commit_id;
10216 error = got_object_open_as_commit(&commit, repo, commit_id);
10217 if (error)
10218 goto done;
10220 parent_ids = got_object_commit_get_parent_ids(commit);
10221 pid = STAILQ_FIRST(parent_ids);
10222 if (pid == NULL) {
10223 error = got_error(GOT_ERR_EMPTY_REBASE);
10224 goto done;
10226 error = collect_commits(&commits, commit_id, &pid->id,
10227 yca_id, got_worktree_get_path_prefix(worktree),
10228 GOT_ERR_REBASE_PATH, repo);
10229 got_object_commit_close(commit);
10230 commit = NULL;
10231 if (error)
10232 goto done;
10234 if (!continue_rebase) {
10235 error = got_worktree_rebase_prepare(&new_base_branch,
10236 &tmp_branch, &fileindex, worktree, branch, repo);
10237 if (error)
10238 goto done;
10241 if (STAILQ_EMPTY(&commits)) {
10242 if (continue_rebase) {
10243 error = rebase_complete(worktree, fileindex,
10244 branch, new_base_branch, tmp_branch, repo,
10245 create_backup);
10246 goto done;
10247 } else {
10248 /* Fast-forward the reference of the branch. */
10249 struct got_object_id *new_head_commit_id;
10250 char *id_str;
10251 error = got_ref_resolve(&new_head_commit_id, repo,
10252 new_base_branch);
10253 if (error)
10254 goto done;
10255 error = got_object_id_str(&id_str, new_head_commit_id);
10256 printf("Forwarding %s to commit %s\n",
10257 got_ref_get_name(branch), id_str);
10258 free(id_str);
10259 error = got_ref_change_ref(branch,
10260 new_head_commit_id);
10261 if (error)
10262 goto done;
10263 /* No backup needed since objects did not change. */
10264 create_backup = 0;
10268 pid = NULL;
10269 STAILQ_FOREACH(qid, &commits, entry) {
10271 commit_id = &qid->id;
10272 parent_id = pid ? &pid->id : yca_id;
10273 pid = qid;
10275 memset(&upa, 0, sizeof(upa));
10276 error = got_worktree_rebase_merge_files(&merged_paths,
10277 worktree, fileindex, parent_id, commit_id, repo,
10278 update_progress, &upa, check_cancelled, NULL);
10279 if (error)
10280 goto done;
10282 print_merge_progress_stats(&upa);
10283 if (upa.conflicts > 0 || upa.missing > 0 ||
10284 upa.not_deleted > 0 || upa.unversioned > 0) {
10285 if (upa.conflicts > 0) {
10286 error = show_rebase_merge_conflict(&qid->id,
10287 repo);
10288 if (error)
10289 goto done;
10291 got_worktree_rebase_pathlist_free(&merged_paths);
10292 break;
10295 error = rebase_commit(&merged_paths, worktree, fileindex,
10296 tmp_branch, commit_id, repo);
10297 got_worktree_rebase_pathlist_free(&merged_paths);
10298 if (error)
10299 goto done;
10302 if (upa.conflicts > 0 || upa.missing > 0 ||
10303 upa.not_deleted > 0 || upa.unversioned > 0) {
10304 error = got_worktree_rebase_postpone(worktree, fileindex);
10305 if (error)
10306 goto done;
10307 if (upa.conflicts > 0 && upa.missing == 0 &&
10308 upa.not_deleted == 0 && upa.unversioned == 0) {
10309 error = got_error_msg(GOT_ERR_CONFLICTS,
10310 "conflicts must be resolved before rebasing "
10311 "can continue");
10312 } else if (upa.conflicts > 0) {
10313 error = got_error_msg(GOT_ERR_CONFLICTS,
10314 "conflicts must be resolved before rebasing "
10315 "can continue; changes destined for some "
10316 "files were not yet merged and should be "
10317 "merged manually if required before the "
10318 "rebase operation is continued");
10319 } else {
10320 error = got_error_msg(GOT_ERR_CONFLICTS,
10321 "changes destined for some files were not "
10322 "yet merged and should be merged manually "
10323 "if required before the rebase operation "
10324 "is continued");
10326 } else
10327 error = rebase_complete(worktree, fileindex, branch,
10328 new_base_branch, tmp_branch, repo, create_backup);
10329 done:
10330 got_object_id_queue_free(&commits);
10331 free(branch_head_commit_id);
10332 free(resume_commit_id);
10333 free(yca_id);
10334 if (commit)
10335 got_object_commit_close(commit);
10336 if (branch)
10337 got_ref_close(branch);
10338 if (new_base_branch)
10339 got_ref_close(new_base_branch);
10340 if (tmp_branch)
10341 got_ref_close(tmp_branch);
10342 if (worktree)
10343 got_worktree_close(worktree);
10344 if (repo) {
10345 const struct got_error *close_err = got_repo_close(repo);
10346 if (error == NULL)
10347 error = close_err;
10349 if (pack_fds) {
10350 const struct got_error *pack_err =
10351 got_repo_pack_fds_close(pack_fds);
10352 if (error == NULL)
10353 error = pack_err;
10355 return error;
10358 __dead static void
10359 usage_histedit(void)
10361 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10362 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10363 getprogname());
10364 exit(1);
10367 #define GOT_HISTEDIT_PICK 'p'
10368 #define GOT_HISTEDIT_EDIT 'e'
10369 #define GOT_HISTEDIT_FOLD 'f'
10370 #define GOT_HISTEDIT_DROP 'd'
10371 #define GOT_HISTEDIT_MESG 'm'
10373 static const struct got_histedit_cmd {
10374 unsigned char code;
10375 const char *name;
10376 const char *desc;
10377 } got_histedit_cmds[] = {
10378 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10379 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10380 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10381 "be used" },
10382 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10383 { GOT_HISTEDIT_MESG, "mesg",
10384 "single-line log message for commit above (open editor if empty)" },
10387 struct got_histedit_list_entry {
10388 TAILQ_ENTRY(got_histedit_list_entry) entry;
10389 struct got_object_id *commit_id;
10390 const struct got_histedit_cmd *cmd;
10391 char *logmsg;
10393 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10395 static const struct got_error *
10396 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10397 FILE *f, struct got_repository *repo)
10399 const struct got_error *err = NULL;
10400 char *logmsg = NULL, *id_str = NULL;
10401 struct got_commit_object *commit = NULL;
10402 int n;
10404 err = got_object_open_as_commit(&commit, repo, commit_id);
10405 if (err)
10406 goto done;
10408 err = get_short_logmsg(&logmsg, 34, commit);
10409 if (err)
10410 goto done;
10412 err = got_object_id_str(&id_str, commit_id);
10413 if (err)
10414 goto done;
10416 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10417 if (n < 0)
10418 err = got_ferror(f, GOT_ERR_IO);
10419 done:
10420 if (commit)
10421 got_object_commit_close(commit);
10422 free(id_str);
10423 free(logmsg);
10424 return err;
10427 static const struct got_error *
10428 histedit_write_commit_list(struct got_object_id_queue *commits,
10429 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10430 struct got_repository *repo)
10432 const struct got_error *err = NULL;
10433 struct got_object_qid *qid;
10434 const char *histedit_cmd = NULL;
10436 if (STAILQ_EMPTY(commits))
10437 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10439 STAILQ_FOREACH(qid, commits, entry) {
10440 histedit_cmd = got_histedit_cmds[0].name;
10441 if (edit_only)
10442 histedit_cmd = "edit";
10443 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10444 histedit_cmd = "fold";
10445 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10446 if (err)
10447 break;
10448 if (edit_logmsg_only) {
10449 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10450 if (n < 0) {
10451 err = got_ferror(f, GOT_ERR_IO);
10452 break;
10457 return err;
10460 static const struct got_error *
10461 write_cmd_list(FILE *f, const char *branch_name,
10462 struct got_object_id_queue *commits)
10464 const struct got_error *err = NULL;
10465 size_t i;
10466 int n;
10467 char *id_str;
10468 struct got_object_qid *qid;
10470 qid = STAILQ_FIRST(commits);
10471 err = got_object_id_str(&id_str, &qid->id);
10472 if (err)
10473 return err;
10475 n = fprintf(f,
10476 "# Editing the history of branch '%s' starting at\n"
10477 "# commit %s\n"
10478 "# Commits will be processed in order from top to "
10479 "bottom of this file.\n", branch_name, id_str);
10480 if (n < 0) {
10481 err = got_ferror(f, GOT_ERR_IO);
10482 goto done;
10485 n = fprintf(f, "# Available histedit commands:\n");
10486 if (n < 0) {
10487 err = got_ferror(f, GOT_ERR_IO);
10488 goto done;
10491 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10492 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10493 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10494 cmd->desc);
10495 if (n < 0) {
10496 err = got_ferror(f, GOT_ERR_IO);
10497 break;
10500 done:
10501 free(id_str);
10502 return err;
10505 static const struct got_error *
10506 histedit_syntax_error(int lineno)
10508 static char msg[42];
10509 int ret;
10511 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10512 lineno);
10513 if (ret == -1 || ret >= sizeof(msg))
10514 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10516 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10519 static const struct got_error *
10520 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10521 char *logmsg, struct got_repository *repo)
10523 const struct got_error *err;
10524 struct got_commit_object *folded_commit = NULL;
10525 char *id_str, *folded_logmsg = NULL;
10527 err = got_object_id_str(&id_str, hle->commit_id);
10528 if (err)
10529 return err;
10531 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10532 if (err)
10533 goto done;
10535 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10536 if (err)
10537 goto done;
10538 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10539 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10540 folded_logmsg) == -1) {
10541 err = got_error_from_errno("asprintf");
10543 done:
10544 if (folded_commit)
10545 got_object_commit_close(folded_commit);
10546 free(id_str);
10547 free(folded_logmsg);
10548 return err;
10551 static struct got_histedit_list_entry *
10552 get_folded_commits(struct got_histedit_list_entry *hle)
10554 struct got_histedit_list_entry *prev, *folded = NULL;
10556 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10557 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10558 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10559 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10560 folded = prev;
10561 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10564 return folded;
10567 static const struct got_error *
10568 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10569 struct got_repository *repo)
10571 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10572 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10573 const struct got_error *err = NULL;
10574 struct got_commit_object *commit = NULL;
10575 int logmsg_len;
10576 int fd;
10577 struct got_histedit_list_entry *folded = NULL;
10579 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10580 if (err)
10581 return err;
10583 folded = get_folded_commits(hle);
10584 if (folded) {
10585 while (folded != hle) {
10586 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10587 folded = TAILQ_NEXT(folded, entry);
10588 continue;
10590 err = append_folded_commit_msg(&new_msg, folded,
10591 logmsg, repo);
10592 if (err)
10593 goto done;
10594 free(logmsg);
10595 logmsg = new_msg;
10596 folded = TAILQ_NEXT(folded, entry);
10600 err = got_object_id_str(&id_str, hle->commit_id);
10601 if (err)
10602 goto done;
10603 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10604 if (err)
10605 goto done;
10606 logmsg_len = asprintf(&new_msg,
10607 "%s\n# original log message of commit %s: %s",
10608 logmsg ? logmsg : "", id_str, orig_logmsg);
10609 if (logmsg_len == -1) {
10610 err = got_error_from_errno("asprintf");
10611 goto done;
10613 free(logmsg);
10614 logmsg = new_msg;
10616 err = got_object_id_str(&id_str, hle->commit_id);
10617 if (err)
10618 goto done;
10620 err = got_opentemp_named_fd(&logmsg_path, &fd,
10621 GOT_TMPDIR_STR "/got-logmsg");
10622 if (err)
10623 goto done;
10625 write(fd, logmsg, logmsg_len);
10626 close(fd);
10628 err = get_editor(&editor);
10629 if (err)
10630 goto done;
10632 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10633 logmsg_len, 0);
10634 if (err) {
10635 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10636 goto done;
10637 err = NULL;
10638 hle->logmsg = strdup(new_msg);
10639 if (hle->logmsg == NULL)
10640 err = got_error_from_errno("strdup");
10642 done:
10643 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10644 err = got_error_from_errno2("unlink", logmsg_path);
10645 free(logmsg_path);
10646 free(logmsg);
10647 free(orig_logmsg);
10648 free(editor);
10649 if (commit)
10650 got_object_commit_close(commit);
10651 return err;
10654 static const struct got_error *
10655 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10656 FILE *f, struct got_repository *repo)
10658 const struct got_error *err = NULL;
10659 char *line = NULL, *p, *end;
10660 size_t i, size;
10661 ssize_t len;
10662 int lineno = 0;
10663 const struct got_histedit_cmd *cmd;
10664 struct got_object_id *commit_id = NULL;
10665 struct got_histedit_list_entry *hle = NULL;
10667 for (;;) {
10668 len = getline(&line, &size, f);
10669 if (len == -1) {
10670 const struct got_error *getline_err;
10671 if (feof(f))
10672 break;
10673 getline_err = got_error_from_errno("getline");
10674 err = got_ferror(f, getline_err->code);
10675 break;
10677 lineno++;
10678 p = line;
10679 while (isspace((unsigned char)p[0]))
10680 p++;
10681 if (p[0] == '#' || p[0] == '\0') {
10682 free(line);
10683 line = NULL;
10684 continue;
10686 cmd = NULL;
10687 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10688 cmd = &got_histedit_cmds[i];
10689 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10690 isspace((unsigned char)p[strlen(cmd->name)])) {
10691 p += strlen(cmd->name);
10692 break;
10694 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10695 p++;
10696 break;
10699 if (i == nitems(got_histedit_cmds)) {
10700 err = histedit_syntax_error(lineno);
10701 break;
10703 while (isspace((unsigned char)p[0]))
10704 p++;
10705 if (cmd->code == GOT_HISTEDIT_MESG) {
10706 if (hle == NULL || hle->logmsg != NULL) {
10707 err = got_error(GOT_ERR_HISTEDIT_CMD);
10708 break;
10710 if (p[0] == '\0') {
10711 err = histedit_edit_logmsg(hle, repo);
10712 if (err)
10713 break;
10714 } else {
10715 hle->logmsg = strdup(p);
10716 if (hle->logmsg == NULL) {
10717 err = got_error_from_errno("strdup");
10718 break;
10721 free(line);
10722 line = NULL;
10723 continue;
10724 } else {
10725 end = p;
10726 while (end[0] && !isspace((unsigned char)end[0]))
10727 end++;
10728 *end = '\0';
10730 err = got_object_resolve_id_str(&commit_id, repo, p);
10731 if (err) {
10732 /* override error code */
10733 err = histedit_syntax_error(lineno);
10734 break;
10737 hle = malloc(sizeof(*hle));
10738 if (hle == NULL) {
10739 err = got_error_from_errno("malloc");
10740 break;
10742 hle->cmd = cmd;
10743 hle->commit_id = commit_id;
10744 hle->logmsg = NULL;
10745 commit_id = NULL;
10746 free(line);
10747 line = NULL;
10748 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10751 free(line);
10752 free(commit_id);
10753 return err;
10756 static const struct got_error *
10757 histedit_check_script(struct got_histedit_list *histedit_cmds,
10758 struct got_object_id_queue *commits, struct got_repository *repo)
10760 const struct got_error *err = NULL;
10761 struct got_object_qid *qid;
10762 struct got_histedit_list_entry *hle;
10763 static char msg[92];
10764 char *id_str;
10766 if (TAILQ_EMPTY(histedit_cmds))
10767 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10768 "histedit script contains no commands");
10769 if (STAILQ_EMPTY(commits))
10770 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10772 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10773 struct got_histedit_list_entry *hle2;
10774 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10775 if (hle == hle2)
10776 continue;
10777 if (got_object_id_cmp(hle->commit_id,
10778 hle2->commit_id) != 0)
10779 continue;
10780 err = got_object_id_str(&id_str, hle->commit_id);
10781 if (err)
10782 return err;
10783 snprintf(msg, sizeof(msg), "commit %s is listed "
10784 "more than once in histedit script", id_str);
10785 free(id_str);
10786 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10790 STAILQ_FOREACH(qid, commits, entry) {
10791 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10792 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10793 break;
10795 if (hle == NULL) {
10796 err = got_object_id_str(&id_str, &qid->id);
10797 if (err)
10798 return err;
10799 snprintf(msg, sizeof(msg),
10800 "commit %s missing from histedit script", id_str);
10801 free(id_str);
10802 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10806 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10807 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10808 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10809 "last commit in histedit script cannot be folded");
10811 return NULL;
10814 static const struct got_error *
10815 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10816 const char *path, struct got_object_id_queue *commits,
10817 struct got_repository *repo)
10819 const struct got_error *err = NULL;
10820 char *editor;
10821 FILE *f = NULL;
10823 err = get_editor(&editor);
10824 if (err)
10825 return err;
10827 if (spawn_editor(editor, path) == -1) {
10828 err = got_error_from_errno("failed spawning editor");
10829 goto done;
10832 f = fopen(path, "re");
10833 if (f == NULL) {
10834 err = got_error_from_errno("fopen");
10835 goto done;
10837 err = histedit_parse_list(histedit_cmds, f, repo);
10838 if (err)
10839 goto done;
10841 err = histedit_check_script(histedit_cmds, commits, repo);
10842 done:
10843 if (f && fclose(f) == EOF && err == NULL)
10844 err = got_error_from_errno("fclose");
10845 free(editor);
10846 return err;
10849 static const struct got_error *
10850 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10851 struct got_object_id_queue *, const char *, const char *,
10852 struct got_repository *);
10854 static const struct got_error *
10855 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10856 struct got_object_id_queue *commits, const char *branch_name,
10857 int edit_logmsg_only, int fold_only, int edit_only,
10858 struct got_repository *repo)
10860 const struct got_error *err;
10861 FILE *f = NULL;
10862 char *path = NULL;
10864 err = got_opentemp_named(&path, &f, "got-histedit");
10865 if (err)
10866 return err;
10868 err = write_cmd_list(f, branch_name, commits);
10869 if (err)
10870 goto done;
10872 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10873 fold_only, edit_only, repo);
10874 if (err)
10875 goto done;
10877 if (edit_logmsg_only || fold_only || edit_only) {
10878 rewind(f);
10879 err = histedit_parse_list(histedit_cmds, f, repo);
10880 } else {
10881 if (fclose(f) == EOF) {
10882 err = got_error_from_errno("fclose");
10883 goto done;
10885 f = NULL;
10886 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10887 if (err) {
10888 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10889 err->code != GOT_ERR_HISTEDIT_CMD)
10890 goto done;
10891 err = histedit_edit_list_retry(histedit_cmds, err,
10892 commits, path, branch_name, repo);
10895 done:
10896 if (f && fclose(f) == EOF && err == NULL)
10897 err = got_error_from_errno("fclose");
10898 if (path && unlink(path) != 0 && err == NULL)
10899 err = got_error_from_errno2("unlink", path);
10900 free(path);
10901 return err;
10904 static const struct got_error *
10905 histedit_save_list(struct got_histedit_list *histedit_cmds,
10906 struct got_worktree *worktree, struct got_repository *repo)
10908 const struct got_error *err = NULL;
10909 char *path = NULL;
10910 FILE *f = NULL;
10911 struct got_histedit_list_entry *hle;
10912 struct got_commit_object *commit = NULL;
10914 err = got_worktree_get_histedit_script_path(&path, worktree);
10915 if (err)
10916 return err;
10918 f = fopen(path, "we");
10919 if (f == NULL) {
10920 err = got_error_from_errno2("fopen", path);
10921 goto done;
10923 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10924 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10925 repo);
10926 if (err)
10927 break;
10929 if (hle->logmsg) {
10930 int n = fprintf(f, "%c %s\n",
10931 GOT_HISTEDIT_MESG, hle->logmsg);
10932 if (n < 0) {
10933 err = got_ferror(f, GOT_ERR_IO);
10934 break;
10938 done:
10939 if (f && fclose(f) == EOF && err == NULL)
10940 err = got_error_from_errno("fclose");
10941 free(path);
10942 if (commit)
10943 got_object_commit_close(commit);
10944 return err;
10947 static void
10948 histedit_free_list(struct got_histedit_list *histedit_cmds)
10950 struct got_histedit_list_entry *hle;
10952 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10953 TAILQ_REMOVE(histedit_cmds, hle, entry);
10954 free(hle);
10958 static const struct got_error *
10959 histedit_load_list(struct got_histedit_list *histedit_cmds,
10960 const char *path, struct got_repository *repo)
10962 const struct got_error *err = NULL;
10963 FILE *f = NULL;
10965 f = fopen(path, "re");
10966 if (f == NULL) {
10967 err = got_error_from_errno2("fopen", path);
10968 goto done;
10971 err = histedit_parse_list(histedit_cmds, f, repo);
10972 done:
10973 if (f && fclose(f) == EOF && err == NULL)
10974 err = got_error_from_errno("fclose");
10975 return err;
10978 static const struct got_error *
10979 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10980 const struct got_error *edit_err, struct got_object_id_queue *commits,
10981 const char *path, const char *branch_name, struct got_repository *repo)
10983 const struct got_error *err = NULL, *prev_err = edit_err;
10984 int resp = ' ';
10986 while (resp != 'c' && resp != 'r' && resp != 'a') {
10987 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10988 "or (a)bort: ", getprogname(), prev_err->msg);
10989 resp = getchar();
10990 if (resp == '\n')
10991 resp = getchar();
10992 if (resp == 'c') {
10993 histedit_free_list(histedit_cmds);
10994 err = histedit_run_editor(histedit_cmds, path, commits,
10995 repo);
10996 if (err) {
10997 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10998 err->code != GOT_ERR_HISTEDIT_CMD)
10999 break;
11000 prev_err = err;
11001 resp = ' ';
11002 continue;
11004 break;
11005 } else if (resp == 'r') {
11006 histedit_free_list(histedit_cmds);
11007 err = histedit_edit_script(histedit_cmds,
11008 commits, branch_name, 0, 0, 0, repo);
11009 if (err) {
11010 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11011 err->code != GOT_ERR_HISTEDIT_CMD)
11012 break;
11013 prev_err = err;
11014 resp = ' ';
11015 continue;
11017 break;
11018 } else if (resp == 'a') {
11019 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11020 break;
11021 } else
11022 printf("invalid response '%c'\n", resp);
11025 return err;
11028 static const struct got_error *
11029 histedit_complete(struct got_worktree *worktree,
11030 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11031 struct got_reference *branch, struct got_repository *repo)
11033 printf("Switching work tree to %s\n",
11034 got_ref_get_symref_target(branch));
11035 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11036 branch, repo);
11039 static const struct got_error *
11040 show_histedit_progress(struct got_commit_object *commit,
11041 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11043 const struct got_error *err;
11044 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11046 err = got_object_id_str(&old_id_str, hle->commit_id);
11047 if (err)
11048 goto done;
11050 if (new_id) {
11051 err = got_object_id_str(&new_id_str, new_id);
11052 if (err)
11053 goto done;
11056 old_id_str[12] = '\0';
11057 if (new_id_str)
11058 new_id_str[12] = '\0';
11060 if (hle->logmsg) {
11061 logmsg = strdup(hle->logmsg);
11062 if (logmsg == NULL) {
11063 err = got_error_from_errno("strdup");
11064 goto done;
11066 trim_logmsg(logmsg, 42);
11067 } else {
11068 err = get_short_logmsg(&logmsg, 42, commit);
11069 if (err)
11070 goto done;
11073 switch (hle->cmd->code) {
11074 case GOT_HISTEDIT_PICK:
11075 case GOT_HISTEDIT_EDIT:
11076 printf("%s -> %s: %s\n", old_id_str,
11077 new_id_str ? new_id_str : "no-op change", logmsg);
11078 break;
11079 case GOT_HISTEDIT_DROP:
11080 case GOT_HISTEDIT_FOLD:
11081 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11082 logmsg);
11083 break;
11084 default:
11085 break;
11087 done:
11088 free(old_id_str);
11089 free(new_id_str);
11090 return err;
11093 static const struct got_error *
11094 histedit_commit(struct got_pathlist_head *merged_paths,
11095 struct got_worktree *worktree, struct got_fileindex *fileindex,
11096 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11097 struct got_repository *repo)
11099 const struct got_error *err;
11100 struct got_commit_object *commit;
11101 struct got_object_id *new_commit_id;
11103 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11104 && hle->logmsg == NULL) {
11105 err = histedit_edit_logmsg(hle, repo);
11106 if (err)
11107 return err;
11110 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11111 if (err)
11112 return err;
11114 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11115 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11116 hle->logmsg, repo);
11117 if (err) {
11118 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11119 goto done;
11120 err = show_histedit_progress(commit, hle, NULL);
11121 } else {
11122 err = show_histedit_progress(commit, hle, new_commit_id);
11123 free(new_commit_id);
11125 done:
11126 got_object_commit_close(commit);
11127 return err;
11130 static const struct got_error *
11131 histedit_skip_commit(struct got_histedit_list_entry *hle,
11132 struct got_worktree *worktree, struct got_repository *repo)
11134 const struct got_error *error;
11135 struct got_commit_object *commit;
11137 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11138 repo);
11139 if (error)
11140 return error;
11142 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11143 if (error)
11144 return error;
11146 error = show_histedit_progress(commit, hle, NULL);
11147 got_object_commit_close(commit);
11148 return error;
11151 static const struct got_error *
11152 check_local_changes(void *arg, unsigned char status,
11153 unsigned char staged_status, const char *path,
11154 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11155 struct got_object_id *commit_id, int dirfd, const char *de_name)
11157 int *have_local_changes = arg;
11159 switch (status) {
11160 case GOT_STATUS_ADD:
11161 case GOT_STATUS_DELETE:
11162 case GOT_STATUS_MODIFY:
11163 case GOT_STATUS_CONFLICT:
11164 *have_local_changes = 1;
11165 return got_error(GOT_ERR_CANCELLED);
11166 default:
11167 break;
11170 switch (staged_status) {
11171 case GOT_STATUS_ADD:
11172 case GOT_STATUS_DELETE:
11173 case GOT_STATUS_MODIFY:
11174 *have_local_changes = 1;
11175 return got_error(GOT_ERR_CANCELLED);
11176 default:
11177 break;
11180 return NULL;
11183 static const struct got_error *
11184 cmd_histedit(int argc, char *argv[])
11186 const struct got_error *error = NULL;
11187 struct got_worktree *worktree = NULL;
11188 struct got_fileindex *fileindex = NULL;
11189 struct got_repository *repo = NULL;
11190 char *cwd = NULL;
11191 struct got_reference *branch = NULL;
11192 struct got_reference *tmp_branch = NULL;
11193 struct got_object_id *resume_commit_id = NULL;
11194 struct got_object_id *base_commit_id = NULL;
11195 struct got_object_id *head_commit_id = NULL;
11196 struct got_commit_object *commit = NULL;
11197 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11198 struct got_update_progress_arg upa;
11199 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11200 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11201 int list_backups = 0, delete_backups = 0;
11202 const char *edit_script_path = NULL;
11203 struct got_object_id_queue commits;
11204 struct got_pathlist_head merged_paths;
11205 const struct got_object_id_queue *parent_ids;
11206 struct got_object_qid *pid;
11207 struct got_histedit_list histedit_cmds;
11208 struct got_histedit_list_entry *hle;
11209 int *pack_fds = NULL;
11211 STAILQ_INIT(&commits);
11212 TAILQ_INIT(&histedit_cmds);
11213 TAILQ_INIT(&merged_paths);
11214 memset(&upa, 0, sizeof(upa));
11216 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11217 switch (ch) {
11218 case 'a':
11219 abort_edit = 1;
11220 break;
11221 case 'c':
11222 continue_edit = 1;
11223 break;
11224 case 'e':
11225 edit_only = 1;
11226 break;
11227 case 'f':
11228 fold_only = 1;
11229 break;
11230 case 'F':
11231 edit_script_path = optarg;
11232 break;
11233 case 'm':
11234 edit_logmsg_only = 1;
11235 break;
11236 case 'l':
11237 list_backups = 1;
11238 break;
11239 case 'X':
11240 delete_backups = 1;
11241 break;
11242 default:
11243 usage_histedit();
11244 /* NOTREACHED */
11248 argc -= optind;
11249 argv += optind;
11251 #ifndef PROFILE
11252 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11253 "unveil", NULL) == -1)
11254 err(1, "pledge");
11255 #endif
11256 if (abort_edit && continue_edit)
11257 option_conflict('a', 'c');
11258 if (edit_script_path && edit_logmsg_only)
11259 option_conflict('F', 'm');
11260 if (abort_edit && edit_logmsg_only)
11261 option_conflict('a', 'm');
11262 if (continue_edit && edit_logmsg_only)
11263 option_conflict('c', 'm');
11264 if (abort_edit && fold_only)
11265 option_conflict('a', 'f');
11266 if (continue_edit && fold_only)
11267 option_conflict('c', 'f');
11268 if (fold_only && edit_logmsg_only)
11269 option_conflict('f', 'm');
11270 if (edit_script_path && fold_only)
11271 option_conflict('F', 'f');
11272 if (abort_edit && edit_only)
11273 option_conflict('a', 'e');
11274 if (continue_edit && edit_only)
11275 option_conflict('c', 'e');
11276 if (edit_only && edit_logmsg_only)
11277 option_conflict('e', 'm');
11278 if (edit_script_path && edit_only)
11279 option_conflict('F', 'e');
11280 if (list_backups) {
11281 if (abort_edit)
11282 option_conflict('l', 'a');
11283 if (continue_edit)
11284 option_conflict('l', 'c');
11285 if (edit_script_path)
11286 option_conflict('l', 'F');
11287 if (edit_logmsg_only)
11288 option_conflict('l', 'm');
11289 if (fold_only)
11290 option_conflict('l', 'f');
11291 if (edit_only)
11292 option_conflict('l', 'e');
11293 if (delete_backups)
11294 option_conflict('l', 'X');
11295 if (argc != 0 && argc != 1)
11296 usage_histedit();
11297 } else if (delete_backups) {
11298 if (abort_edit)
11299 option_conflict('X', 'a');
11300 if (continue_edit)
11301 option_conflict('X', 'c');
11302 if (edit_script_path)
11303 option_conflict('X', 'F');
11304 if (edit_logmsg_only)
11305 option_conflict('X', 'm');
11306 if (fold_only)
11307 option_conflict('X', 'f');
11308 if (edit_only)
11309 option_conflict('X', 'e');
11310 if (list_backups)
11311 option_conflict('X', 'l');
11312 if (argc != 0 && argc != 1)
11313 usage_histedit();
11314 } else if (argc != 0)
11315 usage_histedit();
11318 * This command cannot apply unveil(2) in all cases because the
11319 * user may choose to run an editor to edit the histedit script
11320 * and to edit individual commit log messages.
11321 * unveil(2) traverses exec(2); if an editor is used we have to
11322 * apply unveil after edit script and log messages have been written.
11323 * XXX TODO: Make use of unveil(2) where possible.
11326 cwd = getcwd(NULL, 0);
11327 if (cwd == NULL) {
11328 error = got_error_from_errno("getcwd");
11329 goto done;
11332 error = got_repo_pack_fds_open(&pack_fds);
11333 if (error != NULL)
11334 goto done;
11336 error = got_worktree_open(&worktree, cwd);
11337 if (error) {
11338 if (list_backups || delete_backups) {
11339 if (error->code != GOT_ERR_NOT_WORKTREE)
11340 goto done;
11341 } else {
11342 if (error->code == GOT_ERR_NOT_WORKTREE)
11343 error = wrap_not_worktree_error(error,
11344 "histedit", cwd);
11345 goto done;
11349 if (list_backups || delete_backups) {
11350 error = got_repo_open(&repo,
11351 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11352 NULL, pack_fds);
11353 if (error != NULL)
11354 goto done;
11355 error = apply_unveil(got_repo_get_path(repo), 0,
11356 worktree ? got_worktree_get_root_path(worktree) : NULL);
11357 if (error)
11358 goto done;
11359 error = process_backup_refs(
11360 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11361 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11362 goto done; /* nothing else to do */
11365 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11366 NULL, pack_fds);
11367 if (error != NULL)
11368 goto done;
11370 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11371 if (error)
11372 goto done;
11373 if (rebase_in_progress) {
11374 error = got_error(GOT_ERR_REBASING);
11375 goto done;
11378 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11379 repo);
11380 if (error)
11381 goto done;
11382 if (merge_in_progress) {
11383 error = got_error(GOT_ERR_MERGE_BUSY);
11384 goto done;
11387 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11388 if (error)
11389 goto done;
11391 if (edit_in_progress && edit_logmsg_only) {
11392 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11393 "histedit operation is in progress in this "
11394 "work tree and must be continued or aborted "
11395 "before the -m option can be used");
11396 goto done;
11398 if (edit_in_progress && fold_only) {
11399 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11400 "histedit operation is in progress in this "
11401 "work tree and must be continued or aborted "
11402 "before the -f option can be used");
11403 goto done;
11405 if (edit_in_progress && edit_only) {
11406 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11407 "histedit operation is in progress in this "
11408 "work tree and must be continued or aborted "
11409 "before the -e option can be used");
11410 goto done;
11413 if (edit_in_progress && abort_edit) {
11414 error = got_worktree_histedit_continue(&resume_commit_id,
11415 &tmp_branch, &branch, &base_commit_id, &fileindex,
11416 worktree, repo);
11417 if (error)
11418 goto done;
11419 printf("Switching work tree to %s\n",
11420 got_ref_get_symref_target(branch));
11421 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11422 branch, base_commit_id, abort_progress, &upa);
11423 if (error)
11424 goto done;
11425 printf("Histedit of %s aborted\n",
11426 got_ref_get_symref_target(branch));
11427 print_merge_progress_stats(&upa);
11428 goto done; /* nothing else to do */
11429 } else if (abort_edit) {
11430 error = got_error(GOT_ERR_NOT_HISTEDIT);
11431 goto done;
11434 if (continue_edit) {
11435 char *path;
11437 if (!edit_in_progress) {
11438 error = got_error(GOT_ERR_NOT_HISTEDIT);
11439 goto done;
11442 error = got_worktree_get_histedit_script_path(&path, worktree);
11443 if (error)
11444 goto done;
11446 error = histedit_load_list(&histedit_cmds, path, repo);
11447 free(path);
11448 if (error)
11449 goto done;
11451 error = got_worktree_histedit_continue(&resume_commit_id,
11452 &tmp_branch, &branch, &base_commit_id, &fileindex,
11453 worktree, repo);
11454 if (error)
11455 goto done;
11457 error = got_ref_resolve(&head_commit_id, repo, branch);
11458 if (error)
11459 goto done;
11461 error = got_object_open_as_commit(&commit, repo,
11462 head_commit_id);
11463 if (error)
11464 goto done;
11465 parent_ids = got_object_commit_get_parent_ids(commit);
11466 pid = STAILQ_FIRST(parent_ids);
11467 if (pid == NULL) {
11468 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11469 goto done;
11471 error = collect_commits(&commits, head_commit_id, &pid->id,
11472 base_commit_id, got_worktree_get_path_prefix(worktree),
11473 GOT_ERR_HISTEDIT_PATH, repo);
11474 got_object_commit_close(commit);
11475 commit = NULL;
11476 if (error)
11477 goto done;
11478 } else {
11479 if (edit_in_progress) {
11480 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11481 goto done;
11484 error = got_ref_open(&branch, repo,
11485 got_worktree_get_head_ref_name(worktree), 0);
11486 if (error != NULL)
11487 goto done;
11489 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11490 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11491 "will not edit commit history of a branch outside "
11492 "the \"refs/heads/\" reference namespace");
11493 goto done;
11496 error = got_ref_resolve(&head_commit_id, repo, branch);
11497 got_ref_close(branch);
11498 branch = NULL;
11499 if (error)
11500 goto done;
11502 error = got_object_open_as_commit(&commit, repo,
11503 head_commit_id);
11504 if (error)
11505 goto done;
11506 parent_ids = got_object_commit_get_parent_ids(commit);
11507 pid = STAILQ_FIRST(parent_ids);
11508 if (pid == NULL) {
11509 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11510 goto done;
11512 error = collect_commits(&commits, head_commit_id, &pid->id,
11513 got_worktree_get_base_commit_id(worktree),
11514 got_worktree_get_path_prefix(worktree),
11515 GOT_ERR_HISTEDIT_PATH, repo);
11516 got_object_commit_close(commit);
11517 commit = NULL;
11518 if (error)
11519 goto done;
11521 if (STAILQ_EMPTY(&commits)) {
11522 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11523 goto done;
11526 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11527 &base_commit_id, &fileindex, worktree, repo);
11528 if (error)
11529 goto done;
11531 if (edit_script_path) {
11532 error = histedit_load_list(&histedit_cmds,
11533 edit_script_path, repo);
11534 if (error) {
11535 got_worktree_histedit_abort(worktree, fileindex,
11536 repo, branch, base_commit_id,
11537 abort_progress, &upa);
11538 print_merge_progress_stats(&upa);
11539 goto done;
11541 } else {
11542 const char *branch_name;
11543 branch_name = got_ref_get_symref_target(branch);
11544 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11545 branch_name += 11;
11546 error = histedit_edit_script(&histedit_cmds, &commits,
11547 branch_name, edit_logmsg_only, fold_only,
11548 edit_only, repo);
11549 if (error) {
11550 got_worktree_histedit_abort(worktree, fileindex,
11551 repo, branch, base_commit_id,
11552 abort_progress, &upa);
11553 print_merge_progress_stats(&upa);
11554 goto done;
11559 error = histedit_save_list(&histedit_cmds, worktree,
11560 repo);
11561 if (error) {
11562 got_worktree_histedit_abort(worktree, fileindex,
11563 repo, branch, base_commit_id,
11564 abort_progress, &upa);
11565 print_merge_progress_stats(&upa);
11566 goto done;
11571 error = histedit_check_script(&histedit_cmds, &commits, repo);
11572 if (error)
11573 goto done;
11575 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11576 if (resume_commit_id) {
11577 if (got_object_id_cmp(hle->commit_id,
11578 resume_commit_id) != 0)
11579 continue;
11581 resume_commit_id = NULL;
11582 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11583 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11584 error = histedit_skip_commit(hle, worktree,
11585 repo);
11586 if (error)
11587 goto done;
11588 } else {
11589 struct got_pathlist_head paths;
11590 int have_changes = 0;
11592 TAILQ_INIT(&paths);
11593 error = got_pathlist_append(&paths, "", NULL);
11594 if (error)
11595 goto done;
11596 error = got_worktree_status(worktree, &paths,
11597 repo, 0, check_local_changes, &have_changes,
11598 check_cancelled, NULL);
11599 got_pathlist_free(&paths);
11600 if (error) {
11601 if (error->code != GOT_ERR_CANCELLED)
11602 goto done;
11603 if (sigint_received || sigpipe_received)
11604 goto done;
11606 if (have_changes) {
11607 error = histedit_commit(NULL, worktree,
11608 fileindex, tmp_branch, hle, repo);
11609 if (error)
11610 goto done;
11611 } else {
11612 error = got_object_open_as_commit(
11613 &commit, repo, hle->commit_id);
11614 if (error)
11615 goto done;
11616 error = show_histedit_progress(commit,
11617 hle, NULL);
11618 got_object_commit_close(commit);
11619 commit = NULL;
11620 if (error)
11621 goto done;
11624 continue;
11627 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11628 error = histedit_skip_commit(hle, worktree, repo);
11629 if (error)
11630 goto done;
11631 continue;
11634 error = got_object_open_as_commit(&commit, repo,
11635 hle->commit_id);
11636 if (error)
11637 goto done;
11638 parent_ids = got_object_commit_get_parent_ids(commit);
11639 pid = STAILQ_FIRST(parent_ids);
11641 error = got_worktree_histedit_merge_files(&merged_paths,
11642 worktree, fileindex, &pid->id, hle->commit_id, repo,
11643 update_progress, &upa, check_cancelled, NULL);
11644 if (error)
11645 goto done;
11646 got_object_commit_close(commit);
11647 commit = NULL;
11649 print_merge_progress_stats(&upa);
11650 if (upa.conflicts > 0 || upa.missing > 0 ||
11651 upa.not_deleted > 0 || upa.unversioned > 0) {
11652 if (upa.conflicts > 0) {
11653 error = show_rebase_merge_conflict(
11654 hle->commit_id, repo);
11655 if (error)
11656 goto done;
11658 got_worktree_rebase_pathlist_free(&merged_paths);
11659 break;
11662 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11663 char *id_str;
11664 error = got_object_id_str(&id_str, hle->commit_id);
11665 if (error)
11666 goto done;
11667 printf("Stopping histedit for amending commit %s\n",
11668 id_str);
11669 free(id_str);
11670 got_worktree_rebase_pathlist_free(&merged_paths);
11671 error = got_worktree_histedit_postpone(worktree,
11672 fileindex);
11673 goto done;
11676 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11677 error = histedit_skip_commit(hle, worktree, repo);
11678 if (error)
11679 goto done;
11680 continue;
11683 error = histedit_commit(&merged_paths, worktree, fileindex,
11684 tmp_branch, hle, repo);
11685 got_worktree_rebase_pathlist_free(&merged_paths);
11686 if (error)
11687 goto done;
11690 if (upa.conflicts > 0 || upa.missing > 0 ||
11691 upa.not_deleted > 0 || upa.unversioned > 0) {
11692 error = got_worktree_histedit_postpone(worktree, fileindex);
11693 if (error)
11694 goto done;
11695 if (upa.conflicts > 0 && upa.missing == 0 &&
11696 upa.not_deleted == 0 && upa.unversioned == 0) {
11697 error = got_error_msg(GOT_ERR_CONFLICTS,
11698 "conflicts must be resolved before histedit "
11699 "can continue");
11700 } else if (upa.conflicts > 0) {
11701 error = got_error_msg(GOT_ERR_CONFLICTS,
11702 "conflicts must be resolved before histedit "
11703 "can continue; changes destined for some "
11704 "files were not yet merged and should be "
11705 "merged manually if required before the "
11706 "histedit operation is continued");
11707 } else {
11708 error = got_error_msg(GOT_ERR_CONFLICTS,
11709 "changes destined for some files were not "
11710 "yet merged and should be merged manually "
11711 "if required before the histedit operation "
11712 "is continued");
11714 } else
11715 error = histedit_complete(worktree, fileindex, tmp_branch,
11716 branch, repo);
11717 done:
11718 got_object_id_queue_free(&commits);
11719 histedit_free_list(&histedit_cmds);
11720 free(head_commit_id);
11721 free(base_commit_id);
11722 free(resume_commit_id);
11723 if (commit)
11724 got_object_commit_close(commit);
11725 if (branch)
11726 got_ref_close(branch);
11727 if (tmp_branch)
11728 got_ref_close(tmp_branch);
11729 if (worktree)
11730 got_worktree_close(worktree);
11731 if (repo) {
11732 const struct got_error *close_err = got_repo_close(repo);
11733 if (error == NULL)
11734 error = close_err;
11736 if (pack_fds) {
11737 const struct got_error *pack_err =
11738 got_repo_pack_fds_close(pack_fds);
11739 if (error == NULL)
11740 error = pack_err;
11742 return error;
11745 __dead static void
11746 usage_integrate(void)
11748 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11749 exit(1);
11752 static const struct got_error *
11753 cmd_integrate(int argc, char *argv[])
11755 const struct got_error *error = NULL;
11756 struct got_repository *repo = NULL;
11757 struct got_worktree *worktree = NULL;
11758 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11759 const char *branch_arg = NULL;
11760 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11761 struct got_fileindex *fileindex = NULL;
11762 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11763 int ch;
11764 struct got_update_progress_arg upa;
11765 int *pack_fds = NULL;
11767 while ((ch = getopt(argc, argv, "")) != -1) {
11768 switch (ch) {
11769 default:
11770 usage_integrate();
11771 /* NOTREACHED */
11775 argc -= optind;
11776 argv += optind;
11778 if (argc != 1)
11779 usage_integrate();
11780 branch_arg = argv[0];
11781 #ifndef PROFILE
11782 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11783 "unveil", NULL) == -1)
11784 err(1, "pledge");
11785 #endif
11786 cwd = getcwd(NULL, 0);
11787 if (cwd == NULL) {
11788 error = got_error_from_errno("getcwd");
11789 goto done;
11792 error = got_repo_pack_fds_open(&pack_fds);
11793 if (error != NULL)
11794 goto done;
11796 error = got_worktree_open(&worktree, cwd);
11797 if (error) {
11798 if (error->code == GOT_ERR_NOT_WORKTREE)
11799 error = wrap_not_worktree_error(error, "integrate",
11800 cwd);
11801 goto done;
11804 error = check_rebase_or_histedit_in_progress(worktree);
11805 if (error)
11806 goto done;
11808 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11809 NULL, pack_fds);
11810 if (error != NULL)
11811 goto done;
11813 error = apply_unveil(got_repo_get_path(repo), 0,
11814 got_worktree_get_root_path(worktree));
11815 if (error)
11816 goto done;
11818 error = check_merge_in_progress(worktree, repo);
11819 if (error)
11820 goto done;
11822 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11823 error = got_error_from_errno("asprintf");
11824 goto done;
11827 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11828 &base_branch_ref, worktree, refname, repo);
11829 if (error)
11830 goto done;
11832 refname = strdup(got_ref_get_name(branch_ref));
11833 if (refname == NULL) {
11834 error = got_error_from_errno("strdup");
11835 got_worktree_integrate_abort(worktree, fileindex, repo,
11836 branch_ref, base_branch_ref);
11837 goto done;
11839 base_refname = strdup(got_ref_get_name(base_branch_ref));
11840 if (base_refname == NULL) {
11841 error = got_error_from_errno("strdup");
11842 got_worktree_integrate_abort(worktree, fileindex, repo,
11843 branch_ref, base_branch_ref);
11844 goto done;
11847 error = got_ref_resolve(&commit_id, repo, branch_ref);
11848 if (error)
11849 goto done;
11851 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11852 if (error)
11853 goto done;
11855 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11856 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11857 "specified branch has already been integrated");
11858 got_worktree_integrate_abort(worktree, fileindex, repo,
11859 branch_ref, base_branch_ref);
11860 goto done;
11863 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11864 if (error) {
11865 if (error->code == GOT_ERR_ANCESTRY)
11866 error = got_error(GOT_ERR_REBASE_REQUIRED);
11867 got_worktree_integrate_abort(worktree, fileindex, repo,
11868 branch_ref, base_branch_ref);
11869 goto done;
11872 memset(&upa, 0, sizeof(upa));
11873 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11874 branch_ref, base_branch_ref, update_progress, &upa,
11875 check_cancelled, NULL);
11876 if (error)
11877 goto done;
11879 printf("Integrated %s into %s\n", refname, base_refname);
11880 print_update_progress_stats(&upa);
11881 done:
11882 if (repo) {
11883 const struct got_error *close_err = got_repo_close(repo);
11884 if (error == NULL)
11885 error = close_err;
11887 if (worktree)
11888 got_worktree_close(worktree);
11889 if (pack_fds) {
11890 const struct got_error *pack_err =
11891 got_repo_pack_fds_close(pack_fds);
11892 if (error == NULL)
11893 error = pack_err;
11895 free(cwd);
11896 free(base_commit_id);
11897 free(commit_id);
11898 free(refname);
11899 free(base_refname);
11900 return error;
11903 __dead static void
11904 usage_merge(void)
11906 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11907 getprogname());
11908 exit(1);
11911 static const struct got_error *
11912 cmd_merge(int argc, char *argv[])
11914 const struct got_error *error = NULL;
11915 struct got_worktree *worktree = NULL;
11916 struct got_repository *repo = NULL;
11917 struct got_fileindex *fileindex = NULL;
11918 char *cwd = NULL, *id_str = NULL, *author = NULL;
11919 struct got_reference *branch = NULL, *wt_branch = NULL;
11920 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11921 struct got_object_id *wt_branch_tip = NULL;
11922 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11923 int interrupt_merge = 0;
11924 struct got_update_progress_arg upa;
11925 struct got_object_id *merge_commit_id = NULL;
11926 char *branch_name = NULL;
11927 int *pack_fds = NULL;
11929 memset(&upa, 0, sizeof(upa));
11931 while ((ch = getopt(argc, argv, "acn")) != -1) {
11932 switch (ch) {
11933 case 'a':
11934 abort_merge = 1;
11935 break;
11936 case 'c':
11937 continue_merge = 1;
11938 break;
11939 case 'n':
11940 interrupt_merge = 1;
11941 break;
11942 default:
11943 usage_rebase();
11944 /* NOTREACHED */
11948 argc -= optind;
11949 argv += optind;
11951 #ifndef PROFILE
11952 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11953 "unveil", NULL) == -1)
11954 err(1, "pledge");
11955 #endif
11957 if (abort_merge && continue_merge)
11958 option_conflict('a', 'c');
11959 if (abort_merge || continue_merge) {
11960 if (argc != 0)
11961 usage_merge();
11962 } else if (argc != 1)
11963 usage_merge();
11965 cwd = getcwd(NULL, 0);
11966 if (cwd == NULL) {
11967 error = got_error_from_errno("getcwd");
11968 goto done;
11971 error = got_repo_pack_fds_open(&pack_fds);
11972 if (error != NULL)
11973 goto done;
11975 error = got_worktree_open(&worktree, cwd);
11976 if (error) {
11977 if (error->code == GOT_ERR_NOT_WORKTREE)
11978 error = wrap_not_worktree_error(error,
11979 "merge", cwd);
11980 goto done;
11983 error = got_repo_open(&repo,
11984 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11985 pack_fds);
11986 if (error != NULL)
11987 goto done;
11989 error = apply_unveil(got_repo_get_path(repo), 0,
11990 worktree ? got_worktree_get_root_path(worktree) : NULL);
11991 if (error)
11992 goto done;
11994 error = check_rebase_or_histedit_in_progress(worktree);
11995 if (error)
11996 goto done;
11998 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11999 repo);
12000 if (error)
12001 goto done;
12003 if (abort_merge) {
12004 if (!merge_in_progress) {
12005 error = got_error(GOT_ERR_NOT_MERGING);
12006 goto done;
12008 error = got_worktree_merge_continue(&branch_name,
12009 &branch_tip, &fileindex, worktree, repo);
12010 if (error)
12011 goto done;
12012 error = got_worktree_merge_abort(worktree, fileindex, repo,
12013 abort_progress, &upa);
12014 if (error)
12015 goto done;
12016 printf("Merge of %s aborted\n", branch_name);
12017 goto done; /* nothing else to do */
12020 error = get_author(&author, repo, worktree);
12021 if (error)
12022 goto done;
12024 if (continue_merge) {
12025 if (!merge_in_progress) {
12026 error = got_error(GOT_ERR_NOT_MERGING);
12027 goto done;
12029 error = got_worktree_merge_continue(&branch_name,
12030 &branch_tip, &fileindex, worktree, repo);
12031 if (error)
12032 goto done;
12033 } else {
12034 error = got_ref_open(&branch, repo, argv[0], 0);
12035 if (error != NULL)
12036 goto done;
12037 branch_name = strdup(got_ref_get_name(branch));
12038 if (branch_name == NULL) {
12039 error = got_error_from_errno("strdup");
12040 goto done;
12042 error = got_ref_resolve(&branch_tip, repo, branch);
12043 if (error)
12044 goto done;
12047 error = got_ref_open(&wt_branch, repo,
12048 got_worktree_get_head_ref_name(worktree), 0);
12049 if (error)
12050 goto done;
12051 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12052 if (error)
12053 goto done;
12054 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12055 wt_branch_tip, branch_tip, 0, repo,
12056 check_cancelled, NULL);
12057 if (error && error->code != GOT_ERR_ANCESTRY)
12058 goto done;
12060 if (!continue_merge) {
12061 error = check_path_prefix(wt_branch_tip, branch_tip,
12062 got_worktree_get_path_prefix(worktree),
12063 GOT_ERR_MERGE_PATH, repo);
12064 if (error)
12065 goto done;
12066 if (yca_id) {
12067 error = check_same_branch(wt_branch_tip, branch,
12068 yca_id, repo);
12069 if (error) {
12070 if (error->code != GOT_ERR_ANCESTRY)
12071 goto done;
12072 error = NULL;
12073 } else {
12074 static char msg[512];
12075 snprintf(msg, sizeof(msg),
12076 "cannot create a merge commit because "
12077 "%s is based on %s; %s can be integrated "
12078 "with 'got integrate' instead", branch_name,
12079 got_worktree_get_head_ref_name(worktree),
12080 branch_name);
12081 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12082 goto done;
12085 error = got_worktree_merge_prepare(&fileindex, worktree,
12086 branch, repo);
12087 if (error)
12088 goto done;
12090 error = got_worktree_merge_branch(worktree, fileindex,
12091 yca_id, branch_tip, repo, update_progress, &upa,
12092 check_cancelled, NULL);
12093 if (error)
12094 goto done;
12095 print_merge_progress_stats(&upa);
12096 if (!upa.did_something) {
12097 error = got_worktree_merge_abort(worktree, fileindex,
12098 repo, abort_progress, &upa);
12099 if (error)
12100 goto done;
12101 printf("Already up-to-date\n");
12102 goto done;
12106 if (interrupt_merge) {
12107 error = got_worktree_merge_postpone(worktree, fileindex);
12108 if (error)
12109 goto done;
12110 printf("Merge of %s interrupted on request\n", branch_name);
12111 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12112 upa.not_deleted > 0 || upa.unversioned > 0) {
12113 error = got_worktree_merge_postpone(worktree, fileindex);
12114 if (error)
12115 goto done;
12116 if (upa.conflicts > 0 && upa.missing == 0 &&
12117 upa.not_deleted == 0 && upa.unversioned == 0) {
12118 error = got_error_msg(GOT_ERR_CONFLICTS,
12119 "conflicts must be resolved before merging "
12120 "can continue");
12121 } else if (upa.conflicts > 0) {
12122 error = got_error_msg(GOT_ERR_CONFLICTS,
12123 "conflicts must be resolved before merging "
12124 "can continue; changes destined for some "
12125 "files were not yet merged and "
12126 "should be merged manually if required before the "
12127 "merge operation is continued");
12128 } else {
12129 error = got_error_msg(GOT_ERR_CONFLICTS,
12130 "changes destined for some "
12131 "files were not yet merged and should be "
12132 "merged manually if required before the "
12133 "merge operation is continued");
12135 goto done;
12136 } else {
12137 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12138 fileindex, author, NULL, 1, branch_tip, branch_name,
12139 repo, continue_merge ? print_status : NULL, NULL);
12140 if (error)
12141 goto done;
12142 error = got_worktree_merge_complete(worktree, fileindex, repo);
12143 if (error)
12144 goto done;
12145 error = got_object_id_str(&id_str, merge_commit_id);
12146 if (error)
12147 goto done;
12148 printf("Merged %s into %s: %s\n", branch_name,
12149 got_worktree_get_head_ref_name(worktree),
12150 id_str);
12153 done:
12154 free(id_str);
12155 free(merge_commit_id);
12156 free(author);
12157 free(branch_tip);
12158 free(branch_name);
12159 free(yca_id);
12160 if (branch)
12161 got_ref_close(branch);
12162 if (wt_branch)
12163 got_ref_close(wt_branch);
12164 if (worktree)
12165 got_worktree_close(worktree);
12166 if (repo) {
12167 const struct got_error *close_err = got_repo_close(repo);
12168 if (error == NULL)
12169 error = close_err;
12171 if (pack_fds) {
12172 const struct got_error *pack_err =
12173 got_repo_pack_fds_close(pack_fds);
12174 if (error == NULL)
12175 error = pack_err;
12177 return error;
12180 __dead static void
12181 usage_stage(void)
12183 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12184 "[-S] [file-path ...]\n",
12185 getprogname());
12186 exit(1);
12189 static const struct got_error *
12190 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12191 const char *path, struct got_object_id *blob_id,
12192 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12193 int dirfd, const char *de_name)
12195 const struct got_error *err = NULL;
12196 char *id_str = NULL;
12198 if (staged_status != GOT_STATUS_ADD &&
12199 staged_status != GOT_STATUS_MODIFY &&
12200 staged_status != GOT_STATUS_DELETE)
12201 return NULL;
12203 if (staged_status == GOT_STATUS_ADD ||
12204 staged_status == GOT_STATUS_MODIFY)
12205 err = got_object_id_str(&id_str, staged_blob_id);
12206 else
12207 err = got_object_id_str(&id_str, blob_id);
12208 if (err)
12209 return err;
12211 printf("%s %c %s\n", id_str, staged_status, path);
12212 free(id_str);
12213 return NULL;
12216 static const struct got_error *
12217 cmd_stage(int argc, char *argv[])
12219 const struct got_error *error = NULL;
12220 struct got_repository *repo = NULL;
12221 struct got_worktree *worktree = NULL;
12222 char *cwd = NULL;
12223 struct got_pathlist_head paths;
12224 struct got_pathlist_entry *pe;
12225 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12226 FILE *patch_script_file = NULL;
12227 const char *patch_script_path = NULL;
12228 struct choose_patch_arg cpa;
12229 int *pack_fds = NULL;
12231 TAILQ_INIT(&paths);
12233 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12234 switch (ch) {
12235 case 'l':
12236 list_stage = 1;
12237 break;
12238 case 'p':
12239 pflag = 1;
12240 break;
12241 case 'F':
12242 patch_script_path = optarg;
12243 break;
12244 case 'S':
12245 allow_bad_symlinks = 1;
12246 break;
12247 default:
12248 usage_stage();
12249 /* NOTREACHED */
12253 argc -= optind;
12254 argv += optind;
12256 #ifndef PROFILE
12257 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12258 "unveil", NULL) == -1)
12259 err(1, "pledge");
12260 #endif
12261 if (list_stage && (pflag || patch_script_path))
12262 errx(1, "-l option cannot be used with other options");
12263 if (patch_script_path && !pflag)
12264 errx(1, "-F option can only be used together with -p option");
12266 cwd = getcwd(NULL, 0);
12267 if (cwd == NULL) {
12268 error = got_error_from_errno("getcwd");
12269 goto done;
12272 error = got_repo_pack_fds_open(&pack_fds);
12273 if (error != NULL)
12274 goto done;
12276 error = got_worktree_open(&worktree, cwd);
12277 if (error) {
12278 if (error->code == GOT_ERR_NOT_WORKTREE)
12279 error = wrap_not_worktree_error(error, "stage", cwd);
12280 goto done;
12283 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12284 NULL, pack_fds);
12285 if (error != NULL)
12286 goto done;
12288 if (patch_script_path) {
12289 patch_script_file = fopen(patch_script_path, "re");
12290 if (patch_script_file == NULL) {
12291 error = got_error_from_errno2("fopen",
12292 patch_script_path);
12293 goto done;
12296 error = apply_unveil(got_repo_get_path(repo), 0,
12297 got_worktree_get_root_path(worktree));
12298 if (error)
12299 goto done;
12301 error = check_merge_in_progress(worktree, repo);
12302 if (error)
12303 goto done;
12305 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12306 if (error)
12307 goto done;
12309 if (list_stage)
12310 error = got_worktree_status(worktree, &paths, repo, 0,
12311 print_stage, NULL, check_cancelled, NULL);
12312 else {
12313 cpa.patch_script_file = patch_script_file;
12314 cpa.action = "stage";
12315 error = got_worktree_stage(worktree, &paths,
12316 pflag ? NULL : print_status, NULL,
12317 pflag ? choose_patch : NULL, &cpa,
12318 allow_bad_symlinks, repo);
12320 done:
12321 if (patch_script_file && fclose(patch_script_file) == EOF &&
12322 error == NULL)
12323 error = got_error_from_errno2("fclose", patch_script_path);
12324 if (repo) {
12325 const struct got_error *close_err = got_repo_close(repo);
12326 if (error == NULL)
12327 error = close_err;
12329 if (worktree)
12330 got_worktree_close(worktree);
12331 if (pack_fds) {
12332 const struct got_error *pack_err =
12333 got_repo_pack_fds_close(pack_fds);
12334 if (error == NULL)
12335 error = pack_err;
12337 TAILQ_FOREACH(pe, &paths, entry)
12338 free((char *)pe->path);
12339 got_pathlist_free(&paths);
12340 free(cwd);
12341 return error;
12344 __dead static void
12345 usage_unstage(void)
12347 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12348 "[file-path ...]\n",
12349 getprogname());
12350 exit(1);
12354 static const struct got_error *
12355 cmd_unstage(int argc, char *argv[])
12357 const struct got_error *error = NULL;
12358 struct got_repository *repo = NULL;
12359 struct got_worktree *worktree = NULL;
12360 char *cwd = NULL;
12361 struct got_pathlist_head paths;
12362 struct got_pathlist_entry *pe;
12363 int ch, pflag = 0;
12364 struct got_update_progress_arg upa;
12365 FILE *patch_script_file = NULL;
12366 const char *patch_script_path = NULL;
12367 struct choose_patch_arg cpa;
12368 int *pack_fds = NULL;
12370 TAILQ_INIT(&paths);
12372 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12373 switch (ch) {
12374 case 'p':
12375 pflag = 1;
12376 break;
12377 case 'F':
12378 patch_script_path = optarg;
12379 break;
12380 default:
12381 usage_unstage();
12382 /* NOTREACHED */
12386 argc -= optind;
12387 argv += optind;
12389 #ifndef PROFILE
12390 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12391 "unveil", NULL) == -1)
12392 err(1, "pledge");
12393 #endif
12394 if (patch_script_path && !pflag)
12395 errx(1, "-F option can only be used together with -p option");
12397 cwd = getcwd(NULL, 0);
12398 if (cwd == NULL) {
12399 error = got_error_from_errno("getcwd");
12400 goto done;
12403 error = got_repo_pack_fds_open(&pack_fds);
12404 if (error != NULL)
12405 goto done;
12407 error = got_worktree_open(&worktree, cwd);
12408 if (error) {
12409 if (error->code == GOT_ERR_NOT_WORKTREE)
12410 error = wrap_not_worktree_error(error, "unstage", cwd);
12411 goto done;
12414 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12415 NULL, pack_fds);
12416 if (error != NULL)
12417 goto done;
12419 if (patch_script_path) {
12420 patch_script_file = fopen(patch_script_path, "re");
12421 if (patch_script_file == NULL) {
12422 error = got_error_from_errno2("fopen",
12423 patch_script_path);
12424 goto done;
12428 error = apply_unveil(got_repo_get_path(repo), 0,
12429 got_worktree_get_root_path(worktree));
12430 if (error)
12431 goto done;
12433 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12434 if (error)
12435 goto done;
12437 cpa.patch_script_file = patch_script_file;
12438 cpa.action = "unstage";
12439 memset(&upa, 0, sizeof(upa));
12440 error = got_worktree_unstage(worktree, &paths, update_progress,
12441 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12442 if (!error)
12443 print_merge_progress_stats(&upa);
12444 done:
12445 if (patch_script_file && fclose(patch_script_file) == EOF &&
12446 error == NULL)
12447 error = got_error_from_errno2("fclose", patch_script_path);
12448 if (repo) {
12449 const struct got_error *close_err = got_repo_close(repo);
12450 if (error == NULL)
12451 error = close_err;
12453 if (worktree)
12454 got_worktree_close(worktree);
12455 if (pack_fds) {
12456 const struct got_error *pack_err =
12457 got_repo_pack_fds_close(pack_fds);
12458 if (error == NULL)
12459 error = pack_err;
12461 TAILQ_FOREACH(pe, &paths, entry)
12462 free((char *)pe->path);
12463 got_pathlist_free(&paths);
12464 free(cwd);
12465 return error;
12468 __dead static void
12469 usage_cat(void)
12471 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12472 "arg1 [arg2 ...]\n", getprogname());
12473 exit(1);
12476 static const struct got_error *
12477 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12479 const struct got_error *err;
12480 struct got_blob_object *blob;
12481 int fd = -1;
12483 fd = got_opentempfd();
12484 if (fd == -1)
12485 return got_error_from_errno("got_opentempfd");
12487 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12488 if (err)
12489 goto done;
12491 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12492 done:
12493 if (fd != -1 && close(fd) == -1 && err == NULL)
12494 err = got_error_from_errno("close");
12495 if (blob)
12496 got_object_blob_close(blob);
12497 return err;
12500 static const struct got_error *
12501 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12503 const struct got_error *err;
12504 struct got_tree_object *tree;
12505 int nentries, i;
12507 err = got_object_open_as_tree(&tree, repo, id);
12508 if (err)
12509 return err;
12511 nentries = got_object_tree_get_nentries(tree);
12512 for (i = 0; i < nentries; i++) {
12513 struct got_tree_entry *te;
12514 char *id_str;
12515 if (sigint_received || sigpipe_received)
12516 break;
12517 te = got_object_tree_get_entry(tree, i);
12518 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12519 if (err)
12520 break;
12521 fprintf(outfile, "%s %.7o %s\n", id_str,
12522 got_tree_entry_get_mode(te),
12523 got_tree_entry_get_name(te));
12524 free(id_str);
12527 got_object_tree_close(tree);
12528 return err;
12531 static const struct got_error *
12532 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12534 const struct got_error *err;
12535 struct got_commit_object *commit;
12536 const struct got_object_id_queue *parent_ids;
12537 struct got_object_qid *pid;
12538 char *id_str = NULL;
12539 const char *logmsg = NULL;
12540 char gmtoff[6];
12542 err = got_object_open_as_commit(&commit, repo, id);
12543 if (err)
12544 return err;
12546 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12547 if (err)
12548 goto done;
12550 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12551 parent_ids = got_object_commit_get_parent_ids(commit);
12552 fprintf(outfile, "numparents %d\n",
12553 got_object_commit_get_nparents(commit));
12554 STAILQ_FOREACH(pid, parent_ids, entry) {
12555 char *pid_str;
12556 err = got_object_id_str(&pid_str, &pid->id);
12557 if (err)
12558 goto done;
12559 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12560 free(pid_str);
12562 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12563 got_object_commit_get_author_gmtoff(commit));
12564 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12565 got_object_commit_get_author(commit),
12566 (long long)got_object_commit_get_author_time(commit),
12567 gmtoff);
12569 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12570 got_object_commit_get_committer_gmtoff(commit));
12571 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12572 got_object_commit_get_author(commit),
12573 (long long)got_object_commit_get_committer_time(commit),
12574 gmtoff);
12576 logmsg = got_object_commit_get_logmsg_raw(commit);
12577 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12578 fprintf(outfile, "%s", logmsg);
12579 done:
12580 free(id_str);
12581 got_object_commit_close(commit);
12582 return err;
12585 static const struct got_error *
12586 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12588 const struct got_error *err;
12589 struct got_tag_object *tag;
12590 char *id_str = NULL;
12591 const char *tagmsg = NULL;
12592 char gmtoff[6];
12594 err = got_object_open_as_tag(&tag, repo, id);
12595 if (err)
12596 return err;
12598 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12599 if (err)
12600 goto done;
12602 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12604 switch (got_object_tag_get_object_type(tag)) {
12605 case GOT_OBJ_TYPE_BLOB:
12606 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12607 GOT_OBJ_LABEL_BLOB);
12608 break;
12609 case GOT_OBJ_TYPE_TREE:
12610 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12611 GOT_OBJ_LABEL_TREE);
12612 break;
12613 case GOT_OBJ_TYPE_COMMIT:
12614 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12615 GOT_OBJ_LABEL_COMMIT);
12616 break;
12617 case GOT_OBJ_TYPE_TAG:
12618 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12619 GOT_OBJ_LABEL_TAG);
12620 break;
12621 default:
12622 break;
12625 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12626 got_object_tag_get_name(tag));
12628 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12629 got_object_tag_get_tagger_gmtoff(tag));
12630 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12631 got_object_tag_get_tagger(tag),
12632 (long long)got_object_tag_get_tagger_time(tag),
12633 gmtoff);
12635 tagmsg = got_object_tag_get_message(tag);
12636 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12637 fprintf(outfile, "%s", tagmsg);
12638 done:
12639 free(id_str);
12640 got_object_tag_close(tag);
12641 return err;
12644 static const struct got_error *
12645 cmd_cat(int argc, char *argv[])
12647 const struct got_error *error;
12648 struct got_repository *repo = NULL;
12649 struct got_worktree *worktree = NULL;
12650 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12651 const char *commit_id_str = NULL;
12652 struct got_object_id *id = NULL, *commit_id = NULL;
12653 struct got_commit_object *commit = NULL;
12654 int ch, obj_type, i, force_path = 0;
12655 struct got_reflist_head refs;
12656 int *pack_fds = NULL;
12658 TAILQ_INIT(&refs);
12660 #ifndef PROFILE
12661 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12662 NULL) == -1)
12663 err(1, "pledge");
12664 #endif
12666 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12667 switch (ch) {
12668 case 'c':
12669 commit_id_str = optarg;
12670 break;
12671 case 'r':
12672 repo_path = realpath(optarg, NULL);
12673 if (repo_path == NULL)
12674 return got_error_from_errno2("realpath",
12675 optarg);
12676 got_path_strip_trailing_slashes(repo_path);
12677 break;
12678 case 'P':
12679 force_path = 1;
12680 break;
12681 default:
12682 usage_cat();
12683 /* NOTREACHED */
12687 argc -= optind;
12688 argv += optind;
12690 cwd = getcwd(NULL, 0);
12691 if (cwd == NULL) {
12692 error = got_error_from_errno("getcwd");
12693 goto done;
12696 error = got_repo_pack_fds_open(&pack_fds);
12697 if (error != NULL)
12698 goto done;
12700 if (repo_path == NULL) {
12701 error = got_worktree_open(&worktree, cwd);
12702 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12703 goto done;
12704 if (worktree) {
12705 repo_path = strdup(
12706 got_worktree_get_repo_path(worktree));
12707 if (repo_path == NULL) {
12708 error = got_error_from_errno("strdup");
12709 goto done;
12712 /* Release work tree lock. */
12713 got_worktree_close(worktree);
12714 worktree = NULL;
12718 if (repo_path == NULL) {
12719 repo_path = strdup(cwd);
12720 if (repo_path == NULL)
12721 return got_error_from_errno("strdup");
12724 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12725 free(repo_path);
12726 if (error != NULL)
12727 goto done;
12729 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12730 if (error)
12731 goto done;
12733 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12734 if (error)
12735 goto done;
12737 if (commit_id_str == NULL)
12738 commit_id_str = GOT_REF_HEAD;
12739 error = got_repo_match_object_id(&commit_id, NULL,
12740 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12741 if (error)
12742 goto done;
12744 error = got_object_open_as_commit(&commit, repo, commit_id);
12745 if (error)
12746 goto done;
12748 for (i = 0; i < argc; i++) {
12749 if (force_path) {
12750 error = got_object_id_by_path(&id, repo, commit,
12751 argv[i]);
12752 if (error)
12753 break;
12754 } else {
12755 error = got_repo_match_object_id(&id, &label, argv[i],
12756 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12757 repo);
12758 if (error) {
12759 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12760 error->code != GOT_ERR_NOT_REF)
12761 break;
12762 error = got_object_id_by_path(&id, repo,
12763 commit, argv[i]);
12764 if (error)
12765 break;
12769 error = got_object_get_type(&obj_type, repo, id);
12770 if (error)
12771 break;
12773 switch (obj_type) {
12774 case GOT_OBJ_TYPE_BLOB:
12775 error = cat_blob(id, repo, stdout);
12776 break;
12777 case GOT_OBJ_TYPE_TREE:
12778 error = cat_tree(id, repo, stdout);
12779 break;
12780 case GOT_OBJ_TYPE_COMMIT:
12781 error = cat_commit(id, repo, stdout);
12782 break;
12783 case GOT_OBJ_TYPE_TAG:
12784 error = cat_tag(id, repo, stdout);
12785 break;
12786 default:
12787 error = got_error(GOT_ERR_OBJ_TYPE);
12788 break;
12790 if (error)
12791 break;
12792 free(label);
12793 label = NULL;
12794 free(id);
12795 id = NULL;
12797 done:
12798 free(label);
12799 free(id);
12800 free(commit_id);
12801 if (commit)
12802 got_object_commit_close(commit);
12803 if (worktree)
12804 got_worktree_close(worktree);
12805 if (repo) {
12806 const struct got_error *close_err = got_repo_close(repo);
12807 if (error == NULL)
12808 error = close_err;
12810 if (pack_fds) {
12811 const struct got_error *pack_err =
12812 got_repo_pack_fds_close(pack_fds);
12813 if (error == NULL)
12814 error = pack_err;
12817 got_ref_list_free(&refs);
12818 return error;
12821 __dead static void
12822 usage_info(void)
12824 fprintf(stderr, "usage: %s info [path ...]\n",
12825 getprogname());
12826 exit(1);
12829 static const struct got_error *
12830 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12831 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12832 struct got_object_id *commit_id)
12834 const struct got_error *err = NULL;
12835 char *id_str = NULL;
12836 char datebuf[128];
12837 struct tm mytm, *tm;
12838 struct got_pathlist_head *paths = arg;
12839 struct got_pathlist_entry *pe;
12842 * Clear error indication from any of the path arguments which
12843 * would cause this file index entry to be displayed.
12845 TAILQ_FOREACH(pe, paths, entry) {
12846 if (got_path_cmp(path, pe->path, strlen(path),
12847 pe->path_len) == 0 ||
12848 got_path_is_child(path, pe->path, pe->path_len))
12849 pe->data = NULL; /* no error */
12852 printf(GOT_COMMIT_SEP_STR);
12853 if (S_ISLNK(mode))
12854 printf("symlink: %s\n", path);
12855 else if (S_ISREG(mode)) {
12856 printf("file: %s\n", path);
12857 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12858 } else if (S_ISDIR(mode))
12859 printf("directory: %s\n", path);
12860 else
12861 printf("something: %s\n", path);
12863 tm = localtime_r(&mtime, &mytm);
12864 if (tm == NULL)
12865 return NULL;
12866 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12867 return got_error(GOT_ERR_NO_SPACE);
12868 printf("timestamp: %s\n", datebuf);
12870 if (blob_id) {
12871 err = got_object_id_str(&id_str, blob_id);
12872 if (err)
12873 return err;
12874 printf("based on blob: %s\n", id_str);
12875 free(id_str);
12878 if (staged_blob_id) {
12879 err = got_object_id_str(&id_str, staged_blob_id);
12880 if (err)
12881 return err;
12882 printf("based on staged blob: %s\n", id_str);
12883 free(id_str);
12886 if (commit_id) {
12887 err = got_object_id_str(&id_str, commit_id);
12888 if (err)
12889 return err;
12890 printf("based on commit: %s\n", id_str);
12891 free(id_str);
12894 return NULL;
12897 static const struct got_error *
12898 cmd_info(int argc, char *argv[])
12900 const struct got_error *error = NULL;
12901 struct got_worktree *worktree = NULL;
12902 char *cwd = NULL, *id_str = NULL;
12903 struct got_pathlist_head paths;
12904 struct got_pathlist_entry *pe;
12905 char *uuidstr = NULL;
12906 int ch, show_files = 0;
12907 int *pack_fds = NULL;
12909 TAILQ_INIT(&paths);
12911 while ((ch = getopt(argc, argv, "")) != -1) {
12912 switch (ch) {
12913 default:
12914 usage_info();
12915 /* NOTREACHED */
12919 argc -= optind;
12920 argv += optind;
12922 #ifndef PROFILE
12923 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12924 NULL) == -1)
12925 err(1, "pledge");
12926 #endif
12927 cwd = getcwd(NULL, 0);
12928 if (cwd == NULL) {
12929 error = got_error_from_errno("getcwd");
12930 goto done;
12933 error = got_repo_pack_fds_open(&pack_fds);
12934 if (error != NULL)
12935 goto done;
12937 error = got_worktree_open(&worktree, cwd);
12938 if (error) {
12939 if (error->code == GOT_ERR_NOT_WORKTREE)
12940 error = wrap_not_worktree_error(error, "info", cwd);
12941 goto done;
12944 #ifndef PROFILE
12945 /* Remove "cpath" promise. */
12946 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12947 NULL) == -1)
12948 err(1, "pledge");
12949 #endif
12950 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12951 if (error)
12952 goto done;
12954 if (argc >= 1) {
12955 error = get_worktree_paths_from_argv(&paths, argc, argv,
12956 worktree);
12957 if (error)
12958 goto done;
12959 show_files = 1;
12962 error = got_object_id_str(&id_str,
12963 got_worktree_get_base_commit_id(worktree));
12964 if (error)
12965 goto done;
12967 error = got_worktree_get_uuid(&uuidstr, worktree);
12968 if (error)
12969 goto done;
12971 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12972 printf("work tree base commit: %s\n", id_str);
12973 printf("work tree path prefix: %s\n",
12974 got_worktree_get_path_prefix(worktree));
12975 printf("work tree branch reference: %s\n",
12976 got_worktree_get_head_ref_name(worktree));
12977 printf("work tree UUID: %s\n", uuidstr);
12978 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12980 if (show_files) {
12981 struct got_pathlist_entry *pe;
12982 TAILQ_FOREACH(pe, &paths, entry) {
12983 if (pe->path_len == 0)
12984 continue;
12986 * Assume this path will fail. This will be corrected
12987 * in print_path_info() in case the path does suceeed.
12989 pe->data = (void *)got_error_path(pe->path,
12990 GOT_ERR_BAD_PATH);
12992 error = got_worktree_path_info(worktree, &paths,
12993 print_path_info, &paths, check_cancelled, NULL);
12994 if (error)
12995 goto done;
12996 TAILQ_FOREACH(pe, &paths, entry) {
12997 if (pe->data != NULL) {
12998 error = pe->data; /* bad path */
12999 break;
13003 done:
13004 if (pack_fds) {
13005 const struct got_error *pack_err =
13006 got_repo_pack_fds_close(pack_fds);
13007 if (error == NULL)
13008 error = pack_err;
13010 TAILQ_FOREACH(pe, &paths, entry)
13011 free((char *)pe->path);
13012 got_pathlist_free(&paths);
13013 free(cwd);
13014 free(id_str);
13015 free(uuidstr);
13016 return error;