Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/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>
40 #include <util.h>
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int, int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_send(void);
106 __dead static void usage_cherrypick(void);
107 __dead static void usage_backout(void);
108 __dead static void usage_rebase(void);
109 __dead static void usage_histedit(void);
110 __dead static void usage_integrate(void);
111 __dead static void usage_stage(void);
112 __dead static void usage_unstage(void);
113 __dead static void usage_cat(void);
114 __dead static void usage_info(void);
116 static const struct got_error* cmd_init(int, char *[]);
117 static const struct got_error* cmd_import(int, char *[]);
118 static const struct got_error* cmd_clone(int, char *[]);
119 static const struct got_error* cmd_fetch(int, char *[]);
120 static const struct got_error* cmd_checkout(int, char *[]);
121 static const struct got_error* cmd_update(int, char *[]);
122 static const struct got_error* cmd_log(int, char *[]);
123 static const struct got_error* cmd_diff(int, char *[]);
124 static const struct got_error* cmd_blame(int, char *[]);
125 static const struct got_error* cmd_tree(int, char *[]);
126 static const struct got_error* cmd_status(int, char *[]);
127 static const struct got_error* cmd_ref(int, char *[]);
128 static const struct got_error* cmd_branch(int, char *[]);
129 static const struct got_error* cmd_tag(int, char *[]);
130 static const struct got_error* cmd_add(int, char *[]);
131 static const struct got_error* cmd_remove(int, char *[]);
132 static const struct got_error* cmd_revert(int, char *[]);
133 static const struct got_error* cmd_commit(int, char *[]);
134 static const struct got_error* cmd_send(int, char *[]);
135 static const struct got_error* cmd_cherrypick(int, char *[]);
136 static const struct got_error* cmd_backout(int, char *[]);
137 static const struct got_error* cmd_rebase(int, char *[]);
138 static const struct got_error* cmd_histedit(int, char *[]);
139 static const struct got_error* cmd_integrate(int, char *[]);
140 static const struct got_error* cmd_stage(int, char *[]);
141 static const struct got_error* cmd_unstage(int, char *[]);
142 static const struct got_error* cmd_cat(int, char *[]);
143 static const struct got_error* cmd_info(int, char *[]);
145 static struct got_cmd got_commands[] = {
146 { "init", cmd_init, usage_init, "" },
147 { "import", cmd_import, usage_import, "im" },
148 { "clone", cmd_clone, usage_clone, "cl" },
149 { "fetch", cmd_fetch, usage_fetch, "fe" },
150 { "checkout", cmd_checkout, usage_checkout, "co" },
151 { "update", cmd_update, usage_update, "up" },
152 { "log", cmd_log, usage_log, "" },
153 { "diff", cmd_diff, usage_diff, "di" },
154 { "blame", cmd_blame, usage_blame, "bl" },
155 { "tree", cmd_tree, usage_tree, "tr" },
156 { "status", cmd_status, usage_status, "st" },
157 { "ref", cmd_ref, usage_ref, "" },
158 { "branch", cmd_branch, usage_branch, "br" },
159 { "tag", cmd_tag, usage_tag, "" },
160 { "add", cmd_add, usage_add, "" },
161 { "remove", cmd_remove, usage_remove, "rm" },
162 { "revert", cmd_revert, usage_revert, "rv" },
163 { "commit", cmd_commit, usage_commit, "ci" },
164 { "send", cmd_send, usage_send, "se" },
165 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
166 { "backout", cmd_backout, usage_backout, "bo" },
167 { "rebase", cmd_rebase, usage_rebase, "rb" },
168 { "histedit", cmd_histedit, usage_histedit, "he" },
169 { "integrate", cmd_integrate, usage_integrate,"ig" },
170 { "stage", cmd_stage, usage_stage, "sg" },
171 { "unstage", cmd_unstage, usage_unstage, "ug" },
172 { "cat", cmd_cat, usage_cat, "" },
173 { "info", cmd_info, usage_info, "" },
174 };
176 static void
177 list_commands(FILE *fp)
179 size_t i;
181 fprintf(fp, "commands:");
182 for (i = 0; i < nitems(got_commands); i++) {
183 struct got_cmd *cmd = &got_commands[i];
184 fprintf(fp, " %s", cmd->cmd_name);
186 fputc('\n', fp);
189 __dead static void
190 option_conflict(char a, char b)
192 errx(1, "-%c and -%c options are mutually exclusive", a, b);
195 int
196 main(int argc, char *argv[])
198 struct got_cmd *cmd;
199 size_t i;
200 int ch;
201 int hflag = 0, Vflag = 0;
202 static struct option longopts[] = {
203 { "version", no_argument, NULL, 'V' },
204 { NULL, 0, NULL, 0 }
205 };
207 setlocale(LC_CTYPE, "");
209 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
210 switch (ch) {
211 case 'h':
212 hflag = 1;
213 break;
214 case 'V':
215 Vflag = 1;
216 break;
217 default:
218 usage(hflag, 1);
219 /* NOTREACHED */
223 argc -= optind;
224 argv += optind;
225 optind = 1;
226 optreset = 1;
228 if (Vflag) {
229 got_version_print_str();
230 return 0;
233 if (argc <= 0)
234 usage(hflag, hflag ? 0 : 1);
236 signal(SIGINT, catch_sigint);
237 signal(SIGPIPE, catch_sigpipe);
239 for (i = 0; i < nitems(got_commands); i++) {
240 const struct got_error *error;
242 cmd = &got_commands[i];
244 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
245 strcmp(cmd->cmd_alias, argv[0]) != 0)
246 continue;
248 if (hflag)
249 got_commands[i].cmd_usage();
251 error = got_commands[i].cmd_main(argc, argv);
252 if (error && error->code != GOT_ERR_CANCELLED &&
253 error->code != GOT_ERR_PRIVSEP_EXIT &&
254 !(sigpipe_received &&
255 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
256 !(sigint_received &&
257 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
258 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
259 return 1;
262 return 0;
265 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
266 list_commands(stderr);
267 return 1;
270 __dead static void
271 usage(int hflag, int status)
273 FILE *fp = (status == 0) ? stdout : stderr;
275 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
276 getprogname());
277 if (hflag)
278 list_commands(fp);
279 exit(status);
282 static const struct got_error *
283 get_editor(char **abspath)
285 const struct got_error *err = NULL;
286 const char *editor;
288 *abspath = NULL;
290 editor = getenv("VISUAL");
291 if (editor == NULL)
292 editor = getenv("EDITOR");
294 if (editor) {
295 err = got_path_find_prog(abspath, editor);
296 if (err)
297 return err;
300 if (*abspath == NULL) {
301 *abspath = strdup("/bin/ed");
302 if (*abspath == NULL)
303 return got_error_from_errno("strdup");
306 return NULL;
309 static const struct got_error *
310 apply_unveil(const char *repo_path, int repo_read_only,
311 const char *worktree_path)
313 const struct got_error *err;
315 #ifdef PROFILE
316 if (unveil("gmon.out", "rwc") != 0)
317 return got_error_from_errno2("unveil", "gmon.out");
318 #endif
319 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
320 return got_error_from_errno2("unveil", repo_path);
322 if (worktree_path && unveil(worktree_path, "rwc") != 0)
323 return got_error_from_errno2("unveil", worktree_path);
325 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
326 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
328 err = got_privsep_unveil_exec_helpers();
329 if (err != NULL)
330 return err;
332 if (unveil(NULL, NULL) != 0)
333 return got_error_from_errno("unveil");
335 return NULL;
338 __dead static void
339 usage_init(void)
341 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
342 exit(1);
345 static const struct got_error *
346 cmd_init(int argc, char *argv[])
348 const struct got_error *error = NULL;
349 char *repo_path = NULL;
350 int ch;
352 while ((ch = getopt(argc, argv, "")) != -1) {
353 switch (ch) {
354 default:
355 usage_init();
356 /* NOTREACHED */
360 argc -= optind;
361 argv += optind;
363 #ifndef PROFILE
364 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
365 err(1, "pledge");
366 #endif
367 if (argc != 1)
368 usage_init();
370 repo_path = strdup(argv[0]);
371 if (repo_path == NULL)
372 return got_error_from_errno("strdup");
374 got_path_strip_trailing_slashes(repo_path);
376 error = got_path_mkdir(repo_path);
377 if (error &&
378 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
379 goto done;
381 error = apply_unveil(repo_path, 0, NULL);
382 if (error)
383 goto done;
385 error = got_repo_init(repo_path);
386 done:
387 free(repo_path);
388 return error;
391 __dead static void
392 usage_import(void)
394 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
395 "[-r repository-path] [-I pattern] path\n", getprogname());
396 exit(1);
399 int
400 spawn_editor(const char *editor, const char *file)
402 pid_t pid;
403 sig_t sighup, sigint, sigquit;
404 int st = -1;
406 sighup = signal(SIGHUP, SIG_IGN);
407 sigint = signal(SIGINT, SIG_IGN);
408 sigquit = signal(SIGQUIT, SIG_IGN);
410 switch (pid = fork()) {
411 case -1:
412 goto doneediting;
413 case 0:
414 execl(editor, editor, file, (char *)NULL);
415 _exit(127);
418 while (waitpid(pid, &st, 0) == -1)
419 if (errno != EINTR)
420 break;
422 doneediting:
423 (void)signal(SIGHUP, sighup);
424 (void)signal(SIGINT, sigint);
425 (void)signal(SIGQUIT, sigquit);
427 if (!WIFEXITED(st)) {
428 errno = EINTR;
429 return -1;
432 return WEXITSTATUS(st);
435 static const struct got_error *
436 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
437 const char *initial_content, size_t initial_content_len,
438 int require_modification)
440 const struct got_error *err = NULL;
441 char *line = NULL;
442 size_t linesize = 0;
443 ssize_t linelen;
444 struct stat st, st2;
445 FILE *fp = NULL;
446 size_t len, logmsg_len;
447 char *initial_content_stripped = NULL, *buf = NULL, *s;
449 *logmsg = NULL;
451 if (stat(logmsg_path, &st) == -1)
452 return got_error_from_errno2("stat", logmsg_path);
454 if (spawn_editor(editor, logmsg_path) == -1)
455 return got_error_from_errno("failed spawning editor");
457 if (stat(logmsg_path, &st2) == -1)
458 return got_error_from_errno("stat");
460 if (require_modification &&
461 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
462 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
463 "no changes made to commit message, aborting");
465 /*
466 * Set up a stripped version of the initial content without comments
467 * and blank lines. We need this in order to check if the message
468 * has in fact been edited.
469 */
470 initial_content_stripped = malloc(initial_content_len + 1);
471 if (initial_content_stripped == NULL)
472 return got_error_from_errno("malloc");
473 initial_content_stripped[0] = '\0';
475 buf = strdup(initial_content);
476 if (buf == NULL) {
477 err = got_error_from_errno("strdup");
478 goto done;
480 s = buf;
481 len = 0;
482 while ((line = strsep(&s, "\n")) != NULL) {
483 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
484 continue; /* remove comments and leading empty lines */
485 len = strlcat(initial_content_stripped, line,
486 initial_content_len + 1);
487 if (len >= initial_content_len + 1) {
488 err = got_error(GOT_ERR_NO_SPACE);
489 goto done;
492 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
493 initial_content_stripped[len - 1] = '\0';
494 len--;
497 logmsg_len = st2.st_size;
498 *logmsg = malloc(logmsg_len + 1);
499 if (*logmsg == NULL)
500 return got_error_from_errno("malloc");
501 (*logmsg)[0] = '\0';
503 fp = fopen(logmsg_path, "r");
504 if (fp == NULL) {
505 err = got_error_from_errno("fopen");
506 goto done;
509 len = 0;
510 while ((linelen = getline(&line, &linesize, fp)) != -1) {
511 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
512 continue; /* remove comments and leading empty lines */
513 len = strlcat(*logmsg, line, logmsg_len + 1);
514 if (len >= logmsg_len + 1) {
515 err = got_error(GOT_ERR_NO_SPACE);
516 goto done;
519 free(line);
520 if (ferror(fp)) {
521 err = got_ferror(fp, GOT_ERR_IO);
522 goto done;
524 while (len > 0 && (*logmsg)[len - 1] == '\n') {
525 (*logmsg)[len - 1] = '\0';
526 len--;
529 if (len == 0) {
530 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
531 "commit message cannot be empty, aborting");
532 goto done;
534 if (require_modification &&
535 strcmp(*logmsg, initial_content_stripped) == 0)
536 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
537 "no changes made to commit message, aborting");
538 done:
539 free(initial_content_stripped);
540 free(buf);
541 if (fp && fclose(fp) == EOF && err == NULL)
542 err = got_error_from_errno("fclose");
543 if (err) {
544 free(*logmsg);
545 *logmsg = NULL;
547 return err;
550 static const struct got_error *
551 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
552 const char *path_dir, const char *branch_name)
554 char *initial_content = NULL;
555 const struct got_error *err = NULL;
556 int initial_content_len;
557 int fd = -1;
559 initial_content_len = asprintf(&initial_content,
560 "\n# %s to be imported to branch %s\n", path_dir,
561 branch_name);
562 if (initial_content_len == -1)
563 return got_error_from_errno("asprintf");
565 err = got_opentemp_named_fd(logmsg_path, &fd,
566 GOT_TMPDIR_STR "/got-importmsg");
567 if (err)
568 goto done;
570 if (write(fd, initial_content, initial_content_len) == -1) {
571 err = got_error_from_errno2("write", *logmsg_path);
572 goto done;
575 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
576 initial_content_len, 1);
577 done:
578 if (fd != -1 && close(fd) == -1 && err == NULL)
579 err = got_error_from_errno2("close", *logmsg_path);
580 free(initial_content);
581 if (err) {
582 free(*logmsg_path);
583 *logmsg_path = NULL;
585 return err;
588 static const struct got_error *
589 import_progress(void *arg, const char *path)
591 printf("A %s\n", path);
592 return NULL;
595 static const struct got_error *
596 get_author(char **author, struct got_repository *repo,
597 struct got_worktree *worktree)
599 const struct got_error *err = NULL;
600 const char *got_author = NULL, *name, *email;
601 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
603 *author = NULL;
605 if (worktree)
606 worktree_conf = got_worktree_get_gotconfig(worktree);
607 repo_conf = got_repo_get_gotconfig(repo);
609 /*
610 * Priority of potential author information sources, from most
611 * significant to least significant:
612 * 1) work tree's .got/got.conf file
613 * 2) repository's got.conf file
614 * 3) repository's git config file
615 * 4) environment variables
616 * 5) global git config files (in user's home directory or /etc)
617 */
619 if (worktree_conf)
620 got_author = got_gotconfig_get_author(worktree_conf);
621 if (got_author == NULL)
622 got_author = got_gotconfig_get_author(repo_conf);
623 if (got_author == NULL) {
624 name = got_repo_get_gitconfig_author_name(repo);
625 email = got_repo_get_gitconfig_author_email(repo);
626 if (name && email) {
627 if (asprintf(author, "%s <%s>", name, email) == -1)
628 return got_error_from_errno("asprintf");
629 return NULL;
632 got_author = getenv("GOT_AUTHOR");
633 if (got_author == NULL) {
634 name = got_repo_get_global_gitconfig_author_name(repo);
635 email = got_repo_get_global_gitconfig_author_email(
636 repo);
637 if (name && email) {
638 if (asprintf(author, "%s <%s>", name, email)
639 == -1)
640 return got_error_from_errno("asprintf");
641 return NULL;
643 /* TODO: Look up user in password database? */
644 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
648 *author = strdup(got_author);
649 if (*author == NULL)
650 return got_error_from_errno("strdup");
652 /*
653 * Really dumb email address check; we're only doing this to
654 * avoid git's object parser breaking on commits we create.
655 */
656 while (*got_author && *got_author != '<')
657 got_author++;
658 if (*got_author != '<') {
659 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
660 goto done;
662 while (*got_author && *got_author != '@')
663 got_author++;
664 if (*got_author != '@') {
665 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
666 goto done;
668 while (*got_author && *got_author != '>')
669 got_author++;
670 if (*got_author != '>')
671 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
672 done:
673 if (err) {
674 free(*author);
675 *author = NULL;
677 return err;
680 static const struct got_error *
681 get_gitconfig_path(char **gitconfig_path)
683 const char *homedir = getenv("HOME");
685 *gitconfig_path = NULL;
686 if (homedir) {
687 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
688 return got_error_from_errno("asprintf");
691 return NULL;
694 static const struct got_error *
695 cmd_import(int argc, char *argv[])
697 const struct got_error *error = NULL;
698 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
699 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
700 const char *branch_name = "main";
701 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
702 struct got_repository *repo = NULL;
703 struct got_reference *branch_ref = NULL, *head_ref = NULL;
704 struct got_object_id *new_commit_id = NULL;
705 int ch;
706 struct got_pathlist_head ignores;
707 struct got_pathlist_entry *pe;
708 int preserve_logmsg = 0;
710 TAILQ_INIT(&ignores);
712 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
713 switch (ch) {
714 case 'b':
715 branch_name = optarg;
716 break;
717 case 'm':
718 logmsg = strdup(optarg);
719 if (logmsg == NULL) {
720 error = got_error_from_errno("strdup");
721 goto done;
723 break;
724 case 'r':
725 repo_path = realpath(optarg, NULL);
726 if (repo_path == NULL) {
727 error = got_error_from_errno2("realpath",
728 optarg);
729 goto done;
731 break;
732 case 'I':
733 if (optarg[0] == '\0')
734 break;
735 error = got_pathlist_insert(&pe, &ignores, optarg,
736 NULL);
737 if (error)
738 goto done;
739 break;
740 default:
741 usage_import();
742 /* NOTREACHED */
746 argc -= optind;
747 argv += optind;
749 #ifndef PROFILE
750 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
751 "unveil",
752 NULL) == -1)
753 err(1, "pledge");
754 #endif
755 if (argc != 1)
756 usage_import();
758 if (repo_path == NULL) {
759 repo_path = getcwd(NULL, 0);
760 if (repo_path == NULL)
761 return got_error_from_errno("getcwd");
763 got_path_strip_trailing_slashes(repo_path);
764 error = get_gitconfig_path(&gitconfig_path);
765 if (error)
766 goto done;
767 error = got_repo_open(&repo, repo_path, gitconfig_path);
768 if (error)
769 goto done;
771 error = get_author(&author, repo, NULL);
772 if (error)
773 return error;
775 /*
776 * Don't let the user create a branch name with a leading '-'.
777 * While technically a valid reference name, this case is usually
778 * an unintended typo.
779 */
780 if (branch_name[0] == '-')
781 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
783 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
784 error = got_error_from_errno("asprintf");
785 goto done;
788 error = got_ref_open(&branch_ref, repo, refname, 0);
789 if (error) {
790 if (error->code != GOT_ERR_NOT_REF)
791 goto done;
792 } else {
793 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
794 "import target branch already exists");
795 goto done;
798 path_dir = realpath(argv[0], NULL);
799 if (path_dir == NULL) {
800 error = got_error_from_errno2("realpath", argv[0]);
801 goto done;
803 got_path_strip_trailing_slashes(path_dir);
805 /*
806 * unveil(2) traverses exec(2); if an editor is used we have
807 * to apply unveil after the log message has been written.
808 */
809 if (logmsg == NULL || strlen(logmsg) == 0) {
810 error = get_editor(&editor);
811 if (error)
812 goto done;
813 free(logmsg);
814 error = collect_import_msg(&logmsg, &logmsg_path, editor,
815 path_dir, refname);
816 if (error) {
817 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
818 logmsg_path != NULL)
819 preserve_logmsg = 1;
820 goto done;
824 if (unveil(path_dir, "r") != 0) {
825 error = got_error_from_errno2("unveil", path_dir);
826 if (logmsg_path)
827 preserve_logmsg = 1;
828 goto done;
831 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
832 if (error) {
833 if (logmsg_path)
834 preserve_logmsg = 1;
835 goto done;
838 error = got_repo_import(&new_commit_id, path_dir, logmsg,
839 author, &ignores, repo, import_progress, NULL);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
847 if (error) {
848 if (logmsg_path)
849 preserve_logmsg = 1;
850 goto done;
853 error = got_ref_write(branch_ref, repo);
854 if (error) {
855 if (logmsg_path)
856 preserve_logmsg = 1;
857 goto done;
860 error = got_object_id_str(&id_str, new_commit_id);
861 if (error) {
862 if (logmsg_path)
863 preserve_logmsg = 1;
864 goto done;
867 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
868 if (error) {
869 if (error->code != GOT_ERR_NOT_REF) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
876 branch_ref);
877 if (error) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_write(head_ref, repo);
884 if (error) {
885 if (logmsg_path)
886 preserve_logmsg = 1;
887 goto done;
891 printf("Created branch %s with commit %s\n",
892 got_ref_get_name(branch_ref), id_str);
893 done:
894 if (preserve_logmsg) {
895 fprintf(stderr, "%s: log message preserved in %s\n",
896 getprogname(), logmsg_path);
897 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
898 error = got_error_from_errno2("unlink", logmsg_path);
899 free(logmsg);
900 free(logmsg_path);
901 free(repo_path);
902 free(editor);
903 free(refname);
904 free(new_commit_id);
905 free(id_str);
906 free(author);
907 free(gitconfig_path);
908 if (branch_ref)
909 got_ref_close(branch_ref);
910 if (head_ref)
911 got_ref_close(head_ref);
912 return error;
915 __dead static void
916 usage_clone(void)
918 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
919 "[-R reference] repository-url [directory]\n", getprogname());
920 exit(1);
923 struct got_fetch_progress_arg {
924 char last_scaled_size[FMT_SCALED_STRSIZE];
925 int last_p_indexed;
926 int last_p_resolved;
927 int verbosity;
929 struct got_repository *repo;
931 int create_configs;
932 int configs_created;
933 struct {
934 struct got_pathlist_head *symrefs;
935 struct got_pathlist_head *wanted_branches;
936 struct got_pathlist_head *wanted_refs;
937 const char *proto;
938 const char *host;
939 const char *port;
940 const char *remote_repo_path;
941 const char *git_url;
942 int fetch_all_branches;
943 int mirror_references;
944 } config_info;
945 };
947 /* XXX forward declaration */
948 static const struct got_error *
949 create_config_files(const char *proto, const char *host, const char *port,
950 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
951 int mirror_references, struct got_pathlist_head *symrefs,
952 struct got_pathlist_head *wanted_branches,
953 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
955 static const struct got_error *
956 fetch_progress(void *arg, const char *message, off_t packfile_size,
957 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
959 const struct got_error *err = NULL;
960 struct got_fetch_progress_arg *a = arg;
961 char scaled_size[FMT_SCALED_STRSIZE];
962 int p_indexed, p_resolved;
963 int print_size = 0, print_indexed = 0, print_resolved = 0;
965 /*
966 * In order to allow a failed clone to be resumed with 'got fetch'
967 * we try to create configuration files as soon as possible.
968 * Once the server has sent information about its default branch
969 * we have all required information.
970 */
971 if (a->create_configs && !a->configs_created &&
972 !TAILQ_EMPTY(a->config_info.symrefs)) {
973 err = create_config_files(a->config_info.proto,
974 a->config_info.host, a->config_info.port,
975 a->config_info.remote_repo_path,
976 a->config_info.git_url,
977 a->config_info.fetch_all_branches,
978 a->config_info.mirror_references,
979 a->config_info.symrefs,
980 a->config_info.wanted_branches,
981 a->config_info.wanted_refs, a->repo);
982 if (err)
983 return err;
984 a->configs_created = 1;
987 if (a->verbosity < 0)
988 return NULL;
990 if (message && message[0] != '\0') {
991 printf("\rserver: %s", message);
992 fflush(stdout);
993 return NULL;
996 if (packfile_size > 0 || nobj_indexed > 0) {
997 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
998 (a->last_scaled_size[0] == '\0' ||
999 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1000 print_size = 1;
1001 if (strlcpy(a->last_scaled_size, scaled_size,
1002 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1003 return got_error(GOT_ERR_NO_SPACE);
1005 if (nobj_indexed > 0) {
1006 p_indexed = (nobj_indexed * 100) / nobj_total;
1007 if (p_indexed != a->last_p_indexed) {
1008 a->last_p_indexed = p_indexed;
1009 print_indexed = 1;
1010 print_size = 1;
1013 if (nobj_resolved > 0) {
1014 p_resolved = (nobj_resolved * 100) /
1015 (nobj_total - nobj_loose);
1016 if (p_resolved != a->last_p_resolved) {
1017 a->last_p_resolved = p_resolved;
1018 print_resolved = 1;
1019 print_indexed = 1;
1020 print_size = 1;
1025 if (print_size || print_indexed || print_resolved)
1026 printf("\r");
1027 if (print_size)
1028 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1029 if (print_indexed)
1030 printf("; indexing %d%%", p_indexed);
1031 if (print_resolved)
1032 printf("; resolving deltas %d%%", p_resolved);
1033 if (print_size || print_indexed || print_resolved)
1034 fflush(stdout);
1036 return NULL;
1039 static const struct got_error *
1040 create_symref(const char *refname, struct got_reference *target_ref,
1041 int verbosity, struct got_repository *repo)
1043 const struct got_error *err;
1044 struct got_reference *head_symref;
1046 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1047 if (err)
1048 return err;
1050 err = got_ref_write(head_symref, repo);
1051 if (err == NULL && verbosity > 0) {
1052 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1053 got_ref_get_name(target_ref));
1055 got_ref_close(head_symref);
1056 return err;
1059 static const struct got_error *
1060 list_remote_refs(struct got_pathlist_head *symrefs,
1061 struct got_pathlist_head *refs)
1063 const struct got_error *err;
1064 struct got_pathlist_entry *pe;
1066 TAILQ_FOREACH(pe, symrefs, entry) {
1067 const char *refname = pe->path;
1068 const char *targetref = pe->data;
1070 printf("%s: %s\n", refname, targetref);
1073 TAILQ_FOREACH(pe, refs, entry) {
1074 const char *refname = pe->path;
1075 struct got_object_id *id = pe->data;
1076 char *id_str;
1078 err = got_object_id_str(&id_str, id);
1079 if (err)
1080 return err;
1081 printf("%s: %s\n", refname, id_str);
1082 free(id_str);
1085 return NULL;
1088 static const struct got_error *
1089 create_ref(const char *refname, struct got_object_id *id,
1090 int verbosity, struct got_repository *repo)
1092 const struct got_error *err = NULL;
1093 struct got_reference *ref;
1094 char *id_str;
1096 err = got_object_id_str(&id_str, id);
1097 if (err)
1098 return err;
1100 err = got_ref_alloc(&ref, refname, id);
1101 if (err)
1102 goto done;
1104 err = got_ref_write(ref, repo);
1105 got_ref_close(ref);
1107 if (err == NULL && verbosity >= 0)
1108 printf("Created reference %s: %s\n", refname, id_str);
1109 done:
1110 free(id_str);
1111 return err;
1114 static int
1115 match_wanted_ref(const char *refname, const char *wanted_ref)
1117 if (strncmp(refname, "refs/", 5) != 0)
1118 return 0;
1119 refname += 5;
1122 * Prevent fetching of references that won't make any
1123 * sense outside of the remote repository's context.
1125 if (strncmp(refname, "got/", 4) == 0)
1126 return 0;
1127 if (strncmp(refname, "remotes/", 8) == 0)
1128 return 0;
1130 if (strncmp(wanted_ref, "refs/", 5) == 0)
1131 wanted_ref += 5;
1133 /* Allow prefix match. */
1134 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1135 return 1;
1137 /* Allow exact match. */
1138 return (strcmp(refname, wanted_ref) == 0);
1141 static int
1142 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1144 struct got_pathlist_entry *pe;
1146 TAILQ_FOREACH(pe, wanted_refs, entry) {
1147 if (match_wanted_ref(refname, pe->path))
1148 return 1;
1151 return 0;
1154 static const struct got_error *
1155 create_wanted_ref(const char *refname, struct got_object_id *id,
1156 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1158 const struct got_error *err;
1159 char *remote_refname;
1161 if (strncmp("refs/", refname, 5) == 0)
1162 refname += 5;
1164 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1165 remote_repo_name, refname) == -1)
1166 return got_error_from_errno("asprintf");
1168 err = create_ref(remote_refname, id, verbosity, repo);
1169 free(remote_refname);
1170 return err;
1173 static const struct got_error *
1174 create_gotconfig(const char *proto, const char *host, const char *port,
1175 const char *remote_repo_path, const char *default_branch,
1176 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1177 struct got_pathlist_head *wanted_refs, int mirror_references,
1178 struct got_repository *repo)
1180 const struct got_error *err = NULL;
1181 char *gotconfig_path = NULL;
1182 char *gotconfig = NULL;
1183 FILE *gotconfig_file = NULL;
1184 const char *branchname = NULL;
1185 char *branches = NULL, *refs = NULL;
1186 ssize_t n;
1188 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1189 struct got_pathlist_entry *pe;
1190 TAILQ_FOREACH(pe, wanted_branches, entry) {
1191 char *s;
1192 branchname = pe->path;
1193 if (strncmp(branchname, "refs/heads/", 11) == 0)
1194 branchname += 11;
1195 if (asprintf(&s, "%s\"%s\" ",
1196 branches ? branches : "", branchname) == -1) {
1197 err = got_error_from_errno("asprintf");
1198 goto done;
1200 free(branches);
1201 branches = s;
1203 } else if (!fetch_all_branches && default_branch) {
1204 branchname = default_branch;
1205 if (strncmp(branchname, "refs/heads/", 11) == 0)
1206 branchname += 11;
1207 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1208 err = got_error_from_errno("asprintf");
1209 goto done;
1212 if (!TAILQ_EMPTY(wanted_refs)) {
1213 struct got_pathlist_entry *pe;
1214 TAILQ_FOREACH(pe, wanted_refs, entry) {
1215 char *s;
1216 const char *refname = pe->path;
1217 if (strncmp(refname, "refs/", 5) == 0)
1218 branchname += 5;
1219 if (asprintf(&s, "%s\"%s\" ",
1220 refs ? refs : "", refname) == -1) {
1221 err = got_error_from_errno("asprintf");
1222 goto done;
1224 free(refs);
1225 refs = s;
1229 /* Create got.conf(5). */
1230 gotconfig_path = got_repo_get_path_gotconfig(repo);
1231 if (gotconfig_path == NULL) {
1232 err = got_error_from_errno("got_repo_get_path_gotconfig");
1233 goto done;
1235 gotconfig_file = fopen(gotconfig_path, "a");
1236 if (gotconfig_file == NULL) {
1237 err = got_error_from_errno2("fopen", gotconfig_path);
1238 goto done;
1240 if (asprintf(&gotconfig,
1241 "remote \"%s\" {\n"
1242 "\tserver %s\n"
1243 "\tprotocol %s\n"
1244 "%s%s%s"
1245 "\trepository \"%s\"\n"
1246 "%s%s%s"
1247 "%s%s%s"
1248 "%s"
1249 "%s"
1250 "}\n",
1251 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1252 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1253 remote_repo_path, branches ? "\tbranch { " : "",
1254 branches ? branches : "", branches ? "}\n" : "",
1255 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1256 mirror_references ? "\tmirror-references yes\n" : "",
1257 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1258 err = got_error_from_errno("asprintf");
1259 goto done;
1261 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1262 if (n != strlen(gotconfig)) {
1263 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1264 goto done;
1267 done:
1268 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1269 err = got_error_from_errno2("fclose", gotconfig_path);
1270 free(gotconfig_path);
1271 free(branches);
1272 return err;
1275 static const struct got_error *
1276 create_gitconfig(const char *git_url, const char *default_branch,
1277 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1278 struct got_pathlist_head *wanted_refs, int mirror_references,
1279 struct got_repository *repo)
1281 const struct got_error *err = NULL;
1282 char *gitconfig_path = NULL;
1283 char *gitconfig = NULL;
1284 FILE *gitconfig_file = NULL;
1285 char *branches = NULL, *refs = NULL;
1286 const char *branchname;
1287 ssize_t n;
1289 /* Create a config file Git can understand. */
1290 gitconfig_path = got_repo_get_path_gitconfig(repo);
1291 if (gitconfig_path == NULL) {
1292 err = got_error_from_errno("got_repo_get_path_gitconfig");
1293 goto done;
1295 gitconfig_file = fopen(gitconfig_path, "a");
1296 if (gitconfig_file == NULL) {
1297 err = got_error_from_errno2("fopen", gitconfig_path);
1298 goto done;
1300 if (fetch_all_branches) {
1301 if (mirror_references) {
1302 if (asprintf(&branches,
1303 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1304 err = got_error_from_errno("asprintf");
1305 goto done;
1307 } else if (asprintf(&branches,
1308 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1309 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1310 err = got_error_from_errno("asprintf");
1311 goto done;
1313 } else if (!TAILQ_EMPTY(wanted_branches)) {
1314 struct got_pathlist_entry *pe;
1315 TAILQ_FOREACH(pe, wanted_branches, entry) {
1316 char *s;
1317 branchname = pe->path;
1318 if (strncmp(branchname, "refs/heads/", 11) == 0)
1319 branchname += 11;
1320 if (mirror_references) {
1321 if (asprintf(&s,
1322 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1323 branches ? branches : "",
1324 branchname, branchname) == -1) {
1325 err = got_error_from_errno("asprintf");
1326 goto done;
1328 } else if (asprintf(&s,
1329 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1330 branches ? branches : "",
1331 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1332 branchname) == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 free(branches);
1337 branches = s;
1339 } else {
1341 * If the server specified a default branch, use just that one.
1342 * Otherwise fall back to fetching all branches on next fetch.
1344 if (default_branch) {
1345 branchname = default_branch;
1346 if (strncmp(branchname, "refs/heads/", 11) == 0)
1347 branchname += 11;
1348 } else
1349 branchname = "*"; /* fall back to all branches */
1350 if (mirror_references) {
1351 if (asprintf(&branches,
1352 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1353 branchname, branchname) == -1) {
1354 err = got_error_from_errno("asprintf");
1355 goto done;
1357 } else if (asprintf(&branches,
1358 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1359 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1360 branchname) == -1) {
1361 err = got_error_from_errno("asprintf");
1362 goto done;
1365 if (!TAILQ_EMPTY(wanted_refs)) {
1366 struct got_pathlist_entry *pe;
1367 TAILQ_FOREACH(pe, wanted_refs, entry) {
1368 char *s;
1369 const char *refname = pe->path;
1370 if (strncmp(refname, "refs/", 5) == 0)
1371 refname += 5;
1372 if (mirror_references) {
1373 if (asprintf(&s,
1374 "%s\tfetch = refs/%s:refs/%s\n",
1375 refs ? refs : "", refname, refname) == -1) {
1376 err = got_error_from_errno("asprintf");
1377 goto done;
1379 } else if (asprintf(&s,
1380 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1381 refs ? refs : "",
1382 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1383 refname) == -1) {
1384 err = got_error_from_errno("asprintf");
1385 goto done;
1387 free(refs);
1388 refs = s;
1392 if (asprintf(&gitconfig,
1393 "[remote \"%s\"]\n"
1394 "\turl = %s\n"
1395 "%s"
1396 "%s"
1397 "\tfetch = refs/tags/*:refs/tags/*\n",
1398 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1399 refs ? refs : "") == -1) {
1400 err = got_error_from_errno("asprintf");
1401 goto done;
1403 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1404 if (n != strlen(gitconfig)) {
1405 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1406 goto done;
1408 done:
1409 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1410 err = got_error_from_errno2("fclose", gitconfig_path);
1411 free(gitconfig_path);
1412 free(branches);
1413 return err;
1416 static const struct got_error *
1417 create_config_files(const char *proto, const char *host, const char *port,
1418 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1419 int mirror_references, struct got_pathlist_head *symrefs,
1420 struct got_pathlist_head *wanted_branches,
1421 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1423 const struct got_error *err = NULL;
1424 const char *default_branch = NULL;
1425 struct got_pathlist_entry *pe;
1428 * If we asked for a set of wanted branches then use the first
1429 * one of those.
1431 if (!TAILQ_EMPTY(wanted_branches)) {
1432 pe = TAILQ_FIRST(wanted_branches);
1433 default_branch = pe->path;
1434 } else {
1435 /* First HEAD ref listed by server is the default branch. */
1436 TAILQ_FOREACH(pe, symrefs, entry) {
1437 const char *refname = pe->path;
1438 const char *target = pe->data;
1440 if (strcmp(refname, GOT_REF_HEAD) != 0)
1441 continue;
1443 default_branch = target;
1444 break;
1448 /* Create got.conf(5). */
1449 err = create_gotconfig(proto, host, port, remote_repo_path,
1450 default_branch, fetch_all_branches, wanted_branches,
1451 wanted_refs, mirror_references, repo);
1452 if (err)
1453 return err;
1455 /* Create a config file Git can understand. */
1456 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1457 wanted_branches, wanted_refs, mirror_references, repo);
1460 static const struct got_error *
1461 cmd_clone(int argc, char *argv[])
1463 const struct got_error *error = NULL;
1464 const char *uri, *dirname;
1465 char *proto, *host, *port, *repo_name, *server_path;
1466 char *default_destdir = NULL, *id_str = NULL;
1467 const char *repo_path;
1468 struct got_repository *repo = NULL;
1469 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1470 struct got_pathlist_entry *pe;
1471 struct got_object_id *pack_hash = NULL;
1472 int ch, fetchfd = -1, fetchstatus;
1473 pid_t fetchpid = -1;
1474 struct got_fetch_progress_arg fpa;
1475 char *git_url = NULL;
1476 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1477 int list_refs_only = 0;
1479 TAILQ_INIT(&refs);
1480 TAILQ_INIT(&symrefs);
1481 TAILQ_INIT(&wanted_branches);
1482 TAILQ_INIT(&wanted_refs);
1484 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1485 switch (ch) {
1486 case 'a':
1487 fetch_all_branches = 1;
1488 break;
1489 case 'b':
1490 error = got_pathlist_append(&wanted_branches,
1491 optarg, NULL);
1492 if (error)
1493 return error;
1494 break;
1495 case 'l':
1496 list_refs_only = 1;
1497 break;
1498 case 'm':
1499 mirror_references = 1;
1500 break;
1501 case 'v':
1502 if (verbosity < 0)
1503 verbosity = 0;
1504 else if (verbosity < 3)
1505 verbosity++;
1506 break;
1507 case 'q':
1508 verbosity = -1;
1509 break;
1510 case 'R':
1511 error = got_pathlist_append(&wanted_refs,
1512 optarg, NULL);
1513 if (error)
1514 return error;
1515 break;
1516 default:
1517 usage_clone();
1518 break;
1521 argc -= optind;
1522 argv += optind;
1524 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1525 option_conflict('a', 'b');
1526 if (list_refs_only) {
1527 if (!TAILQ_EMPTY(&wanted_branches))
1528 option_conflict('l', 'b');
1529 if (fetch_all_branches)
1530 option_conflict('l', 'a');
1531 if (mirror_references)
1532 option_conflict('l', 'm');
1533 if (!TAILQ_EMPTY(&wanted_refs))
1534 option_conflict('l', 'R');
1537 uri = argv[0];
1539 if (argc == 1)
1540 dirname = NULL;
1541 else if (argc == 2)
1542 dirname = argv[1];
1543 else
1544 usage_clone();
1546 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1547 &repo_name, uri);
1548 if (error)
1549 goto done;
1551 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1552 host, port ? ":" : "", port ? port : "",
1553 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1554 error = got_error_from_errno("asprintf");
1555 goto done;
1558 if (strcmp(proto, "git") == 0) {
1559 #ifndef PROFILE
1560 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1561 "sendfd dns inet unveil", NULL) == -1)
1562 err(1, "pledge");
1563 #endif
1564 } else if (strcmp(proto, "git+ssh") == 0 ||
1565 strcmp(proto, "ssh") == 0) {
1566 #ifndef PROFILE
1567 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1568 "sendfd unveil", NULL) == -1)
1569 err(1, "pledge");
1570 #endif
1571 } else if (strcmp(proto, "http") == 0 ||
1572 strcmp(proto, "git+http") == 0) {
1573 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1574 goto done;
1575 } else {
1576 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1577 goto done;
1579 if (dirname == NULL) {
1580 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1581 error = got_error_from_errno("asprintf");
1582 goto done;
1584 repo_path = default_destdir;
1585 } else
1586 repo_path = dirname;
1588 if (!list_refs_only) {
1589 error = got_path_mkdir(repo_path);
1590 if (error &&
1591 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1592 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1593 goto done;
1594 if (!got_path_dir_is_empty(repo_path)) {
1595 error = got_error_path(repo_path,
1596 GOT_ERR_DIR_NOT_EMPTY);
1597 goto done;
1601 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1602 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1603 error = got_error_from_errno2("unveil",
1604 GOT_FETCH_PATH_SSH);
1605 goto done;
1608 error = apply_unveil(repo_path, 0, NULL);
1609 if (error)
1610 goto done;
1612 if (verbosity >= 0)
1613 printf("Connecting to %s%s%s\n", host,
1614 port ? ":" : "", port ? port : "");
1616 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1617 server_path, verbosity);
1618 if (error)
1619 goto done;
1621 if (!list_refs_only) {
1622 error = got_repo_init(repo_path);
1623 if (error)
1624 goto done;
1625 error = got_repo_open(&repo, repo_path, NULL);
1626 if (error)
1627 goto done;
1630 fpa.last_scaled_size[0] = '\0';
1631 fpa.last_p_indexed = -1;
1632 fpa.last_p_resolved = -1;
1633 fpa.verbosity = verbosity;
1634 fpa.create_configs = 1;
1635 fpa.configs_created = 0;
1636 fpa.repo = repo;
1637 fpa.config_info.symrefs = &symrefs;
1638 fpa.config_info.wanted_branches = &wanted_branches;
1639 fpa.config_info.wanted_refs = &wanted_refs;
1640 fpa.config_info.proto = proto;
1641 fpa.config_info.host = host;
1642 fpa.config_info.port = port;
1643 fpa.config_info.remote_repo_path = server_path;
1644 fpa.config_info.git_url = git_url;
1645 fpa.config_info.fetch_all_branches = fetch_all_branches;
1646 fpa.config_info.mirror_references = mirror_references;
1647 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1648 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1649 fetch_all_branches, &wanted_branches, &wanted_refs,
1650 list_refs_only, verbosity, fetchfd, repo,
1651 fetch_progress, &fpa);
1652 if (error)
1653 goto done;
1655 if (list_refs_only) {
1656 error = list_remote_refs(&symrefs, &refs);
1657 goto done;
1660 error = got_object_id_str(&id_str, pack_hash);
1661 if (error)
1662 goto done;
1663 if (verbosity >= 0)
1664 printf("\nFetched %s.pack\n", id_str);
1665 free(id_str);
1667 /* Set up references provided with the pack file. */
1668 TAILQ_FOREACH(pe, &refs, entry) {
1669 const char *refname = pe->path;
1670 struct got_object_id *id = pe->data;
1671 char *remote_refname;
1673 if (is_wanted_ref(&wanted_refs, refname) &&
1674 !mirror_references) {
1675 error = create_wanted_ref(refname, id,
1676 GOT_FETCH_DEFAULT_REMOTE_NAME,
1677 verbosity - 1, repo);
1678 if (error)
1679 goto done;
1680 continue;
1683 error = create_ref(refname, id, verbosity - 1, repo);
1684 if (error)
1685 goto done;
1687 if (mirror_references)
1688 continue;
1690 if (strncmp("refs/heads/", refname, 11) != 0)
1691 continue;
1693 if (asprintf(&remote_refname,
1694 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1695 refname + 11) == -1) {
1696 error = got_error_from_errno("asprintf");
1697 goto done;
1699 error = create_ref(remote_refname, id, verbosity - 1, repo);
1700 free(remote_refname);
1701 if (error)
1702 goto done;
1705 /* Set the HEAD reference if the server provided one. */
1706 TAILQ_FOREACH(pe, &symrefs, entry) {
1707 struct got_reference *target_ref;
1708 const char *refname = pe->path;
1709 const char *target = pe->data;
1710 char *remote_refname = NULL, *remote_target = NULL;
1712 if (strcmp(refname, GOT_REF_HEAD) != 0)
1713 continue;
1715 error = got_ref_open(&target_ref, repo, target, 0);
1716 if (error) {
1717 if (error->code == GOT_ERR_NOT_REF) {
1718 error = NULL;
1719 continue;
1721 goto done;
1724 error = create_symref(refname, target_ref, verbosity, repo);
1725 got_ref_close(target_ref);
1726 if (error)
1727 goto done;
1729 if (mirror_references)
1730 continue;
1732 if (strncmp("refs/heads/", target, 11) != 0)
1733 continue;
1735 if (asprintf(&remote_refname,
1736 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1737 refname) == -1) {
1738 error = got_error_from_errno("asprintf");
1739 goto done;
1741 if (asprintf(&remote_target,
1742 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1743 target + 11) == -1) {
1744 error = got_error_from_errno("asprintf");
1745 free(remote_refname);
1746 goto done;
1748 error = got_ref_open(&target_ref, repo, remote_target, 0);
1749 if (error) {
1750 free(remote_refname);
1751 free(remote_target);
1752 if (error->code == GOT_ERR_NOT_REF) {
1753 error = NULL;
1754 continue;
1756 goto done;
1758 error = create_symref(remote_refname, target_ref,
1759 verbosity - 1, repo);
1760 free(remote_refname);
1761 free(remote_target);
1762 got_ref_close(target_ref);
1763 if (error)
1764 goto done;
1766 if (pe == NULL) {
1768 * We failed to set the HEAD reference. If we asked for
1769 * a set of wanted branches use the first of one of those
1770 * which could be fetched instead.
1772 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1773 const char *target = pe->path;
1774 struct got_reference *target_ref;
1776 error = got_ref_open(&target_ref, repo, target, 0);
1777 if (error) {
1778 if (error->code == GOT_ERR_NOT_REF) {
1779 error = NULL;
1780 continue;
1782 goto done;
1785 error = create_symref(GOT_REF_HEAD, target_ref,
1786 verbosity, repo);
1787 got_ref_close(target_ref);
1788 if (error)
1789 goto done;
1790 break;
1794 if (verbosity >= 0)
1795 printf("Created %s repository '%s'\n",
1796 mirror_references ? "mirrored" : "cloned", repo_path);
1797 done:
1798 if (fetchpid > 0) {
1799 if (kill(fetchpid, SIGTERM) == -1)
1800 error = got_error_from_errno("kill");
1801 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1802 error = got_error_from_errno("waitpid");
1804 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1805 error = got_error_from_errno("close");
1806 if (repo) {
1807 const struct got_error *close_err = got_repo_close(repo);
1808 if (error == NULL)
1809 error = close_err;
1811 TAILQ_FOREACH(pe, &refs, entry) {
1812 free((void *)pe->path);
1813 free(pe->data);
1815 got_pathlist_free(&refs);
1816 TAILQ_FOREACH(pe, &symrefs, entry) {
1817 free((void *)pe->path);
1818 free(pe->data);
1820 got_pathlist_free(&symrefs);
1821 got_pathlist_free(&wanted_branches);
1822 got_pathlist_free(&wanted_refs);
1823 free(pack_hash);
1824 free(proto);
1825 free(host);
1826 free(port);
1827 free(server_path);
1828 free(repo_name);
1829 free(default_destdir);
1830 free(git_url);
1831 return error;
1834 static const struct got_error *
1835 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1836 int replace_tags, int verbosity, struct got_repository *repo)
1838 const struct got_error *err = NULL;
1839 char *new_id_str = NULL;
1840 struct got_object_id *old_id = NULL;
1842 err = got_object_id_str(&new_id_str, new_id);
1843 if (err)
1844 goto done;
1846 if (!replace_tags &&
1847 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1848 err = got_ref_resolve(&old_id, repo, ref);
1849 if (err)
1850 goto done;
1851 if (got_object_id_cmp(old_id, new_id) == 0)
1852 goto done;
1853 if (verbosity >= 0) {
1854 printf("Rejecting update of existing tag %s: %s\n",
1855 got_ref_get_name(ref), new_id_str);
1857 goto done;
1860 if (got_ref_is_symbolic(ref)) {
1861 if (verbosity >= 0) {
1862 printf("Replacing reference %s: %s\n",
1863 got_ref_get_name(ref),
1864 got_ref_get_symref_target(ref));
1866 err = got_ref_change_symref_to_ref(ref, new_id);
1867 if (err)
1868 goto done;
1869 err = got_ref_write(ref, repo);
1870 if (err)
1871 goto done;
1872 } else {
1873 err = got_ref_resolve(&old_id, repo, ref);
1874 if (err)
1875 goto done;
1876 if (got_object_id_cmp(old_id, new_id) == 0)
1877 goto done;
1879 err = got_ref_change_ref(ref, new_id);
1880 if (err)
1881 goto done;
1882 err = got_ref_write(ref, repo);
1883 if (err)
1884 goto done;
1887 if (verbosity >= 0)
1888 printf("Updated %s: %s\n", got_ref_get_name(ref),
1889 new_id_str);
1890 done:
1891 free(old_id);
1892 free(new_id_str);
1893 return err;
1896 static const struct got_error *
1897 update_symref(const char *refname, struct got_reference *target_ref,
1898 int verbosity, struct got_repository *repo)
1900 const struct got_error *err = NULL, *unlock_err;
1901 struct got_reference *symref;
1902 int symref_is_locked = 0;
1904 err = got_ref_open(&symref, repo, refname, 1);
1905 if (err) {
1906 if (err->code != GOT_ERR_NOT_REF)
1907 return err;
1908 err = got_ref_alloc_symref(&symref, refname, target_ref);
1909 if (err)
1910 goto done;
1912 err = got_ref_write(symref, repo);
1913 if (err)
1914 goto done;
1916 if (verbosity >= 0)
1917 printf("Created reference %s: %s\n",
1918 got_ref_get_name(symref),
1919 got_ref_get_symref_target(symref));
1920 } else {
1921 symref_is_locked = 1;
1923 if (strcmp(got_ref_get_symref_target(symref),
1924 got_ref_get_name(target_ref)) == 0)
1925 goto done;
1927 err = got_ref_change_symref(symref,
1928 got_ref_get_name(target_ref));
1929 if (err)
1930 goto done;
1932 err = got_ref_write(symref, repo);
1933 if (err)
1934 goto done;
1936 if (verbosity >= 0)
1937 printf("Updated %s: %s\n", got_ref_get_name(symref),
1938 got_ref_get_symref_target(symref));
1941 done:
1942 if (symref_is_locked) {
1943 unlock_err = got_ref_unlock(symref);
1944 if (unlock_err && err == NULL)
1945 err = unlock_err;
1947 got_ref_close(symref);
1948 return err;
1951 __dead static void
1952 usage_fetch(void)
1954 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1955 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1956 "[remote-repository-name]\n",
1957 getprogname());
1958 exit(1);
1961 static const struct got_error *
1962 delete_missing_ref(struct got_reference *ref,
1963 int verbosity, struct got_repository *repo)
1965 const struct got_error *err = NULL;
1966 struct got_object_id *id = NULL;
1967 char *id_str = NULL;
1969 if (got_ref_is_symbolic(ref)) {
1970 err = got_ref_delete(ref, repo);
1971 if (err)
1972 return err;
1973 if (verbosity >= 0) {
1974 printf("Deleted %s: %s\n",
1975 got_ref_get_name(ref),
1976 got_ref_get_symref_target(ref));
1978 } else {
1979 err = got_ref_resolve(&id, repo, ref);
1980 if (err)
1981 return err;
1982 err = got_object_id_str(&id_str, id);
1983 if (err)
1984 goto done;
1986 err = got_ref_delete(ref, repo);
1987 if (err)
1988 goto done;
1989 if (verbosity >= 0) {
1990 printf("Deleted %s: %s\n",
1991 got_ref_get_name(ref), id_str);
1994 done:
1995 free(id);
1996 free(id_str);
1997 return NULL;
2000 static const struct got_error *
2001 delete_missing_refs(struct got_pathlist_head *their_refs,
2002 struct got_pathlist_head *their_symrefs,
2003 const struct got_remote_repo *remote,
2004 int verbosity, struct got_repository *repo)
2006 const struct got_error *err = NULL, *unlock_err;
2007 struct got_reflist_head my_refs;
2008 struct got_reflist_entry *re;
2009 struct got_pathlist_entry *pe;
2010 char *remote_namespace = NULL;
2011 char *local_refname = NULL;
2013 TAILQ_INIT(&my_refs);
2015 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2016 == -1)
2017 return got_error_from_errno("asprintf");
2019 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2020 if (err)
2021 goto done;
2023 TAILQ_FOREACH(re, &my_refs, entry) {
2024 const char *refname = got_ref_get_name(re->ref);
2026 if (!remote->mirror_references) {
2027 if (strncmp(refname, remote_namespace,
2028 strlen(remote_namespace)) == 0) {
2029 if (strcmp(refname + strlen(remote_namespace),
2030 GOT_REF_HEAD) == 0)
2031 continue;
2032 if (asprintf(&local_refname, "refs/heads/%s",
2033 refname + strlen(remote_namespace)) == -1) {
2034 err = got_error_from_errno("asprintf");
2035 goto done;
2037 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2038 continue;
2041 TAILQ_FOREACH(pe, their_refs, entry) {
2042 if (strcmp(local_refname, pe->path) == 0)
2043 break;
2045 if (pe != NULL)
2046 continue;
2048 TAILQ_FOREACH(pe, their_symrefs, entry) {
2049 if (strcmp(local_refname, pe->path) == 0)
2050 break;
2052 if (pe != NULL)
2053 continue;
2055 err = delete_missing_ref(re->ref, verbosity, repo);
2056 if (err)
2057 break;
2059 if (local_refname) {
2060 struct got_reference *ref;
2061 err = got_ref_open(&ref, repo, local_refname, 1);
2062 if (err) {
2063 if (err->code != GOT_ERR_NOT_REF)
2064 break;
2065 free(local_refname);
2066 local_refname = NULL;
2067 continue;
2069 err = delete_missing_ref(ref, verbosity, repo);
2070 if (err)
2071 break;
2072 unlock_err = got_ref_unlock(ref);
2073 got_ref_close(ref);
2074 if (unlock_err && err == NULL) {
2075 err = unlock_err;
2076 break;
2079 free(local_refname);
2080 local_refname = NULL;
2083 done:
2084 free(remote_namespace);
2085 free(local_refname);
2086 return err;
2089 static const struct got_error *
2090 update_wanted_ref(const char *refname, struct got_object_id *id,
2091 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2093 const struct got_error *err, *unlock_err;
2094 char *remote_refname;
2095 struct got_reference *ref;
2097 if (strncmp("refs/", refname, 5) == 0)
2098 refname += 5;
2100 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2101 remote_repo_name, refname) == -1)
2102 return got_error_from_errno("asprintf");
2104 err = got_ref_open(&ref, repo, remote_refname, 1);
2105 if (err) {
2106 if (err->code != GOT_ERR_NOT_REF)
2107 goto done;
2108 err = create_ref(remote_refname, id, verbosity, repo);
2109 } else {
2110 err = update_ref(ref, id, 0, verbosity, repo);
2111 unlock_err = got_ref_unlock(ref);
2112 if (unlock_err && err == NULL)
2113 err = unlock_err;
2114 got_ref_close(ref);
2116 done:
2117 free(remote_refname);
2118 return err;
2121 static const struct got_error *
2122 delete_ref(struct got_repository *repo, struct got_reference *ref)
2124 const struct got_error *err = NULL;
2125 struct got_object_id *id = NULL;
2126 char *id_str = NULL;
2127 const char *target;
2129 if (got_ref_is_symbolic(ref)) {
2130 target = got_ref_get_symref_target(ref);
2131 } else {
2132 err = got_ref_resolve(&id, repo, ref);
2133 if (err)
2134 goto done;
2135 err = got_object_id_str(&id_str, id);
2136 if (err)
2137 goto done;
2138 target = id_str;
2141 err = got_ref_delete(ref, repo);
2142 if (err)
2143 goto done;
2145 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2146 done:
2147 free(id);
2148 free(id_str);
2149 return err;
2152 static const struct got_error *
2153 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2155 const struct got_error *err = NULL;
2156 struct got_reflist_head refs;
2157 struct got_reflist_entry *re;
2158 char *prefix;
2160 TAILQ_INIT(&refs);
2162 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2163 err = got_error_from_errno("asprintf");
2164 goto done;
2166 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2167 if (err)
2168 goto done;
2170 TAILQ_FOREACH(re, &refs, entry)
2171 delete_ref(repo, re->ref);
2172 done:
2173 got_ref_list_free(&refs);
2174 return err;
2177 static const struct got_error *
2178 cmd_fetch(int argc, char *argv[])
2180 const struct got_error *error = NULL, *unlock_err;
2181 char *cwd = NULL, *repo_path = NULL;
2182 const char *remote_name;
2183 char *proto = NULL, *host = NULL, *port = NULL;
2184 char *repo_name = NULL, *server_path = NULL;
2185 const struct got_remote_repo *remotes, *remote = NULL;
2186 int nremotes;
2187 char *id_str = NULL;
2188 struct got_repository *repo = NULL;
2189 struct got_worktree *worktree = NULL;
2190 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2191 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2192 struct got_pathlist_entry *pe;
2193 struct got_object_id *pack_hash = NULL;
2194 int i, ch, fetchfd = -1, fetchstatus;
2195 pid_t fetchpid = -1;
2196 struct got_fetch_progress_arg fpa;
2197 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2198 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2200 TAILQ_INIT(&refs);
2201 TAILQ_INIT(&symrefs);
2202 TAILQ_INIT(&wanted_branches);
2203 TAILQ_INIT(&wanted_refs);
2205 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2206 switch (ch) {
2207 case 'a':
2208 fetch_all_branches = 1;
2209 break;
2210 case 'b':
2211 error = got_pathlist_append(&wanted_branches,
2212 optarg, NULL);
2213 if (error)
2214 return error;
2215 break;
2216 case 'd':
2217 delete_refs = 1;
2218 break;
2219 case 'l':
2220 list_refs_only = 1;
2221 break;
2222 case 'r':
2223 repo_path = realpath(optarg, NULL);
2224 if (repo_path == NULL)
2225 return got_error_from_errno2("realpath",
2226 optarg);
2227 got_path_strip_trailing_slashes(repo_path);
2228 break;
2229 case 't':
2230 replace_tags = 1;
2231 break;
2232 case 'v':
2233 if (verbosity < 0)
2234 verbosity = 0;
2235 else if (verbosity < 3)
2236 verbosity++;
2237 break;
2238 case 'q':
2239 verbosity = -1;
2240 break;
2241 case 'R':
2242 error = got_pathlist_append(&wanted_refs,
2243 optarg, NULL);
2244 if (error)
2245 return error;
2246 break;
2247 case 'X':
2248 delete_remote = 1;
2249 break;
2250 default:
2251 usage_fetch();
2252 break;
2255 argc -= optind;
2256 argv += optind;
2258 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2259 option_conflict('a', 'b');
2260 if (list_refs_only) {
2261 if (!TAILQ_EMPTY(&wanted_branches))
2262 option_conflict('l', 'b');
2263 if (fetch_all_branches)
2264 option_conflict('l', 'a');
2265 if (delete_refs)
2266 option_conflict('l', 'd');
2267 if (delete_remote)
2268 option_conflict('l', 'X');
2270 if (delete_remote) {
2271 if (fetch_all_branches)
2272 option_conflict('X', 'a');
2273 if (!TAILQ_EMPTY(&wanted_branches))
2274 option_conflict('X', 'b');
2275 if (delete_refs)
2276 option_conflict('X', 'd');
2277 if (replace_tags)
2278 option_conflict('X', 't');
2279 if (!TAILQ_EMPTY(&wanted_refs))
2280 option_conflict('X', 'R');
2283 if (argc == 0) {
2284 if (delete_remote)
2285 errx(1, "-X option requires a remote name");
2286 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2287 } else if (argc == 1)
2288 remote_name = argv[0];
2289 else
2290 usage_fetch();
2292 cwd = getcwd(NULL, 0);
2293 if (cwd == NULL) {
2294 error = got_error_from_errno("getcwd");
2295 goto done;
2298 if (repo_path == NULL) {
2299 error = got_worktree_open(&worktree, cwd);
2300 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2301 goto done;
2302 else
2303 error = NULL;
2304 if (worktree) {
2305 repo_path =
2306 strdup(got_worktree_get_repo_path(worktree));
2307 if (repo_path == NULL)
2308 error = got_error_from_errno("strdup");
2309 if (error)
2310 goto done;
2311 } else {
2312 repo_path = strdup(cwd);
2313 if (repo_path == NULL) {
2314 error = got_error_from_errno("strdup");
2315 goto done;
2320 error = got_repo_open(&repo, repo_path, NULL);
2321 if (error)
2322 goto done;
2324 if (delete_remote) {
2325 error = delete_refs_for_remote(repo, remote_name);
2326 goto done; /* nothing else to do */
2329 if (worktree) {
2330 worktree_conf = got_worktree_get_gotconfig(worktree);
2331 if (worktree_conf) {
2332 got_gotconfig_get_remotes(&nremotes, &remotes,
2333 worktree_conf);
2334 for (i = 0; i < nremotes; i++) {
2335 if (strcmp(remotes[i].name, remote_name) == 0) {
2336 remote = &remotes[i];
2337 break;
2342 if (remote == NULL) {
2343 repo_conf = got_repo_get_gotconfig(repo);
2344 if (repo_conf) {
2345 got_gotconfig_get_remotes(&nremotes, &remotes,
2346 repo_conf);
2347 for (i = 0; i < nremotes; i++) {
2348 if (strcmp(remotes[i].name, remote_name) == 0) {
2349 remote = &remotes[i];
2350 break;
2355 if (remote == NULL) {
2356 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2357 for (i = 0; i < nremotes; i++) {
2358 if (strcmp(remotes[i].name, remote_name) == 0) {
2359 remote = &remotes[i];
2360 break;
2364 if (remote == NULL) {
2365 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2366 goto done;
2369 if (TAILQ_EMPTY(&wanted_branches)) {
2370 if (!fetch_all_branches)
2371 fetch_all_branches = remote->fetch_all_branches;
2372 for (i = 0; i < remote->nfetch_branches; i++) {
2373 got_pathlist_append(&wanted_branches,
2374 remote->fetch_branches[i], NULL);
2377 if (TAILQ_EMPTY(&wanted_refs)) {
2378 for (i = 0; i < remote->nfetch_refs; i++) {
2379 got_pathlist_append(&wanted_refs,
2380 remote->fetch_refs[i], NULL);
2384 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2385 &repo_name, remote->fetch_url);
2386 if (error)
2387 goto done;
2389 if (strcmp(proto, "git") == 0) {
2390 #ifndef PROFILE
2391 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2392 "sendfd dns inet unveil", NULL) == -1)
2393 err(1, "pledge");
2394 #endif
2395 } else if (strcmp(proto, "git+ssh") == 0 ||
2396 strcmp(proto, "ssh") == 0) {
2397 #ifndef PROFILE
2398 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2399 "sendfd unveil", NULL) == -1)
2400 err(1, "pledge");
2401 #endif
2402 } else if (strcmp(proto, "http") == 0 ||
2403 strcmp(proto, "git+http") == 0) {
2404 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2405 goto done;
2406 } else {
2407 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2408 goto done;
2411 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2412 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2413 error = got_error_from_errno2("unveil",
2414 GOT_FETCH_PATH_SSH);
2415 goto done;
2418 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2419 if (error)
2420 goto done;
2422 if (verbosity >= 0)
2423 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2424 port ? ":" : "", port ? port : "");
2426 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2427 server_path, verbosity);
2428 if (error)
2429 goto done;
2431 fpa.last_scaled_size[0] = '\0';
2432 fpa.last_p_indexed = -1;
2433 fpa.last_p_resolved = -1;
2434 fpa.verbosity = verbosity;
2435 fpa.repo = repo;
2436 fpa.create_configs = 0;
2437 fpa.configs_created = 0;
2438 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2439 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2440 remote->mirror_references, fetch_all_branches, &wanted_branches,
2441 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2442 fetch_progress, &fpa);
2443 if (error)
2444 goto done;
2446 if (list_refs_only) {
2447 error = list_remote_refs(&symrefs, &refs);
2448 goto done;
2451 if (pack_hash == NULL) {
2452 if (verbosity >= 0)
2453 printf("Already up-to-date\n");
2454 } else if (verbosity >= 0) {
2455 error = got_object_id_str(&id_str, pack_hash);
2456 if (error)
2457 goto done;
2458 printf("\nFetched %s.pack\n", id_str);
2459 free(id_str);
2460 id_str = NULL;
2463 /* Update references provided with the pack file. */
2464 TAILQ_FOREACH(pe, &refs, entry) {
2465 const char *refname = pe->path;
2466 struct got_object_id *id = pe->data;
2467 struct got_reference *ref;
2468 char *remote_refname;
2470 if (is_wanted_ref(&wanted_refs, refname) &&
2471 !remote->mirror_references) {
2472 error = update_wanted_ref(refname, id,
2473 remote->name, verbosity, repo);
2474 if (error)
2475 goto done;
2476 continue;
2479 if (remote->mirror_references ||
2480 strncmp("refs/tags/", refname, 10) == 0) {
2481 error = got_ref_open(&ref, repo, refname, 1);
2482 if (error) {
2483 if (error->code != GOT_ERR_NOT_REF)
2484 goto done;
2485 error = create_ref(refname, id, verbosity,
2486 repo);
2487 if (error)
2488 goto done;
2489 } else {
2490 error = update_ref(ref, id, replace_tags,
2491 verbosity, repo);
2492 unlock_err = got_ref_unlock(ref);
2493 if (unlock_err && error == NULL)
2494 error = unlock_err;
2495 got_ref_close(ref);
2496 if (error)
2497 goto done;
2499 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2500 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2501 remote_name, refname + 11) == -1) {
2502 error = got_error_from_errno("asprintf");
2503 goto done;
2506 error = got_ref_open(&ref, repo, remote_refname, 1);
2507 if (error) {
2508 if (error->code != GOT_ERR_NOT_REF)
2509 goto done;
2510 error = create_ref(remote_refname, id,
2511 verbosity, repo);
2512 if (error)
2513 goto done;
2514 } else {
2515 error = update_ref(ref, id, replace_tags,
2516 verbosity, repo);
2517 unlock_err = got_ref_unlock(ref);
2518 if (unlock_err && error == NULL)
2519 error = unlock_err;
2520 got_ref_close(ref);
2521 if (error)
2522 goto done;
2525 /* Also create a local branch if none exists yet. */
2526 error = got_ref_open(&ref, repo, refname, 1);
2527 if (error) {
2528 if (error->code != GOT_ERR_NOT_REF)
2529 goto done;
2530 error = create_ref(refname, id, verbosity,
2531 repo);
2532 if (error)
2533 goto done;
2534 } else {
2535 unlock_err = got_ref_unlock(ref);
2536 if (unlock_err && error == NULL)
2537 error = unlock_err;
2538 got_ref_close(ref);
2542 if (delete_refs) {
2543 error = delete_missing_refs(&refs, &symrefs, remote,
2544 verbosity, repo);
2545 if (error)
2546 goto done;
2549 if (!remote->mirror_references) {
2550 /* Update remote HEAD reference if the server provided one. */
2551 TAILQ_FOREACH(pe, &symrefs, entry) {
2552 struct got_reference *target_ref;
2553 const char *refname = pe->path;
2554 const char *target = pe->data;
2555 char *remote_refname = NULL, *remote_target = NULL;
2557 if (strcmp(refname, GOT_REF_HEAD) != 0)
2558 continue;
2560 if (strncmp("refs/heads/", target, 11) != 0)
2561 continue;
2563 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2564 remote->name, refname) == -1) {
2565 error = got_error_from_errno("asprintf");
2566 goto done;
2568 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2569 remote->name, target + 11) == -1) {
2570 error = got_error_from_errno("asprintf");
2571 free(remote_refname);
2572 goto done;
2575 error = got_ref_open(&target_ref, repo, remote_target,
2576 0);
2577 if (error) {
2578 free(remote_refname);
2579 free(remote_target);
2580 if (error->code == GOT_ERR_NOT_REF) {
2581 error = NULL;
2582 continue;
2584 goto done;
2586 error = update_symref(remote_refname, target_ref,
2587 verbosity, repo);
2588 free(remote_refname);
2589 free(remote_target);
2590 got_ref_close(target_ref);
2591 if (error)
2592 goto done;
2595 done:
2596 if (fetchpid > 0) {
2597 if (kill(fetchpid, SIGTERM) == -1)
2598 error = got_error_from_errno("kill");
2599 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2600 error = got_error_from_errno("waitpid");
2602 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2603 error = got_error_from_errno("close");
2604 if (repo) {
2605 const struct got_error *close_err = got_repo_close(repo);
2606 if (error == NULL)
2607 error = close_err;
2609 if (worktree)
2610 got_worktree_close(worktree);
2611 TAILQ_FOREACH(pe, &refs, entry) {
2612 free((void *)pe->path);
2613 free(pe->data);
2615 got_pathlist_free(&refs);
2616 TAILQ_FOREACH(pe, &symrefs, entry) {
2617 free((void *)pe->path);
2618 free(pe->data);
2620 got_pathlist_free(&symrefs);
2621 got_pathlist_free(&wanted_branches);
2622 got_pathlist_free(&wanted_refs);
2623 free(id_str);
2624 free(cwd);
2625 free(repo_path);
2626 free(pack_hash);
2627 free(proto);
2628 free(host);
2629 free(port);
2630 free(server_path);
2631 free(repo_name);
2632 return error;
2636 __dead static void
2637 usage_checkout(void)
2639 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2640 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2641 exit(1);
2644 static void
2645 show_worktree_base_ref_warning(void)
2647 fprintf(stderr, "%s: warning: could not create a reference "
2648 "to the work tree's base commit; the commit could be "
2649 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2650 "repository writable and running 'got update' will prevent this\n",
2651 getprogname());
2654 struct got_checkout_progress_arg {
2655 const char *worktree_path;
2656 int had_base_commit_ref_error;
2659 static const struct got_error *
2660 checkout_progress(void *arg, unsigned char status, const char *path)
2662 struct got_checkout_progress_arg *a = arg;
2664 /* Base commit bump happens silently. */
2665 if (status == GOT_STATUS_BUMP_BASE)
2666 return NULL;
2668 if (status == GOT_STATUS_BASE_REF_ERR) {
2669 a->had_base_commit_ref_error = 1;
2670 return NULL;
2673 while (path[0] == '/')
2674 path++;
2676 printf("%c %s/%s\n", status, a->worktree_path, path);
2677 return NULL;
2680 static const struct got_error *
2681 check_cancelled(void *arg)
2683 if (sigint_received || sigpipe_received)
2684 return got_error(GOT_ERR_CANCELLED);
2685 return NULL;
2688 static const struct got_error *
2689 check_linear_ancestry(struct got_object_id *commit_id,
2690 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2691 struct got_repository *repo)
2693 const struct got_error *err = NULL;
2694 struct got_object_id *yca_id;
2696 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2697 commit_id, base_commit_id, repo, check_cancelled, NULL);
2698 if (err)
2699 return err;
2701 if (yca_id == NULL)
2702 return got_error(GOT_ERR_ANCESTRY);
2705 * Require a straight line of history between the target commit
2706 * and the work tree's base commit.
2708 * Non-linear situations such as this require a rebase:
2710 * (commit) D F (base_commit)
2711 * \ /
2712 * C E
2713 * \ /
2714 * B (yca)
2715 * |
2716 * A
2718 * 'got update' only handles linear cases:
2719 * Update forwards in time: A (base/yca) - B - C - D (commit)
2720 * Update backwards in time: D (base) - C - B - A (commit/yca)
2722 if (allow_forwards_in_time_only) {
2723 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2724 return got_error(GOT_ERR_ANCESTRY);
2725 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2726 got_object_id_cmp(base_commit_id, yca_id) != 0)
2727 return got_error(GOT_ERR_ANCESTRY);
2729 free(yca_id);
2730 return NULL;
2733 static const struct got_error *
2734 check_same_branch(struct got_object_id *commit_id,
2735 struct got_reference *head_ref, struct got_object_id *yca_id,
2736 struct got_repository *repo)
2738 const struct got_error *err = NULL;
2739 struct got_commit_graph *graph = NULL;
2740 struct got_object_id *head_commit_id = NULL;
2741 int is_same_branch = 0;
2743 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2744 if (err)
2745 goto done;
2747 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2748 is_same_branch = 1;
2749 goto done;
2751 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2752 is_same_branch = 1;
2753 goto done;
2756 err = got_commit_graph_open(&graph, "/", 1);
2757 if (err)
2758 goto done;
2760 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2761 check_cancelled, NULL);
2762 if (err)
2763 goto done;
2765 for (;;) {
2766 struct got_object_id *id;
2767 err = got_commit_graph_iter_next(&id, graph, repo,
2768 check_cancelled, NULL);
2769 if (err) {
2770 if (err->code == GOT_ERR_ITER_COMPLETED)
2771 err = NULL;
2772 break;
2775 if (id) {
2776 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2777 break;
2778 if (got_object_id_cmp(id, commit_id) == 0) {
2779 is_same_branch = 1;
2780 break;
2784 done:
2785 if (graph)
2786 got_commit_graph_close(graph);
2787 free(head_commit_id);
2788 if (!err && !is_same_branch)
2789 err = got_error(GOT_ERR_ANCESTRY);
2790 return err;
2793 static const struct got_error *
2794 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2796 static char msg[512];
2797 const char *branch_name;
2799 if (got_ref_is_symbolic(ref))
2800 branch_name = got_ref_get_symref_target(ref);
2801 else
2802 branch_name = got_ref_get_name(ref);
2804 if (strncmp("refs/heads/", branch_name, 11) == 0)
2805 branch_name += 11;
2807 snprintf(msg, sizeof(msg),
2808 "target commit is not contained in branch '%s'; "
2809 "the branch to use must be specified with -b; "
2810 "if necessary a new branch can be created for "
2811 "this commit with 'got branch -c %s BRANCH_NAME'",
2812 branch_name, commit_id_str);
2814 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2817 static const struct got_error *
2818 cmd_checkout(int argc, char *argv[])
2820 const struct got_error *error = NULL;
2821 struct got_repository *repo = NULL;
2822 struct got_reference *head_ref = NULL;
2823 struct got_worktree *worktree = NULL;
2824 char *repo_path = NULL;
2825 char *worktree_path = NULL;
2826 const char *path_prefix = "";
2827 const char *branch_name = GOT_REF_HEAD;
2828 char *commit_id_str = NULL;
2829 char *cwd = NULL;
2830 int ch, same_path_prefix, allow_nonempty = 0;
2831 struct got_pathlist_head paths;
2832 struct got_checkout_progress_arg cpa;
2834 TAILQ_INIT(&paths);
2836 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2837 switch (ch) {
2838 case 'b':
2839 branch_name = optarg;
2840 break;
2841 case 'c':
2842 commit_id_str = strdup(optarg);
2843 if (commit_id_str == NULL)
2844 return got_error_from_errno("strdup");
2845 break;
2846 case 'E':
2847 allow_nonempty = 1;
2848 break;
2849 case 'p':
2850 path_prefix = optarg;
2851 break;
2852 default:
2853 usage_checkout();
2854 /* NOTREACHED */
2858 argc -= optind;
2859 argv += optind;
2861 #ifndef PROFILE
2862 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2863 "unveil", NULL) == -1)
2864 err(1, "pledge");
2865 #endif
2866 if (argc == 1) {
2867 char *base, *dotgit;
2868 const char *path;
2869 repo_path = realpath(argv[0], NULL);
2870 if (repo_path == NULL)
2871 return got_error_from_errno2("realpath", argv[0]);
2872 cwd = getcwd(NULL, 0);
2873 if (cwd == NULL) {
2874 error = got_error_from_errno("getcwd");
2875 goto done;
2877 if (path_prefix[0])
2878 path = path_prefix;
2879 else
2880 path = repo_path;
2881 error = got_path_basename(&base, path);
2882 if (error)
2883 goto done;
2884 dotgit = strstr(base, ".git");
2885 if (dotgit)
2886 *dotgit = '\0';
2887 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2888 error = got_error_from_errno("asprintf");
2889 free(base);
2890 goto done;
2892 free(base);
2893 } else if (argc == 2) {
2894 repo_path = realpath(argv[0], NULL);
2895 if (repo_path == NULL) {
2896 error = got_error_from_errno2("realpath", argv[0]);
2897 goto done;
2899 worktree_path = realpath(argv[1], NULL);
2900 if (worktree_path == NULL) {
2901 if (errno != ENOENT) {
2902 error = got_error_from_errno2("realpath",
2903 argv[1]);
2904 goto done;
2906 worktree_path = strdup(argv[1]);
2907 if (worktree_path == NULL) {
2908 error = got_error_from_errno("strdup");
2909 goto done;
2912 } else
2913 usage_checkout();
2915 got_path_strip_trailing_slashes(repo_path);
2916 got_path_strip_trailing_slashes(worktree_path);
2918 error = got_repo_open(&repo, repo_path, NULL);
2919 if (error != NULL)
2920 goto done;
2922 /* Pre-create work tree path for unveil(2) */
2923 error = got_path_mkdir(worktree_path);
2924 if (error) {
2925 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2926 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2927 goto done;
2928 if (!allow_nonempty &&
2929 !got_path_dir_is_empty(worktree_path)) {
2930 error = got_error_path(worktree_path,
2931 GOT_ERR_DIR_NOT_EMPTY);
2932 goto done;
2936 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2937 if (error)
2938 goto done;
2940 error = got_ref_open(&head_ref, repo, branch_name, 0);
2941 if (error != NULL)
2942 goto done;
2944 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2945 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2946 goto done;
2948 error = got_worktree_open(&worktree, worktree_path);
2949 if (error != NULL)
2950 goto done;
2952 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2953 path_prefix);
2954 if (error != NULL)
2955 goto done;
2956 if (!same_path_prefix) {
2957 error = got_error(GOT_ERR_PATH_PREFIX);
2958 goto done;
2961 if (commit_id_str) {
2962 struct got_object_id *commit_id;
2963 struct got_reflist_head refs;
2964 TAILQ_INIT(&refs);
2965 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2966 NULL);
2967 if (error)
2968 goto done;
2969 error = got_repo_match_object_id(&commit_id, NULL,
2970 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2971 got_ref_list_free(&refs);
2972 if (error)
2973 goto done;
2974 error = check_linear_ancestry(commit_id,
2975 got_worktree_get_base_commit_id(worktree), 0, repo);
2976 if (error != NULL) {
2977 free(commit_id);
2978 if (error->code == GOT_ERR_ANCESTRY) {
2979 error = checkout_ancestry_error(
2980 head_ref, commit_id_str);
2982 goto done;
2984 error = check_same_branch(commit_id, head_ref, NULL, repo);
2985 if (error) {
2986 if (error->code == GOT_ERR_ANCESTRY) {
2987 error = checkout_ancestry_error(
2988 head_ref, commit_id_str);
2990 goto done;
2992 error = got_worktree_set_base_commit_id(worktree, repo,
2993 commit_id);
2994 free(commit_id);
2995 if (error)
2996 goto done;
2999 error = got_pathlist_append(&paths, "", NULL);
3000 if (error)
3001 goto done;
3002 cpa.worktree_path = worktree_path;
3003 cpa.had_base_commit_ref_error = 0;
3004 error = got_worktree_checkout_files(worktree, &paths, repo,
3005 checkout_progress, &cpa, check_cancelled, NULL);
3006 if (error != NULL)
3007 goto done;
3009 printf("Now shut up and hack\n");
3010 if (cpa.had_base_commit_ref_error)
3011 show_worktree_base_ref_warning();
3012 done:
3013 got_pathlist_free(&paths);
3014 free(commit_id_str);
3015 free(repo_path);
3016 free(worktree_path);
3017 free(cwd);
3018 return error;
3021 struct got_update_progress_arg {
3022 int did_something;
3023 int conflicts;
3024 int obstructed;
3025 int not_updated;
3028 void
3029 print_update_progress_stats(struct got_update_progress_arg *upa)
3031 if (!upa->did_something)
3032 return;
3034 if (upa->conflicts > 0)
3035 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3036 if (upa->obstructed > 0)
3037 printf("File paths obstructed by a non-regular file: %d\n",
3038 upa->obstructed);
3039 if (upa->not_updated > 0)
3040 printf("Files not updated because of existing merge "
3041 "conflicts: %d\n", upa->not_updated);
3044 __dead static void
3045 usage_update(void)
3047 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
3048 getprogname());
3049 exit(1);
3052 static const struct got_error *
3053 update_progress(void *arg, unsigned char status, const char *path)
3055 struct got_update_progress_arg *upa = arg;
3057 if (status == GOT_STATUS_EXISTS ||
3058 status == GOT_STATUS_BASE_REF_ERR)
3059 return NULL;
3061 upa->did_something = 1;
3063 /* Base commit bump happens silently. */
3064 if (status == GOT_STATUS_BUMP_BASE)
3065 return NULL;
3067 if (status == GOT_STATUS_CONFLICT)
3068 upa->conflicts++;
3069 if (status == GOT_STATUS_OBSTRUCTED)
3070 upa->obstructed++;
3071 if (status == GOT_STATUS_CANNOT_UPDATE)
3072 upa->not_updated++;
3074 while (path[0] == '/')
3075 path++;
3076 printf("%c %s\n", status, path);
3077 return NULL;
3080 static const struct got_error *
3081 switch_head_ref(struct got_reference *head_ref,
3082 struct got_object_id *commit_id, struct got_worktree *worktree,
3083 struct got_repository *repo)
3085 const struct got_error *err = NULL;
3086 char *base_id_str;
3087 int ref_has_moved = 0;
3089 /* Trivial case: switching between two different references. */
3090 if (strcmp(got_ref_get_name(head_ref),
3091 got_worktree_get_head_ref_name(worktree)) != 0) {
3092 printf("Switching work tree from %s to %s\n",
3093 got_worktree_get_head_ref_name(worktree),
3094 got_ref_get_name(head_ref));
3095 return got_worktree_set_head_ref(worktree, head_ref);
3098 err = check_linear_ancestry(commit_id,
3099 got_worktree_get_base_commit_id(worktree), 0, repo);
3100 if (err) {
3101 if (err->code != GOT_ERR_ANCESTRY)
3102 return err;
3103 ref_has_moved = 1;
3105 if (!ref_has_moved)
3106 return NULL;
3108 /* Switching to a rebased branch with the same reference name. */
3109 err = got_object_id_str(&base_id_str,
3110 got_worktree_get_base_commit_id(worktree));
3111 if (err)
3112 return err;
3113 printf("Reference %s now points at a different branch\n",
3114 got_worktree_get_head_ref_name(worktree));
3115 printf("Switching work tree from %s to %s\n", base_id_str,
3116 got_worktree_get_head_ref_name(worktree));
3117 return NULL;
3120 static const struct got_error *
3121 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3123 const struct got_error *err;
3124 int in_progress;
3126 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3127 if (err)
3128 return err;
3129 if (in_progress)
3130 return got_error(GOT_ERR_REBASING);
3132 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3133 if (err)
3134 return err;
3135 if (in_progress)
3136 return got_error(GOT_ERR_HISTEDIT_BUSY);
3138 return NULL;
3141 static const struct got_error *
3142 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3143 char *argv[], struct got_worktree *worktree)
3145 const struct got_error *err = NULL;
3146 char *path;
3147 int i;
3149 if (argc == 0) {
3150 path = strdup("");
3151 if (path == NULL)
3152 return got_error_from_errno("strdup");
3153 return got_pathlist_append(paths, path, NULL);
3156 for (i = 0; i < argc; i++) {
3157 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3158 if (err)
3159 break;
3160 err = got_pathlist_append(paths, path, NULL);
3161 if (err) {
3162 free(path);
3163 break;
3167 return err;
3170 static const struct got_error *
3171 wrap_not_worktree_error(const struct got_error *orig_err,
3172 const char *cmdname, const char *path)
3174 const struct got_error *err;
3175 struct got_repository *repo;
3176 static char msg[512];
3178 err = got_repo_open(&repo, path, NULL);
3179 if (err)
3180 return orig_err;
3182 snprintf(msg, sizeof(msg),
3183 "'got %s' needs a work tree in addition to a git repository\n"
3184 "Work trees can be checked out from this Git repository with "
3185 "'got checkout'.\n"
3186 "The got(1) manual page contains more information.", cmdname);
3187 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3188 got_repo_close(repo);
3189 return err;
3192 static const struct got_error *
3193 cmd_update(int argc, char *argv[])
3195 const struct got_error *error = NULL;
3196 struct got_repository *repo = NULL;
3197 struct got_worktree *worktree = NULL;
3198 char *worktree_path = NULL;
3199 struct got_object_id *commit_id = NULL;
3200 char *commit_id_str = NULL;
3201 const char *branch_name = NULL;
3202 struct got_reference *head_ref = NULL;
3203 struct got_pathlist_head paths;
3204 struct got_pathlist_entry *pe;
3205 int ch;
3206 struct got_update_progress_arg upa;
3208 TAILQ_INIT(&paths);
3210 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
3211 switch (ch) {
3212 case 'b':
3213 branch_name = optarg;
3214 break;
3215 case 'c':
3216 commit_id_str = strdup(optarg);
3217 if (commit_id_str == NULL)
3218 return got_error_from_errno("strdup");
3219 break;
3220 default:
3221 usage_update();
3222 /* NOTREACHED */
3226 argc -= optind;
3227 argv += optind;
3229 #ifndef PROFILE
3230 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3231 "unveil", NULL) == -1)
3232 err(1, "pledge");
3233 #endif
3234 worktree_path = getcwd(NULL, 0);
3235 if (worktree_path == NULL) {
3236 error = got_error_from_errno("getcwd");
3237 goto done;
3239 error = got_worktree_open(&worktree, worktree_path);
3240 if (error) {
3241 if (error->code == GOT_ERR_NOT_WORKTREE)
3242 error = wrap_not_worktree_error(error, "update",
3243 worktree_path);
3244 goto done;
3247 error = check_rebase_or_histedit_in_progress(worktree);
3248 if (error)
3249 goto done;
3251 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3252 NULL);
3253 if (error != NULL)
3254 goto done;
3256 error = apply_unveil(got_repo_get_path(repo), 0,
3257 got_worktree_get_root_path(worktree));
3258 if (error)
3259 goto done;
3261 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3262 if (error)
3263 goto done;
3265 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3266 got_worktree_get_head_ref_name(worktree), 0);
3267 if (error != NULL)
3268 goto done;
3269 if (commit_id_str == NULL) {
3270 error = got_ref_resolve(&commit_id, repo, head_ref);
3271 if (error != NULL)
3272 goto done;
3273 error = got_object_id_str(&commit_id_str, commit_id);
3274 if (error != NULL)
3275 goto done;
3276 } else {
3277 struct got_reflist_head refs;
3278 TAILQ_INIT(&refs);
3279 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3280 NULL);
3281 if (error)
3282 goto done;
3283 error = got_repo_match_object_id(&commit_id, NULL,
3284 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3285 got_ref_list_free(&refs);
3286 free(commit_id_str);
3287 commit_id_str = NULL;
3288 if (error)
3289 goto done;
3290 error = got_object_id_str(&commit_id_str, commit_id);
3291 if (error)
3292 goto done;
3295 if (branch_name) {
3296 struct got_object_id *head_commit_id;
3297 TAILQ_FOREACH(pe, &paths, entry) {
3298 if (pe->path_len == 0)
3299 continue;
3300 error = got_error_msg(GOT_ERR_BAD_PATH,
3301 "switching between branches requires that "
3302 "the entire work tree gets updated");
3303 goto done;
3305 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3306 if (error)
3307 goto done;
3308 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3309 repo);
3310 free(head_commit_id);
3311 if (error != NULL)
3312 goto done;
3313 error = check_same_branch(commit_id, head_ref, NULL, repo);
3314 if (error)
3315 goto done;
3316 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3317 if (error)
3318 goto done;
3319 } else {
3320 error = check_linear_ancestry(commit_id,
3321 got_worktree_get_base_commit_id(worktree), 0, repo);
3322 if (error != NULL) {
3323 if (error->code == GOT_ERR_ANCESTRY)
3324 error = got_error(GOT_ERR_BRANCH_MOVED);
3325 goto done;
3327 error = check_same_branch(commit_id, head_ref, NULL, repo);
3328 if (error)
3329 goto done;
3332 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3333 commit_id) != 0) {
3334 error = got_worktree_set_base_commit_id(worktree, repo,
3335 commit_id);
3336 if (error)
3337 goto done;
3340 memset(&upa, 0, sizeof(upa));
3341 error = got_worktree_checkout_files(worktree, &paths, repo,
3342 update_progress, &upa, check_cancelled, NULL);
3343 if (error != NULL)
3344 goto done;
3346 if (upa.did_something)
3347 printf("Updated to commit %s\n", commit_id_str);
3348 else
3349 printf("Already up-to-date\n");
3350 print_update_progress_stats(&upa);
3351 done:
3352 free(worktree_path);
3353 TAILQ_FOREACH(pe, &paths, entry)
3354 free((char *)pe->path);
3355 got_pathlist_free(&paths);
3356 free(commit_id);
3357 free(commit_id_str);
3358 return error;
3361 static const struct got_error *
3362 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3363 const char *path, int diff_context, int ignore_whitespace,
3364 int force_text_diff, struct got_repository *repo)
3366 const struct got_error *err = NULL;
3367 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3369 if (blob_id1) {
3370 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3371 if (err)
3372 goto done;
3375 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3376 if (err)
3377 goto done;
3379 while (path[0] == '/')
3380 path++;
3381 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3382 diff_context, ignore_whitespace, force_text_diff, stdout);
3383 done:
3384 if (blob1)
3385 got_object_blob_close(blob1);
3386 got_object_blob_close(blob2);
3387 return err;
3390 static const struct got_error *
3391 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3392 const char *path, int diff_context, int ignore_whitespace,
3393 int force_text_diff, struct got_repository *repo)
3395 const struct got_error *err = NULL;
3396 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3397 struct got_diff_blob_output_unidiff_arg arg;
3399 if (tree_id1) {
3400 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3401 if (err)
3402 goto done;
3405 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3406 if (err)
3407 goto done;
3409 arg.diff_context = diff_context;
3410 arg.ignore_whitespace = ignore_whitespace;
3411 arg.force_text_diff = force_text_diff;
3412 arg.outfile = stdout;
3413 arg.line_offsets = NULL;
3414 arg.nlines = 0;
3415 while (path[0] == '/')
3416 path++;
3417 err = got_diff_tree(tree1, tree2, path, path, repo,
3418 got_diff_blob_output_unidiff, &arg, 1);
3419 done:
3420 if (tree1)
3421 got_object_tree_close(tree1);
3422 if (tree2)
3423 got_object_tree_close(tree2);
3424 return err;
3427 static const struct got_error *
3428 get_changed_paths(struct got_pathlist_head *paths,
3429 struct got_commit_object *commit, struct got_repository *repo)
3431 const struct got_error *err = NULL;
3432 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3433 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3434 struct got_object_qid *qid;
3436 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3437 if (qid != NULL) {
3438 struct got_commit_object *pcommit;
3439 err = got_object_open_as_commit(&pcommit, repo,
3440 qid->id);
3441 if (err)
3442 return err;
3444 tree_id1 = got_object_id_dup(
3445 got_object_commit_get_tree_id(pcommit));
3446 if (tree_id1 == NULL) {
3447 got_object_commit_close(pcommit);
3448 return got_error_from_errno("got_object_id_dup");
3450 got_object_commit_close(pcommit);
3454 if (tree_id1) {
3455 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3456 if (err)
3457 goto done;
3460 tree_id2 = got_object_commit_get_tree_id(commit);
3461 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3462 if (err)
3463 goto done;
3465 err = got_diff_tree(tree1, tree2, "", "", repo,
3466 got_diff_tree_collect_changed_paths, paths, 0);
3467 done:
3468 if (tree1)
3469 got_object_tree_close(tree1);
3470 if (tree2)
3471 got_object_tree_close(tree2);
3472 free(tree_id1);
3473 return err;
3476 static const struct got_error *
3477 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3478 const char *path, int diff_context, struct got_repository *repo)
3480 const struct got_error *err = NULL;
3481 struct got_commit_object *pcommit = NULL;
3482 char *id_str1 = NULL, *id_str2 = NULL;
3483 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3484 struct got_object_qid *qid;
3486 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3487 if (qid != NULL) {
3488 err = got_object_open_as_commit(&pcommit, repo,
3489 qid->id);
3490 if (err)
3491 return err;
3494 if (path && path[0] != '\0') {
3495 int obj_type;
3496 err = got_object_id_by_path(&obj_id2, repo, id, path);
3497 if (err)
3498 goto done;
3499 err = got_object_id_str(&id_str2, obj_id2);
3500 if (err) {
3501 free(obj_id2);
3502 goto done;
3504 if (pcommit) {
3505 err = got_object_id_by_path(&obj_id1, repo,
3506 qid->id, path);
3507 if (err) {
3508 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3509 free(obj_id2);
3510 goto done;
3512 } else {
3513 err = got_object_id_str(&id_str1, obj_id1);
3514 if (err) {
3515 free(obj_id2);
3516 goto done;
3520 err = got_object_get_type(&obj_type, repo, obj_id2);
3521 if (err) {
3522 free(obj_id2);
3523 goto done;
3525 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3526 switch (obj_type) {
3527 case GOT_OBJ_TYPE_BLOB:
3528 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3529 0, 0, repo);
3530 break;
3531 case GOT_OBJ_TYPE_TREE:
3532 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3533 0, 0, repo);
3534 break;
3535 default:
3536 err = got_error(GOT_ERR_OBJ_TYPE);
3537 break;
3539 free(obj_id1);
3540 free(obj_id2);
3541 } else {
3542 obj_id2 = got_object_commit_get_tree_id(commit);
3543 err = got_object_id_str(&id_str2, obj_id2);
3544 if (err)
3545 goto done;
3546 if (pcommit) {
3547 obj_id1 = got_object_commit_get_tree_id(pcommit);
3548 err = got_object_id_str(&id_str1, obj_id1);
3549 if (err)
3550 goto done;
3552 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3553 id_str2);
3554 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3555 repo);
3557 done:
3558 free(id_str1);
3559 free(id_str2);
3560 if (pcommit)
3561 got_object_commit_close(pcommit);
3562 return err;
3565 static char *
3566 get_datestr(time_t *time, char *datebuf)
3568 struct tm mytm, *tm;
3569 char *p, *s;
3571 tm = gmtime_r(time, &mytm);
3572 if (tm == NULL)
3573 return NULL;
3574 s = asctime_r(tm, datebuf);
3575 if (s == NULL)
3576 return NULL;
3577 p = strchr(s, '\n');
3578 if (p)
3579 *p = '\0';
3580 return s;
3583 static const struct got_error *
3584 match_logmsg(int *have_match, struct got_object_id *id,
3585 struct got_commit_object *commit, regex_t *regex)
3587 const struct got_error *err = NULL;
3588 regmatch_t regmatch;
3589 char *id_str = NULL, *logmsg = NULL;
3591 *have_match = 0;
3593 err = got_object_id_str(&id_str, id);
3594 if (err)
3595 return err;
3597 err = got_object_commit_get_logmsg(&logmsg, commit);
3598 if (err)
3599 goto done;
3601 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3602 *have_match = 1;
3603 done:
3604 free(id_str);
3605 free(logmsg);
3606 return err;
3609 static void
3610 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3611 regex_t *regex)
3613 regmatch_t regmatch;
3614 struct got_pathlist_entry *pe;
3616 *have_match = 0;
3618 TAILQ_FOREACH(pe, changed_paths, entry) {
3619 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3620 *have_match = 1;
3621 break;
3626 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3628 static const struct got_error*
3629 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3630 struct got_object_id *id, struct got_repository *repo)
3632 static const struct got_error *err = NULL;
3633 struct got_reflist_entry *re;
3634 char *s;
3635 const char *name;
3637 *refs_str = NULL;
3639 TAILQ_FOREACH(re, refs, entry) {
3640 struct got_tag_object *tag = NULL;
3641 struct got_object_id *ref_id;
3642 int cmp;
3644 name = got_ref_get_name(re->ref);
3645 if (strcmp(name, GOT_REF_HEAD) == 0)
3646 continue;
3647 if (strncmp(name, "refs/", 5) == 0)
3648 name += 5;
3649 if (strncmp(name, "got/", 4) == 0)
3650 continue;
3651 if (strncmp(name, "heads/", 6) == 0)
3652 name += 6;
3653 if (strncmp(name, "remotes/", 8) == 0) {
3654 name += 8;
3655 s = strstr(name, "/" GOT_REF_HEAD);
3656 if (s != NULL && s[strlen(s)] == '\0')
3657 continue;
3659 err = got_ref_resolve(&ref_id, repo, re->ref);
3660 if (err)
3661 break;
3662 if (strncmp(name, "tags/", 5) == 0) {
3663 err = got_object_open_as_tag(&tag, repo, ref_id);
3664 if (err) {
3665 if (err->code != GOT_ERR_OBJ_TYPE) {
3666 free(ref_id);
3667 break;
3669 /* Ref points at something other than a tag. */
3670 err = NULL;
3671 tag = NULL;
3674 cmp = got_object_id_cmp(tag ?
3675 got_object_tag_get_object_id(tag) : ref_id, id);
3676 free(ref_id);
3677 if (tag)
3678 got_object_tag_close(tag);
3679 if (cmp != 0)
3680 continue;
3681 s = *refs_str;
3682 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3683 s ? ", " : "", name) == -1) {
3684 err = got_error_from_errno("asprintf");
3685 free(s);
3686 *refs_str = NULL;
3687 break;
3689 free(s);
3692 return err;
3695 static const struct got_error *
3696 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3697 struct got_repository *repo, const char *path,
3698 struct got_pathlist_head *changed_paths, int show_patch,
3699 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3700 const char *custom_refs_str)
3702 const struct got_error *err = NULL;
3703 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3704 char datebuf[26];
3705 time_t committer_time;
3706 const char *author, *committer;
3707 char *refs_str = NULL;
3709 err = got_object_id_str(&id_str, id);
3710 if (err)
3711 return err;
3713 if (custom_refs_str == NULL) {
3714 struct got_reflist_head *refs;
3715 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3716 if (refs) {
3717 err = build_refs_str(&refs_str, refs, id, repo);
3718 if (err)
3719 goto done;
3723 printf(GOT_COMMIT_SEP_STR);
3724 if (custom_refs_str)
3725 printf("commit %s (%s)\n", id_str, custom_refs_str);
3726 else
3727 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3728 refs_str ? refs_str : "", refs_str ? ")" : "");
3729 free(id_str);
3730 id_str = NULL;
3731 free(refs_str);
3732 refs_str = NULL;
3733 printf("from: %s\n", got_object_commit_get_author(commit));
3734 committer_time = got_object_commit_get_committer_time(commit);
3735 datestr = get_datestr(&committer_time, datebuf);
3736 if (datestr)
3737 printf("date: %s UTC\n", datestr);
3738 author = got_object_commit_get_author(commit);
3739 committer = got_object_commit_get_committer(commit);
3740 if (strcmp(author, committer) != 0)
3741 printf("via: %s\n", committer);
3742 if (got_object_commit_get_nparents(commit) > 1) {
3743 const struct got_object_id_queue *parent_ids;
3744 struct got_object_qid *qid;
3745 int n = 1;
3746 parent_ids = got_object_commit_get_parent_ids(commit);
3747 STAILQ_FOREACH(qid, parent_ids, entry) {
3748 err = got_object_id_str(&id_str, qid->id);
3749 if (err)
3750 goto done;
3751 printf("parent %d: %s\n", n++, id_str);
3752 free(id_str);
3753 id_str = NULL;
3757 err = got_object_commit_get_logmsg(&logmsg0, commit);
3758 if (err)
3759 goto done;
3761 logmsg = logmsg0;
3762 do {
3763 line = strsep(&logmsg, "\n");
3764 if (line)
3765 printf(" %s\n", line);
3766 } while (line);
3767 free(logmsg0);
3769 if (changed_paths) {
3770 struct got_pathlist_entry *pe;
3771 TAILQ_FOREACH(pe, changed_paths, entry) {
3772 struct got_diff_changed_path *cp = pe->data;
3773 printf(" %c %s\n", cp->status, pe->path);
3775 printf("\n");
3777 if (show_patch) {
3778 err = print_patch(commit, id, path, diff_context, repo);
3779 if (err == 0)
3780 printf("\n");
3783 if (fflush(stdout) != 0 && err == NULL)
3784 err = got_error_from_errno("fflush");
3785 done:
3786 free(id_str);
3787 free(refs_str);
3788 return err;
3791 static const struct got_error *
3792 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3793 struct got_repository *repo, const char *path, int show_changed_paths,
3794 int show_patch, const char *search_pattern, int diff_context, int limit,
3795 int log_branches, int reverse_display_order,
3796 struct got_reflist_object_id_map *refs_idmap)
3798 const struct got_error *err;
3799 struct got_commit_graph *graph;
3800 regex_t regex;
3801 int have_match;
3802 struct got_object_id_queue reversed_commits;
3803 struct got_object_qid *qid;
3804 struct got_commit_object *commit;
3805 struct got_pathlist_head changed_paths;
3806 struct got_pathlist_entry *pe;
3808 STAILQ_INIT(&reversed_commits);
3809 TAILQ_INIT(&changed_paths);
3811 if (search_pattern && regcomp(&regex, search_pattern,
3812 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3813 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3815 err = got_commit_graph_open(&graph, path, !log_branches);
3816 if (err)
3817 return err;
3818 err = got_commit_graph_iter_start(graph, root_id, repo,
3819 check_cancelled, NULL);
3820 if (err)
3821 goto done;
3822 for (;;) {
3823 struct got_object_id *id;
3825 if (sigint_received || sigpipe_received)
3826 break;
3828 err = got_commit_graph_iter_next(&id, graph, repo,
3829 check_cancelled, NULL);
3830 if (err) {
3831 if (err->code == GOT_ERR_ITER_COMPLETED)
3832 err = NULL;
3833 break;
3835 if (id == NULL)
3836 break;
3838 err = got_object_open_as_commit(&commit, repo, id);
3839 if (err)
3840 break;
3842 if (show_changed_paths && !reverse_display_order) {
3843 err = get_changed_paths(&changed_paths, commit, repo);
3844 if (err)
3845 break;
3848 if (search_pattern) {
3849 err = match_logmsg(&have_match, id, commit, &regex);
3850 if (err) {
3851 got_object_commit_close(commit);
3852 break;
3854 if (have_match == 0 && show_changed_paths)
3855 match_changed_paths(&have_match,
3856 &changed_paths, &regex);
3857 if (have_match == 0) {
3858 got_object_commit_close(commit);
3859 TAILQ_FOREACH(pe, &changed_paths, entry) {
3860 free((char *)pe->path);
3861 free(pe->data);
3863 got_pathlist_free(&changed_paths);
3864 continue;
3868 if (reverse_display_order) {
3869 err = got_object_qid_alloc(&qid, id);
3870 if (err)
3871 break;
3872 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3873 got_object_commit_close(commit);
3874 } else {
3875 err = print_commit(commit, id, repo, path,
3876 show_changed_paths ? &changed_paths : NULL,
3877 show_patch, diff_context, refs_idmap, NULL);
3878 got_object_commit_close(commit);
3879 if (err)
3880 break;
3882 if ((limit && --limit == 0) ||
3883 (end_id && got_object_id_cmp(id, end_id) == 0))
3884 break;
3886 TAILQ_FOREACH(pe, &changed_paths, entry) {
3887 free((char *)pe->path);
3888 free(pe->data);
3890 got_pathlist_free(&changed_paths);
3892 if (reverse_display_order) {
3893 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3894 err = got_object_open_as_commit(&commit, repo, qid->id);
3895 if (err)
3896 break;
3897 if (show_changed_paths) {
3898 err = get_changed_paths(&changed_paths,
3899 commit, repo);
3900 if (err)
3901 break;
3903 err = print_commit(commit, qid->id, repo, path,
3904 show_changed_paths ? &changed_paths : NULL,
3905 show_patch, diff_context, refs_idmap, NULL);
3906 got_object_commit_close(commit);
3907 if (err)
3908 break;
3909 TAILQ_FOREACH(pe, &changed_paths, entry) {
3910 free((char *)pe->path);
3911 free(pe->data);
3913 got_pathlist_free(&changed_paths);
3916 done:
3917 while (!STAILQ_EMPTY(&reversed_commits)) {
3918 qid = STAILQ_FIRST(&reversed_commits);
3919 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3920 got_object_qid_free(qid);
3922 TAILQ_FOREACH(pe, &changed_paths, entry) {
3923 free((char *)pe->path);
3924 free(pe->data);
3926 got_pathlist_free(&changed_paths);
3927 if (search_pattern)
3928 regfree(&regex);
3929 got_commit_graph_close(graph);
3930 return err;
3933 __dead static void
3934 usage_log(void)
3936 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3937 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3938 "[-R] [path]\n", getprogname());
3939 exit(1);
3942 static int
3943 get_default_log_limit(void)
3945 const char *got_default_log_limit;
3946 long long n;
3947 const char *errstr;
3949 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3950 if (got_default_log_limit == NULL)
3951 return 0;
3952 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3953 if (errstr != NULL)
3954 return 0;
3955 return n;
3958 static const struct got_error *
3959 cmd_log(int argc, char *argv[])
3961 const struct got_error *error;
3962 struct got_repository *repo = NULL;
3963 struct got_worktree *worktree = NULL;
3964 struct got_object_id *start_id = NULL, *end_id = NULL;
3965 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3966 const char *start_commit = NULL, *end_commit = NULL;
3967 const char *search_pattern = NULL;
3968 int diff_context = -1, ch;
3969 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3970 int reverse_display_order = 0;
3971 const char *errstr;
3972 struct got_reflist_head refs;
3973 struct got_reflist_object_id_map *refs_idmap = NULL;
3975 TAILQ_INIT(&refs);
3977 #ifndef PROFILE
3978 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3979 NULL)
3980 == -1)
3981 err(1, "pledge");
3982 #endif
3984 limit = get_default_log_limit();
3986 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3987 switch (ch) {
3988 case 'p':
3989 show_patch = 1;
3990 break;
3991 case 'P':
3992 show_changed_paths = 1;
3993 break;
3994 case 'c':
3995 start_commit = optarg;
3996 break;
3997 case 'C':
3998 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3999 &errstr);
4000 if (errstr != NULL)
4001 err(1, "-C option %s", errstr);
4002 break;
4003 case 'l':
4004 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4005 if (errstr != NULL)
4006 err(1, "-l option %s", errstr);
4007 break;
4008 case 'b':
4009 log_branches = 1;
4010 break;
4011 case 'r':
4012 repo_path = realpath(optarg, NULL);
4013 if (repo_path == NULL)
4014 return got_error_from_errno2("realpath",
4015 optarg);
4016 got_path_strip_trailing_slashes(repo_path);
4017 break;
4018 case 'R':
4019 reverse_display_order = 1;
4020 break;
4021 case 's':
4022 search_pattern = optarg;
4023 break;
4024 case 'x':
4025 end_commit = optarg;
4026 break;
4027 default:
4028 usage_log();
4029 /* NOTREACHED */
4033 argc -= optind;
4034 argv += optind;
4036 if (diff_context == -1)
4037 diff_context = 3;
4038 else if (!show_patch)
4039 errx(1, "-C requires -p");
4041 cwd = getcwd(NULL, 0);
4042 if (cwd == NULL) {
4043 error = got_error_from_errno("getcwd");
4044 goto done;
4047 if (repo_path == NULL) {
4048 error = got_worktree_open(&worktree, cwd);
4049 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4050 goto done;
4051 error = NULL;
4054 if (argc == 1) {
4055 if (worktree) {
4056 error = got_worktree_resolve_path(&path, worktree,
4057 argv[0]);
4058 if (error)
4059 goto done;
4060 } else {
4061 path = strdup(argv[0]);
4062 if (path == NULL) {
4063 error = got_error_from_errno("strdup");
4064 goto done;
4067 } else if (argc != 0)
4068 usage_log();
4070 if (repo_path == NULL) {
4071 repo_path = worktree ?
4072 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4074 if (repo_path == NULL) {
4075 error = got_error_from_errno("strdup");
4076 goto done;
4079 error = got_repo_open(&repo, repo_path, NULL);
4080 if (error != NULL)
4081 goto done;
4083 error = apply_unveil(got_repo_get_path(repo), 1,
4084 worktree ? got_worktree_get_root_path(worktree) : NULL);
4085 if (error)
4086 goto done;
4088 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4089 if (error)
4090 goto done;
4092 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4093 if (error)
4094 goto done;
4096 if (start_commit == NULL) {
4097 struct got_reference *head_ref;
4098 struct got_commit_object *commit = NULL;
4099 error = got_ref_open(&head_ref, repo,
4100 worktree ? got_worktree_get_head_ref_name(worktree)
4101 : GOT_REF_HEAD, 0);
4102 if (error != NULL)
4103 goto done;
4104 error = got_ref_resolve(&start_id, repo, head_ref);
4105 got_ref_close(head_ref);
4106 if (error != NULL)
4107 goto done;
4108 error = got_object_open_as_commit(&commit, repo,
4109 start_id);
4110 if (error != NULL)
4111 goto done;
4112 got_object_commit_close(commit);
4113 } else {
4114 error = got_repo_match_object_id(&start_id, NULL,
4115 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4116 if (error != NULL)
4117 goto done;
4119 if (end_commit != NULL) {
4120 error = got_repo_match_object_id(&end_id, NULL,
4121 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4122 if (error != NULL)
4123 goto done;
4126 if (worktree) {
4128 * If a path was specified on the command line it was resolved
4129 * to a path in the work tree above. Prepend the work tree's
4130 * path prefix to obtain the corresponding in-repository path.
4132 if (path) {
4133 const char *prefix;
4134 prefix = got_worktree_get_path_prefix(worktree);
4135 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4136 (path[0] != '\0') ? "/" : "", path) == -1) {
4137 error = got_error_from_errno("asprintf");
4138 goto done;
4141 } else
4142 error = got_repo_map_path(&in_repo_path, repo,
4143 path ? path : "");
4144 if (error != NULL)
4145 goto done;
4146 if (in_repo_path) {
4147 free(path);
4148 path = in_repo_path;
4151 error = print_commits(start_id, end_id, repo, path ? path : "",
4152 show_changed_paths, show_patch, search_pattern, diff_context,
4153 limit, log_branches, reverse_display_order, refs_idmap);
4154 done:
4155 free(path);
4156 free(repo_path);
4157 free(cwd);
4158 if (worktree)
4159 got_worktree_close(worktree);
4160 if (repo) {
4161 const struct got_error *close_err = got_repo_close(repo);
4162 if (error == NULL)
4163 error = close_err;
4165 if (refs_idmap)
4166 got_reflist_object_id_map_free(refs_idmap);
4167 got_ref_list_free(&refs);
4168 return error;
4171 __dead static void
4172 usage_diff(void)
4174 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4175 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4176 exit(1);
4179 struct print_diff_arg {
4180 struct got_repository *repo;
4181 struct got_worktree *worktree;
4182 int diff_context;
4183 const char *id_str;
4184 int header_shown;
4185 int diff_staged;
4186 int ignore_whitespace;
4187 int force_text_diff;
4191 * Create a file which contains the target path of a symlink so we can feed
4192 * it as content to the diff engine.
4194 static const struct got_error *
4195 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4196 const char *abspath)
4198 const struct got_error *err = NULL;
4199 char target_path[PATH_MAX];
4200 ssize_t target_len, outlen;
4202 *fd = -1;
4204 if (dirfd != -1) {
4205 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4206 if (target_len == -1)
4207 return got_error_from_errno2("readlinkat", abspath);
4208 } else {
4209 target_len = readlink(abspath, target_path, PATH_MAX);
4210 if (target_len == -1)
4211 return got_error_from_errno2("readlink", abspath);
4214 *fd = got_opentempfd();
4215 if (*fd == -1)
4216 return got_error_from_errno("got_opentempfd");
4218 outlen = write(*fd, target_path, target_len);
4219 if (outlen == -1) {
4220 err = got_error_from_errno("got_opentempfd");
4221 goto done;
4224 if (lseek(*fd, 0, SEEK_SET) == -1) {
4225 err = got_error_from_errno2("lseek", abspath);
4226 goto done;
4228 done:
4229 if (err) {
4230 close(*fd);
4231 *fd = -1;
4233 return err;
4236 static const struct got_error *
4237 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4238 const char *path, struct got_object_id *blob_id,
4239 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4240 int dirfd, const char *de_name)
4242 struct print_diff_arg *a = arg;
4243 const struct got_error *err = NULL;
4244 struct got_blob_object *blob1 = NULL;
4245 int fd = -1;
4246 FILE *f2 = NULL;
4247 char *abspath = NULL, *label1 = NULL;
4248 struct stat sb;
4250 if (a->diff_staged) {
4251 if (staged_status != GOT_STATUS_MODIFY &&
4252 staged_status != GOT_STATUS_ADD &&
4253 staged_status != GOT_STATUS_DELETE)
4254 return NULL;
4255 } else {
4256 if (staged_status == GOT_STATUS_DELETE)
4257 return NULL;
4258 if (status == GOT_STATUS_NONEXISTENT)
4259 return got_error_set_errno(ENOENT, path);
4260 if (status != GOT_STATUS_MODIFY &&
4261 status != GOT_STATUS_ADD &&
4262 status != GOT_STATUS_DELETE &&
4263 status != GOT_STATUS_CONFLICT)
4264 return NULL;
4267 if (!a->header_shown) {
4268 printf("diff %s %s%s\n", a->id_str,
4269 got_worktree_get_root_path(a->worktree),
4270 a->diff_staged ? " (staged changes)" : "");
4271 a->header_shown = 1;
4274 if (a->diff_staged) {
4275 const char *label1 = NULL, *label2 = NULL;
4276 switch (staged_status) {
4277 case GOT_STATUS_MODIFY:
4278 label1 = path;
4279 label2 = path;
4280 break;
4281 case GOT_STATUS_ADD:
4282 label2 = path;
4283 break;
4284 case GOT_STATUS_DELETE:
4285 label1 = path;
4286 break;
4287 default:
4288 return got_error(GOT_ERR_FILE_STATUS);
4290 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4291 staged_blob_id, label1, label2, a->diff_context,
4292 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4295 if (staged_status == GOT_STATUS_ADD ||
4296 staged_status == GOT_STATUS_MODIFY) {
4297 char *id_str;
4298 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4299 8192);
4300 if (err)
4301 goto done;
4302 err = got_object_id_str(&id_str, staged_blob_id);
4303 if (err)
4304 goto done;
4305 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4306 err = got_error_from_errno("asprintf");
4307 free(id_str);
4308 goto done;
4310 free(id_str);
4311 } else if (status != GOT_STATUS_ADD) {
4312 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4313 if (err)
4314 goto done;
4317 if (status != GOT_STATUS_DELETE) {
4318 if (asprintf(&abspath, "%s/%s",
4319 got_worktree_get_root_path(a->worktree), path) == -1) {
4320 err = got_error_from_errno("asprintf");
4321 goto done;
4324 if (dirfd != -1) {
4325 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4326 if (fd == -1) {
4327 if (errno != ELOOP) {
4328 err = got_error_from_errno2("openat",
4329 abspath);
4330 goto done;
4332 err = get_symlink_target_file(&fd, dirfd,
4333 de_name, abspath);
4334 if (err)
4335 goto done;
4337 } else {
4338 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4339 if (fd == -1) {
4340 if (errno != ELOOP) {
4341 err = got_error_from_errno2("open",
4342 abspath);
4343 goto done;
4345 err = get_symlink_target_file(&fd, dirfd,
4346 de_name, abspath);
4347 if (err)
4348 goto done;
4351 if (fstat(fd, &sb) == -1) {
4352 err = got_error_from_errno2("fstat", abspath);
4353 goto done;
4355 f2 = fdopen(fd, "r");
4356 if (f2 == NULL) {
4357 err = got_error_from_errno2("fdopen", abspath);
4358 goto done;
4360 fd = -1;
4361 } else
4362 sb.st_size = 0;
4364 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4365 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4366 done:
4367 if (blob1)
4368 got_object_blob_close(blob1);
4369 if (f2 && fclose(f2) == EOF && err == NULL)
4370 err = got_error_from_errno("fclose");
4371 if (fd != -1 && close(fd) == -1 && err == NULL)
4372 err = got_error_from_errno("close");
4373 free(abspath);
4374 return err;
4377 static const struct got_error *
4378 cmd_diff(int argc, char *argv[])
4380 const struct got_error *error;
4381 struct got_repository *repo = NULL;
4382 struct got_worktree *worktree = NULL;
4383 char *cwd = NULL, *repo_path = NULL;
4384 struct got_object_id *id1 = NULL, *id2 = NULL;
4385 const char *id_str1 = NULL, *id_str2 = NULL;
4386 char *label1 = NULL, *label2 = NULL;
4387 int type1, type2;
4388 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4389 int force_text_diff = 0;
4390 const char *errstr;
4391 char *path = NULL;
4392 struct got_reflist_head refs;
4394 TAILQ_INIT(&refs);
4396 #ifndef PROFILE
4397 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4398 NULL) == -1)
4399 err(1, "pledge");
4400 #endif
4402 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4403 switch (ch) {
4404 case 'a':
4405 force_text_diff = 1;
4406 break;
4407 case 'C':
4408 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4409 &errstr);
4410 if (errstr != NULL)
4411 err(1, "-C option %s", errstr);
4412 break;
4413 case 'r':
4414 repo_path = realpath(optarg, NULL);
4415 if (repo_path == NULL)
4416 return got_error_from_errno2("realpath",
4417 optarg);
4418 got_path_strip_trailing_slashes(repo_path);
4419 break;
4420 case 's':
4421 diff_staged = 1;
4422 break;
4423 case 'w':
4424 ignore_whitespace = 1;
4425 break;
4426 default:
4427 usage_diff();
4428 /* NOTREACHED */
4432 argc -= optind;
4433 argv += optind;
4435 cwd = getcwd(NULL, 0);
4436 if (cwd == NULL) {
4437 error = got_error_from_errno("getcwd");
4438 goto done;
4440 if (argc <= 1) {
4441 if (repo_path)
4442 errx(1,
4443 "-r option can't be used when diffing a work tree");
4444 error = got_worktree_open(&worktree, cwd);
4445 if (error) {
4446 if (error->code == GOT_ERR_NOT_WORKTREE)
4447 error = wrap_not_worktree_error(error, "diff",
4448 cwd);
4449 goto done;
4451 repo_path = strdup(got_worktree_get_repo_path(worktree));
4452 if (repo_path == NULL) {
4453 error = got_error_from_errno("strdup");
4454 goto done;
4456 if (argc == 1) {
4457 error = got_worktree_resolve_path(&path, worktree,
4458 argv[0]);
4459 if (error)
4460 goto done;
4461 } else {
4462 path = strdup("");
4463 if (path == NULL) {
4464 error = got_error_from_errno("strdup");
4465 goto done;
4468 } else if (argc == 2) {
4469 if (diff_staged)
4470 errx(1, "-s option can't be used when diffing "
4471 "objects in repository");
4472 id_str1 = argv[0];
4473 id_str2 = argv[1];
4474 if (repo_path == NULL) {
4475 error = got_worktree_open(&worktree, cwd);
4476 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4477 goto done;
4478 repo_path = strdup(worktree ?
4479 got_worktree_get_repo_path(worktree) : cwd);
4480 if (repo_path == NULL) {
4481 error = got_error_from_errno("strdup");
4482 goto done;
4485 } else
4486 usage_diff();
4488 error = got_repo_open(&repo, repo_path, NULL);
4489 free(repo_path);
4490 if (error != NULL)
4491 goto done;
4493 error = apply_unveil(got_repo_get_path(repo), 1,
4494 worktree ? got_worktree_get_root_path(worktree) : NULL);
4495 if (error)
4496 goto done;
4498 if (argc <= 1) {
4499 struct print_diff_arg arg;
4500 struct got_pathlist_head paths;
4501 char *id_str;
4503 TAILQ_INIT(&paths);
4505 error = got_object_id_str(&id_str,
4506 got_worktree_get_base_commit_id(worktree));
4507 if (error)
4508 goto done;
4509 arg.repo = repo;
4510 arg.worktree = worktree;
4511 arg.diff_context = diff_context;
4512 arg.id_str = id_str;
4513 arg.header_shown = 0;
4514 arg.diff_staged = diff_staged;
4515 arg.ignore_whitespace = ignore_whitespace;
4516 arg.force_text_diff = force_text_diff;
4518 error = got_pathlist_append(&paths, path, NULL);
4519 if (error)
4520 goto done;
4522 error = got_worktree_status(worktree, &paths, repo, 0,
4523 print_diff, &arg, check_cancelled, NULL);
4524 free(id_str);
4525 got_pathlist_free(&paths);
4526 goto done;
4529 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4530 if (error)
4531 return error;
4533 error = got_repo_match_object_id(&id1, &label1, id_str1,
4534 GOT_OBJ_TYPE_ANY, &refs, repo);
4535 if (error)
4536 goto done;
4538 error = got_repo_match_object_id(&id2, &label2, id_str2,
4539 GOT_OBJ_TYPE_ANY, &refs, repo);
4540 if (error)
4541 goto done;
4543 error = got_object_get_type(&type1, repo, id1);
4544 if (error)
4545 goto done;
4547 error = got_object_get_type(&type2, repo, id2);
4548 if (error)
4549 goto done;
4551 if (type1 != type2) {
4552 error = got_error(GOT_ERR_OBJ_TYPE);
4553 goto done;
4556 switch (type1) {
4557 case GOT_OBJ_TYPE_BLOB:
4558 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4559 NULL, NULL, diff_context, ignore_whitespace,
4560 force_text_diff, repo, stdout);
4561 break;
4562 case GOT_OBJ_TYPE_TREE:
4563 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4564 "", "", diff_context, ignore_whitespace, force_text_diff,
4565 repo, stdout);
4566 break;
4567 case GOT_OBJ_TYPE_COMMIT:
4568 printf("diff %s %s\n", label1, label2);
4569 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4570 diff_context, ignore_whitespace, force_text_diff, repo,
4571 stdout);
4572 break;
4573 default:
4574 error = got_error(GOT_ERR_OBJ_TYPE);
4576 done:
4577 free(label1);
4578 free(label2);
4579 free(id1);
4580 free(id2);
4581 free(path);
4582 if (worktree)
4583 got_worktree_close(worktree);
4584 if (repo) {
4585 const struct got_error *close_err = got_repo_close(repo);
4586 if (error == NULL)
4587 error = close_err;
4589 got_ref_list_free(&refs);
4590 return error;
4593 __dead static void
4594 usage_blame(void)
4596 fprintf(stderr,
4597 "usage: %s blame [-c commit] [-r repository-path] path\n",
4598 getprogname());
4599 exit(1);
4602 struct blame_line {
4603 int annotated;
4604 char *id_str;
4605 char *committer;
4606 char datebuf[11]; /* YYYY-MM-DD + NUL */
4609 struct blame_cb_args {
4610 struct blame_line *lines;
4611 int nlines;
4612 int nlines_prec;
4613 int lineno_cur;
4614 off_t *line_offsets;
4615 FILE *f;
4616 struct got_repository *repo;
4619 static const struct got_error *
4620 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4622 const struct got_error *err = NULL;
4623 struct blame_cb_args *a = arg;
4624 struct blame_line *bline;
4625 char *line = NULL;
4626 size_t linesize = 0;
4627 struct got_commit_object *commit = NULL;
4628 off_t offset;
4629 struct tm tm;
4630 time_t committer_time;
4632 if (nlines != a->nlines ||
4633 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4634 return got_error(GOT_ERR_RANGE);
4636 if (sigint_received)
4637 return got_error(GOT_ERR_ITER_COMPLETED);
4639 if (lineno == -1)
4640 return NULL; /* no change in this commit */
4642 /* Annotate this line. */
4643 bline = &a->lines[lineno - 1];
4644 if (bline->annotated)
4645 return NULL;
4646 err = got_object_id_str(&bline->id_str, id);
4647 if (err)
4648 return err;
4650 err = got_object_open_as_commit(&commit, a->repo, id);
4651 if (err)
4652 goto done;
4654 bline->committer = strdup(got_object_commit_get_committer(commit));
4655 if (bline->committer == NULL) {
4656 err = got_error_from_errno("strdup");
4657 goto done;
4660 committer_time = got_object_commit_get_committer_time(commit);
4661 if (gmtime_r(&committer_time, &tm) == NULL)
4662 return got_error_from_errno("gmtime_r");
4663 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4664 &tm) == 0) {
4665 err = got_error(GOT_ERR_NO_SPACE);
4666 goto done;
4668 bline->annotated = 1;
4670 /* Print lines annotated so far. */
4671 bline = &a->lines[a->lineno_cur - 1];
4672 if (!bline->annotated)
4673 goto done;
4675 offset = a->line_offsets[a->lineno_cur - 1];
4676 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4677 err = got_error_from_errno("fseeko");
4678 goto done;
4681 while (bline->annotated) {
4682 char *smallerthan, *at, *nl, *committer;
4683 size_t len;
4685 if (getline(&line, &linesize, a->f) == -1) {
4686 if (ferror(a->f))
4687 err = got_error_from_errno("getline");
4688 break;
4691 committer = bline->committer;
4692 smallerthan = strchr(committer, '<');
4693 if (smallerthan && smallerthan[1] != '\0')
4694 committer = smallerthan + 1;
4695 at = strchr(committer, '@');
4696 if (at)
4697 *at = '\0';
4698 len = strlen(committer);
4699 if (len >= 9)
4700 committer[8] = '\0';
4702 nl = strchr(line, '\n');
4703 if (nl)
4704 *nl = '\0';
4705 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4706 bline->id_str, bline->datebuf, committer, line);
4708 a->lineno_cur++;
4709 bline = &a->lines[a->lineno_cur - 1];
4711 done:
4712 if (commit)
4713 got_object_commit_close(commit);
4714 free(line);
4715 return err;
4718 static const struct got_error *
4719 cmd_blame(int argc, char *argv[])
4721 const struct got_error *error;
4722 struct got_repository *repo = NULL;
4723 struct got_worktree *worktree = NULL;
4724 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4725 char *link_target = NULL;
4726 struct got_object_id *obj_id = NULL;
4727 struct got_object_id *commit_id = NULL;
4728 struct got_blob_object *blob = NULL;
4729 char *commit_id_str = NULL;
4730 struct blame_cb_args bca;
4731 int ch, obj_type, i;
4732 off_t filesize;
4734 memset(&bca, 0, sizeof(bca));
4736 #ifndef PROFILE
4737 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4738 NULL) == -1)
4739 err(1, "pledge");
4740 #endif
4742 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4743 switch (ch) {
4744 case 'c':
4745 commit_id_str = optarg;
4746 break;
4747 case 'r':
4748 repo_path = realpath(optarg, NULL);
4749 if (repo_path == NULL)
4750 return got_error_from_errno2("realpath",
4751 optarg);
4752 got_path_strip_trailing_slashes(repo_path);
4753 break;
4754 default:
4755 usage_blame();
4756 /* NOTREACHED */
4760 argc -= optind;
4761 argv += optind;
4763 if (argc == 1)
4764 path = argv[0];
4765 else
4766 usage_blame();
4768 cwd = getcwd(NULL, 0);
4769 if (cwd == NULL) {
4770 error = got_error_from_errno("getcwd");
4771 goto done;
4773 if (repo_path == NULL) {
4774 error = got_worktree_open(&worktree, cwd);
4775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4776 goto done;
4777 else
4778 error = NULL;
4779 if (worktree) {
4780 repo_path =
4781 strdup(got_worktree_get_repo_path(worktree));
4782 if (repo_path == NULL) {
4783 error = got_error_from_errno("strdup");
4784 if (error)
4785 goto done;
4787 } else {
4788 repo_path = strdup(cwd);
4789 if (repo_path == NULL) {
4790 error = got_error_from_errno("strdup");
4791 goto done;
4796 error = got_repo_open(&repo, repo_path, NULL);
4797 if (error != NULL)
4798 goto done;
4800 if (worktree) {
4801 const char *prefix = got_worktree_get_path_prefix(worktree);
4802 char *p;
4804 error = got_worktree_resolve_path(&p, worktree, path);
4805 if (error)
4806 goto done;
4807 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4808 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4809 p) == -1) {
4810 error = got_error_from_errno("asprintf");
4811 free(p);
4812 goto done;
4814 free(p);
4815 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4816 } else {
4817 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4818 if (error)
4819 goto done;
4820 error = got_repo_map_path(&in_repo_path, repo, path);
4822 if (error)
4823 goto done;
4825 if (commit_id_str == NULL) {
4826 struct got_reference *head_ref;
4827 error = got_ref_open(&head_ref, repo, worktree ?
4828 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4829 if (error != NULL)
4830 goto done;
4831 error = got_ref_resolve(&commit_id, repo, head_ref);
4832 got_ref_close(head_ref);
4833 if (error != NULL)
4834 goto done;
4835 } else {
4836 struct got_reflist_head refs;
4837 TAILQ_INIT(&refs);
4838 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4839 NULL);
4840 if (error)
4841 goto done;
4842 error = got_repo_match_object_id(&commit_id, NULL,
4843 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4844 got_ref_list_free(&refs);
4845 if (error)
4846 goto done;
4849 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4850 commit_id, repo);
4851 if (error)
4852 goto done;
4854 error = got_object_id_by_path(&obj_id, repo, commit_id,
4855 link_target ? link_target : in_repo_path);
4856 if (error)
4857 goto done;
4859 error = got_object_get_type(&obj_type, repo, obj_id);
4860 if (error)
4861 goto done;
4863 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4864 error = got_error_path(link_target ? link_target : in_repo_path,
4865 GOT_ERR_OBJ_TYPE);
4866 goto done;
4869 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4870 if (error)
4871 goto done;
4872 bca.f = got_opentemp();
4873 if (bca.f == NULL) {
4874 error = got_error_from_errno("got_opentemp");
4875 goto done;
4877 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4878 &bca.line_offsets, bca.f, blob);
4879 if (error || bca.nlines == 0)
4880 goto done;
4882 /* Don't include \n at EOF in the blame line count. */
4883 if (bca.line_offsets[bca.nlines - 1] == filesize)
4884 bca.nlines--;
4886 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4887 if (bca.lines == NULL) {
4888 error = got_error_from_errno("calloc");
4889 goto done;
4891 bca.lineno_cur = 1;
4892 bca.nlines_prec = 0;
4893 i = bca.nlines;
4894 while (i > 0) {
4895 i /= 10;
4896 bca.nlines_prec++;
4898 bca.repo = repo;
4900 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4901 repo, blame_cb, &bca, check_cancelled, NULL);
4902 done:
4903 free(in_repo_path);
4904 free(link_target);
4905 free(repo_path);
4906 free(cwd);
4907 free(commit_id);
4908 free(obj_id);
4909 if (blob)
4910 got_object_blob_close(blob);
4911 if (worktree)
4912 got_worktree_close(worktree);
4913 if (repo) {
4914 const struct got_error *close_err = got_repo_close(repo);
4915 if (error == NULL)
4916 error = close_err;
4918 if (bca.lines) {
4919 for (i = 0; i < bca.nlines; i++) {
4920 struct blame_line *bline = &bca.lines[i];
4921 free(bline->id_str);
4922 free(bline->committer);
4924 free(bca.lines);
4926 free(bca.line_offsets);
4927 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4928 error = got_error_from_errno("fclose");
4929 return error;
4932 __dead static void
4933 usage_tree(void)
4935 fprintf(stderr,
4936 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4937 getprogname());
4938 exit(1);
4941 static const struct got_error *
4942 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4943 const char *root_path, struct got_repository *repo)
4945 const struct got_error *err = NULL;
4946 int is_root_path = (strcmp(path, root_path) == 0);
4947 const char *modestr = "";
4948 mode_t mode = got_tree_entry_get_mode(te);
4949 char *link_target = NULL;
4951 path += strlen(root_path);
4952 while (path[0] == '/')
4953 path++;
4955 if (got_object_tree_entry_is_submodule(te))
4956 modestr = "$";
4957 else if (S_ISLNK(mode)) {
4958 int i;
4960 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4961 if (err)
4962 return err;
4963 for (i = 0; i < strlen(link_target); i++) {
4964 if (!isprint((unsigned char)link_target[i]))
4965 link_target[i] = '?';
4968 modestr = "@";
4970 else if (S_ISDIR(mode))
4971 modestr = "/";
4972 else if (mode & S_IXUSR)
4973 modestr = "*";
4975 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4976 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4977 link_target ? " -> ": "", link_target ? link_target : "");
4979 free(link_target);
4980 return NULL;
4983 static const struct got_error *
4984 print_tree(const char *path, struct got_object_id *commit_id,
4985 int show_ids, int recurse, const char *root_path,
4986 struct got_repository *repo)
4988 const struct got_error *err = NULL;
4989 struct got_object_id *tree_id = NULL;
4990 struct got_tree_object *tree = NULL;
4991 int nentries, i;
4993 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4994 if (err)
4995 goto done;
4997 err = got_object_open_as_tree(&tree, repo, tree_id);
4998 if (err)
4999 goto done;
5000 nentries = got_object_tree_get_nentries(tree);
5001 for (i = 0; i < nentries; i++) {
5002 struct got_tree_entry *te;
5003 char *id = NULL;
5005 if (sigint_received || sigpipe_received)
5006 break;
5008 te = got_object_tree_get_entry(tree, i);
5009 if (show_ids) {
5010 char *id_str;
5011 err = got_object_id_str(&id_str,
5012 got_tree_entry_get_id(te));
5013 if (err)
5014 goto done;
5015 if (asprintf(&id, "%s ", id_str) == -1) {
5016 err = got_error_from_errno("asprintf");
5017 free(id_str);
5018 goto done;
5020 free(id_str);
5022 err = print_entry(te, id, path, root_path, repo);
5023 free(id);
5024 if (err)
5025 goto done;
5027 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5028 char *child_path;
5029 if (asprintf(&child_path, "%s%s%s", path,
5030 path[0] == '/' && path[1] == '\0' ? "" : "/",
5031 got_tree_entry_get_name(te)) == -1) {
5032 err = got_error_from_errno("asprintf");
5033 goto done;
5035 err = print_tree(child_path, commit_id, show_ids, 1,
5036 root_path, repo);
5037 free(child_path);
5038 if (err)
5039 goto done;
5042 done:
5043 if (tree)
5044 got_object_tree_close(tree);
5045 free(tree_id);
5046 return err;
5049 static const struct got_error *
5050 cmd_tree(int argc, char *argv[])
5052 const struct got_error *error;
5053 struct got_repository *repo = NULL;
5054 struct got_worktree *worktree = NULL;
5055 const char *path, *refname = NULL;
5056 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5057 struct got_object_id *commit_id = NULL;
5058 char *commit_id_str = NULL;
5059 int show_ids = 0, recurse = 0;
5060 int ch;
5062 #ifndef PROFILE
5063 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5064 NULL) == -1)
5065 err(1, "pledge");
5066 #endif
5068 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5069 switch (ch) {
5070 case 'c':
5071 commit_id_str = optarg;
5072 break;
5073 case 'r':
5074 repo_path = realpath(optarg, NULL);
5075 if (repo_path == NULL)
5076 return got_error_from_errno2("realpath",
5077 optarg);
5078 got_path_strip_trailing_slashes(repo_path);
5079 break;
5080 case 'i':
5081 show_ids = 1;
5082 break;
5083 case 'R':
5084 recurse = 1;
5085 break;
5086 default:
5087 usage_tree();
5088 /* NOTREACHED */
5092 argc -= optind;
5093 argv += optind;
5095 if (argc == 1)
5096 path = argv[0];
5097 else if (argc > 1)
5098 usage_tree();
5099 else
5100 path = NULL;
5102 cwd = getcwd(NULL, 0);
5103 if (cwd == NULL) {
5104 error = got_error_from_errno("getcwd");
5105 goto done;
5107 if (repo_path == NULL) {
5108 error = got_worktree_open(&worktree, cwd);
5109 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5110 goto done;
5111 else
5112 error = NULL;
5113 if (worktree) {
5114 repo_path =
5115 strdup(got_worktree_get_repo_path(worktree));
5116 if (repo_path == NULL)
5117 error = got_error_from_errno("strdup");
5118 if (error)
5119 goto done;
5120 } else {
5121 repo_path = strdup(cwd);
5122 if (repo_path == NULL) {
5123 error = got_error_from_errno("strdup");
5124 goto done;
5129 error = got_repo_open(&repo, repo_path, NULL);
5130 if (error != NULL)
5131 goto done;
5133 if (worktree) {
5134 const char *prefix = got_worktree_get_path_prefix(worktree);
5135 char *p;
5137 if (path == NULL)
5138 path = "";
5139 error = got_worktree_resolve_path(&p, worktree, path);
5140 if (error)
5141 goto done;
5142 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5143 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5144 p) == -1) {
5145 error = got_error_from_errno("asprintf");
5146 free(p);
5147 goto done;
5149 free(p);
5150 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5151 if (error)
5152 goto done;
5153 } else {
5154 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5155 if (error)
5156 goto done;
5157 if (path == NULL)
5158 path = "/";
5159 error = got_repo_map_path(&in_repo_path, repo, path);
5160 if (error != NULL)
5161 goto done;
5164 if (commit_id_str == NULL) {
5165 struct got_reference *head_ref;
5166 if (worktree)
5167 refname = got_worktree_get_head_ref_name(worktree);
5168 else
5169 refname = GOT_REF_HEAD;
5170 error = got_ref_open(&head_ref, repo, refname, 0);
5171 if (error != NULL)
5172 goto done;
5173 error = got_ref_resolve(&commit_id, repo, head_ref);
5174 got_ref_close(head_ref);
5175 if (error != NULL)
5176 goto done;
5177 } else {
5178 struct got_reflist_head refs;
5179 TAILQ_INIT(&refs);
5180 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5181 NULL);
5182 if (error)
5183 goto done;
5184 error = got_repo_match_object_id(&commit_id, NULL,
5185 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5186 got_ref_list_free(&refs);
5187 if (error)
5188 goto done;
5191 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5192 in_repo_path, repo);
5193 done:
5194 free(in_repo_path);
5195 free(repo_path);
5196 free(cwd);
5197 free(commit_id);
5198 if (worktree)
5199 got_worktree_close(worktree);
5200 if (repo) {
5201 const struct got_error *close_err = got_repo_close(repo);
5202 if (error == NULL)
5203 error = close_err;
5205 return error;
5208 __dead static void
5209 usage_status(void)
5211 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5212 getprogname());
5213 exit(1);
5216 static const struct got_error *
5217 print_status(void *arg, unsigned char status, unsigned char staged_status,
5218 const char *path, struct got_object_id *blob_id,
5219 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5220 int dirfd, const char *de_name)
5222 if (status == staged_status && (status == GOT_STATUS_DELETE))
5223 status = GOT_STATUS_NO_CHANGE;
5224 if (arg) {
5225 char *status_codes = arg;
5226 size_t ncodes = strlen(status_codes);
5227 int i;
5228 for (i = 0; i < ncodes ; i++) {
5229 if (status == status_codes[i] ||
5230 staged_status == status_codes[i])
5231 break;
5233 if (i == ncodes)
5234 return NULL;
5236 printf("%c%c %s\n", status, staged_status, path);
5237 return NULL;
5240 static const struct got_error *
5241 cmd_status(int argc, char *argv[])
5243 const struct got_error *error = NULL;
5244 struct got_repository *repo = NULL;
5245 struct got_worktree *worktree = NULL;
5246 char *cwd = NULL, *status_codes = NULL;;
5247 struct got_pathlist_head paths;
5248 struct got_pathlist_entry *pe;
5249 int ch, i, no_ignores = 0;
5251 TAILQ_INIT(&paths);
5253 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5254 switch (ch) {
5255 case 'I':
5256 no_ignores = 1;
5257 break;
5258 case 's':
5259 for (i = 0; i < strlen(optarg); i++) {
5260 switch (optarg[i]) {
5261 case GOT_STATUS_MODIFY:
5262 case GOT_STATUS_ADD:
5263 case GOT_STATUS_DELETE:
5264 case GOT_STATUS_CONFLICT:
5265 case GOT_STATUS_MISSING:
5266 case GOT_STATUS_OBSTRUCTED:
5267 case GOT_STATUS_UNVERSIONED:
5268 case GOT_STATUS_MODE_CHANGE:
5269 case GOT_STATUS_NONEXISTENT:
5270 break;
5271 default:
5272 errx(1, "invalid status code '%c'",
5273 optarg[i]);
5276 status_codes = optarg;
5277 break;
5278 default:
5279 usage_status();
5280 /* NOTREACHED */
5284 argc -= optind;
5285 argv += optind;
5287 #ifndef PROFILE
5288 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5289 NULL) == -1)
5290 err(1, "pledge");
5291 #endif
5292 cwd = getcwd(NULL, 0);
5293 if (cwd == NULL) {
5294 error = got_error_from_errno("getcwd");
5295 goto done;
5298 error = got_worktree_open(&worktree, cwd);
5299 if (error) {
5300 if (error->code == GOT_ERR_NOT_WORKTREE)
5301 error = wrap_not_worktree_error(error, "status", cwd);
5302 goto done;
5305 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5306 NULL);
5307 if (error != NULL)
5308 goto done;
5310 error = apply_unveil(got_repo_get_path(repo), 1,
5311 got_worktree_get_root_path(worktree));
5312 if (error)
5313 goto done;
5315 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5316 if (error)
5317 goto done;
5319 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5320 print_status, status_codes, check_cancelled, NULL);
5321 done:
5322 TAILQ_FOREACH(pe, &paths, entry)
5323 free((char *)pe->path);
5324 got_pathlist_free(&paths);
5325 free(cwd);
5326 return error;
5329 __dead static void
5330 usage_ref(void)
5332 fprintf(stderr,
5333 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5334 "[-d] [name]\n",
5335 getprogname());
5336 exit(1);
5339 static const struct got_error *
5340 list_refs(struct got_repository *repo, const char *refname)
5342 static const struct got_error *err = NULL;
5343 struct got_reflist_head refs;
5344 struct got_reflist_entry *re;
5346 TAILQ_INIT(&refs);
5347 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5348 if (err)
5349 return err;
5351 TAILQ_FOREACH(re, &refs, entry) {
5352 char *refstr;
5353 refstr = got_ref_to_str(re->ref);
5354 if (refstr == NULL)
5355 return got_error_from_errno("got_ref_to_str");
5356 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5357 free(refstr);
5360 got_ref_list_free(&refs);
5361 return NULL;
5364 static const struct got_error *
5365 delete_ref_by_name(struct got_repository *repo, const char *refname)
5367 const struct got_error *err;
5368 struct got_reference *ref;
5370 err = got_ref_open(&ref, repo, refname, 0);
5371 if (err)
5372 return err;
5374 err = delete_ref(repo, ref);
5375 got_ref_close(ref);
5376 return err;
5379 static const struct got_error *
5380 add_ref(struct got_repository *repo, const char *refname, const char *target)
5382 const struct got_error *err = NULL;
5383 struct got_object_id *id;
5384 struct got_reference *ref = NULL;
5387 * Don't let the user create a reference name with a leading '-'.
5388 * While technically a valid reference name, this case is usually
5389 * an unintended typo.
5391 if (refname[0] == '-')
5392 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5394 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5395 repo);
5396 if (err) {
5397 struct got_reference *target_ref;
5399 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5400 return err;
5401 err = got_ref_open(&target_ref, repo, target, 0);
5402 if (err)
5403 return err;
5404 err = got_ref_resolve(&id, repo, target_ref);
5405 got_ref_close(target_ref);
5406 if (err)
5407 return err;
5410 err = got_ref_alloc(&ref, refname, id);
5411 if (err)
5412 goto done;
5414 err = got_ref_write(ref, repo);
5415 done:
5416 if (ref)
5417 got_ref_close(ref);
5418 free(id);
5419 return err;
5422 static const struct got_error *
5423 add_symref(struct got_repository *repo, const char *refname, const char *target)
5425 const struct got_error *err = NULL;
5426 struct got_reference *ref = NULL;
5427 struct got_reference *target_ref = NULL;
5430 * Don't let the user create a reference name with a leading '-'.
5431 * While technically a valid reference name, this case is usually
5432 * an unintended typo.
5434 if (refname[0] == '-')
5435 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5437 err = got_ref_open(&target_ref, repo, target, 0);
5438 if (err)
5439 return err;
5441 err = got_ref_alloc_symref(&ref, refname, target_ref);
5442 if (err)
5443 goto done;
5445 err = got_ref_write(ref, repo);
5446 done:
5447 if (target_ref)
5448 got_ref_close(target_ref);
5449 if (ref)
5450 got_ref_close(ref);
5451 return err;
5454 static const struct got_error *
5455 cmd_ref(int argc, char *argv[])
5457 const struct got_error *error = NULL;
5458 struct got_repository *repo = NULL;
5459 struct got_worktree *worktree = NULL;
5460 char *cwd = NULL, *repo_path = NULL;
5461 int ch, do_list = 0, do_delete = 0;
5462 const char *obj_arg = NULL, *symref_target= NULL;
5463 char *refname = NULL;
5465 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5466 switch (ch) {
5467 case 'c':
5468 obj_arg = optarg;
5469 break;
5470 case 'd':
5471 do_delete = 1;
5472 break;
5473 case 'r':
5474 repo_path = realpath(optarg, NULL);
5475 if (repo_path == NULL)
5476 return got_error_from_errno2("realpath",
5477 optarg);
5478 got_path_strip_trailing_slashes(repo_path);
5479 break;
5480 case 'l':
5481 do_list = 1;
5482 break;
5483 case 's':
5484 symref_target = optarg;
5485 break;
5486 default:
5487 usage_ref();
5488 /* NOTREACHED */
5492 if (obj_arg && do_list)
5493 option_conflict('c', 'l');
5494 if (obj_arg && do_delete)
5495 option_conflict('c', 'd');
5496 if (obj_arg && symref_target)
5497 option_conflict('c', 's');
5498 if (symref_target && do_delete)
5499 option_conflict('s', 'd');
5500 if (symref_target && do_list)
5501 option_conflict('s', 'l');
5502 if (do_delete && do_list)
5503 option_conflict('d', 'l');
5505 argc -= optind;
5506 argv += optind;
5508 if (do_list) {
5509 if (argc != 0 && argc != 1)
5510 usage_ref();
5511 if (argc == 1) {
5512 refname = strdup(argv[0]);
5513 if (refname == NULL) {
5514 error = got_error_from_errno("strdup");
5515 goto done;
5518 } else {
5519 if (argc != 1)
5520 usage_ref();
5521 refname = strdup(argv[0]);
5522 if (refname == NULL) {
5523 error = got_error_from_errno("strdup");
5524 goto done;
5528 if (refname)
5529 got_path_strip_trailing_slashes(refname);
5531 #ifndef PROFILE
5532 if (do_list) {
5533 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5534 NULL) == -1)
5535 err(1, "pledge");
5536 } else {
5537 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5538 "sendfd unveil", NULL) == -1)
5539 err(1, "pledge");
5541 #endif
5542 cwd = getcwd(NULL, 0);
5543 if (cwd == NULL) {
5544 error = got_error_from_errno("getcwd");
5545 goto done;
5548 if (repo_path == NULL) {
5549 error = got_worktree_open(&worktree, cwd);
5550 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5551 goto done;
5552 else
5553 error = NULL;
5554 if (worktree) {
5555 repo_path =
5556 strdup(got_worktree_get_repo_path(worktree));
5557 if (repo_path == NULL)
5558 error = got_error_from_errno("strdup");
5559 if (error)
5560 goto done;
5561 } else {
5562 repo_path = strdup(cwd);
5563 if (repo_path == NULL) {
5564 error = got_error_from_errno("strdup");
5565 goto done;
5570 error = got_repo_open(&repo, repo_path, NULL);
5571 if (error != NULL)
5572 goto done;
5574 error = apply_unveil(got_repo_get_path(repo), do_list,
5575 worktree ? got_worktree_get_root_path(worktree) : NULL);
5576 if (error)
5577 goto done;
5579 if (do_list)
5580 error = list_refs(repo, refname);
5581 else if (do_delete)
5582 error = delete_ref_by_name(repo, refname);
5583 else if (symref_target)
5584 error = add_symref(repo, refname, symref_target);
5585 else {
5586 if (obj_arg == NULL)
5587 usage_ref();
5588 error = add_ref(repo, refname, obj_arg);
5590 done:
5591 free(refname);
5592 if (repo) {
5593 const struct got_error *close_err = got_repo_close(repo);
5594 if (error == NULL)
5595 error = close_err;
5597 if (worktree)
5598 got_worktree_close(worktree);
5599 free(cwd);
5600 free(repo_path);
5601 return error;
5604 __dead static void
5605 usage_branch(void)
5607 fprintf(stderr,
5608 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5609 "[name]\n", getprogname());
5610 exit(1);
5613 static const struct got_error *
5614 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5615 struct got_reference *ref)
5617 const struct got_error *err = NULL;
5618 const char *refname, *marker = " ";
5619 char *refstr;
5621 refname = got_ref_get_name(ref);
5622 if (worktree && strcmp(refname,
5623 got_worktree_get_head_ref_name(worktree)) == 0) {
5624 struct got_object_id *id = NULL;
5626 err = got_ref_resolve(&id, repo, ref);
5627 if (err)
5628 return err;
5629 if (got_object_id_cmp(id,
5630 got_worktree_get_base_commit_id(worktree)) == 0)
5631 marker = "* ";
5632 else
5633 marker = "~ ";
5634 free(id);
5637 if (strncmp(refname, "refs/heads/", 11) == 0)
5638 refname += 11;
5639 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5640 refname += 18;
5641 if (strncmp(refname, "refs/remotes/", 13) == 0)
5642 refname += 13;
5644 refstr = got_ref_to_str(ref);
5645 if (refstr == NULL)
5646 return got_error_from_errno("got_ref_to_str");
5648 printf("%s%s: %s\n", marker, refname, refstr);
5649 free(refstr);
5650 return NULL;
5653 static const struct got_error *
5654 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5656 const char *refname;
5658 if (worktree == NULL)
5659 return got_error(GOT_ERR_NOT_WORKTREE);
5661 refname = got_worktree_get_head_ref_name(worktree);
5663 if (strncmp(refname, "refs/heads/", 11) == 0)
5664 refname += 11;
5665 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5666 refname += 18;
5668 printf("%s\n", refname);
5670 return NULL;
5673 static const struct got_error *
5674 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5676 static const struct got_error *err = NULL;
5677 struct got_reflist_head refs;
5678 struct got_reflist_entry *re;
5679 struct got_reference *temp_ref = NULL;
5680 int rebase_in_progress, histedit_in_progress;
5682 TAILQ_INIT(&refs);
5684 if (worktree) {
5685 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5686 worktree);
5687 if (err)
5688 return err;
5690 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5691 worktree);
5692 if (err)
5693 return err;
5695 if (rebase_in_progress || histedit_in_progress) {
5696 err = got_ref_open(&temp_ref, repo,
5697 got_worktree_get_head_ref_name(worktree), 0);
5698 if (err)
5699 return err;
5700 list_branch(repo, worktree, temp_ref);
5701 got_ref_close(temp_ref);
5705 err = got_ref_list(&refs, repo, "refs/heads",
5706 got_ref_cmp_by_name, NULL);
5707 if (err)
5708 return err;
5710 TAILQ_FOREACH(re, &refs, entry)
5711 list_branch(repo, worktree, re->ref);
5713 got_ref_list_free(&refs);
5715 err = got_ref_list(&refs, repo, "refs/remotes",
5716 got_ref_cmp_by_name, NULL);
5717 if (err)
5718 return err;
5720 TAILQ_FOREACH(re, &refs, entry)
5721 list_branch(repo, worktree, re->ref);
5723 got_ref_list_free(&refs);
5725 return NULL;
5728 static const struct got_error *
5729 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5730 const char *branch_name)
5732 const struct got_error *err = NULL;
5733 struct got_reference *ref = NULL;
5734 char *refname, *remote_refname = NULL;
5736 if (strncmp(branch_name, "refs/", 5) == 0)
5737 branch_name += 5;
5738 if (strncmp(branch_name, "heads/", 6) == 0)
5739 branch_name += 6;
5740 else if (strncmp(branch_name, "remotes/", 8) == 0)
5741 branch_name += 8;
5743 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5744 return got_error_from_errno("asprintf");
5746 if (asprintf(&remote_refname, "refs/remotes/%s",
5747 branch_name) == -1) {
5748 err = got_error_from_errno("asprintf");
5749 goto done;
5752 err = got_ref_open(&ref, repo, refname, 0);
5753 if (err) {
5754 const struct got_error *err2;
5755 if (err->code != GOT_ERR_NOT_REF)
5756 goto done;
5758 * Keep 'err' intact such that if neither branch exists
5759 * we report "refs/heads" rather than "refs/remotes" in
5760 * our error message.
5762 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5763 if (err2)
5764 goto done;
5765 err = NULL;
5768 if (worktree &&
5769 strcmp(got_worktree_get_head_ref_name(worktree),
5770 got_ref_get_name(ref)) == 0) {
5771 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5772 "will not delete this work tree's current branch");
5773 goto done;
5776 err = delete_ref(repo, ref);
5777 done:
5778 if (ref)
5779 got_ref_close(ref);
5780 free(refname);
5781 free(remote_refname);
5782 return err;
5785 static const struct got_error *
5786 add_branch(struct got_repository *repo, const char *branch_name,
5787 struct got_object_id *base_commit_id)
5789 const struct got_error *err = NULL;
5790 struct got_reference *ref = NULL;
5791 char *base_refname = NULL, *refname = NULL;
5794 * Don't let the user create a branch name with a leading '-'.
5795 * While technically a valid reference name, this case is usually
5796 * an unintended typo.
5798 if (branch_name[0] == '-')
5799 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5801 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5802 branch_name += 11;
5804 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5805 err = got_error_from_errno("asprintf");
5806 goto done;
5809 err = got_ref_open(&ref, repo, refname, 0);
5810 if (err == NULL) {
5811 err = got_error(GOT_ERR_BRANCH_EXISTS);
5812 goto done;
5813 } else if (err->code != GOT_ERR_NOT_REF)
5814 goto done;
5816 err = got_ref_alloc(&ref, refname, base_commit_id);
5817 if (err)
5818 goto done;
5820 err = got_ref_write(ref, repo);
5821 done:
5822 if (ref)
5823 got_ref_close(ref);
5824 free(base_refname);
5825 free(refname);
5826 return err;
5829 static const struct got_error *
5830 cmd_branch(int argc, char *argv[])
5832 const struct got_error *error = NULL;
5833 struct got_repository *repo = NULL;
5834 struct got_worktree *worktree = NULL;
5835 char *cwd = NULL, *repo_path = NULL;
5836 int ch, do_list = 0, do_show = 0, do_update = 1;
5837 const char *delref = NULL, *commit_id_arg = NULL;
5838 struct got_reference *ref = NULL;
5839 struct got_pathlist_head paths;
5840 struct got_pathlist_entry *pe;
5841 struct got_object_id *commit_id = NULL;
5842 char *commit_id_str = NULL;
5844 TAILQ_INIT(&paths);
5846 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5847 switch (ch) {
5848 case 'c':
5849 commit_id_arg = optarg;
5850 break;
5851 case 'd':
5852 delref = optarg;
5853 break;
5854 case 'r':
5855 repo_path = realpath(optarg, NULL);
5856 if (repo_path == NULL)
5857 return got_error_from_errno2("realpath",
5858 optarg);
5859 got_path_strip_trailing_slashes(repo_path);
5860 break;
5861 case 'l':
5862 do_list = 1;
5863 break;
5864 case 'n':
5865 do_update = 0;
5866 break;
5867 default:
5868 usage_branch();
5869 /* NOTREACHED */
5873 if (do_list && delref)
5874 option_conflict('l', 'd');
5876 argc -= optind;
5877 argv += optind;
5879 if (!do_list && !delref && argc == 0)
5880 do_show = 1;
5882 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5883 errx(1, "-c option can only be used when creating a branch");
5885 if (do_list || delref) {
5886 if (argc > 0)
5887 usage_branch();
5888 } else if (!do_show && argc != 1)
5889 usage_branch();
5891 #ifndef PROFILE
5892 if (do_list || do_show) {
5893 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5894 NULL) == -1)
5895 err(1, "pledge");
5896 } else {
5897 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5898 "sendfd unveil", NULL) == -1)
5899 err(1, "pledge");
5901 #endif
5902 cwd = getcwd(NULL, 0);
5903 if (cwd == NULL) {
5904 error = got_error_from_errno("getcwd");
5905 goto done;
5908 if (repo_path == NULL) {
5909 error = got_worktree_open(&worktree, cwd);
5910 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5911 goto done;
5912 else
5913 error = NULL;
5914 if (worktree) {
5915 repo_path =
5916 strdup(got_worktree_get_repo_path(worktree));
5917 if (repo_path == NULL)
5918 error = got_error_from_errno("strdup");
5919 if (error)
5920 goto done;
5921 } else {
5922 repo_path = strdup(cwd);
5923 if (repo_path == NULL) {
5924 error = got_error_from_errno("strdup");
5925 goto done;
5930 error = got_repo_open(&repo, repo_path, NULL);
5931 if (error != NULL)
5932 goto done;
5934 error = apply_unveil(got_repo_get_path(repo), do_list,
5935 worktree ? got_worktree_get_root_path(worktree) : NULL);
5936 if (error)
5937 goto done;
5939 if (do_show)
5940 error = show_current_branch(repo, worktree);
5941 else if (do_list)
5942 error = list_branches(repo, worktree);
5943 else if (delref)
5944 error = delete_branch(repo, worktree, delref);
5945 else {
5946 struct got_reflist_head refs;
5947 TAILQ_INIT(&refs);
5948 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5949 NULL);
5950 if (error)
5951 goto done;
5952 if (commit_id_arg == NULL)
5953 commit_id_arg = worktree ?
5954 got_worktree_get_head_ref_name(worktree) :
5955 GOT_REF_HEAD;
5956 error = got_repo_match_object_id(&commit_id, NULL,
5957 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5958 got_ref_list_free(&refs);
5959 if (error)
5960 goto done;
5961 error = add_branch(repo, argv[0], commit_id);
5962 if (error)
5963 goto done;
5964 if (worktree && do_update) {
5965 struct got_update_progress_arg upa;
5966 char *branch_refname = NULL;
5968 error = got_object_id_str(&commit_id_str, commit_id);
5969 if (error)
5970 goto done;
5971 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5972 worktree);
5973 if (error)
5974 goto done;
5975 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5976 == -1) {
5977 error = got_error_from_errno("asprintf");
5978 goto done;
5980 error = got_ref_open(&ref, repo, branch_refname, 0);
5981 free(branch_refname);
5982 if (error)
5983 goto done;
5984 error = switch_head_ref(ref, commit_id, worktree,
5985 repo);
5986 if (error)
5987 goto done;
5988 error = got_worktree_set_base_commit_id(worktree, repo,
5989 commit_id);
5990 if (error)
5991 goto done;
5992 memset(&upa, 0, sizeof(upa));
5993 error = got_worktree_checkout_files(worktree, &paths,
5994 repo, update_progress, &upa, check_cancelled,
5995 NULL);
5996 if (error)
5997 goto done;
5998 if (upa.did_something)
5999 printf("Updated to commit %s\n", commit_id_str);
6000 print_update_progress_stats(&upa);
6003 done:
6004 if (ref)
6005 got_ref_close(ref);
6006 if (repo) {
6007 const struct got_error *close_err = got_repo_close(repo);
6008 if (error == NULL)
6009 error = close_err;
6011 if (worktree)
6012 got_worktree_close(worktree);
6013 free(cwd);
6014 free(repo_path);
6015 free(commit_id);
6016 free(commit_id_str);
6017 TAILQ_FOREACH(pe, &paths, entry)
6018 free((char *)pe->path);
6019 got_pathlist_free(&paths);
6020 return error;
6024 __dead static void
6025 usage_tag(void)
6027 fprintf(stderr,
6028 "usage: %s tag [-c commit] [-r repository] [-l] "
6029 "[-m message] name\n", getprogname());
6030 exit(1);
6033 #if 0
6034 static const struct got_error *
6035 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6037 const struct got_error *err = NULL;
6038 struct got_reflist_entry *re, *se, *new;
6039 struct got_object_id *re_id, *se_id;
6040 struct got_tag_object *re_tag, *se_tag;
6041 time_t re_time, se_time;
6043 STAILQ_FOREACH(re, tags, entry) {
6044 se = STAILQ_FIRST(sorted);
6045 if (se == NULL) {
6046 err = got_reflist_entry_dup(&new, re);
6047 if (err)
6048 return err;
6049 STAILQ_INSERT_HEAD(sorted, new, entry);
6050 continue;
6051 } else {
6052 err = got_ref_resolve(&re_id, repo, re->ref);
6053 if (err)
6054 break;
6055 err = got_object_open_as_tag(&re_tag, repo, re_id);
6056 free(re_id);
6057 if (err)
6058 break;
6059 re_time = got_object_tag_get_tagger_time(re_tag);
6060 got_object_tag_close(re_tag);
6063 while (se) {
6064 err = got_ref_resolve(&se_id, repo, re->ref);
6065 if (err)
6066 break;
6067 err = got_object_open_as_tag(&se_tag, repo, se_id);
6068 free(se_id);
6069 if (err)
6070 break;
6071 se_time = got_object_tag_get_tagger_time(se_tag);
6072 got_object_tag_close(se_tag);
6074 if (se_time > re_time) {
6075 err = got_reflist_entry_dup(&new, re);
6076 if (err)
6077 return err;
6078 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6079 break;
6081 se = STAILQ_NEXT(se, entry);
6082 continue;
6085 done:
6086 return err;
6088 #endif
6090 static const struct got_error *
6091 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6093 static const struct got_error *err = NULL;
6094 struct got_reflist_head refs;
6095 struct got_reflist_entry *re;
6097 TAILQ_INIT(&refs);
6099 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6100 if (err)
6101 return err;
6103 TAILQ_FOREACH(re, &refs, entry) {
6104 const char *refname;
6105 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6106 char datebuf[26];
6107 const char *tagger;
6108 time_t tagger_time;
6109 struct got_object_id *id;
6110 struct got_tag_object *tag;
6111 struct got_commit_object *commit = NULL;
6113 refname = got_ref_get_name(re->ref);
6114 if (strncmp(refname, "refs/tags/", 10) != 0)
6115 continue;
6116 refname += 10;
6117 refstr = got_ref_to_str(re->ref);
6118 if (refstr == NULL) {
6119 err = got_error_from_errno("got_ref_to_str");
6120 break;
6122 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6123 free(refstr);
6125 err = got_ref_resolve(&id, repo, re->ref);
6126 if (err)
6127 break;
6128 err = got_object_open_as_tag(&tag, repo, id);
6129 if (err) {
6130 if (err->code != GOT_ERR_OBJ_TYPE) {
6131 free(id);
6132 break;
6134 /* "lightweight" tag */
6135 err = got_object_open_as_commit(&commit, repo, id);
6136 if (err) {
6137 free(id);
6138 break;
6140 tagger = got_object_commit_get_committer(commit);
6141 tagger_time =
6142 got_object_commit_get_committer_time(commit);
6143 err = got_object_id_str(&id_str, id);
6144 free(id);
6145 if (err)
6146 break;
6147 } else {
6148 free(id);
6149 tagger = got_object_tag_get_tagger(tag);
6150 tagger_time = got_object_tag_get_tagger_time(tag);
6151 err = got_object_id_str(&id_str,
6152 got_object_tag_get_object_id(tag));
6153 if (err)
6154 break;
6156 printf("from: %s\n", tagger);
6157 datestr = get_datestr(&tagger_time, datebuf);
6158 if (datestr)
6159 printf("date: %s UTC\n", datestr);
6160 if (commit)
6161 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6162 else {
6163 switch (got_object_tag_get_object_type(tag)) {
6164 case GOT_OBJ_TYPE_BLOB:
6165 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6166 id_str);
6167 break;
6168 case GOT_OBJ_TYPE_TREE:
6169 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6170 id_str);
6171 break;
6172 case GOT_OBJ_TYPE_COMMIT:
6173 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6174 id_str);
6175 break;
6176 case GOT_OBJ_TYPE_TAG:
6177 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6178 id_str);
6179 break;
6180 default:
6181 break;
6184 free(id_str);
6185 if (commit) {
6186 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6187 if (err)
6188 break;
6189 got_object_commit_close(commit);
6190 } else {
6191 tagmsg0 = strdup(got_object_tag_get_message(tag));
6192 got_object_tag_close(tag);
6193 if (tagmsg0 == NULL) {
6194 err = got_error_from_errno("strdup");
6195 break;
6199 tagmsg = tagmsg0;
6200 do {
6201 line = strsep(&tagmsg, "\n");
6202 if (line)
6203 printf(" %s\n", line);
6204 } while (line);
6205 free(tagmsg0);
6208 got_ref_list_free(&refs);
6209 return NULL;
6212 static const struct got_error *
6213 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6214 const char *tag_name, const char *repo_path)
6216 const struct got_error *err = NULL;
6217 char *template = NULL, *initial_content = NULL;
6218 char *editor = NULL;
6219 int initial_content_len;
6220 int fd = -1;
6222 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6223 err = got_error_from_errno("asprintf");
6224 goto done;
6227 initial_content_len = asprintf(&initial_content,
6228 "\n# tagging commit %s as %s\n",
6229 commit_id_str, tag_name);
6230 if (initial_content_len == -1) {
6231 err = got_error_from_errno("asprintf");
6232 goto done;
6235 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6236 if (err)
6237 goto done;
6239 if (write(fd, initial_content, initial_content_len) == -1) {
6240 err = got_error_from_errno2("write", *tagmsg_path);
6241 goto done;
6244 err = get_editor(&editor);
6245 if (err)
6246 goto done;
6247 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6248 initial_content_len, 1);
6249 done:
6250 free(initial_content);
6251 free(template);
6252 free(editor);
6254 if (fd != -1 && close(fd) == -1 && err == NULL)
6255 err = got_error_from_errno2("close", *tagmsg_path);
6257 /* Editor is done; we can now apply unveil(2) */
6258 if (err == NULL)
6259 err = apply_unveil(repo_path, 0, NULL);
6260 if (err) {
6261 free(*tagmsg);
6262 *tagmsg = NULL;
6264 return err;
6267 static const struct got_error *
6268 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6269 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6271 const struct got_error *err = NULL;
6272 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6273 char *label = NULL, *commit_id_str = NULL;
6274 struct got_reference *ref = NULL;
6275 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6276 char *tagmsg_path = NULL, *tag_id_str = NULL;
6277 int preserve_tagmsg = 0;
6278 struct got_reflist_head refs;
6280 TAILQ_INIT(&refs);
6283 * Don't let the user create a tag name with a leading '-'.
6284 * While technically a valid reference name, this case is usually
6285 * an unintended typo.
6287 if (tag_name[0] == '-')
6288 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6290 err = get_author(&tagger, repo, worktree);
6291 if (err)
6292 return err;
6294 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6295 if (err)
6296 goto done;
6298 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6299 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6300 if (err)
6301 goto done;
6303 err = got_object_id_str(&commit_id_str, commit_id);
6304 if (err)
6305 goto done;
6307 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6308 refname = strdup(tag_name);
6309 if (refname == NULL) {
6310 err = got_error_from_errno("strdup");
6311 goto done;
6313 tag_name += 10;
6314 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6315 err = got_error_from_errno("asprintf");
6316 goto done;
6319 err = got_ref_open(&ref, repo, refname, 0);
6320 if (err == NULL) {
6321 err = got_error(GOT_ERR_TAG_EXISTS);
6322 goto done;
6323 } else if (err->code != GOT_ERR_NOT_REF)
6324 goto done;
6326 if (tagmsg_arg == NULL) {
6327 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6328 tag_name, got_repo_get_path(repo));
6329 if (err) {
6330 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6331 tagmsg_path != NULL)
6332 preserve_tagmsg = 1;
6333 goto done;
6337 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6338 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6339 if (err) {
6340 if (tagmsg_path)
6341 preserve_tagmsg = 1;
6342 goto done;
6345 err = got_ref_alloc(&ref, refname, tag_id);
6346 if (err) {
6347 if (tagmsg_path)
6348 preserve_tagmsg = 1;
6349 goto done;
6352 err = got_ref_write(ref, repo);
6353 if (err) {
6354 if (tagmsg_path)
6355 preserve_tagmsg = 1;
6356 goto done;
6359 err = got_object_id_str(&tag_id_str, tag_id);
6360 if (err) {
6361 if (tagmsg_path)
6362 preserve_tagmsg = 1;
6363 goto done;
6365 printf("Created tag %s\n", tag_id_str);
6366 done:
6367 if (preserve_tagmsg) {
6368 fprintf(stderr, "%s: tag message preserved in %s\n",
6369 getprogname(), tagmsg_path);
6370 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6371 err = got_error_from_errno2("unlink", tagmsg_path);
6372 free(tag_id_str);
6373 if (ref)
6374 got_ref_close(ref);
6375 free(commit_id);
6376 free(commit_id_str);
6377 free(refname);
6378 free(tagmsg);
6379 free(tagmsg_path);
6380 free(tagger);
6381 got_ref_list_free(&refs);
6382 return err;
6385 static const struct got_error *
6386 cmd_tag(int argc, char *argv[])
6388 const struct got_error *error = NULL;
6389 struct got_repository *repo = NULL;
6390 struct got_worktree *worktree = NULL;
6391 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6392 char *gitconfig_path = NULL;
6393 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6394 int ch, do_list = 0;
6396 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6397 switch (ch) {
6398 case 'c':
6399 commit_id_arg = optarg;
6400 break;
6401 case 'm':
6402 tagmsg = optarg;
6403 break;
6404 case 'r':
6405 repo_path = realpath(optarg, NULL);
6406 if (repo_path == NULL)
6407 return got_error_from_errno2("realpath",
6408 optarg);
6409 got_path_strip_trailing_slashes(repo_path);
6410 break;
6411 case 'l':
6412 do_list = 1;
6413 break;
6414 default:
6415 usage_tag();
6416 /* NOTREACHED */
6420 argc -= optind;
6421 argv += optind;
6423 if (do_list) {
6424 if (commit_id_arg != NULL)
6425 errx(1,
6426 "-c option can only be used when creating a tag");
6427 if (tagmsg)
6428 option_conflict('l', 'm');
6429 if (argc > 0)
6430 usage_tag();
6431 } else if (argc != 1)
6432 usage_tag();
6434 tag_name = argv[0];
6436 #ifndef PROFILE
6437 if (do_list) {
6438 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6439 NULL) == -1)
6440 err(1, "pledge");
6441 } else {
6442 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6443 "sendfd unveil", NULL) == -1)
6444 err(1, "pledge");
6446 #endif
6447 cwd = getcwd(NULL, 0);
6448 if (cwd == NULL) {
6449 error = got_error_from_errno("getcwd");
6450 goto done;
6453 if (repo_path == NULL) {
6454 error = got_worktree_open(&worktree, cwd);
6455 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6456 goto done;
6457 else
6458 error = NULL;
6459 if (worktree) {
6460 repo_path =
6461 strdup(got_worktree_get_repo_path(worktree));
6462 if (repo_path == NULL)
6463 error = got_error_from_errno("strdup");
6464 if (error)
6465 goto done;
6466 } else {
6467 repo_path = strdup(cwd);
6468 if (repo_path == NULL) {
6469 error = got_error_from_errno("strdup");
6470 goto done;
6475 if (do_list) {
6476 error = got_repo_open(&repo, repo_path, NULL);
6477 if (error != NULL)
6478 goto done;
6479 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6480 if (error)
6481 goto done;
6482 error = list_tags(repo, worktree);
6483 } else {
6484 error = get_gitconfig_path(&gitconfig_path);
6485 if (error)
6486 goto done;
6487 error = got_repo_open(&repo, repo_path, gitconfig_path);
6488 if (error != NULL)
6489 goto done;
6491 if (tagmsg) {
6492 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6493 if (error)
6494 goto done;
6497 if (commit_id_arg == NULL) {
6498 struct got_reference *head_ref;
6499 struct got_object_id *commit_id;
6500 error = got_ref_open(&head_ref, repo,
6501 worktree ? got_worktree_get_head_ref_name(worktree)
6502 : GOT_REF_HEAD, 0);
6503 if (error)
6504 goto done;
6505 error = got_ref_resolve(&commit_id, repo, head_ref);
6506 got_ref_close(head_ref);
6507 if (error)
6508 goto done;
6509 error = got_object_id_str(&commit_id_str, commit_id);
6510 free(commit_id);
6511 if (error)
6512 goto done;
6515 error = add_tag(repo, worktree, tag_name,
6516 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6518 done:
6519 if (repo) {
6520 const struct got_error *close_err = got_repo_close(repo);
6521 if (error == NULL)
6522 error = close_err;
6524 if (worktree)
6525 got_worktree_close(worktree);
6526 free(cwd);
6527 free(repo_path);
6528 free(gitconfig_path);
6529 free(commit_id_str);
6530 return error;
6533 __dead static void
6534 usage_add(void)
6536 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6537 getprogname());
6538 exit(1);
6541 static const struct got_error *
6542 add_progress(void *arg, unsigned char status, const char *path)
6544 while (path[0] == '/')
6545 path++;
6546 printf("%c %s\n", status, path);
6547 return NULL;
6550 static const struct got_error *
6551 cmd_add(int argc, char *argv[])
6553 const struct got_error *error = NULL;
6554 struct got_repository *repo = NULL;
6555 struct got_worktree *worktree = NULL;
6556 char *cwd = NULL;
6557 struct got_pathlist_head paths;
6558 struct got_pathlist_entry *pe;
6559 int ch, can_recurse = 0, no_ignores = 0;
6561 TAILQ_INIT(&paths);
6563 while ((ch = getopt(argc, argv, "IR")) != -1) {
6564 switch (ch) {
6565 case 'I':
6566 no_ignores = 1;
6567 break;
6568 case 'R':
6569 can_recurse = 1;
6570 break;
6571 default:
6572 usage_add();
6573 /* NOTREACHED */
6577 argc -= optind;
6578 argv += optind;
6580 #ifndef PROFILE
6581 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6582 NULL) == -1)
6583 err(1, "pledge");
6584 #endif
6585 if (argc < 1)
6586 usage_add();
6588 cwd = getcwd(NULL, 0);
6589 if (cwd == NULL) {
6590 error = got_error_from_errno("getcwd");
6591 goto done;
6594 error = got_worktree_open(&worktree, cwd);
6595 if (error) {
6596 if (error->code == GOT_ERR_NOT_WORKTREE)
6597 error = wrap_not_worktree_error(error, "add", cwd);
6598 goto done;
6601 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6602 NULL);
6603 if (error != NULL)
6604 goto done;
6606 error = apply_unveil(got_repo_get_path(repo), 1,
6607 got_worktree_get_root_path(worktree));
6608 if (error)
6609 goto done;
6611 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6612 if (error)
6613 goto done;
6615 if (!can_recurse) {
6616 char *ondisk_path;
6617 struct stat sb;
6618 TAILQ_FOREACH(pe, &paths, entry) {
6619 if (asprintf(&ondisk_path, "%s/%s",
6620 got_worktree_get_root_path(worktree),
6621 pe->path) == -1) {
6622 error = got_error_from_errno("asprintf");
6623 goto done;
6625 if (lstat(ondisk_path, &sb) == -1) {
6626 if (errno == ENOENT) {
6627 free(ondisk_path);
6628 continue;
6630 error = got_error_from_errno2("lstat",
6631 ondisk_path);
6632 free(ondisk_path);
6633 goto done;
6635 free(ondisk_path);
6636 if (S_ISDIR(sb.st_mode)) {
6637 error = got_error_msg(GOT_ERR_BAD_PATH,
6638 "adding directories requires -R option");
6639 goto done;
6644 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6645 NULL, repo, no_ignores);
6646 done:
6647 if (repo) {
6648 const struct got_error *close_err = got_repo_close(repo);
6649 if (error == NULL)
6650 error = close_err;
6652 if (worktree)
6653 got_worktree_close(worktree);
6654 TAILQ_FOREACH(pe, &paths, entry)
6655 free((char *)pe->path);
6656 got_pathlist_free(&paths);
6657 free(cwd);
6658 return error;
6661 __dead static void
6662 usage_remove(void)
6664 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6665 "path ...\n", getprogname());
6666 exit(1);
6669 static const struct got_error *
6670 print_remove_status(void *arg, unsigned char status,
6671 unsigned char staged_status, const char *path)
6673 while (path[0] == '/')
6674 path++;
6675 if (status == GOT_STATUS_NONEXISTENT)
6676 return NULL;
6677 if (status == staged_status && (status == GOT_STATUS_DELETE))
6678 status = GOT_STATUS_NO_CHANGE;
6679 printf("%c%c %s\n", status, staged_status, path);
6680 return NULL;
6683 static const struct got_error *
6684 cmd_remove(int argc, char *argv[])
6686 const struct got_error *error = NULL;
6687 struct got_worktree *worktree = NULL;
6688 struct got_repository *repo = NULL;
6689 const char *status_codes = NULL;
6690 char *cwd = NULL;
6691 struct got_pathlist_head paths;
6692 struct got_pathlist_entry *pe;
6693 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6695 TAILQ_INIT(&paths);
6697 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6698 switch (ch) {
6699 case 'f':
6700 delete_local_mods = 1;
6701 break;
6702 case 'k':
6703 keep_on_disk = 1;
6704 break;
6705 case 'R':
6706 can_recurse = 1;
6707 break;
6708 case 's':
6709 for (i = 0; i < strlen(optarg); i++) {
6710 switch (optarg[i]) {
6711 case GOT_STATUS_MODIFY:
6712 delete_local_mods = 1;
6713 break;
6714 case GOT_STATUS_MISSING:
6715 break;
6716 default:
6717 errx(1, "invalid status code '%c'",
6718 optarg[i]);
6721 status_codes = optarg;
6722 break;
6723 default:
6724 usage_remove();
6725 /* NOTREACHED */
6729 argc -= optind;
6730 argv += optind;
6732 #ifndef PROFILE
6733 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6734 NULL) == -1)
6735 err(1, "pledge");
6736 #endif
6737 if (argc < 1)
6738 usage_remove();
6740 cwd = getcwd(NULL, 0);
6741 if (cwd == NULL) {
6742 error = got_error_from_errno("getcwd");
6743 goto done;
6745 error = got_worktree_open(&worktree, cwd);
6746 if (error) {
6747 if (error->code == GOT_ERR_NOT_WORKTREE)
6748 error = wrap_not_worktree_error(error, "remove", cwd);
6749 goto done;
6752 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6753 NULL);
6754 if (error)
6755 goto done;
6757 error = apply_unveil(got_repo_get_path(repo), 1,
6758 got_worktree_get_root_path(worktree));
6759 if (error)
6760 goto done;
6762 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6763 if (error)
6764 goto done;
6766 if (!can_recurse) {
6767 char *ondisk_path;
6768 struct stat sb;
6769 TAILQ_FOREACH(pe, &paths, entry) {
6770 if (asprintf(&ondisk_path, "%s/%s",
6771 got_worktree_get_root_path(worktree),
6772 pe->path) == -1) {
6773 error = got_error_from_errno("asprintf");
6774 goto done;
6776 if (lstat(ondisk_path, &sb) == -1) {
6777 if (errno == ENOENT) {
6778 free(ondisk_path);
6779 continue;
6781 error = got_error_from_errno2("lstat",
6782 ondisk_path);
6783 free(ondisk_path);
6784 goto done;
6786 free(ondisk_path);
6787 if (S_ISDIR(sb.st_mode)) {
6788 error = got_error_msg(GOT_ERR_BAD_PATH,
6789 "removing directories requires -R option");
6790 goto done;
6795 error = got_worktree_schedule_delete(worktree, &paths,
6796 delete_local_mods, status_codes, print_remove_status, NULL,
6797 repo, keep_on_disk);
6798 done:
6799 if (repo) {
6800 const struct got_error *close_err = got_repo_close(repo);
6801 if (error == NULL)
6802 error = close_err;
6804 if (worktree)
6805 got_worktree_close(worktree);
6806 TAILQ_FOREACH(pe, &paths, entry)
6807 free((char *)pe->path);
6808 got_pathlist_free(&paths);
6809 free(cwd);
6810 return error;
6813 __dead static void
6814 usage_revert(void)
6816 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6817 "path ...\n", getprogname());
6818 exit(1);
6821 static const struct got_error *
6822 revert_progress(void *arg, unsigned char status, const char *path)
6824 if (status == GOT_STATUS_UNVERSIONED)
6825 return NULL;
6827 while (path[0] == '/')
6828 path++;
6829 printf("%c %s\n", status, path);
6830 return NULL;
6833 struct choose_patch_arg {
6834 FILE *patch_script_file;
6835 const char *action;
6838 static const struct got_error *
6839 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6840 int nchanges, const char *action)
6842 char *line = NULL;
6843 size_t linesize = 0;
6844 ssize_t linelen;
6846 switch (status) {
6847 case GOT_STATUS_ADD:
6848 printf("A %s\n%s this addition? [y/n] ", path, action);
6849 break;
6850 case GOT_STATUS_DELETE:
6851 printf("D %s\n%s this deletion? [y/n] ", path, action);
6852 break;
6853 case GOT_STATUS_MODIFY:
6854 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6855 return got_error_from_errno("fseek");
6856 printf(GOT_COMMIT_SEP_STR);
6857 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6858 printf("%s", line);
6859 if (ferror(patch_file))
6860 return got_error_from_errno("getline");
6861 printf(GOT_COMMIT_SEP_STR);
6862 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6863 path, n, nchanges, action);
6864 break;
6865 default:
6866 return got_error_path(path, GOT_ERR_FILE_STATUS);
6869 return NULL;
6872 static const struct got_error *
6873 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6874 FILE *patch_file, int n, int nchanges)
6876 const struct got_error *err = NULL;
6877 char *line = NULL;
6878 size_t linesize = 0;
6879 ssize_t linelen;
6880 int resp = ' ';
6881 struct choose_patch_arg *a = arg;
6883 *choice = GOT_PATCH_CHOICE_NONE;
6885 if (a->patch_script_file) {
6886 char *nl;
6887 err = show_change(status, path, patch_file, n, nchanges,
6888 a->action);
6889 if (err)
6890 return err;
6891 linelen = getline(&line, &linesize, a->patch_script_file);
6892 if (linelen == -1) {
6893 if (ferror(a->patch_script_file))
6894 return got_error_from_errno("getline");
6895 return NULL;
6897 nl = strchr(line, '\n');
6898 if (nl)
6899 *nl = '\0';
6900 if (strcmp(line, "y") == 0) {
6901 *choice = GOT_PATCH_CHOICE_YES;
6902 printf("y\n");
6903 } else if (strcmp(line, "n") == 0) {
6904 *choice = GOT_PATCH_CHOICE_NO;
6905 printf("n\n");
6906 } else if (strcmp(line, "q") == 0 &&
6907 status == GOT_STATUS_MODIFY) {
6908 *choice = GOT_PATCH_CHOICE_QUIT;
6909 printf("q\n");
6910 } else
6911 printf("invalid response '%s'\n", line);
6912 free(line);
6913 return NULL;
6916 while (resp != 'y' && resp != 'n' && resp != 'q') {
6917 err = show_change(status, path, patch_file, n, nchanges,
6918 a->action);
6919 if (err)
6920 return err;
6921 resp = getchar();
6922 if (resp == '\n')
6923 resp = getchar();
6924 if (status == GOT_STATUS_MODIFY) {
6925 if (resp != 'y' && resp != 'n' && resp != 'q') {
6926 printf("invalid response '%c'\n", resp);
6927 resp = ' ';
6929 } else if (resp != 'y' && resp != 'n') {
6930 printf("invalid response '%c'\n", resp);
6931 resp = ' ';
6935 if (resp == 'y')
6936 *choice = GOT_PATCH_CHOICE_YES;
6937 else if (resp == 'n')
6938 *choice = GOT_PATCH_CHOICE_NO;
6939 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6940 *choice = GOT_PATCH_CHOICE_QUIT;
6942 return NULL;
6946 static const struct got_error *
6947 cmd_revert(int argc, char *argv[])
6949 const struct got_error *error = NULL;
6950 struct got_worktree *worktree = NULL;
6951 struct got_repository *repo = NULL;
6952 char *cwd = NULL, *path = NULL;
6953 struct got_pathlist_head paths;
6954 struct got_pathlist_entry *pe;
6955 int ch, can_recurse = 0, pflag = 0;
6956 FILE *patch_script_file = NULL;
6957 const char *patch_script_path = NULL;
6958 struct choose_patch_arg cpa;
6960 TAILQ_INIT(&paths);
6962 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6963 switch (ch) {
6964 case 'p':
6965 pflag = 1;
6966 break;
6967 case 'F':
6968 patch_script_path = optarg;
6969 break;
6970 case 'R':
6971 can_recurse = 1;
6972 break;
6973 default:
6974 usage_revert();
6975 /* NOTREACHED */
6979 argc -= optind;
6980 argv += optind;
6982 #ifndef PROFILE
6983 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6984 "unveil", NULL) == -1)
6985 err(1, "pledge");
6986 #endif
6987 if (argc < 1)
6988 usage_revert();
6989 if (patch_script_path && !pflag)
6990 errx(1, "-F option can only be used together with -p option");
6992 cwd = getcwd(NULL, 0);
6993 if (cwd == NULL) {
6994 error = got_error_from_errno("getcwd");
6995 goto done;
6997 error = got_worktree_open(&worktree, cwd);
6998 if (error) {
6999 if (error->code == GOT_ERR_NOT_WORKTREE)
7000 error = wrap_not_worktree_error(error, "revert", cwd);
7001 goto done;
7004 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7005 NULL);
7006 if (error != NULL)
7007 goto done;
7009 if (patch_script_path) {
7010 patch_script_file = fopen(patch_script_path, "r");
7011 if (patch_script_file == NULL) {
7012 error = got_error_from_errno2("fopen",
7013 patch_script_path);
7014 goto done;
7017 error = apply_unveil(got_repo_get_path(repo), 1,
7018 got_worktree_get_root_path(worktree));
7019 if (error)
7020 goto done;
7022 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7023 if (error)
7024 goto done;
7026 if (!can_recurse) {
7027 char *ondisk_path;
7028 struct stat sb;
7029 TAILQ_FOREACH(pe, &paths, entry) {
7030 if (asprintf(&ondisk_path, "%s/%s",
7031 got_worktree_get_root_path(worktree),
7032 pe->path) == -1) {
7033 error = got_error_from_errno("asprintf");
7034 goto done;
7036 if (lstat(ondisk_path, &sb) == -1) {
7037 if (errno == ENOENT) {
7038 free(ondisk_path);
7039 continue;
7041 error = got_error_from_errno2("lstat",
7042 ondisk_path);
7043 free(ondisk_path);
7044 goto done;
7046 free(ondisk_path);
7047 if (S_ISDIR(sb.st_mode)) {
7048 error = got_error_msg(GOT_ERR_BAD_PATH,
7049 "reverting directories requires -R option");
7050 goto done;
7055 cpa.patch_script_file = patch_script_file;
7056 cpa.action = "revert";
7057 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7058 pflag ? choose_patch : NULL, &cpa, repo);
7059 done:
7060 if (patch_script_file && fclose(patch_script_file) == EOF &&
7061 error == NULL)
7062 error = got_error_from_errno2("fclose", patch_script_path);
7063 if (repo) {
7064 const struct got_error *close_err = got_repo_close(repo);
7065 if (error == NULL)
7066 error = close_err;
7068 if (worktree)
7069 got_worktree_close(worktree);
7070 free(path);
7071 free(cwd);
7072 return error;
7075 __dead static void
7076 usage_commit(void)
7078 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7079 "[path ...]\n", getprogname());
7080 exit(1);
7083 struct collect_commit_logmsg_arg {
7084 const char *cmdline_log;
7085 const char *prepared_log;
7086 int non_interactive;
7087 const char *editor;
7088 const char *worktree_path;
7089 const char *branch_name;
7090 const char *repo_path;
7091 char *logmsg_path;
7095 static const struct got_error *
7096 read_prepared_logmsg(char **logmsg, const char *path)
7098 const struct got_error *err = NULL;
7099 FILE *f = NULL;
7100 struct stat sb;
7101 size_t r;
7103 *logmsg = NULL;
7104 memset(&sb, 0, sizeof(sb));
7106 f = fopen(path, "r");
7107 if (f == NULL)
7108 return got_error_from_errno2("fopen", path);
7110 if (fstat(fileno(f), &sb) == -1) {
7111 err = got_error_from_errno2("fstat", path);
7112 goto done;
7114 if (sb.st_size == 0) {
7115 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7116 goto done;
7119 *logmsg = malloc(sb.st_size + 1);
7120 if (*logmsg == NULL) {
7121 err = got_error_from_errno("malloc");
7122 goto done;
7125 r = fread(*logmsg, 1, sb.st_size, f);
7126 if (r != sb.st_size) {
7127 if (ferror(f))
7128 err = got_error_from_errno2("fread", path);
7129 else
7130 err = got_error(GOT_ERR_IO);
7131 goto done;
7133 (*logmsg)[sb.st_size] = '\0';
7134 done:
7135 if (fclose(f) == EOF && err == NULL)
7136 err = got_error_from_errno2("fclose", path);
7137 if (err) {
7138 free(*logmsg);
7139 *logmsg = NULL;
7141 return err;
7145 static const struct got_error *
7146 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7147 void *arg)
7149 char *initial_content = NULL;
7150 struct got_pathlist_entry *pe;
7151 const struct got_error *err = NULL;
7152 char *template = NULL;
7153 struct collect_commit_logmsg_arg *a = arg;
7154 int initial_content_len;
7155 int fd = -1;
7156 size_t len;
7158 /* if a message was specified on the command line, just use it */
7159 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7160 len = strlen(a->cmdline_log) + 1;
7161 *logmsg = malloc(len + 1);
7162 if (*logmsg == NULL)
7163 return got_error_from_errno("malloc");
7164 strlcpy(*logmsg, a->cmdline_log, len);
7165 return NULL;
7166 } else if (a->prepared_log != NULL && a->non_interactive)
7167 return read_prepared_logmsg(logmsg, a->prepared_log);
7169 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7170 return got_error_from_errno("asprintf");
7172 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7173 if (err)
7174 goto done;
7176 if (a->prepared_log) {
7177 char *msg;
7178 err = read_prepared_logmsg(&msg, a->prepared_log);
7179 if (err)
7180 goto done;
7181 if (write(fd, msg, strlen(msg)) == -1) {
7182 err = got_error_from_errno2("write", a->logmsg_path);
7183 free(msg);
7184 goto done;
7186 free(msg);
7189 initial_content_len = asprintf(&initial_content,
7190 "\n# changes to be committed on branch %s:\n",
7191 a->branch_name);
7192 if (initial_content_len == -1) {
7193 err = got_error_from_errno("asprintf");
7194 goto done;
7197 if (write(fd, initial_content, initial_content_len) == -1) {
7198 err = got_error_from_errno2("write", a->logmsg_path);
7199 goto done;
7202 TAILQ_FOREACH(pe, commitable_paths, entry) {
7203 struct got_commitable *ct = pe->data;
7204 dprintf(fd, "# %c %s\n",
7205 got_commitable_get_status(ct),
7206 got_commitable_get_path(ct));
7209 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7210 initial_content_len, a->prepared_log ? 0 : 1);
7211 done:
7212 free(initial_content);
7213 free(template);
7215 if (fd != -1 && close(fd) == -1 && err == NULL)
7216 err = got_error_from_errno2("close", a->logmsg_path);
7218 /* Editor is done; we can now apply unveil(2) */
7219 if (err == NULL)
7220 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7221 if (err) {
7222 free(*logmsg);
7223 *logmsg = NULL;
7225 return err;
7228 static const struct got_error *
7229 cmd_commit(int argc, char *argv[])
7231 const struct got_error *error = NULL;
7232 struct got_worktree *worktree = NULL;
7233 struct got_repository *repo = NULL;
7234 char *cwd = NULL, *id_str = NULL;
7235 struct got_object_id *id = NULL;
7236 const char *logmsg = NULL;
7237 char *prepared_logmsg = NULL;
7238 struct collect_commit_logmsg_arg cl_arg;
7239 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7240 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7241 int allow_bad_symlinks = 0, non_interactive = 0;
7242 struct got_pathlist_head paths;
7244 TAILQ_INIT(&paths);
7245 cl_arg.logmsg_path = NULL;
7247 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7248 switch (ch) {
7249 case 'F':
7250 if (logmsg != NULL)
7251 option_conflict('F', 'm');
7252 prepared_logmsg = realpath(optarg, NULL);
7253 if (prepared_logmsg == NULL)
7254 return got_error_from_errno2("realpath",
7255 optarg);
7256 break;
7257 case 'm':
7258 if (prepared_logmsg)
7259 option_conflict('m', 'F');
7260 logmsg = optarg;
7261 break;
7262 case 'N':
7263 non_interactive = 1;
7264 break;
7265 case 'S':
7266 allow_bad_symlinks = 1;
7267 break;
7268 default:
7269 usage_commit();
7270 /* NOTREACHED */
7274 argc -= optind;
7275 argv += optind;
7277 #ifndef PROFILE
7278 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7279 "unveil", NULL) == -1)
7280 err(1, "pledge");
7281 #endif
7282 cwd = getcwd(NULL, 0);
7283 if (cwd == NULL) {
7284 error = got_error_from_errno("getcwd");
7285 goto done;
7287 error = got_worktree_open(&worktree, cwd);
7288 if (error) {
7289 if (error->code == GOT_ERR_NOT_WORKTREE)
7290 error = wrap_not_worktree_error(error, "commit", cwd);
7291 goto done;
7294 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7295 if (error)
7296 goto done;
7297 if (rebase_in_progress) {
7298 error = got_error(GOT_ERR_REBASING);
7299 goto done;
7302 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7303 worktree);
7304 if (error)
7305 goto done;
7307 error = get_gitconfig_path(&gitconfig_path);
7308 if (error)
7309 goto done;
7310 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7311 gitconfig_path);
7312 if (error != NULL)
7313 goto done;
7315 error = get_author(&author, repo, worktree);
7316 if (error)
7317 return error;
7320 * unveil(2) traverses exec(2); if an editor is used we have
7321 * to apply unveil after the log message has been written.
7323 if (logmsg == NULL || strlen(logmsg) == 0)
7324 error = get_editor(&editor);
7325 else
7326 error = apply_unveil(got_repo_get_path(repo), 0,
7327 got_worktree_get_root_path(worktree));
7328 if (error)
7329 goto done;
7331 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7332 if (error)
7333 goto done;
7335 cl_arg.editor = editor;
7336 cl_arg.cmdline_log = logmsg;
7337 cl_arg.prepared_log = prepared_logmsg;
7338 cl_arg.non_interactive = non_interactive;
7339 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7340 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7341 if (!histedit_in_progress) {
7342 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7343 error = got_error(GOT_ERR_COMMIT_BRANCH);
7344 goto done;
7346 cl_arg.branch_name += 11;
7348 cl_arg.repo_path = got_repo_get_path(repo);
7349 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7350 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7351 print_status, NULL, repo);
7352 if (error) {
7353 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7354 cl_arg.logmsg_path != NULL)
7355 preserve_logmsg = 1;
7356 goto done;
7359 error = got_object_id_str(&id_str, id);
7360 if (error)
7361 goto done;
7362 printf("Created commit %s\n", id_str);
7363 done:
7364 if (preserve_logmsg) {
7365 fprintf(stderr, "%s: log message preserved in %s\n",
7366 getprogname(), cl_arg.logmsg_path);
7367 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7368 error == NULL)
7369 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7370 free(cl_arg.logmsg_path);
7371 if (repo) {
7372 const struct got_error *close_err = got_repo_close(repo);
7373 if (error == NULL)
7374 error = close_err;
7376 if (worktree)
7377 got_worktree_close(worktree);
7378 free(cwd);
7379 free(id_str);
7380 free(gitconfig_path);
7381 free(editor);
7382 free(author);
7383 free(prepared_logmsg);
7384 return error;
7387 __dead static void
7388 usage_send(void)
7390 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7391 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7392 "[remote-repository]\n", getprogname());
7393 exit(1);
7396 struct got_send_progress_arg {
7397 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7398 int verbosity;
7399 int last_ncommits;
7400 int last_nobj_total;
7401 int last_p_deltify;
7402 int last_p_written;
7403 int last_p_sent;
7404 int printed_something;
7405 int sent_something;
7406 struct got_pathlist_head *delete_branches;
7409 static const struct got_error *
7410 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7411 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7412 int success)
7414 struct got_send_progress_arg *a = arg;
7415 char scaled_packsize[FMT_SCALED_STRSIZE];
7416 char scaled_sent[FMT_SCALED_STRSIZE];
7417 int p_deltify = 0, p_written = 0, p_sent = 0;
7418 int print_searching = 0, print_total = 0;
7419 int print_deltify = 0, print_written = 0, print_sent = 0;
7421 if (a->verbosity < 0)
7422 return NULL;
7424 if (refname) {
7425 const char *status = success ? "accepted" : "rejected";
7427 if (success) {
7428 struct got_pathlist_entry *pe;
7429 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7430 const char *branchname = pe->path;
7431 if (got_path_cmp(branchname, refname,
7432 strlen(branchname), strlen(refname)) == 0) {
7433 status = "deleted";
7434 a->sent_something = 1;
7435 break;
7440 if (a->printed_something)
7441 putchar('\n');
7442 printf("Server has %s %s", status, refname);
7443 a->printed_something = 1;
7444 return NULL;
7447 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7448 return got_error_from_errno("fmt_scaled");
7449 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7450 return got_error_from_errno("fmt_scaled");
7452 if (a->last_ncommits != ncommits) {
7453 print_searching = 1;
7454 a->last_ncommits = ncommits;
7457 if (a->last_nobj_total != nobj_total) {
7458 print_searching = 1;
7459 print_total = 1;
7460 a->last_nobj_total = nobj_total;
7463 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7464 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7465 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7466 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7467 return got_error(GOT_ERR_NO_SPACE);
7470 if (nobj_deltify > 0 || nobj_written > 0) {
7471 if (nobj_deltify > 0) {
7472 p_deltify = (nobj_deltify * 100) / nobj_total;
7473 if (p_deltify != a->last_p_deltify) {
7474 a->last_p_deltify = p_deltify;
7475 print_searching = 1;
7476 print_total = 1;
7477 print_deltify = 1;
7480 if (nobj_written > 0) {
7481 p_written = (nobj_written * 100) / nobj_total;
7482 if (p_written != a->last_p_written) {
7483 a->last_p_written = p_written;
7484 print_searching = 1;
7485 print_total = 1;
7486 print_deltify = 1;
7487 print_written = 1;
7492 if (bytes_sent > 0) {
7493 p_sent = (bytes_sent * 100) / packfile_size;
7494 if (p_sent != a->last_p_sent) {
7495 a->last_p_sent = p_sent;
7496 print_searching = 1;
7497 print_total = 1;
7498 print_deltify = 1;
7499 print_written = 1;
7500 print_sent = 1;
7502 a->sent_something = 1;
7505 if (print_searching || print_total || print_deltify || print_written ||
7506 print_sent)
7507 printf("\r");
7508 if (print_searching)
7509 printf("packing %d reference%s", ncommits,
7510 ncommits == 1 ? "" : "s");
7511 if (print_total)
7512 printf("; %d object%s", nobj_total,
7513 nobj_total == 1 ? "" : "s");
7514 if (print_deltify)
7515 printf("; deltify: %d%%", p_deltify);
7516 if (print_sent)
7517 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7518 scaled_packsize, p_sent);
7519 else if (print_written)
7520 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7521 scaled_packsize, p_written);
7522 if (print_searching || print_total || print_deltify ||
7523 print_written || print_sent) {
7524 a->printed_something = 1;
7525 fflush(stdout);
7527 return NULL;
7530 static const struct got_error *
7531 cmd_send(int argc, char *argv[])
7533 const struct got_error *error = NULL;
7534 char *cwd = NULL, *repo_path = NULL;
7535 const char *remote_name;
7536 char *proto = NULL, *host = NULL, *port = NULL;
7537 char *repo_name = NULL, *server_path = NULL;
7538 const struct got_remote_repo *remotes, *remote = NULL;
7539 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7540 struct got_repository *repo = NULL;
7541 struct got_worktree *worktree = NULL;
7542 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7543 struct got_pathlist_head branches;
7544 struct got_pathlist_head tags;
7545 struct got_reflist_head all_branches;
7546 struct got_reflist_head all_tags;
7547 struct got_pathlist_head delete_args;
7548 struct got_pathlist_head delete_branches;
7549 struct got_reflist_entry *re;
7550 struct got_pathlist_entry *pe;
7551 int i, ch, sendfd = -1, sendstatus;
7552 pid_t sendpid = -1;
7553 struct got_send_progress_arg spa;
7554 int verbosity = 0, overwrite_refs = 0;
7555 int send_all_branches = 0, send_all_tags = 0;
7556 struct got_reference *ref = NULL;
7558 TAILQ_INIT(&branches);
7559 TAILQ_INIT(&tags);
7560 TAILQ_INIT(&all_branches);
7561 TAILQ_INIT(&all_tags);
7562 TAILQ_INIT(&delete_args);
7563 TAILQ_INIT(&delete_branches);
7565 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7566 switch (ch) {
7567 case 'a':
7568 send_all_branches = 1;
7569 break;
7570 case 'b':
7571 error = got_pathlist_append(&branches, optarg, NULL);
7572 if (error)
7573 return error;
7574 nbranches++;
7575 break;
7576 case 'd':
7577 error = got_pathlist_append(&delete_args, optarg, NULL);
7578 if (error)
7579 return error;
7580 break;
7581 case 'f':
7582 overwrite_refs = 1;
7583 break;
7584 case 'r':
7585 repo_path = realpath(optarg, NULL);
7586 if (repo_path == NULL)
7587 return got_error_from_errno2("realpath",
7588 optarg);
7589 got_path_strip_trailing_slashes(repo_path);
7590 break;
7591 case 't':
7592 error = got_pathlist_append(&tags, optarg, NULL);
7593 if (error)
7594 return error;
7595 ntags++;
7596 break;
7597 case 'T':
7598 send_all_tags = 1;
7599 break;
7600 case 'v':
7601 if (verbosity < 0)
7602 verbosity = 0;
7603 else if (verbosity < 3)
7604 verbosity++;
7605 break;
7606 case 'q':
7607 verbosity = -1;
7608 break;
7609 default:
7610 usage_send();
7611 /* NOTREACHED */
7614 argc -= optind;
7615 argv += optind;
7617 if (send_all_branches && !TAILQ_EMPTY(&branches))
7618 option_conflict('a', 'b');
7619 if (send_all_tags && !TAILQ_EMPTY(&tags))
7620 option_conflict('T', 't');
7623 if (argc == 0)
7624 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7625 else if (argc == 1)
7626 remote_name = argv[0];
7627 else
7628 usage_send();
7630 cwd = getcwd(NULL, 0);
7631 if (cwd == NULL) {
7632 error = got_error_from_errno("getcwd");
7633 goto done;
7636 if (repo_path == NULL) {
7637 error = got_worktree_open(&worktree, cwd);
7638 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7639 goto done;
7640 else
7641 error = NULL;
7642 if (worktree) {
7643 repo_path =
7644 strdup(got_worktree_get_repo_path(worktree));
7645 if (repo_path == NULL)
7646 error = got_error_from_errno("strdup");
7647 if (error)
7648 goto done;
7649 } else {
7650 repo_path = strdup(cwd);
7651 if (repo_path == NULL) {
7652 error = got_error_from_errno("strdup");
7653 goto done;
7658 error = got_repo_open(&repo, repo_path, NULL);
7659 if (error)
7660 goto done;
7662 if (worktree) {
7663 worktree_conf = got_worktree_get_gotconfig(worktree);
7664 if (worktree_conf) {
7665 got_gotconfig_get_remotes(&nremotes, &remotes,
7666 worktree_conf);
7667 for (i = 0; i < nremotes; i++) {
7668 if (strcmp(remotes[i].name, remote_name) == 0) {
7669 remote = &remotes[i];
7670 break;
7675 if (remote == NULL) {
7676 repo_conf = got_repo_get_gotconfig(repo);
7677 if (repo_conf) {
7678 got_gotconfig_get_remotes(&nremotes, &remotes,
7679 repo_conf);
7680 for (i = 0; i < nremotes; i++) {
7681 if (strcmp(remotes[i].name, remote_name) == 0) {
7682 remote = &remotes[i];
7683 break;
7688 if (remote == NULL) {
7689 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7690 for (i = 0; i < nremotes; i++) {
7691 if (strcmp(remotes[i].name, remote_name) == 0) {
7692 remote = &remotes[i];
7693 break;
7697 if (remote == NULL) {
7698 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7699 goto done;
7702 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
7703 &repo_name, remote->send_url);
7704 if (error)
7705 goto done;
7707 if (strcmp(proto, "git") == 0) {
7708 #ifndef PROFILE
7709 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7710 "sendfd dns inet unveil", NULL) == -1)
7711 err(1, "pledge");
7712 #endif
7713 } else if (strcmp(proto, "git+ssh") == 0 ||
7714 strcmp(proto, "ssh") == 0) {
7715 #ifndef PROFILE
7716 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7717 "sendfd unveil", NULL) == -1)
7718 err(1, "pledge");
7719 #endif
7720 } else if (strcmp(proto, "http") == 0 ||
7721 strcmp(proto, "git+http") == 0) {
7722 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7723 goto done;
7724 } else {
7725 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7726 goto done;
7729 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
7730 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
7731 error = got_error_from_errno2("unveil",
7732 GOT_FETCH_PATH_SSH);
7733 goto done;
7736 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7737 if (error)
7738 goto done;
7740 if (send_all_branches) {
7741 error = got_ref_list(&all_branches, repo, "refs/heads",
7742 got_ref_cmp_by_name, NULL);
7743 if (error)
7744 goto done;
7745 TAILQ_FOREACH(re, &all_branches, entry) {
7746 const char *branchname = got_ref_get_name(re->ref);
7747 error = got_pathlist_append(&branches,
7748 branchname, NULL);
7749 if (error)
7750 goto done;
7751 nbranches++;
7753 } else if (nbranches == 0) {
7754 for (i = 0; i < remote->nsend_branches; i++) {
7755 got_pathlist_append(&branches,
7756 remote->send_branches[i], NULL);
7760 if (send_all_tags) {
7761 error = got_ref_list(&all_tags, repo, "refs/tags",
7762 got_ref_cmp_by_name, NULL);
7763 if (error)
7764 goto done;
7765 TAILQ_FOREACH(re, &all_tags, entry) {
7766 const char *tagname = got_ref_get_name(re->ref);
7767 error = got_pathlist_append(&tags,
7768 tagname, NULL);
7769 if (error)
7770 goto done;
7771 ntags++;
7776 * To prevent accidents only branches in refs/heads/ can be deleted
7777 * with 'got send -d'.
7778 * Deleting anything else requires local repository access or Git.
7780 TAILQ_FOREACH(pe, &delete_args, entry) {
7781 const char *branchname = pe->path;
7782 char *s;
7783 struct got_pathlist_entry *new;
7784 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7785 s = strdup(branchname);
7786 if (s == NULL) {
7787 error = got_error_from_errno("strdup");
7788 goto done;
7790 } else {
7791 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7792 error = got_error_from_errno("asprintf");
7793 goto done;
7796 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7797 if (error || new == NULL /* duplicate */)
7798 free(s);
7799 if (error)
7800 goto done;
7801 ndelete_branches++;
7804 if (nbranches == 0 && ndelete_branches == 0) {
7805 struct got_reference *head_ref;
7806 if (worktree)
7807 error = got_ref_open(&head_ref, repo,
7808 got_worktree_get_head_ref_name(worktree), 0);
7809 else
7810 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7811 if (error)
7812 goto done;
7813 if (got_ref_is_symbolic(head_ref)) {
7814 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7815 got_ref_close(head_ref);
7816 if (error)
7817 goto done;
7818 } else
7819 ref = head_ref;
7820 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7821 NULL);
7822 if (error)
7823 goto done;
7824 nbranches++;
7827 if (verbosity >= 0)
7828 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7829 port ? ":" : "", port ? port : "");
7831 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7832 server_path, verbosity);
7833 if (error)
7834 goto done;
7836 memset(&spa, 0, sizeof(spa));
7837 spa.last_scaled_packsize[0] = '\0';
7838 spa.last_p_deltify = -1;
7839 spa.last_p_written = -1;
7840 spa.verbosity = verbosity;
7841 spa.delete_branches = &delete_branches;
7842 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7843 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7844 check_cancelled, NULL);
7845 if (spa.printed_something)
7846 putchar('\n');
7847 if (error)
7848 goto done;
7849 if (!spa.sent_something && verbosity >= 0)
7850 printf("Already up-to-date\n");
7851 done:
7852 if (sendpid > 0) {
7853 if (kill(sendpid, SIGTERM) == -1)
7854 error = got_error_from_errno("kill");
7855 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7856 error = got_error_from_errno("waitpid");
7858 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7859 error = got_error_from_errno("close");
7860 if (repo) {
7861 const struct got_error *close_err = got_repo_close(repo);
7862 if (error == NULL)
7863 error = close_err;
7865 if (worktree)
7866 got_worktree_close(worktree);
7867 if (ref)
7868 got_ref_close(ref);
7869 got_pathlist_free(&branches);
7870 got_pathlist_free(&tags);
7871 got_ref_list_free(&all_branches);
7872 got_ref_list_free(&all_tags);
7873 got_pathlist_free(&delete_args);
7874 TAILQ_FOREACH(pe, &delete_branches, entry)
7875 free((char *)pe->path);
7876 got_pathlist_free(&delete_branches);
7877 free(cwd);
7878 free(repo_path);
7879 free(proto);
7880 free(host);
7881 free(port);
7882 free(server_path);
7883 free(repo_name);
7884 return error;
7887 __dead static void
7888 usage_cherrypick(void)
7890 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7891 exit(1);
7894 static const struct got_error *
7895 cmd_cherrypick(int argc, char *argv[])
7897 const struct got_error *error = NULL;
7898 struct got_worktree *worktree = NULL;
7899 struct got_repository *repo = NULL;
7900 char *cwd = NULL, *commit_id_str = NULL;
7901 struct got_object_id *commit_id = NULL;
7902 struct got_commit_object *commit = NULL;
7903 struct got_object_qid *pid;
7904 int ch;
7905 struct got_update_progress_arg upa;
7907 while ((ch = getopt(argc, argv, "")) != -1) {
7908 switch (ch) {
7909 default:
7910 usage_cherrypick();
7911 /* NOTREACHED */
7915 argc -= optind;
7916 argv += optind;
7918 #ifndef PROFILE
7919 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7920 "unveil", NULL) == -1)
7921 err(1, "pledge");
7922 #endif
7923 if (argc != 1)
7924 usage_cherrypick();
7926 cwd = getcwd(NULL, 0);
7927 if (cwd == NULL) {
7928 error = got_error_from_errno("getcwd");
7929 goto done;
7931 error = got_worktree_open(&worktree, cwd);
7932 if (error) {
7933 if (error->code == GOT_ERR_NOT_WORKTREE)
7934 error = wrap_not_worktree_error(error, "cherrypick",
7935 cwd);
7936 goto done;
7939 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7940 NULL);
7941 if (error != NULL)
7942 goto done;
7944 error = apply_unveil(got_repo_get_path(repo), 0,
7945 got_worktree_get_root_path(worktree));
7946 if (error)
7947 goto done;
7949 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7950 GOT_OBJ_TYPE_COMMIT, repo);
7951 if (error != NULL) {
7952 struct got_reference *ref;
7953 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7954 goto done;
7955 error = got_ref_open(&ref, repo, argv[0], 0);
7956 if (error != NULL)
7957 goto done;
7958 error = got_ref_resolve(&commit_id, repo, ref);
7959 got_ref_close(ref);
7960 if (error != NULL)
7961 goto done;
7963 error = got_object_id_str(&commit_id_str, commit_id);
7964 if (error)
7965 goto done;
7967 error = got_object_open_as_commit(&commit, repo, commit_id);
7968 if (error)
7969 goto done;
7970 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7971 memset(&upa, 0, sizeof(upa));
7972 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7973 commit_id, repo, update_progress, &upa, check_cancelled,
7974 NULL);
7975 if (error != NULL)
7976 goto done;
7978 if (upa.did_something)
7979 printf("Merged commit %s\n", commit_id_str);
7980 print_update_progress_stats(&upa);
7981 done:
7982 if (commit)
7983 got_object_commit_close(commit);
7984 free(commit_id_str);
7985 if (worktree)
7986 got_worktree_close(worktree);
7987 if (repo) {
7988 const struct got_error *close_err = got_repo_close(repo);
7989 if (error == NULL)
7990 error = close_err;
7992 return error;
7995 __dead static void
7996 usage_backout(void)
7998 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7999 exit(1);
8002 static const struct got_error *
8003 cmd_backout(int argc, char *argv[])
8005 const struct got_error *error = NULL;
8006 struct got_worktree *worktree = NULL;
8007 struct got_repository *repo = NULL;
8008 char *cwd = NULL, *commit_id_str = NULL;
8009 struct got_object_id *commit_id = NULL;
8010 struct got_commit_object *commit = NULL;
8011 struct got_object_qid *pid;
8012 int ch;
8013 struct got_update_progress_arg upa;
8015 while ((ch = getopt(argc, argv, "")) != -1) {
8016 switch (ch) {
8017 default:
8018 usage_backout();
8019 /* NOTREACHED */
8023 argc -= optind;
8024 argv += optind;
8026 #ifndef PROFILE
8027 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8028 "unveil", NULL) == -1)
8029 err(1, "pledge");
8030 #endif
8031 if (argc != 1)
8032 usage_backout();
8034 cwd = getcwd(NULL, 0);
8035 if (cwd == NULL) {
8036 error = got_error_from_errno("getcwd");
8037 goto done;
8039 error = got_worktree_open(&worktree, cwd);
8040 if (error) {
8041 if (error->code == GOT_ERR_NOT_WORKTREE)
8042 error = wrap_not_worktree_error(error, "backout", cwd);
8043 goto done;
8046 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8047 NULL);
8048 if (error != NULL)
8049 goto done;
8051 error = apply_unveil(got_repo_get_path(repo), 0,
8052 got_worktree_get_root_path(worktree));
8053 if (error)
8054 goto done;
8056 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8057 GOT_OBJ_TYPE_COMMIT, repo);
8058 if (error != NULL) {
8059 struct got_reference *ref;
8060 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8061 goto done;
8062 error = got_ref_open(&ref, repo, argv[0], 0);
8063 if (error != NULL)
8064 goto done;
8065 error = got_ref_resolve(&commit_id, repo, ref);
8066 got_ref_close(ref);
8067 if (error != NULL)
8068 goto done;
8070 error = got_object_id_str(&commit_id_str, commit_id);
8071 if (error)
8072 goto done;
8074 error = got_object_open_as_commit(&commit, repo, commit_id);
8075 if (error)
8076 goto done;
8077 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8078 if (pid == NULL) {
8079 error = got_error(GOT_ERR_ROOT_COMMIT);
8080 goto done;
8083 memset(&upa, 0, sizeof(upa));
8084 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8085 update_progress, &upa, check_cancelled, NULL);
8086 if (error != NULL)
8087 goto done;
8089 if (upa.did_something)
8090 printf("Backed out commit %s\n", commit_id_str);
8091 print_update_progress_stats(&upa);
8092 done:
8093 if (commit)
8094 got_object_commit_close(commit);
8095 free(commit_id_str);
8096 if (worktree)
8097 got_worktree_close(worktree);
8098 if (repo) {
8099 const struct got_error *close_err = got_repo_close(repo);
8100 if (error == NULL)
8101 error = close_err;
8103 return error;
8106 __dead static void
8107 usage_rebase(void)
8109 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8110 getprogname());
8111 exit(1);
8114 void
8115 trim_logmsg(char *logmsg, int limit)
8117 char *nl;
8118 size_t len;
8120 len = strlen(logmsg);
8121 if (len > limit)
8122 len = limit;
8123 logmsg[len] = '\0';
8124 nl = strchr(logmsg, '\n');
8125 if (nl)
8126 *nl = '\0';
8129 static const struct got_error *
8130 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8132 const struct got_error *err;
8133 char *logmsg0 = NULL;
8134 const char *s;
8136 err = got_object_commit_get_logmsg(&logmsg0, commit);
8137 if (err)
8138 return err;
8140 s = logmsg0;
8141 while (isspace((unsigned char)s[0]))
8142 s++;
8144 *logmsg = strdup(s);
8145 if (*logmsg == NULL) {
8146 err = got_error_from_errno("strdup");
8147 goto done;
8150 trim_logmsg(*logmsg, limit);
8151 done:
8152 free(logmsg0);
8153 return err;
8156 static const struct got_error *
8157 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8159 const struct got_error *err;
8160 struct got_commit_object *commit = NULL;
8161 char *id_str = NULL, *logmsg = NULL;
8163 err = got_object_open_as_commit(&commit, repo, id);
8164 if (err)
8165 return err;
8167 err = got_object_id_str(&id_str, id);
8168 if (err)
8169 goto done;
8171 id_str[12] = '\0';
8173 err = get_short_logmsg(&logmsg, 42, commit);
8174 if (err)
8175 goto done;
8177 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8178 done:
8179 free(id_str);
8180 got_object_commit_close(commit);
8181 free(logmsg);
8182 return err;
8185 static const struct got_error *
8186 show_rebase_progress(struct got_commit_object *commit,
8187 struct got_object_id *old_id, struct got_object_id *new_id)
8189 const struct got_error *err;
8190 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8192 err = got_object_id_str(&old_id_str, old_id);
8193 if (err)
8194 goto done;
8196 if (new_id) {
8197 err = got_object_id_str(&new_id_str, new_id);
8198 if (err)
8199 goto done;
8202 old_id_str[12] = '\0';
8203 if (new_id_str)
8204 new_id_str[12] = '\0';
8206 err = get_short_logmsg(&logmsg, 42, commit);
8207 if (err)
8208 goto done;
8210 printf("%s -> %s: %s\n", old_id_str,
8211 new_id_str ? new_id_str : "no-op change", logmsg);
8212 done:
8213 free(old_id_str);
8214 free(new_id_str);
8215 free(logmsg);
8216 return err;
8219 static const struct got_error *
8220 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8221 struct got_reference *branch, struct got_reference *new_base_branch,
8222 struct got_reference *tmp_branch, struct got_repository *repo,
8223 int create_backup)
8225 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8226 return got_worktree_rebase_complete(worktree, fileindex,
8227 new_base_branch, tmp_branch, branch, repo, create_backup);
8230 static const struct got_error *
8231 rebase_commit(struct got_pathlist_head *merged_paths,
8232 struct got_worktree *worktree, struct got_fileindex *fileindex,
8233 struct got_reference *tmp_branch,
8234 struct got_object_id *commit_id, struct got_repository *repo)
8236 const struct got_error *error;
8237 struct got_commit_object *commit;
8238 struct got_object_id *new_commit_id;
8240 error = got_object_open_as_commit(&commit, repo, commit_id);
8241 if (error)
8242 return error;
8244 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8245 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8246 if (error) {
8247 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8248 goto done;
8249 error = show_rebase_progress(commit, commit_id, NULL);
8250 } else {
8251 error = show_rebase_progress(commit, commit_id, new_commit_id);
8252 free(new_commit_id);
8254 done:
8255 got_object_commit_close(commit);
8256 return error;
8259 struct check_path_prefix_arg {
8260 const char *path_prefix;
8261 size_t len;
8262 int errcode;
8265 static const struct got_error *
8266 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8267 struct got_blob_object *blob2, struct got_object_id *id1,
8268 struct got_object_id *id2, const char *path1, const char *path2,
8269 mode_t mode1, mode_t mode2, struct got_repository *repo)
8271 struct check_path_prefix_arg *a = arg;
8273 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8274 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8275 return got_error(a->errcode);
8277 return NULL;
8280 static const struct got_error *
8281 check_path_prefix(struct got_object_id *parent_id,
8282 struct got_object_id *commit_id, const char *path_prefix,
8283 int errcode, struct got_repository *repo)
8285 const struct got_error *err;
8286 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8287 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8288 struct check_path_prefix_arg cpp_arg;
8290 if (got_path_is_root_dir(path_prefix))
8291 return NULL;
8293 err = got_object_open_as_commit(&commit, repo, commit_id);
8294 if (err)
8295 goto done;
8297 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8298 if (err)
8299 goto done;
8301 err = got_object_open_as_tree(&tree1, repo,
8302 got_object_commit_get_tree_id(parent_commit));
8303 if (err)
8304 goto done;
8306 err = got_object_open_as_tree(&tree2, repo,
8307 got_object_commit_get_tree_id(commit));
8308 if (err)
8309 goto done;
8311 cpp_arg.path_prefix = path_prefix;
8312 while (cpp_arg.path_prefix[0] == '/')
8313 cpp_arg.path_prefix++;
8314 cpp_arg.len = strlen(cpp_arg.path_prefix);
8315 cpp_arg.errcode = errcode;
8316 err = got_diff_tree(tree1, tree2, "", "", repo,
8317 check_path_prefix_in_diff, &cpp_arg, 0);
8318 done:
8319 if (tree1)
8320 got_object_tree_close(tree1);
8321 if (tree2)
8322 got_object_tree_close(tree2);
8323 if (commit)
8324 got_object_commit_close(commit);
8325 if (parent_commit)
8326 got_object_commit_close(parent_commit);
8327 return err;
8330 static const struct got_error *
8331 collect_commits(struct got_object_id_queue *commits,
8332 struct got_object_id *initial_commit_id,
8333 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8334 const char *path_prefix, int path_prefix_errcode,
8335 struct got_repository *repo)
8337 const struct got_error *err = NULL;
8338 struct got_commit_graph *graph = NULL;
8339 struct got_object_id *parent_id = NULL;
8340 struct got_object_qid *qid;
8341 struct got_object_id *commit_id = initial_commit_id;
8343 err = got_commit_graph_open(&graph, "/", 1);
8344 if (err)
8345 return err;
8347 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8348 check_cancelled, NULL);
8349 if (err)
8350 goto done;
8351 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8352 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8353 check_cancelled, NULL);
8354 if (err) {
8355 if (err->code == GOT_ERR_ITER_COMPLETED) {
8356 err = got_error_msg(GOT_ERR_ANCESTRY,
8357 "ran out of commits to rebase before "
8358 "youngest common ancestor commit has "
8359 "been reached?!?");
8361 goto done;
8362 } else {
8363 err = check_path_prefix(parent_id, commit_id,
8364 path_prefix, path_prefix_errcode, repo);
8365 if (err)
8366 goto done;
8368 err = got_object_qid_alloc(&qid, commit_id);
8369 if (err)
8370 goto done;
8371 STAILQ_INSERT_HEAD(commits, qid, entry);
8372 commit_id = parent_id;
8375 done:
8376 got_commit_graph_close(graph);
8377 return err;
8380 static const struct got_error *
8381 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8383 const struct got_error *err = NULL;
8384 time_t committer_time;
8385 struct tm tm;
8386 char datebuf[11]; /* YYYY-MM-DD + NUL */
8387 char *author0 = NULL, *author, *smallerthan;
8388 char *logmsg0 = NULL, *logmsg, *newline;
8390 committer_time = got_object_commit_get_committer_time(commit);
8391 if (gmtime_r(&committer_time, &tm) == NULL)
8392 return got_error_from_errno("gmtime_r");
8393 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8394 return got_error(GOT_ERR_NO_SPACE);
8396 author0 = strdup(got_object_commit_get_author(commit));
8397 if (author0 == NULL)
8398 return got_error_from_errno("strdup");
8399 author = author0;
8400 smallerthan = strchr(author, '<');
8401 if (smallerthan && smallerthan[1] != '\0')
8402 author = smallerthan + 1;
8403 author[strcspn(author, "@>")] = '\0';
8405 err = got_object_commit_get_logmsg(&logmsg0, commit);
8406 if (err)
8407 goto done;
8408 logmsg = logmsg0;
8409 while (*logmsg == '\n')
8410 logmsg++;
8411 newline = strchr(logmsg, '\n');
8412 if (newline)
8413 *newline = '\0';
8415 if (asprintf(brief_str, "%s %s %s",
8416 datebuf, author, logmsg) == -1)
8417 err = got_error_from_errno("asprintf");
8418 done:
8419 free(author0);
8420 free(logmsg0);
8421 return err;
8424 static const struct got_error *
8425 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8426 struct got_repository *repo)
8428 const struct got_error *err;
8429 char *id_str;
8431 err = got_object_id_str(&id_str, id);
8432 if (err)
8433 return err;
8435 err = got_ref_delete(ref, repo);
8436 if (err)
8437 goto done;
8439 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8440 done:
8441 free(id_str);
8442 return err;
8445 static const struct got_error *
8446 print_backup_ref(const char *branch_name, const char *new_id_str,
8447 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8448 struct got_reflist_object_id_map *refs_idmap,
8449 struct got_repository *repo)
8451 const struct got_error *err = NULL;
8452 struct got_reflist_head *refs;
8453 char *refs_str = NULL;
8454 struct got_object_id *new_commit_id = NULL;
8455 struct got_commit_object *new_commit = NULL;
8456 char *new_commit_brief_str = NULL;
8457 struct got_object_id *yca_id = NULL;
8458 struct got_commit_object *yca_commit = NULL;
8459 char *yca_id_str = NULL, *yca_brief_str = NULL;
8460 char *custom_refs_str;
8462 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8463 return got_error_from_errno("asprintf");
8465 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8466 0, 0, refs_idmap, custom_refs_str);
8467 if (err)
8468 goto done;
8470 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8471 if (err)
8472 goto done;
8474 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8475 if (refs) {
8476 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8477 if (err)
8478 goto done;
8481 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8482 if (err)
8483 goto done;
8485 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8486 if (err)
8487 goto done;
8489 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8490 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8491 if (err)
8492 goto done;
8494 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8495 refs_str ? " (" : "", refs_str ? refs_str : "",
8496 refs_str ? ")" : "", new_commit_brief_str);
8497 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8498 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8499 free(refs_str);
8500 refs_str = NULL;
8502 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8503 if (err)
8504 goto done;
8506 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8507 if (err)
8508 goto done;
8510 err = got_object_id_str(&yca_id_str, yca_id);
8511 if (err)
8512 goto done;
8514 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8515 if (refs) {
8516 err = build_refs_str(&refs_str, refs, yca_id, repo);
8517 if (err)
8518 goto done;
8520 printf("history forked at %s%s%s%s\n %s\n",
8521 yca_id_str,
8522 refs_str ? " (" : "", refs_str ? refs_str : "",
8523 refs_str ? ")" : "", yca_brief_str);
8525 done:
8526 free(custom_refs_str);
8527 free(new_commit_id);
8528 free(refs_str);
8529 free(yca_id);
8530 free(yca_id_str);
8531 free(yca_brief_str);
8532 if (new_commit)
8533 got_object_commit_close(new_commit);
8534 if (yca_commit)
8535 got_object_commit_close(yca_commit);
8537 return NULL;
8540 static const struct got_error *
8541 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8542 int delete, struct got_repository *repo)
8544 const struct got_error *err;
8545 struct got_reflist_head refs, backup_refs;
8546 struct got_reflist_entry *re;
8547 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8548 struct got_object_id *old_commit_id = NULL;
8549 char *branch_name = NULL;
8550 struct got_commit_object *old_commit = NULL;
8551 struct got_reflist_object_id_map *refs_idmap = NULL;
8552 int wanted_branch_found = 0;
8554 TAILQ_INIT(&refs);
8555 TAILQ_INIT(&backup_refs);
8557 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8558 if (err)
8559 return err;
8561 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8562 if (err)
8563 goto done;
8565 if (wanted_branch_name) {
8566 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8567 wanted_branch_name += 11;
8570 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8571 got_ref_cmp_by_commit_timestamp_descending, repo);
8572 if (err)
8573 goto done;
8575 TAILQ_FOREACH(re, &backup_refs, entry) {
8576 const char *refname = got_ref_get_name(re->ref);
8577 char *slash;
8579 err = check_cancelled(NULL);
8580 if (err)
8581 break;
8583 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8584 if (err)
8585 break;
8587 err = got_object_open_as_commit(&old_commit, repo,
8588 old_commit_id);
8589 if (err)
8590 break;
8592 if (strncmp(backup_ref_prefix, refname,
8593 backup_ref_prefix_len) == 0)
8594 refname += backup_ref_prefix_len;
8596 while (refname[0] == '/')
8597 refname++;
8599 branch_name = strdup(refname);
8600 if (branch_name == NULL) {
8601 err = got_error_from_errno("strdup");
8602 break;
8604 slash = strrchr(branch_name, '/');
8605 if (slash) {
8606 *slash = '\0';
8607 refname += strlen(branch_name) + 1;
8610 if (wanted_branch_name == NULL ||
8611 strcmp(wanted_branch_name, branch_name) == 0) {
8612 wanted_branch_found = 1;
8613 if (delete) {
8614 err = delete_backup_ref(re->ref,
8615 old_commit_id, repo);
8616 } else {
8617 err = print_backup_ref(branch_name, refname,
8618 old_commit_id, old_commit, refs_idmap,
8619 repo);
8621 if (err)
8622 break;
8625 free(old_commit_id);
8626 old_commit_id = NULL;
8627 free(branch_name);
8628 branch_name = NULL;
8629 got_object_commit_close(old_commit);
8630 old_commit = NULL;
8633 if (wanted_branch_name && !wanted_branch_found) {
8634 err = got_error_fmt(GOT_ERR_NOT_REF,
8635 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8637 done:
8638 if (refs_idmap)
8639 got_reflist_object_id_map_free(refs_idmap);
8640 got_ref_list_free(&refs);
8641 got_ref_list_free(&backup_refs);
8642 free(old_commit_id);
8643 free(branch_name);
8644 if (old_commit)
8645 got_object_commit_close(old_commit);
8646 return err;
8649 static const struct got_error *
8650 cmd_rebase(int argc, char *argv[])
8652 const struct got_error *error = NULL;
8653 struct got_worktree *worktree = NULL;
8654 struct got_repository *repo = NULL;
8655 struct got_fileindex *fileindex = NULL;
8656 char *cwd = NULL;
8657 struct got_reference *branch = NULL;
8658 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8659 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8660 struct got_object_id *resume_commit_id = NULL;
8661 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8662 struct got_commit_object *commit = NULL;
8663 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8664 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8665 int delete_backups = 0;
8666 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8667 struct got_object_id_queue commits;
8668 struct got_pathlist_head merged_paths;
8669 const struct got_object_id_queue *parent_ids;
8670 struct got_object_qid *qid, *pid;
8672 STAILQ_INIT(&commits);
8673 TAILQ_INIT(&merged_paths);
8675 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8676 switch (ch) {
8677 case 'a':
8678 abort_rebase = 1;
8679 break;
8680 case 'c':
8681 continue_rebase = 1;
8682 break;
8683 case 'l':
8684 list_backups = 1;
8685 break;
8686 case 'X':
8687 delete_backups = 1;
8688 break;
8689 default:
8690 usage_rebase();
8691 /* NOTREACHED */
8695 argc -= optind;
8696 argv += optind;
8698 #ifndef PROFILE
8699 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8700 "unveil", NULL) == -1)
8701 err(1, "pledge");
8702 #endif
8703 if (list_backups) {
8704 if (abort_rebase)
8705 option_conflict('l', 'a');
8706 if (continue_rebase)
8707 option_conflict('l', 'c');
8708 if (delete_backups)
8709 option_conflict('l', 'X');
8710 if (argc != 0 && argc != 1)
8711 usage_rebase();
8712 } else if (delete_backups) {
8713 if (abort_rebase)
8714 option_conflict('X', 'a');
8715 if (continue_rebase)
8716 option_conflict('X', 'c');
8717 if (list_backups)
8718 option_conflict('l', 'X');
8719 if (argc != 0 && argc != 1)
8720 usage_rebase();
8721 } else {
8722 if (abort_rebase && continue_rebase)
8723 usage_rebase();
8724 else if (abort_rebase || continue_rebase) {
8725 if (argc != 0)
8726 usage_rebase();
8727 } else if (argc != 1)
8728 usage_rebase();
8731 cwd = getcwd(NULL, 0);
8732 if (cwd == NULL) {
8733 error = got_error_from_errno("getcwd");
8734 goto done;
8736 error = got_worktree_open(&worktree, cwd);
8737 if (error) {
8738 if (list_backups || delete_backups) {
8739 if (error->code != GOT_ERR_NOT_WORKTREE)
8740 goto done;
8741 } else {
8742 if (error->code == GOT_ERR_NOT_WORKTREE)
8743 error = wrap_not_worktree_error(error,
8744 "rebase", cwd);
8745 goto done;
8749 error = got_repo_open(&repo,
8750 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8751 if (error != NULL)
8752 goto done;
8754 error = apply_unveil(got_repo_get_path(repo), 0,
8755 worktree ? got_worktree_get_root_path(worktree) : NULL);
8756 if (error)
8757 goto done;
8759 if (list_backups || delete_backups) {
8760 error = process_backup_refs(
8761 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8762 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8763 goto done; /* nothing else to do */
8766 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8767 worktree);
8768 if (error)
8769 goto done;
8770 if (histedit_in_progress) {
8771 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8772 goto done;
8775 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8776 if (error)
8777 goto done;
8779 if (abort_rebase) {
8780 struct got_update_progress_arg upa;
8781 if (!rebase_in_progress) {
8782 error = got_error(GOT_ERR_NOT_REBASING);
8783 goto done;
8785 error = got_worktree_rebase_continue(&resume_commit_id,
8786 &new_base_branch, &tmp_branch, &branch, &fileindex,
8787 worktree, repo);
8788 if (error)
8789 goto done;
8790 printf("Switching work tree to %s\n",
8791 got_ref_get_symref_target(new_base_branch));
8792 memset(&upa, 0, sizeof(upa));
8793 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8794 new_base_branch, update_progress, &upa);
8795 if (error)
8796 goto done;
8797 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8798 print_update_progress_stats(&upa);
8799 goto done; /* nothing else to do */
8802 if (continue_rebase) {
8803 if (!rebase_in_progress) {
8804 error = got_error(GOT_ERR_NOT_REBASING);
8805 goto done;
8807 error = got_worktree_rebase_continue(&resume_commit_id,
8808 &new_base_branch, &tmp_branch, &branch, &fileindex,
8809 worktree, repo);
8810 if (error)
8811 goto done;
8813 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8814 resume_commit_id, repo);
8815 if (error)
8816 goto done;
8818 yca_id = got_object_id_dup(resume_commit_id);
8819 if (yca_id == NULL) {
8820 error = got_error_from_errno("got_object_id_dup");
8821 goto done;
8823 } else {
8824 error = got_ref_open(&branch, repo, argv[0], 0);
8825 if (error != NULL)
8826 goto done;
8829 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8830 if (error)
8831 goto done;
8833 if (!continue_rebase) {
8834 struct got_object_id *base_commit_id;
8836 base_commit_id = got_worktree_get_base_commit_id(worktree);
8837 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8838 base_commit_id, branch_head_commit_id, repo,
8839 check_cancelled, NULL);
8840 if (error)
8841 goto done;
8842 if (yca_id == NULL) {
8843 error = got_error_msg(GOT_ERR_ANCESTRY,
8844 "specified branch shares no common ancestry "
8845 "with work tree's branch");
8846 goto done;
8849 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8850 if (error) {
8851 if (error->code != GOT_ERR_ANCESTRY)
8852 goto done;
8853 error = NULL;
8854 } else {
8855 static char msg[128];
8856 snprintf(msg, sizeof(msg),
8857 "%s is already based on %s",
8858 got_ref_get_name(branch),
8859 got_worktree_get_head_ref_name(worktree));
8860 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8861 goto done;
8863 error = got_worktree_rebase_prepare(&new_base_branch,
8864 &tmp_branch, &fileindex, worktree, branch, repo);
8865 if (error)
8866 goto done;
8869 commit_id = branch_head_commit_id;
8870 error = got_object_open_as_commit(&commit, repo, commit_id);
8871 if (error)
8872 goto done;
8874 parent_ids = got_object_commit_get_parent_ids(commit);
8875 pid = STAILQ_FIRST(parent_ids);
8876 if (pid == NULL) {
8877 if (!continue_rebase) {
8878 struct got_update_progress_arg upa;
8879 memset(&upa, 0, sizeof(upa));
8880 error = got_worktree_rebase_abort(worktree, fileindex,
8881 repo, new_base_branch, update_progress, &upa);
8882 if (error)
8883 goto done;
8884 printf("Rebase of %s aborted\n",
8885 got_ref_get_name(branch));
8886 print_update_progress_stats(&upa);
8889 error = got_error(GOT_ERR_EMPTY_REBASE);
8890 goto done;
8892 error = collect_commits(&commits, commit_id, pid->id,
8893 yca_id, got_worktree_get_path_prefix(worktree),
8894 GOT_ERR_REBASE_PATH, repo);
8895 got_object_commit_close(commit);
8896 commit = NULL;
8897 if (error)
8898 goto done;
8900 if (STAILQ_EMPTY(&commits)) {
8901 if (continue_rebase) {
8902 error = rebase_complete(worktree, fileindex,
8903 branch, new_base_branch, tmp_branch, repo,
8904 create_backup);
8905 goto done;
8906 } else {
8907 /* Fast-forward the reference of the branch. */
8908 struct got_object_id *new_head_commit_id;
8909 char *id_str;
8910 error = got_ref_resolve(&new_head_commit_id, repo,
8911 new_base_branch);
8912 if (error)
8913 goto done;
8914 error = got_object_id_str(&id_str, new_head_commit_id);
8915 printf("Forwarding %s to commit %s\n",
8916 got_ref_get_name(branch), id_str);
8917 free(id_str);
8918 error = got_ref_change_ref(branch,
8919 new_head_commit_id);
8920 if (error)
8921 goto done;
8922 /* No backup needed since objects did not change. */
8923 create_backup = 0;
8927 pid = NULL;
8928 STAILQ_FOREACH(qid, &commits, entry) {
8929 struct got_update_progress_arg upa;
8931 commit_id = qid->id;
8932 parent_id = pid ? pid->id : yca_id;
8933 pid = qid;
8935 memset(&upa, 0, sizeof(upa));
8936 error = got_worktree_rebase_merge_files(&merged_paths,
8937 worktree, fileindex, parent_id, commit_id, repo,
8938 update_progress, &upa, check_cancelled, NULL);
8939 if (error)
8940 goto done;
8942 print_update_progress_stats(&upa);
8943 if (upa.conflicts > 0)
8944 rebase_status = GOT_STATUS_CONFLICT;
8946 if (rebase_status == GOT_STATUS_CONFLICT) {
8947 error = show_rebase_merge_conflict(qid->id, repo);
8948 if (error)
8949 goto done;
8950 got_worktree_rebase_pathlist_free(&merged_paths);
8951 break;
8954 error = rebase_commit(&merged_paths, worktree, fileindex,
8955 tmp_branch, commit_id, repo);
8956 got_worktree_rebase_pathlist_free(&merged_paths);
8957 if (error)
8958 goto done;
8961 if (rebase_status == GOT_STATUS_CONFLICT) {
8962 error = got_worktree_rebase_postpone(worktree, fileindex);
8963 if (error)
8964 goto done;
8965 error = got_error_msg(GOT_ERR_CONFLICTS,
8966 "conflicts must be resolved before rebasing can continue");
8967 } else
8968 error = rebase_complete(worktree, fileindex, branch,
8969 new_base_branch, tmp_branch, repo, create_backup);
8970 done:
8971 got_object_id_queue_free(&commits);
8972 free(branch_head_commit_id);
8973 free(resume_commit_id);
8974 free(yca_id);
8975 if (commit)
8976 got_object_commit_close(commit);
8977 if (branch)
8978 got_ref_close(branch);
8979 if (new_base_branch)
8980 got_ref_close(new_base_branch);
8981 if (tmp_branch)
8982 got_ref_close(tmp_branch);
8983 if (worktree)
8984 got_worktree_close(worktree);
8985 if (repo) {
8986 const struct got_error *close_err = got_repo_close(repo);
8987 if (error == NULL)
8988 error = close_err;
8990 return error;
8993 __dead static void
8994 usage_histedit(void)
8996 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
8997 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
8998 getprogname());
8999 exit(1);
9002 #define GOT_HISTEDIT_PICK 'p'
9003 #define GOT_HISTEDIT_EDIT 'e'
9004 #define GOT_HISTEDIT_FOLD 'f'
9005 #define GOT_HISTEDIT_DROP 'd'
9006 #define GOT_HISTEDIT_MESG 'm'
9008 static struct got_histedit_cmd {
9009 unsigned char code;
9010 const char *name;
9011 const char *desc;
9012 } got_histedit_cmds[] = {
9013 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9014 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9015 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9016 "be used" },
9017 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9018 { GOT_HISTEDIT_MESG, "mesg",
9019 "single-line log message for commit above (open editor if empty)" },
9022 struct got_histedit_list_entry {
9023 TAILQ_ENTRY(got_histedit_list_entry) entry;
9024 struct got_object_id *commit_id;
9025 const struct got_histedit_cmd *cmd;
9026 char *logmsg;
9028 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9030 static const struct got_error *
9031 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9032 FILE *f, struct got_repository *repo)
9034 const struct got_error *err = NULL;
9035 char *logmsg = NULL, *id_str = NULL;
9036 struct got_commit_object *commit = NULL;
9037 int n;
9039 err = got_object_open_as_commit(&commit, repo, commit_id);
9040 if (err)
9041 goto done;
9043 err = get_short_logmsg(&logmsg, 34, commit);
9044 if (err)
9045 goto done;
9047 err = got_object_id_str(&id_str, commit_id);
9048 if (err)
9049 goto done;
9051 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9052 if (n < 0)
9053 err = got_ferror(f, GOT_ERR_IO);
9054 done:
9055 if (commit)
9056 got_object_commit_close(commit);
9057 free(id_str);
9058 free(logmsg);
9059 return err;
9062 static const struct got_error *
9063 histedit_write_commit_list(struct got_object_id_queue *commits,
9064 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9066 const struct got_error *err = NULL;
9067 struct got_object_qid *qid;
9068 const char *histedit_cmd = NULL;
9070 if (STAILQ_EMPTY(commits))
9071 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9073 STAILQ_FOREACH(qid, commits, entry) {
9074 histedit_cmd = got_histedit_cmds[0].name;
9075 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9076 histedit_cmd = "fold";
9077 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9078 if (err)
9079 break;
9080 if (edit_logmsg_only) {
9081 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9082 if (n < 0) {
9083 err = got_ferror(f, GOT_ERR_IO);
9084 break;
9089 return err;
9092 static const struct got_error *
9093 write_cmd_list(FILE *f, const char *branch_name,
9094 struct got_object_id_queue *commits)
9096 const struct got_error *err = NULL;
9097 size_t i;
9098 int n;
9099 char *id_str;
9100 struct got_object_qid *qid;
9102 qid = STAILQ_FIRST(commits);
9103 err = got_object_id_str(&id_str, qid->id);
9104 if (err)
9105 return err;
9107 n = fprintf(f,
9108 "# Editing the history of branch '%s' starting at\n"
9109 "# commit %s\n"
9110 "# Commits will be processed in order from top to "
9111 "bottom of this file.\n", branch_name, id_str);
9112 if (n < 0) {
9113 err = got_ferror(f, GOT_ERR_IO);
9114 goto done;
9117 n = fprintf(f, "# Available histedit commands:\n");
9118 if (n < 0) {
9119 err = got_ferror(f, GOT_ERR_IO);
9120 goto done;
9123 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9124 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9125 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9126 cmd->desc);
9127 if (n < 0) {
9128 err = got_ferror(f, GOT_ERR_IO);
9129 break;
9132 done:
9133 free(id_str);
9134 return err;
9137 static const struct got_error *
9138 histedit_syntax_error(int lineno)
9140 static char msg[42];
9141 int ret;
9143 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9144 lineno);
9145 if (ret == -1 || ret >= sizeof(msg))
9146 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9148 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9151 static const struct got_error *
9152 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9153 char *logmsg, struct got_repository *repo)
9155 const struct got_error *err;
9156 struct got_commit_object *folded_commit = NULL;
9157 char *id_str, *folded_logmsg = NULL;
9159 err = got_object_id_str(&id_str, hle->commit_id);
9160 if (err)
9161 return err;
9163 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9164 if (err)
9165 goto done;
9167 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9168 if (err)
9169 goto done;
9170 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9171 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9172 folded_logmsg) == -1) {
9173 err = got_error_from_errno("asprintf");
9175 done:
9176 if (folded_commit)
9177 got_object_commit_close(folded_commit);
9178 free(id_str);
9179 free(folded_logmsg);
9180 return err;
9183 static struct got_histedit_list_entry *
9184 get_folded_commits(struct got_histedit_list_entry *hle)
9186 struct got_histedit_list_entry *prev, *folded = NULL;
9188 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9189 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9190 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9191 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9192 folded = prev;
9193 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9196 return folded;
9199 static const struct got_error *
9200 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9201 struct got_repository *repo)
9203 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9204 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9205 const struct got_error *err = NULL;
9206 struct got_commit_object *commit = NULL;
9207 int logmsg_len;
9208 int fd;
9209 struct got_histedit_list_entry *folded = NULL;
9211 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9212 if (err)
9213 return err;
9215 folded = get_folded_commits(hle);
9216 if (folded) {
9217 while (folded != hle) {
9218 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9219 folded = TAILQ_NEXT(folded, entry);
9220 continue;
9222 err = append_folded_commit_msg(&new_msg, folded,
9223 logmsg, repo);
9224 if (err)
9225 goto done;
9226 free(logmsg);
9227 logmsg = new_msg;
9228 folded = TAILQ_NEXT(folded, entry);
9232 err = got_object_id_str(&id_str, hle->commit_id);
9233 if (err)
9234 goto done;
9235 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9236 if (err)
9237 goto done;
9238 logmsg_len = asprintf(&new_msg,
9239 "%s\n# original log message of commit %s: %s",
9240 logmsg ? logmsg : "", id_str, orig_logmsg);
9241 if (logmsg_len == -1) {
9242 err = got_error_from_errno("asprintf");
9243 goto done;
9245 free(logmsg);
9246 logmsg = new_msg;
9248 err = got_object_id_str(&id_str, hle->commit_id);
9249 if (err)
9250 goto done;
9252 err = got_opentemp_named_fd(&logmsg_path, &fd,
9253 GOT_TMPDIR_STR "/got-logmsg");
9254 if (err)
9255 goto done;
9257 write(fd, logmsg, logmsg_len);
9258 close(fd);
9260 err = get_editor(&editor);
9261 if (err)
9262 goto done;
9264 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9265 logmsg_len, 0);
9266 if (err) {
9267 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9268 goto done;
9269 err = NULL;
9270 hle->logmsg = strdup(new_msg);
9271 if (hle->logmsg == NULL)
9272 err = got_error_from_errno("strdup");
9274 done:
9275 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9276 err = got_error_from_errno2("unlink", logmsg_path);
9277 free(logmsg_path);
9278 free(logmsg);
9279 free(orig_logmsg);
9280 free(editor);
9281 if (commit)
9282 got_object_commit_close(commit);
9283 return err;
9286 static const struct got_error *
9287 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9288 FILE *f, struct got_repository *repo)
9290 const struct got_error *err = NULL;
9291 char *line = NULL, *p, *end;
9292 size_t i, size;
9293 ssize_t len;
9294 int lineno = 0;
9295 const struct got_histedit_cmd *cmd;
9296 struct got_object_id *commit_id = NULL;
9297 struct got_histedit_list_entry *hle = NULL;
9299 for (;;) {
9300 len = getline(&line, &size, f);
9301 if (len == -1) {
9302 const struct got_error *getline_err;
9303 if (feof(f))
9304 break;
9305 getline_err = got_error_from_errno("getline");
9306 err = got_ferror(f, getline_err->code);
9307 break;
9309 lineno++;
9310 p = line;
9311 while (isspace((unsigned char)p[0]))
9312 p++;
9313 if (p[0] == '#' || p[0] == '\0') {
9314 free(line);
9315 line = NULL;
9316 continue;
9318 cmd = NULL;
9319 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9320 cmd = &got_histedit_cmds[i];
9321 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9322 isspace((unsigned char)p[strlen(cmd->name)])) {
9323 p += strlen(cmd->name);
9324 break;
9326 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9327 p++;
9328 break;
9331 if (i == nitems(got_histedit_cmds)) {
9332 err = histedit_syntax_error(lineno);
9333 break;
9335 while (isspace((unsigned char)p[0]))
9336 p++;
9337 if (cmd->code == GOT_HISTEDIT_MESG) {
9338 if (hle == NULL || hle->logmsg != NULL) {
9339 err = got_error(GOT_ERR_HISTEDIT_CMD);
9340 break;
9342 if (p[0] == '\0') {
9343 err = histedit_edit_logmsg(hle, repo);
9344 if (err)
9345 break;
9346 } else {
9347 hle->logmsg = strdup(p);
9348 if (hle->logmsg == NULL) {
9349 err = got_error_from_errno("strdup");
9350 break;
9353 free(line);
9354 line = NULL;
9355 continue;
9356 } else {
9357 end = p;
9358 while (end[0] && !isspace((unsigned char)end[0]))
9359 end++;
9360 *end = '\0';
9362 err = got_object_resolve_id_str(&commit_id, repo, p);
9363 if (err) {
9364 /* override error code */
9365 err = histedit_syntax_error(lineno);
9366 break;
9369 hle = malloc(sizeof(*hle));
9370 if (hle == NULL) {
9371 err = got_error_from_errno("malloc");
9372 break;
9374 hle->cmd = cmd;
9375 hle->commit_id = commit_id;
9376 hle->logmsg = NULL;
9377 commit_id = NULL;
9378 free(line);
9379 line = NULL;
9380 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9383 free(line);
9384 free(commit_id);
9385 return err;
9388 static const struct got_error *
9389 histedit_check_script(struct got_histedit_list *histedit_cmds,
9390 struct got_object_id_queue *commits, struct got_repository *repo)
9392 const struct got_error *err = NULL;
9393 struct got_object_qid *qid;
9394 struct got_histedit_list_entry *hle;
9395 static char msg[92];
9396 char *id_str;
9398 if (TAILQ_EMPTY(histedit_cmds))
9399 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9400 "histedit script contains no commands");
9401 if (STAILQ_EMPTY(commits))
9402 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9404 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9405 struct got_histedit_list_entry *hle2;
9406 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9407 if (hle == hle2)
9408 continue;
9409 if (got_object_id_cmp(hle->commit_id,
9410 hle2->commit_id) != 0)
9411 continue;
9412 err = got_object_id_str(&id_str, hle->commit_id);
9413 if (err)
9414 return err;
9415 snprintf(msg, sizeof(msg), "commit %s is listed "
9416 "more than once in histedit script", id_str);
9417 free(id_str);
9418 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9422 STAILQ_FOREACH(qid, commits, entry) {
9423 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9424 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9425 break;
9427 if (hle == NULL) {
9428 err = got_object_id_str(&id_str, qid->id);
9429 if (err)
9430 return err;
9431 snprintf(msg, sizeof(msg),
9432 "commit %s missing from histedit script", id_str);
9433 free(id_str);
9434 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9438 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9439 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9440 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9441 "last commit in histedit script cannot be folded");
9443 return NULL;
9446 static const struct got_error *
9447 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9448 const char *path, struct got_object_id_queue *commits,
9449 struct got_repository *repo)
9451 const struct got_error *err = NULL;
9452 char *editor;
9453 FILE *f = NULL;
9455 err = get_editor(&editor);
9456 if (err)
9457 return err;
9459 if (spawn_editor(editor, path) == -1) {
9460 err = got_error_from_errno("failed spawning editor");
9461 goto done;
9464 f = fopen(path, "r");
9465 if (f == NULL) {
9466 err = got_error_from_errno("fopen");
9467 goto done;
9469 err = histedit_parse_list(histedit_cmds, f, repo);
9470 if (err)
9471 goto done;
9473 err = histedit_check_script(histedit_cmds, commits, repo);
9474 done:
9475 if (f && fclose(f) == EOF && err == NULL)
9476 err = got_error_from_errno("fclose");
9477 free(editor);
9478 return err;
9481 static const struct got_error *
9482 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9483 struct got_object_id_queue *, const char *, const char *,
9484 struct got_repository *);
9486 static const struct got_error *
9487 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9488 struct got_object_id_queue *commits, const char *branch_name,
9489 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9491 const struct got_error *err;
9492 FILE *f = NULL;
9493 char *path = NULL;
9495 err = got_opentemp_named(&path, &f, "got-histedit");
9496 if (err)
9497 return err;
9499 err = write_cmd_list(f, branch_name, commits);
9500 if (err)
9501 goto done;
9503 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9504 fold_only, repo);
9505 if (err)
9506 goto done;
9508 if (edit_logmsg_only || fold_only) {
9509 rewind(f);
9510 err = histedit_parse_list(histedit_cmds, f, repo);
9511 } else {
9512 if (fclose(f) == EOF) {
9513 err = got_error_from_errno("fclose");
9514 goto done;
9516 f = NULL;
9517 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9518 if (err) {
9519 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9520 err->code != GOT_ERR_HISTEDIT_CMD)
9521 goto done;
9522 err = histedit_edit_list_retry(histedit_cmds, err,
9523 commits, path, branch_name, repo);
9526 done:
9527 if (f && fclose(f) == EOF && err == NULL)
9528 err = got_error_from_errno("fclose");
9529 if (path && unlink(path) != 0 && err == NULL)
9530 err = got_error_from_errno2("unlink", path);
9531 free(path);
9532 return err;
9535 static const struct got_error *
9536 histedit_save_list(struct got_histedit_list *histedit_cmds,
9537 struct got_worktree *worktree, struct got_repository *repo)
9539 const struct got_error *err = NULL;
9540 char *path = NULL;
9541 FILE *f = NULL;
9542 struct got_histedit_list_entry *hle;
9543 struct got_commit_object *commit = NULL;
9545 err = got_worktree_get_histedit_script_path(&path, worktree);
9546 if (err)
9547 return err;
9549 f = fopen(path, "w");
9550 if (f == NULL) {
9551 err = got_error_from_errno2("fopen", path);
9552 goto done;
9554 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9555 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9556 repo);
9557 if (err)
9558 break;
9560 if (hle->logmsg) {
9561 int n = fprintf(f, "%c %s\n",
9562 GOT_HISTEDIT_MESG, hle->logmsg);
9563 if (n < 0) {
9564 err = got_ferror(f, GOT_ERR_IO);
9565 break;
9569 done:
9570 if (f && fclose(f) == EOF && err == NULL)
9571 err = got_error_from_errno("fclose");
9572 free(path);
9573 if (commit)
9574 got_object_commit_close(commit);
9575 return err;
9578 void
9579 histedit_free_list(struct got_histedit_list *histedit_cmds)
9581 struct got_histedit_list_entry *hle;
9583 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9584 TAILQ_REMOVE(histedit_cmds, hle, entry);
9585 free(hle);
9589 static const struct got_error *
9590 histedit_load_list(struct got_histedit_list *histedit_cmds,
9591 const char *path, struct got_repository *repo)
9593 const struct got_error *err = NULL;
9594 FILE *f = NULL;
9596 f = fopen(path, "r");
9597 if (f == NULL) {
9598 err = got_error_from_errno2("fopen", path);
9599 goto done;
9602 err = histedit_parse_list(histedit_cmds, f, repo);
9603 done:
9604 if (f && fclose(f) == EOF && err == NULL)
9605 err = got_error_from_errno("fclose");
9606 return err;
9609 static const struct got_error *
9610 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9611 const struct got_error *edit_err, struct got_object_id_queue *commits,
9612 const char *path, const char *branch_name, struct got_repository *repo)
9614 const struct got_error *err = NULL, *prev_err = edit_err;
9615 int resp = ' ';
9617 while (resp != 'c' && resp != 'r' && resp != 'a') {
9618 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9619 "or (a)bort: ", getprogname(), prev_err->msg);
9620 resp = getchar();
9621 if (resp == '\n')
9622 resp = getchar();
9623 if (resp == 'c') {
9624 histedit_free_list(histedit_cmds);
9625 err = histedit_run_editor(histedit_cmds, path, commits,
9626 repo);
9627 if (err) {
9628 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9629 err->code != GOT_ERR_HISTEDIT_CMD)
9630 break;
9631 prev_err = err;
9632 resp = ' ';
9633 continue;
9635 break;
9636 } else if (resp == 'r') {
9637 histedit_free_list(histedit_cmds);
9638 err = histedit_edit_script(histedit_cmds,
9639 commits, branch_name, 0, 0, repo);
9640 if (err) {
9641 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9642 err->code != GOT_ERR_HISTEDIT_CMD)
9643 break;
9644 prev_err = err;
9645 resp = ' ';
9646 continue;
9648 break;
9649 } else if (resp == 'a') {
9650 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9651 break;
9652 } else
9653 printf("invalid response '%c'\n", resp);
9656 return err;
9659 static const struct got_error *
9660 histedit_complete(struct got_worktree *worktree,
9661 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9662 struct got_reference *branch, struct got_repository *repo)
9664 printf("Switching work tree to %s\n",
9665 got_ref_get_symref_target(branch));
9666 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9667 branch, repo);
9670 static const struct got_error *
9671 show_histedit_progress(struct got_commit_object *commit,
9672 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9674 const struct got_error *err;
9675 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9677 err = got_object_id_str(&old_id_str, hle->commit_id);
9678 if (err)
9679 goto done;
9681 if (new_id) {
9682 err = got_object_id_str(&new_id_str, new_id);
9683 if (err)
9684 goto done;
9687 old_id_str[12] = '\0';
9688 if (new_id_str)
9689 new_id_str[12] = '\0';
9691 if (hle->logmsg) {
9692 logmsg = strdup(hle->logmsg);
9693 if (logmsg == NULL) {
9694 err = got_error_from_errno("strdup");
9695 goto done;
9697 trim_logmsg(logmsg, 42);
9698 } else {
9699 err = get_short_logmsg(&logmsg, 42, commit);
9700 if (err)
9701 goto done;
9704 switch (hle->cmd->code) {
9705 case GOT_HISTEDIT_PICK:
9706 case GOT_HISTEDIT_EDIT:
9707 printf("%s -> %s: %s\n", old_id_str,
9708 new_id_str ? new_id_str : "no-op change", logmsg);
9709 break;
9710 case GOT_HISTEDIT_DROP:
9711 case GOT_HISTEDIT_FOLD:
9712 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9713 logmsg);
9714 break;
9715 default:
9716 break;
9718 done:
9719 free(old_id_str);
9720 free(new_id_str);
9721 return err;
9724 static const struct got_error *
9725 histedit_commit(struct got_pathlist_head *merged_paths,
9726 struct got_worktree *worktree, struct got_fileindex *fileindex,
9727 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9728 struct got_repository *repo)
9730 const struct got_error *err;
9731 struct got_commit_object *commit;
9732 struct got_object_id *new_commit_id;
9734 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9735 && hle->logmsg == NULL) {
9736 err = histedit_edit_logmsg(hle, repo);
9737 if (err)
9738 return err;
9741 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9742 if (err)
9743 return err;
9745 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9746 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9747 hle->logmsg, repo);
9748 if (err) {
9749 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9750 goto done;
9751 err = show_histedit_progress(commit, hle, NULL);
9752 } else {
9753 err = show_histedit_progress(commit, hle, new_commit_id);
9754 free(new_commit_id);
9756 done:
9757 got_object_commit_close(commit);
9758 return err;
9761 static const struct got_error *
9762 histedit_skip_commit(struct got_histedit_list_entry *hle,
9763 struct got_worktree *worktree, struct got_repository *repo)
9765 const struct got_error *error;
9766 struct got_commit_object *commit;
9768 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9769 repo);
9770 if (error)
9771 return error;
9773 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9774 if (error)
9775 return error;
9777 error = show_histedit_progress(commit, hle, NULL);
9778 got_object_commit_close(commit);
9779 return error;
9782 static const struct got_error *
9783 check_local_changes(void *arg, unsigned char status,
9784 unsigned char staged_status, const char *path,
9785 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9786 struct got_object_id *commit_id, int dirfd, const char *de_name)
9788 int *have_local_changes = arg;
9790 switch (status) {
9791 case GOT_STATUS_ADD:
9792 case GOT_STATUS_DELETE:
9793 case GOT_STATUS_MODIFY:
9794 case GOT_STATUS_CONFLICT:
9795 *have_local_changes = 1;
9796 return got_error(GOT_ERR_CANCELLED);
9797 default:
9798 break;
9801 switch (staged_status) {
9802 case GOT_STATUS_ADD:
9803 case GOT_STATUS_DELETE:
9804 case GOT_STATUS_MODIFY:
9805 *have_local_changes = 1;
9806 return got_error(GOT_ERR_CANCELLED);
9807 default:
9808 break;
9811 return NULL;
9814 static const struct got_error *
9815 cmd_histedit(int argc, char *argv[])
9817 const struct got_error *error = NULL;
9818 struct got_worktree *worktree = NULL;
9819 struct got_fileindex *fileindex = NULL;
9820 struct got_repository *repo = NULL;
9821 char *cwd = NULL;
9822 struct got_reference *branch = NULL;
9823 struct got_reference *tmp_branch = NULL;
9824 struct got_object_id *resume_commit_id = NULL;
9825 struct got_object_id *base_commit_id = NULL;
9826 struct got_object_id *head_commit_id = NULL;
9827 struct got_commit_object *commit = NULL;
9828 int ch, rebase_in_progress = 0;
9829 struct got_update_progress_arg upa;
9830 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9831 int edit_logmsg_only = 0, fold_only = 0;
9832 int list_backups = 0, delete_backups = 0;
9833 const char *edit_script_path = NULL;
9834 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9835 struct got_object_id_queue commits;
9836 struct got_pathlist_head merged_paths;
9837 const struct got_object_id_queue *parent_ids;
9838 struct got_object_qid *pid;
9839 struct got_histedit_list histedit_cmds;
9840 struct got_histedit_list_entry *hle;
9842 STAILQ_INIT(&commits);
9843 TAILQ_INIT(&histedit_cmds);
9844 TAILQ_INIT(&merged_paths);
9845 memset(&upa, 0, sizeof(upa));
9847 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9848 switch (ch) {
9849 case 'a':
9850 abort_edit = 1;
9851 break;
9852 case 'c':
9853 continue_edit = 1;
9854 break;
9855 case 'f':
9856 fold_only = 1;
9857 break;
9858 case 'F':
9859 edit_script_path = optarg;
9860 break;
9861 case 'm':
9862 edit_logmsg_only = 1;
9863 break;
9864 case 'l':
9865 list_backups = 1;
9866 break;
9867 case 'X':
9868 delete_backups = 1;
9869 break;
9870 default:
9871 usage_histedit();
9872 /* NOTREACHED */
9876 argc -= optind;
9877 argv += optind;
9879 #ifndef PROFILE
9880 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9881 "unveil", NULL) == -1)
9882 err(1, "pledge");
9883 #endif
9884 if (abort_edit && continue_edit)
9885 option_conflict('a', 'c');
9886 if (edit_script_path && edit_logmsg_only)
9887 option_conflict('F', 'm');
9888 if (abort_edit && edit_logmsg_only)
9889 option_conflict('a', 'm');
9890 if (continue_edit && edit_logmsg_only)
9891 option_conflict('c', 'm');
9892 if (abort_edit && fold_only)
9893 option_conflict('a', 'f');
9894 if (continue_edit && fold_only)
9895 option_conflict('c', 'f');
9896 if (fold_only && edit_logmsg_only)
9897 option_conflict('f', 'm');
9898 if (edit_script_path && fold_only)
9899 option_conflict('F', 'f');
9900 if (list_backups) {
9901 if (abort_edit)
9902 option_conflict('l', 'a');
9903 if (continue_edit)
9904 option_conflict('l', 'c');
9905 if (edit_script_path)
9906 option_conflict('l', 'F');
9907 if (edit_logmsg_only)
9908 option_conflict('l', 'm');
9909 if (fold_only)
9910 option_conflict('l', 'f');
9911 if (delete_backups)
9912 option_conflict('l', 'X');
9913 if (argc != 0 && argc != 1)
9914 usage_histedit();
9915 } else if (delete_backups) {
9916 if (abort_edit)
9917 option_conflict('X', 'a');
9918 if (continue_edit)
9919 option_conflict('X', 'c');
9920 if (edit_script_path)
9921 option_conflict('X', 'F');
9922 if (edit_logmsg_only)
9923 option_conflict('X', 'm');
9924 if (fold_only)
9925 option_conflict('X', 'f');
9926 if (list_backups)
9927 option_conflict('X', 'l');
9928 if (argc != 0 && argc != 1)
9929 usage_histedit();
9930 } else if (argc != 0)
9931 usage_histedit();
9934 * This command cannot apply unveil(2) in all cases because the
9935 * user may choose to run an editor to edit the histedit script
9936 * and to edit individual commit log messages.
9937 * unveil(2) traverses exec(2); if an editor is used we have to
9938 * apply unveil after edit script and log messages have been written.
9939 * XXX TODO: Make use of unveil(2) where possible.
9942 cwd = getcwd(NULL, 0);
9943 if (cwd == NULL) {
9944 error = got_error_from_errno("getcwd");
9945 goto done;
9947 error = got_worktree_open(&worktree, cwd);
9948 if (error) {
9949 if (list_backups || delete_backups) {
9950 if (error->code != GOT_ERR_NOT_WORKTREE)
9951 goto done;
9952 } else {
9953 if (error->code == GOT_ERR_NOT_WORKTREE)
9954 error = wrap_not_worktree_error(error,
9955 "histedit", cwd);
9956 goto done;
9960 if (list_backups || delete_backups) {
9961 error = got_repo_open(&repo,
9962 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9963 NULL);
9964 if (error != NULL)
9965 goto done;
9966 error = apply_unveil(got_repo_get_path(repo), 0,
9967 worktree ? got_worktree_get_root_path(worktree) : NULL);
9968 if (error)
9969 goto done;
9970 error = process_backup_refs(
9971 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9972 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9973 goto done; /* nothing else to do */
9976 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9977 NULL);
9978 if (error != NULL)
9979 goto done;
9981 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9982 if (error)
9983 goto done;
9984 if (rebase_in_progress) {
9985 error = got_error(GOT_ERR_REBASING);
9986 goto done;
9989 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
9990 if (error)
9991 goto done;
9993 if (edit_in_progress && edit_logmsg_only) {
9994 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
9995 "histedit operation is in progress in this "
9996 "work tree and must be continued or aborted "
9997 "before the -m option can be used");
9998 goto done;
10000 if (edit_in_progress && fold_only) {
10001 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10002 "histedit operation is in progress in this "
10003 "work tree and must be continued or aborted "
10004 "before the -f option can be used");
10005 goto done;
10008 if (edit_in_progress && abort_edit) {
10009 error = got_worktree_histedit_continue(&resume_commit_id,
10010 &tmp_branch, &branch, &base_commit_id, &fileindex,
10011 worktree, repo);
10012 if (error)
10013 goto done;
10014 printf("Switching work tree to %s\n",
10015 got_ref_get_symref_target(branch));
10016 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10017 branch, base_commit_id, update_progress, &upa);
10018 if (error)
10019 goto done;
10020 printf("Histedit of %s aborted\n",
10021 got_ref_get_symref_target(branch));
10022 print_update_progress_stats(&upa);
10023 goto done; /* nothing else to do */
10024 } else if (abort_edit) {
10025 error = got_error(GOT_ERR_NOT_HISTEDIT);
10026 goto done;
10029 if (continue_edit) {
10030 char *path;
10032 if (!edit_in_progress) {
10033 error = got_error(GOT_ERR_NOT_HISTEDIT);
10034 goto done;
10037 error = got_worktree_get_histedit_script_path(&path, worktree);
10038 if (error)
10039 goto done;
10041 error = histedit_load_list(&histedit_cmds, path, repo);
10042 free(path);
10043 if (error)
10044 goto done;
10046 error = got_worktree_histedit_continue(&resume_commit_id,
10047 &tmp_branch, &branch, &base_commit_id, &fileindex,
10048 worktree, repo);
10049 if (error)
10050 goto done;
10052 error = got_ref_resolve(&head_commit_id, repo, branch);
10053 if (error)
10054 goto done;
10056 error = got_object_open_as_commit(&commit, repo,
10057 head_commit_id);
10058 if (error)
10059 goto done;
10060 parent_ids = got_object_commit_get_parent_ids(commit);
10061 pid = STAILQ_FIRST(parent_ids);
10062 if (pid == NULL) {
10063 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10064 goto done;
10066 error = collect_commits(&commits, head_commit_id, pid->id,
10067 base_commit_id, got_worktree_get_path_prefix(worktree),
10068 GOT_ERR_HISTEDIT_PATH, repo);
10069 got_object_commit_close(commit);
10070 commit = NULL;
10071 if (error)
10072 goto done;
10073 } else {
10074 if (edit_in_progress) {
10075 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10076 goto done;
10079 error = got_ref_open(&branch, repo,
10080 got_worktree_get_head_ref_name(worktree), 0);
10081 if (error != NULL)
10082 goto done;
10084 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10085 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10086 "will not edit commit history of a branch outside "
10087 "the \"refs/heads/\" reference namespace");
10088 goto done;
10091 error = got_ref_resolve(&head_commit_id, repo, branch);
10092 got_ref_close(branch);
10093 branch = NULL;
10094 if (error)
10095 goto done;
10097 error = got_object_open_as_commit(&commit, repo,
10098 head_commit_id);
10099 if (error)
10100 goto done;
10101 parent_ids = got_object_commit_get_parent_ids(commit);
10102 pid = STAILQ_FIRST(parent_ids);
10103 if (pid == NULL) {
10104 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10105 goto done;
10107 error = collect_commits(&commits, head_commit_id, pid->id,
10108 got_worktree_get_base_commit_id(worktree),
10109 got_worktree_get_path_prefix(worktree),
10110 GOT_ERR_HISTEDIT_PATH, repo);
10111 got_object_commit_close(commit);
10112 commit = NULL;
10113 if (error)
10114 goto done;
10116 if (STAILQ_EMPTY(&commits)) {
10117 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10118 goto done;
10121 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10122 &base_commit_id, &fileindex, worktree, repo);
10123 if (error)
10124 goto done;
10126 if (edit_script_path) {
10127 error = histedit_load_list(&histedit_cmds,
10128 edit_script_path, repo);
10129 if (error) {
10130 got_worktree_histedit_abort(worktree, fileindex,
10131 repo, branch, base_commit_id,
10132 update_progress, &upa);
10133 print_update_progress_stats(&upa);
10134 goto done;
10136 } else {
10137 const char *branch_name;
10138 branch_name = got_ref_get_symref_target(branch);
10139 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10140 branch_name += 11;
10141 error = histedit_edit_script(&histedit_cmds, &commits,
10142 branch_name, edit_logmsg_only, fold_only, repo);
10143 if (error) {
10144 got_worktree_histedit_abort(worktree, fileindex,
10145 repo, branch, base_commit_id,
10146 update_progress, &upa);
10147 print_update_progress_stats(&upa);
10148 goto done;
10153 error = histedit_save_list(&histedit_cmds, worktree,
10154 repo);
10155 if (error) {
10156 got_worktree_histedit_abort(worktree, fileindex,
10157 repo, branch, base_commit_id,
10158 update_progress, &upa);
10159 print_update_progress_stats(&upa);
10160 goto done;
10165 error = histedit_check_script(&histedit_cmds, &commits, repo);
10166 if (error)
10167 goto done;
10169 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10170 if (resume_commit_id) {
10171 if (got_object_id_cmp(hle->commit_id,
10172 resume_commit_id) != 0)
10173 continue;
10175 resume_commit_id = NULL;
10176 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10177 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10178 error = histedit_skip_commit(hle, worktree,
10179 repo);
10180 if (error)
10181 goto done;
10182 } else {
10183 struct got_pathlist_head paths;
10184 int have_changes = 0;
10186 TAILQ_INIT(&paths);
10187 error = got_pathlist_append(&paths, "", NULL);
10188 if (error)
10189 goto done;
10190 error = got_worktree_status(worktree, &paths,
10191 repo, 0, check_local_changes, &have_changes,
10192 check_cancelled, NULL);
10193 got_pathlist_free(&paths);
10194 if (error) {
10195 if (error->code != GOT_ERR_CANCELLED)
10196 goto done;
10197 if (sigint_received || sigpipe_received)
10198 goto done;
10200 if (have_changes) {
10201 error = histedit_commit(NULL, worktree,
10202 fileindex, tmp_branch, hle, repo);
10203 if (error)
10204 goto done;
10205 } else {
10206 error = got_object_open_as_commit(
10207 &commit, repo, hle->commit_id);
10208 if (error)
10209 goto done;
10210 error = show_histedit_progress(commit,
10211 hle, NULL);
10212 got_object_commit_close(commit);
10213 commit = NULL;
10214 if (error)
10215 goto done;
10218 continue;
10221 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10222 error = histedit_skip_commit(hle, worktree, repo);
10223 if (error)
10224 goto done;
10225 continue;
10228 error = got_object_open_as_commit(&commit, repo,
10229 hle->commit_id);
10230 if (error)
10231 goto done;
10232 parent_ids = got_object_commit_get_parent_ids(commit);
10233 pid = STAILQ_FIRST(parent_ids);
10235 error = got_worktree_histedit_merge_files(&merged_paths,
10236 worktree, fileindex, pid->id, hle->commit_id, repo,
10237 update_progress, &upa, check_cancelled, NULL);
10238 if (error)
10239 goto done;
10240 got_object_commit_close(commit);
10241 commit = NULL;
10243 print_update_progress_stats(&upa);
10244 if (upa.conflicts > 0)
10245 rebase_status = GOT_STATUS_CONFLICT;
10247 if (rebase_status == GOT_STATUS_CONFLICT) {
10248 error = show_rebase_merge_conflict(hle->commit_id,
10249 repo);
10250 if (error)
10251 goto done;
10252 got_worktree_rebase_pathlist_free(&merged_paths);
10253 break;
10256 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10257 char *id_str;
10258 error = got_object_id_str(&id_str, hle->commit_id);
10259 if (error)
10260 goto done;
10261 printf("Stopping histedit for amending commit %s\n",
10262 id_str);
10263 free(id_str);
10264 got_worktree_rebase_pathlist_free(&merged_paths);
10265 error = got_worktree_histedit_postpone(worktree,
10266 fileindex);
10267 goto done;
10270 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10271 error = histedit_skip_commit(hle, worktree, repo);
10272 if (error)
10273 goto done;
10274 continue;
10277 error = histedit_commit(&merged_paths, worktree, fileindex,
10278 tmp_branch, hle, repo);
10279 got_worktree_rebase_pathlist_free(&merged_paths);
10280 if (error)
10281 goto done;
10284 if (rebase_status == GOT_STATUS_CONFLICT) {
10285 error = got_worktree_histedit_postpone(worktree, fileindex);
10286 if (error)
10287 goto done;
10288 error = got_error_msg(GOT_ERR_CONFLICTS,
10289 "conflicts must be resolved before histedit can continue");
10290 } else
10291 error = histedit_complete(worktree, fileindex, tmp_branch,
10292 branch, repo);
10293 done:
10294 got_object_id_queue_free(&commits);
10295 histedit_free_list(&histedit_cmds);
10296 free(head_commit_id);
10297 free(base_commit_id);
10298 free(resume_commit_id);
10299 if (commit)
10300 got_object_commit_close(commit);
10301 if (branch)
10302 got_ref_close(branch);
10303 if (tmp_branch)
10304 got_ref_close(tmp_branch);
10305 if (worktree)
10306 got_worktree_close(worktree);
10307 if (repo) {
10308 const struct got_error *close_err = got_repo_close(repo);
10309 if (error == NULL)
10310 error = close_err;
10312 return error;
10315 __dead static void
10316 usage_integrate(void)
10318 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10319 exit(1);
10322 static const struct got_error *
10323 cmd_integrate(int argc, char *argv[])
10325 const struct got_error *error = NULL;
10326 struct got_repository *repo = NULL;
10327 struct got_worktree *worktree = NULL;
10328 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10329 const char *branch_arg = NULL;
10330 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10331 struct got_fileindex *fileindex = NULL;
10332 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10333 int ch;
10334 struct got_update_progress_arg upa;
10336 while ((ch = getopt(argc, argv, "")) != -1) {
10337 switch (ch) {
10338 default:
10339 usage_integrate();
10340 /* NOTREACHED */
10344 argc -= optind;
10345 argv += optind;
10347 if (argc != 1)
10348 usage_integrate();
10349 branch_arg = argv[0];
10350 #ifndef PROFILE
10351 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10352 "unveil", NULL) == -1)
10353 err(1, "pledge");
10354 #endif
10355 cwd = getcwd(NULL, 0);
10356 if (cwd == NULL) {
10357 error = got_error_from_errno("getcwd");
10358 goto done;
10361 error = got_worktree_open(&worktree, cwd);
10362 if (error) {
10363 if (error->code == GOT_ERR_NOT_WORKTREE)
10364 error = wrap_not_worktree_error(error, "integrate",
10365 cwd);
10366 goto done;
10369 error = check_rebase_or_histedit_in_progress(worktree);
10370 if (error)
10371 goto done;
10373 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10374 NULL);
10375 if (error != NULL)
10376 goto done;
10378 error = apply_unveil(got_repo_get_path(repo), 0,
10379 got_worktree_get_root_path(worktree));
10380 if (error)
10381 goto done;
10383 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10384 error = got_error_from_errno("asprintf");
10385 goto done;
10388 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10389 &base_branch_ref, worktree, refname, repo);
10390 if (error)
10391 goto done;
10393 refname = strdup(got_ref_get_name(branch_ref));
10394 if (refname == NULL) {
10395 error = got_error_from_errno("strdup");
10396 got_worktree_integrate_abort(worktree, fileindex, repo,
10397 branch_ref, base_branch_ref);
10398 goto done;
10400 base_refname = strdup(got_ref_get_name(base_branch_ref));
10401 if (base_refname == NULL) {
10402 error = got_error_from_errno("strdup");
10403 got_worktree_integrate_abort(worktree, fileindex, repo,
10404 branch_ref, base_branch_ref);
10405 goto done;
10408 error = got_ref_resolve(&commit_id, repo, branch_ref);
10409 if (error)
10410 goto done;
10412 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10413 if (error)
10414 goto done;
10416 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10417 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10418 "specified branch has already been integrated");
10419 got_worktree_integrate_abort(worktree, fileindex, repo,
10420 branch_ref, base_branch_ref);
10421 goto done;
10424 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10425 if (error) {
10426 if (error->code == GOT_ERR_ANCESTRY)
10427 error = got_error(GOT_ERR_REBASE_REQUIRED);
10428 got_worktree_integrate_abort(worktree, fileindex, repo,
10429 branch_ref, base_branch_ref);
10430 goto done;
10433 memset(&upa, 0, sizeof(upa));
10434 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10435 branch_ref, base_branch_ref, update_progress, &upa,
10436 check_cancelled, NULL);
10437 if (error)
10438 goto done;
10440 printf("Integrated %s into %s\n", refname, base_refname);
10441 print_update_progress_stats(&upa);
10442 done:
10443 if (repo) {
10444 const struct got_error *close_err = got_repo_close(repo);
10445 if (error == NULL)
10446 error = close_err;
10448 if (worktree)
10449 got_worktree_close(worktree);
10450 free(cwd);
10451 free(base_commit_id);
10452 free(commit_id);
10453 free(refname);
10454 free(base_refname);
10455 return error;
10458 __dead static void
10459 usage_stage(void)
10461 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10462 "[-S] [file-path ...]\n",
10463 getprogname());
10464 exit(1);
10467 static const struct got_error *
10468 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10469 const char *path, struct got_object_id *blob_id,
10470 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10471 int dirfd, const char *de_name)
10473 const struct got_error *err = NULL;
10474 char *id_str = NULL;
10476 if (staged_status != GOT_STATUS_ADD &&
10477 staged_status != GOT_STATUS_MODIFY &&
10478 staged_status != GOT_STATUS_DELETE)
10479 return NULL;
10481 if (staged_status == GOT_STATUS_ADD ||
10482 staged_status == GOT_STATUS_MODIFY)
10483 err = got_object_id_str(&id_str, staged_blob_id);
10484 else
10485 err = got_object_id_str(&id_str, blob_id);
10486 if (err)
10487 return err;
10489 printf("%s %c %s\n", id_str, staged_status, path);
10490 free(id_str);
10491 return NULL;
10494 static const struct got_error *
10495 cmd_stage(int argc, char *argv[])
10497 const struct got_error *error = NULL;
10498 struct got_repository *repo = NULL;
10499 struct got_worktree *worktree = NULL;
10500 char *cwd = NULL;
10501 struct got_pathlist_head paths;
10502 struct got_pathlist_entry *pe;
10503 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10504 FILE *patch_script_file = NULL;
10505 const char *patch_script_path = NULL;
10506 struct choose_patch_arg cpa;
10508 TAILQ_INIT(&paths);
10510 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10511 switch (ch) {
10512 case 'l':
10513 list_stage = 1;
10514 break;
10515 case 'p':
10516 pflag = 1;
10517 break;
10518 case 'F':
10519 patch_script_path = optarg;
10520 break;
10521 case 'S':
10522 allow_bad_symlinks = 1;
10523 break;
10524 default:
10525 usage_stage();
10526 /* NOTREACHED */
10530 argc -= optind;
10531 argv += optind;
10533 #ifndef PROFILE
10534 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10535 "unveil", NULL) == -1)
10536 err(1, "pledge");
10537 #endif
10538 if (list_stage && (pflag || patch_script_path))
10539 errx(1, "-l option cannot be used with other options");
10540 if (patch_script_path && !pflag)
10541 errx(1, "-F option can only be used together with -p option");
10543 cwd = getcwd(NULL, 0);
10544 if (cwd == NULL) {
10545 error = got_error_from_errno("getcwd");
10546 goto done;
10549 error = got_worktree_open(&worktree, cwd);
10550 if (error) {
10551 if (error->code == GOT_ERR_NOT_WORKTREE)
10552 error = wrap_not_worktree_error(error, "stage", cwd);
10553 goto done;
10556 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10557 NULL);
10558 if (error != NULL)
10559 goto done;
10561 if (patch_script_path) {
10562 patch_script_file = fopen(patch_script_path, "r");
10563 if (patch_script_file == NULL) {
10564 error = got_error_from_errno2("fopen",
10565 patch_script_path);
10566 goto done;
10569 error = apply_unveil(got_repo_get_path(repo), 0,
10570 got_worktree_get_root_path(worktree));
10571 if (error)
10572 goto done;
10574 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10575 if (error)
10576 goto done;
10578 if (list_stage)
10579 error = got_worktree_status(worktree, &paths, repo, 0,
10580 print_stage, NULL, check_cancelled, NULL);
10581 else {
10582 cpa.patch_script_file = patch_script_file;
10583 cpa.action = "stage";
10584 error = got_worktree_stage(worktree, &paths,
10585 pflag ? NULL : print_status, NULL,
10586 pflag ? choose_patch : NULL, &cpa,
10587 allow_bad_symlinks, repo);
10589 done:
10590 if (patch_script_file && fclose(patch_script_file) == EOF &&
10591 error == NULL)
10592 error = got_error_from_errno2("fclose", patch_script_path);
10593 if (repo) {
10594 const struct got_error *close_err = got_repo_close(repo);
10595 if (error == NULL)
10596 error = close_err;
10598 if (worktree)
10599 got_worktree_close(worktree);
10600 TAILQ_FOREACH(pe, &paths, entry)
10601 free((char *)pe->path);
10602 got_pathlist_free(&paths);
10603 free(cwd);
10604 return error;
10607 __dead static void
10608 usage_unstage(void)
10610 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10611 "[file-path ...]\n",
10612 getprogname());
10613 exit(1);
10617 static const struct got_error *
10618 cmd_unstage(int argc, char *argv[])
10620 const struct got_error *error = NULL;
10621 struct got_repository *repo = NULL;
10622 struct got_worktree *worktree = NULL;
10623 char *cwd = NULL;
10624 struct got_pathlist_head paths;
10625 struct got_pathlist_entry *pe;
10626 int ch, pflag = 0;
10627 struct got_update_progress_arg upa;
10628 FILE *patch_script_file = NULL;
10629 const char *patch_script_path = NULL;
10630 struct choose_patch_arg cpa;
10632 TAILQ_INIT(&paths);
10634 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10635 switch (ch) {
10636 case 'p':
10637 pflag = 1;
10638 break;
10639 case 'F':
10640 patch_script_path = optarg;
10641 break;
10642 default:
10643 usage_unstage();
10644 /* NOTREACHED */
10648 argc -= optind;
10649 argv += optind;
10651 #ifndef PROFILE
10652 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10653 "unveil", NULL) == -1)
10654 err(1, "pledge");
10655 #endif
10656 if (patch_script_path && !pflag)
10657 errx(1, "-F option can only be used together with -p option");
10659 cwd = getcwd(NULL, 0);
10660 if (cwd == NULL) {
10661 error = got_error_from_errno("getcwd");
10662 goto done;
10665 error = got_worktree_open(&worktree, cwd);
10666 if (error) {
10667 if (error->code == GOT_ERR_NOT_WORKTREE)
10668 error = wrap_not_worktree_error(error, "unstage", cwd);
10669 goto done;
10672 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10673 NULL);
10674 if (error != NULL)
10675 goto done;
10677 if (patch_script_path) {
10678 patch_script_file = fopen(patch_script_path, "r");
10679 if (patch_script_file == NULL) {
10680 error = got_error_from_errno2("fopen",
10681 patch_script_path);
10682 goto done;
10686 error = apply_unveil(got_repo_get_path(repo), 0,
10687 got_worktree_get_root_path(worktree));
10688 if (error)
10689 goto done;
10691 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10692 if (error)
10693 goto done;
10695 cpa.patch_script_file = patch_script_file;
10696 cpa.action = "unstage";
10697 memset(&upa, 0, sizeof(upa));
10698 error = got_worktree_unstage(worktree, &paths, update_progress,
10699 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10700 if (!error)
10701 print_update_progress_stats(&upa);
10702 done:
10703 if (patch_script_file && fclose(patch_script_file) == EOF &&
10704 error == NULL)
10705 error = got_error_from_errno2("fclose", patch_script_path);
10706 if (repo) {
10707 const struct got_error *close_err = got_repo_close(repo);
10708 if (error == NULL)
10709 error = close_err;
10711 if (worktree)
10712 got_worktree_close(worktree);
10713 TAILQ_FOREACH(pe, &paths, entry)
10714 free((char *)pe->path);
10715 got_pathlist_free(&paths);
10716 free(cwd);
10717 return error;
10720 __dead static void
10721 usage_cat(void)
10723 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10724 "arg1 [arg2 ...]\n", getprogname());
10725 exit(1);
10728 static const struct got_error *
10729 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10731 const struct got_error *err;
10732 struct got_blob_object *blob;
10734 err = got_object_open_as_blob(&blob, repo, id, 8192);
10735 if (err)
10736 return err;
10738 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10739 got_object_blob_close(blob);
10740 return err;
10743 static const struct got_error *
10744 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10746 const struct got_error *err;
10747 struct got_tree_object *tree;
10748 int nentries, i;
10750 err = got_object_open_as_tree(&tree, repo, id);
10751 if (err)
10752 return err;
10754 nentries = got_object_tree_get_nentries(tree);
10755 for (i = 0; i < nentries; i++) {
10756 struct got_tree_entry *te;
10757 char *id_str;
10758 if (sigint_received || sigpipe_received)
10759 break;
10760 te = got_object_tree_get_entry(tree, i);
10761 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10762 if (err)
10763 break;
10764 fprintf(outfile, "%s %.7o %s\n", id_str,
10765 got_tree_entry_get_mode(te),
10766 got_tree_entry_get_name(te));
10767 free(id_str);
10770 got_object_tree_close(tree);
10771 return err;
10774 static const struct got_error *
10775 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10777 const struct got_error *err;
10778 struct got_commit_object *commit;
10779 const struct got_object_id_queue *parent_ids;
10780 struct got_object_qid *pid;
10781 char *id_str = NULL;
10782 const char *logmsg = NULL;
10784 err = got_object_open_as_commit(&commit, repo, id);
10785 if (err)
10786 return err;
10788 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10789 if (err)
10790 goto done;
10792 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10793 parent_ids = got_object_commit_get_parent_ids(commit);
10794 fprintf(outfile, "numparents %d\n",
10795 got_object_commit_get_nparents(commit));
10796 STAILQ_FOREACH(pid, parent_ids, entry) {
10797 char *pid_str;
10798 err = got_object_id_str(&pid_str, pid->id);
10799 if (err)
10800 goto done;
10801 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10802 free(pid_str);
10804 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10805 got_object_commit_get_author(commit),
10806 (long long)got_object_commit_get_author_time(commit));
10808 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10809 got_object_commit_get_author(commit),
10810 (long long)got_object_commit_get_committer_time(commit));
10812 logmsg = got_object_commit_get_logmsg_raw(commit);
10813 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10814 fprintf(outfile, "%s", logmsg);
10815 done:
10816 free(id_str);
10817 got_object_commit_close(commit);
10818 return err;
10821 static const struct got_error *
10822 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10824 const struct got_error *err;
10825 struct got_tag_object *tag;
10826 char *id_str = NULL;
10827 const char *tagmsg = NULL;
10829 err = got_object_open_as_tag(&tag, repo, id);
10830 if (err)
10831 return err;
10833 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10834 if (err)
10835 goto done;
10837 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10839 switch (got_object_tag_get_object_type(tag)) {
10840 case GOT_OBJ_TYPE_BLOB:
10841 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10842 GOT_OBJ_LABEL_BLOB);
10843 break;
10844 case GOT_OBJ_TYPE_TREE:
10845 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10846 GOT_OBJ_LABEL_TREE);
10847 break;
10848 case GOT_OBJ_TYPE_COMMIT:
10849 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10850 GOT_OBJ_LABEL_COMMIT);
10851 break;
10852 case GOT_OBJ_TYPE_TAG:
10853 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10854 GOT_OBJ_LABEL_TAG);
10855 break;
10856 default:
10857 break;
10860 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10861 got_object_tag_get_name(tag));
10863 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10864 got_object_tag_get_tagger(tag),
10865 (long long)got_object_tag_get_tagger_time(tag));
10867 tagmsg = got_object_tag_get_message(tag);
10868 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10869 fprintf(outfile, "%s", tagmsg);
10870 done:
10871 free(id_str);
10872 got_object_tag_close(tag);
10873 return err;
10876 static const struct got_error *
10877 cmd_cat(int argc, char *argv[])
10879 const struct got_error *error;
10880 struct got_repository *repo = NULL;
10881 struct got_worktree *worktree = NULL;
10882 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10883 const char *commit_id_str = NULL;
10884 struct got_object_id *id = NULL, *commit_id = NULL;
10885 int ch, obj_type, i, force_path = 0;
10886 struct got_reflist_head refs;
10888 TAILQ_INIT(&refs);
10890 #ifndef PROFILE
10891 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10892 NULL) == -1)
10893 err(1, "pledge");
10894 #endif
10896 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10897 switch (ch) {
10898 case 'c':
10899 commit_id_str = optarg;
10900 break;
10901 case 'r':
10902 repo_path = realpath(optarg, NULL);
10903 if (repo_path == NULL)
10904 return got_error_from_errno2("realpath",
10905 optarg);
10906 got_path_strip_trailing_slashes(repo_path);
10907 break;
10908 case 'P':
10909 force_path = 1;
10910 break;
10911 default:
10912 usage_cat();
10913 /* NOTREACHED */
10917 argc -= optind;
10918 argv += optind;
10920 cwd = getcwd(NULL, 0);
10921 if (cwd == NULL) {
10922 error = got_error_from_errno("getcwd");
10923 goto done;
10925 error = got_worktree_open(&worktree, cwd);
10926 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10927 goto done;
10928 if (worktree) {
10929 if (repo_path == NULL) {
10930 repo_path = strdup(
10931 got_worktree_get_repo_path(worktree));
10932 if (repo_path == NULL) {
10933 error = got_error_from_errno("strdup");
10934 goto done;
10939 if (repo_path == NULL) {
10940 repo_path = getcwd(NULL, 0);
10941 if (repo_path == NULL)
10942 return got_error_from_errno("getcwd");
10945 error = got_repo_open(&repo, repo_path, NULL);
10946 free(repo_path);
10947 if (error != NULL)
10948 goto done;
10950 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10951 if (error)
10952 goto done;
10954 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10955 if (error)
10956 goto done;
10958 if (commit_id_str == NULL)
10959 commit_id_str = GOT_REF_HEAD;
10960 error = got_repo_match_object_id(&commit_id, NULL,
10961 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10962 if (error)
10963 goto done;
10965 for (i = 0; i < argc; i++) {
10966 if (force_path) {
10967 error = got_object_id_by_path(&id, repo, commit_id,
10968 argv[i]);
10969 if (error)
10970 break;
10971 } else {
10972 error = got_repo_match_object_id(&id, &label, argv[i],
10973 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10974 repo);
10975 if (error) {
10976 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10977 error->code != GOT_ERR_NOT_REF)
10978 break;
10979 error = got_object_id_by_path(&id, repo,
10980 commit_id, argv[i]);
10981 if (error)
10982 break;
10986 error = got_object_get_type(&obj_type, repo, id);
10987 if (error)
10988 break;
10990 switch (obj_type) {
10991 case GOT_OBJ_TYPE_BLOB:
10992 error = cat_blob(id, repo, stdout);
10993 break;
10994 case GOT_OBJ_TYPE_TREE:
10995 error = cat_tree(id, repo, stdout);
10996 break;
10997 case GOT_OBJ_TYPE_COMMIT:
10998 error = cat_commit(id, repo, stdout);
10999 break;
11000 case GOT_OBJ_TYPE_TAG:
11001 error = cat_tag(id, repo, stdout);
11002 break;
11003 default:
11004 error = got_error(GOT_ERR_OBJ_TYPE);
11005 break;
11007 if (error)
11008 break;
11009 free(label);
11010 label = NULL;
11011 free(id);
11012 id = NULL;
11014 done:
11015 free(label);
11016 free(id);
11017 free(commit_id);
11018 if (worktree)
11019 got_worktree_close(worktree);
11020 if (repo) {
11021 const struct got_error *close_err = got_repo_close(repo);
11022 if (error == NULL)
11023 error = close_err;
11025 got_ref_list_free(&refs);
11026 return error;
11029 __dead static void
11030 usage_info(void)
11032 fprintf(stderr, "usage: %s info [path ...]\n",
11033 getprogname());
11034 exit(1);
11037 static const struct got_error *
11038 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11039 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11040 struct got_object_id *commit_id)
11042 const struct got_error *err = NULL;
11043 char *id_str = NULL;
11044 char datebuf[128];
11045 struct tm mytm, *tm;
11046 struct got_pathlist_head *paths = arg;
11047 struct got_pathlist_entry *pe;
11050 * Clear error indication from any of the path arguments which
11051 * would cause this file index entry to be displayed.
11053 TAILQ_FOREACH(pe, paths, entry) {
11054 if (got_path_cmp(path, pe->path, strlen(path),
11055 pe->path_len) == 0 ||
11056 got_path_is_child(path, pe->path, pe->path_len))
11057 pe->data = NULL; /* no error */
11060 printf(GOT_COMMIT_SEP_STR);
11061 if (S_ISLNK(mode))
11062 printf("symlink: %s\n", path);
11063 else if (S_ISREG(mode)) {
11064 printf("file: %s\n", path);
11065 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11066 } else if (S_ISDIR(mode))
11067 printf("directory: %s\n", path);
11068 else
11069 printf("something: %s\n", path);
11071 tm = localtime_r(&mtime, &mytm);
11072 if (tm == NULL)
11073 return NULL;
11074 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11075 return got_error(GOT_ERR_NO_SPACE);
11076 printf("timestamp: %s\n", datebuf);
11078 if (blob_id) {
11079 err = got_object_id_str(&id_str, blob_id);
11080 if (err)
11081 return err;
11082 printf("based on blob: %s\n", id_str);
11083 free(id_str);
11086 if (staged_blob_id) {
11087 err = got_object_id_str(&id_str, staged_blob_id);
11088 if (err)
11089 return err;
11090 printf("based on staged blob: %s\n", id_str);
11091 free(id_str);
11094 if (commit_id) {
11095 err = got_object_id_str(&id_str, commit_id);
11096 if (err)
11097 return err;
11098 printf("based on commit: %s\n", id_str);
11099 free(id_str);
11102 return NULL;
11105 static const struct got_error *
11106 cmd_info(int argc, char *argv[])
11108 const struct got_error *error = NULL;
11109 struct got_worktree *worktree = NULL;
11110 char *cwd = NULL, *id_str = NULL;
11111 struct got_pathlist_head paths;
11112 struct got_pathlist_entry *pe;
11113 char *uuidstr = NULL;
11114 int ch, show_files = 0;
11116 TAILQ_INIT(&paths);
11118 while ((ch = getopt(argc, argv, "")) != -1) {
11119 switch (ch) {
11120 default:
11121 usage_info();
11122 /* NOTREACHED */
11126 argc -= optind;
11127 argv += optind;
11129 #ifndef PROFILE
11130 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11131 NULL) == -1)
11132 err(1, "pledge");
11133 #endif
11134 cwd = getcwd(NULL, 0);
11135 if (cwd == NULL) {
11136 error = got_error_from_errno("getcwd");
11137 goto done;
11140 error = got_worktree_open(&worktree, cwd);
11141 if (error) {
11142 if (error->code == GOT_ERR_NOT_WORKTREE)
11143 error = wrap_not_worktree_error(error, "info", cwd);
11144 goto done;
11147 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11148 if (error)
11149 goto done;
11151 if (argc >= 1) {
11152 error = get_worktree_paths_from_argv(&paths, argc, argv,
11153 worktree);
11154 if (error)
11155 goto done;
11156 show_files = 1;
11159 error = got_object_id_str(&id_str,
11160 got_worktree_get_base_commit_id(worktree));
11161 if (error)
11162 goto done;
11164 error = got_worktree_get_uuid(&uuidstr, worktree);
11165 if (error)
11166 goto done;
11168 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11169 printf("work tree base commit: %s\n", id_str);
11170 printf("work tree path prefix: %s\n",
11171 got_worktree_get_path_prefix(worktree));
11172 printf("work tree branch reference: %s\n",
11173 got_worktree_get_head_ref_name(worktree));
11174 printf("work tree UUID: %s\n", uuidstr);
11175 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11177 if (show_files) {
11178 struct got_pathlist_entry *pe;
11179 TAILQ_FOREACH(pe, &paths, entry) {
11180 if (pe->path_len == 0)
11181 continue;
11183 * Assume this path will fail. This will be corrected
11184 * in print_path_info() in case the path does suceeed.
11186 pe->data = (void *)got_error_path(pe->path,
11187 GOT_ERR_BAD_PATH);
11189 error = got_worktree_path_info(worktree, &paths,
11190 print_path_info, &paths, check_cancelled, NULL);
11191 if (error)
11192 goto done;
11193 TAILQ_FOREACH(pe, &paths, entry) {
11194 if (pe->data != NULL) {
11195 error = pe->data; /* bad path */
11196 break;
11200 done:
11201 TAILQ_FOREACH(pe, &paths, entry)
11202 free((char *)pe->path);
11203 got_pathlist_free(&paths);
11204 free(cwd);
11205 free(id_str);
11206 free(uuidstr);
11207 return error;