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/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_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);
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_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 if (err) {
516 free(*logmsg_path);
517 *logmsg_path = NULL;
519 return err;
522 static const struct got_error *
523 import_progress(void *arg, const char *path)
525 printf("A %s\n", path);
526 return NULL;
529 static const struct got_error *
530 get_author(char **author, struct got_repository *repo,
531 struct got_worktree *worktree)
533 const struct got_error *err = NULL;
534 const char *got_author = NULL, *name, *email;
535 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
537 *author = NULL;
539 if (worktree)
540 worktree_conf = got_worktree_get_gotconfig(worktree);
541 repo_conf = got_repo_get_gotconfig(repo);
543 /*
544 * Priority of potential author information sources, from most
545 * significant to least significant:
546 * 1) work tree's .got/got.conf file
547 * 2) repository's got.conf file
548 * 3) repository's git config file
549 * 4) environment variables
550 * 5) global git config files (in user's home directory or /etc)
551 */
553 if (worktree_conf)
554 got_author = got_gotconfig_get_author(worktree_conf);
555 if (got_author == NULL)
556 got_author = got_gotconfig_get_author(repo_conf);
557 if (got_author == NULL) {
558 name = got_repo_get_gitconfig_author_name(repo);
559 email = got_repo_get_gitconfig_author_email(repo);
560 if (name && email) {
561 if (asprintf(author, "%s <%s>", name, email) == -1)
562 return got_error_from_errno("asprintf");
563 return NULL;
566 got_author = getenv("GOT_AUTHOR");
567 if (got_author == NULL) {
568 name = got_repo_get_global_gitconfig_author_name(repo);
569 email = got_repo_get_global_gitconfig_author_email(
570 repo);
571 if (name && email) {
572 if (asprintf(author, "%s <%s>", name, email)
573 == -1)
574 return got_error_from_errno("asprintf");
575 return NULL;
577 /* TODO: Look up user in password database? */
578 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
582 *author = strdup(got_author);
583 if (*author == NULL)
584 return got_error_from_errno("strdup");
586 /*
587 * Really dumb email address check; we're only doing this to
588 * avoid git's object parser breaking on commits we create.
589 */
590 while (*got_author && *got_author != '<')
591 got_author++;
592 if (*got_author != '<') {
593 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
594 goto done;
596 while (*got_author && *got_author != '@')
597 got_author++;
598 if (*got_author != '@') {
599 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
600 goto done;
602 while (*got_author && *got_author != '>')
603 got_author++;
604 if (*got_author != '>')
605 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
606 done:
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_gitconfig_path(char **gitconfig_path)
617 const char *homedir = getenv("HOME");
619 *gitconfig_path = NULL;
620 if (homedir) {
621 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
622 return got_error_from_errno("asprintf");
625 return NULL;
628 static const struct got_error *
629 cmd_import(int argc, char *argv[])
631 const struct got_error *error = NULL;
632 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
633 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
634 const char *branch_name = "main";
635 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
636 struct got_repository *repo = NULL;
637 struct got_reference *branch_ref = NULL, *head_ref = NULL;
638 struct got_object_id *new_commit_id = NULL;
639 int ch;
640 struct got_pathlist_head ignores;
641 struct got_pathlist_entry *pe;
642 int preserve_logmsg = 0;
644 TAILQ_INIT(&ignores);
646 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
647 switch (ch) {
648 case 'b':
649 branch_name = optarg;
650 break;
651 case 'm':
652 logmsg = strdup(optarg);
653 if (logmsg == NULL) {
654 error = got_error_from_errno("strdup");
655 goto done;
657 break;
658 case 'r':
659 repo_path = realpath(optarg, NULL);
660 if (repo_path == NULL) {
661 error = got_error_from_errno2("realpath",
662 optarg);
663 goto done;
665 break;
666 case 'I':
667 if (optarg[0] == '\0')
668 break;
669 error = got_pathlist_insert(&pe, &ignores, optarg,
670 NULL);
671 if (error)
672 goto done;
673 break;
674 default:
675 usage_import();
676 /* NOTREACHED */
680 argc -= optind;
681 argv += optind;
683 #ifndef PROFILE
684 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
685 "unveil",
686 NULL) == -1)
687 err(1, "pledge");
688 #endif
689 if (argc != 1)
690 usage_import();
692 if (repo_path == NULL) {
693 repo_path = getcwd(NULL, 0);
694 if (repo_path == NULL)
695 return got_error_from_errno("getcwd");
697 got_path_strip_trailing_slashes(repo_path);
698 error = get_gitconfig_path(&gitconfig_path);
699 if (error)
700 goto done;
701 error = got_repo_open(&repo, repo_path, gitconfig_path);
702 if (error)
703 goto done;
705 error = get_author(&author, repo, NULL);
706 if (error)
707 return error;
709 /*
710 * Don't let the user create a branch name with a leading '-'.
711 * While technically a valid reference name, this case is usually
712 * an unintended typo.
713 */
714 if (branch_name[0] == '-')
715 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
717 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
718 error = got_error_from_errno("asprintf");
719 goto done;
722 error = got_ref_open(&branch_ref, repo, refname, 0);
723 if (error) {
724 if (error->code != GOT_ERR_NOT_REF)
725 goto done;
726 } else {
727 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
728 "import target branch already exists");
729 goto done;
732 path_dir = realpath(argv[0], NULL);
733 if (path_dir == NULL) {
734 error = got_error_from_errno2("realpath", argv[0]);
735 goto done;
737 got_path_strip_trailing_slashes(path_dir);
739 /*
740 * unveil(2) traverses exec(2); if an editor is used we have
741 * to apply unveil after the log message has been written.
742 */
743 if (logmsg == NULL || strlen(logmsg) == 0) {
744 error = get_editor(&editor);
745 if (error)
746 goto done;
747 free(logmsg);
748 error = collect_import_msg(&logmsg, &logmsg_path, editor,
749 path_dir, refname);
750 if (error) {
751 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
752 logmsg_path != NULL)
753 preserve_logmsg = 1;
754 goto done;
758 if (unveil(path_dir, "r") != 0) {
759 error = got_error_from_errno2("unveil", path_dir);
760 if (logmsg_path)
761 preserve_logmsg = 1;
762 goto done;
765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
766 if (error) {
767 if (logmsg_path)
768 preserve_logmsg = 1;
769 goto done;
772 error = got_repo_import(&new_commit_id, path_dir, logmsg,
773 author, &ignores, repo, import_progress, NULL);
774 if (error) {
775 if (logmsg_path)
776 preserve_logmsg = 1;
777 goto done;
780 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
781 if (error) {
782 if (logmsg_path)
783 preserve_logmsg = 1;
784 goto done;
787 error = got_ref_write(branch_ref, repo);
788 if (error) {
789 if (logmsg_path)
790 preserve_logmsg = 1;
791 goto done;
794 error = got_object_id_str(&id_str, new_commit_id);
795 if (error) {
796 if (logmsg_path)
797 preserve_logmsg = 1;
798 goto done;
801 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
802 if (error) {
803 if (error->code != GOT_ERR_NOT_REF) {
804 if (logmsg_path)
805 preserve_logmsg = 1;
806 goto done;
809 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
810 branch_ref);
811 if (error) {
812 if (logmsg_path)
813 preserve_logmsg = 1;
814 goto done;
817 error = got_ref_write(head_ref, repo);
818 if (error) {
819 if (logmsg_path)
820 preserve_logmsg = 1;
821 goto done;
825 printf("Created branch %s with commit %s\n",
826 got_ref_get_name(branch_ref), id_str);
827 done:
828 if (preserve_logmsg) {
829 fprintf(stderr, "%s: log message preserved in %s\n",
830 getprogname(), logmsg_path);
831 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
832 error = got_error_from_errno2("unlink", logmsg_path);
833 free(logmsg);
834 free(logmsg_path);
835 free(repo_path);
836 free(editor);
837 free(refname);
838 free(new_commit_id);
839 free(id_str);
840 free(author);
841 free(gitconfig_path);
842 if (branch_ref)
843 got_ref_close(branch_ref);
844 if (head_ref)
845 got_ref_close(head_ref);
846 return error;
849 __dead static void
850 usage_clone(void)
852 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
853 "[-R reference] repository-url [directory]\n", getprogname());
854 exit(1);
857 struct got_fetch_progress_arg {
858 char last_scaled_size[FMT_SCALED_STRSIZE];
859 int last_p_indexed;
860 int last_p_resolved;
861 int verbosity;
863 struct got_repository *repo;
865 int create_configs;
866 int configs_created;
867 struct {
868 struct got_pathlist_head *symrefs;
869 struct got_pathlist_head *wanted_branches;
870 const char *proto;
871 const char *host;
872 const char *port;
873 const char *remote_repo_path;
874 const char *git_url;
875 int fetch_all_branches;
876 int mirror_references;
877 } config_info;
878 };
880 /* XXX forward declaration */
881 static const struct got_error *
882 create_config_files(const char *proto, const char *host, const char *port,
883 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
884 int mirror_references, struct got_pathlist_head *symrefs,
885 struct got_pathlist_head *wanted_branches, struct got_repository *repo);
887 static const struct got_error *
888 fetch_progress(void *arg, const char *message, off_t packfile_size,
889 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
891 const struct got_error *err = NULL;
892 struct got_fetch_progress_arg *a = arg;
893 char scaled_size[FMT_SCALED_STRSIZE];
894 int p_indexed, p_resolved;
895 int print_size = 0, print_indexed = 0, print_resolved = 0;
897 /*
898 * In order to allow a failed clone to be resumed with 'got fetch'
899 * we try to create configuration files as soon as possible.
900 * Once the server has sent information about its default branch
901 * we have all required information.
902 */
903 if (a->create_configs && !a->configs_created &&
904 !TAILQ_EMPTY(a->config_info.symrefs)) {
905 err = create_config_files(a->config_info.proto,
906 a->config_info.host, a->config_info.port,
907 a->config_info.remote_repo_path,
908 a->config_info.git_url,
909 a->config_info.fetch_all_branches,
910 a->config_info.mirror_references,
911 a->config_info.symrefs,
912 a->config_info.wanted_branches, a->repo);
913 if (err)
914 return err;
915 a->configs_created = 1;
918 if (a->verbosity < 0)
919 return NULL;
921 if (message && message[0] != '\0') {
922 printf("\rserver: %s", message);
923 fflush(stdout);
924 return NULL;
927 if (packfile_size > 0 || nobj_indexed > 0) {
928 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
929 (a->last_scaled_size[0] == '\0' ||
930 strcmp(scaled_size, a->last_scaled_size)) != 0) {
931 print_size = 1;
932 if (strlcpy(a->last_scaled_size, scaled_size,
933 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
934 return got_error(GOT_ERR_NO_SPACE);
936 if (nobj_indexed > 0) {
937 p_indexed = (nobj_indexed * 100) / nobj_total;
938 if (p_indexed != a->last_p_indexed) {
939 a->last_p_indexed = p_indexed;
940 print_indexed = 1;
941 print_size = 1;
944 if (nobj_resolved > 0) {
945 p_resolved = (nobj_resolved * 100) /
946 (nobj_total - nobj_loose);
947 if (p_resolved != a->last_p_resolved) {
948 a->last_p_resolved = p_resolved;
949 print_resolved = 1;
950 print_indexed = 1;
951 print_size = 1;
956 if (print_size || print_indexed || print_resolved)
957 printf("\r");
958 if (print_size)
959 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
960 if (print_indexed)
961 printf("; indexing %d%%", p_indexed);
962 if (print_resolved)
963 printf("; resolving deltas %d%%", p_resolved);
964 if (print_size || print_indexed || print_resolved)
965 fflush(stdout);
967 return NULL;
970 static const struct got_error *
971 create_symref(const char *refname, struct got_reference *target_ref,
972 int verbosity, struct got_repository *repo)
974 const struct got_error *err;
975 struct got_reference *head_symref;
977 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
978 if (err)
979 return err;
981 err = got_ref_write(head_symref, repo);
982 if (err == NULL && verbosity > 0) {
983 printf("Created reference %s: %s\n", GOT_REF_HEAD,
984 got_ref_get_name(target_ref));
986 got_ref_close(head_symref);
987 return err;
990 static const struct got_error *
991 list_remote_refs(struct got_pathlist_head *symrefs,
992 struct got_pathlist_head *refs)
994 const struct got_error *err;
995 struct got_pathlist_entry *pe;
997 TAILQ_FOREACH(pe, symrefs, entry) {
998 const char *refname = pe->path;
999 const char *targetref = pe->data;
1001 printf("%s: %s\n", refname, targetref);
1004 TAILQ_FOREACH(pe, refs, entry) {
1005 const char *refname = pe->path;
1006 struct got_object_id *id = pe->data;
1007 char *id_str;
1009 err = got_object_id_str(&id_str, id);
1010 if (err)
1011 return err;
1012 printf("%s: %s\n", refname, id_str);
1013 free(id_str);
1016 return NULL;
1019 static const struct got_error *
1020 create_ref(const char *refname, struct got_object_id *id,
1021 int verbosity, struct got_repository *repo)
1023 const struct got_error *err = NULL;
1024 struct got_reference *ref;
1025 char *id_str;
1027 err = got_object_id_str(&id_str, id);
1028 if (err)
1029 return err;
1031 err = got_ref_alloc(&ref, refname, id);
1032 if (err)
1033 goto done;
1035 err = got_ref_write(ref, repo);
1036 got_ref_close(ref);
1038 if (err == NULL && verbosity >= 0)
1039 printf("Created reference %s: %s\n", refname, id_str);
1040 done:
1041 free(id_str);
1042 return err;
1045 static int
1046 match_wanted_ref(const char *refname, const char *wanted_ref)
1048 if (strncmp(refname, "refs/", 5) != 0)
1049 return 0;
1050 refname += 5;
1053 * Prevent fetching of references that won't make any
1054 * sense outside of the remote repository's context.
1056 if (strncmp(refname, "got/", 4) == 0)
1057 return 0;
1058 if (strncmp(refname, "remotes/", 8) == 0)
1059 return 0;
1061 if (strncmp(wanted_ref, "refs/", 5) == 0)
1062 wanted_ref += 5;
1064 /* Allow prefix match. */
1065 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1066 return 1;
1068 /* Allow exact match. */
1069 return (strcmp(refname, wanted_ref) == 0);
1072 static int
1073 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1075 struct got_pathlist_entry *pe;
1077 TAILQ_FOREACH(pe, wanted_refs, entry) {
1078 if (match_wanted_ref(refname, pe->path))
1079 return 1;
1082 return 0;
1085 static const struct got_error *
1086 create_wanted_ref(const char *refname, struct got_object_id *id,
1087 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1089 const struct got_error *err;
1090 char *remote_refname;
1092 if (strncmp("refs/", refname, 5) == 0)
1093 refname += 5;
1095 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1096 remote_repo_name, refname) == -1)
1097 return got_error_from_errno("asprintf");
1099 err = create_ref(remote_refname, id, verbosity, repo);
1100 free(remote_refname);
1101 return err;
1104 static const struct got_error *
1105 create_gotconfig(const char *proto, const char *host, const char *port,
1106 const char *remote_repo_path, int fetch_all_branches, int mirror_references,
1107 struct got_repository *repo)
1109 const struct got_error *err = NULL;
1110 char *gotconfig_path = NULL;
1111 char *gotconfig = NULL;
1112 FILE *gotconfig_file = NULL;
1113 ssize_t n;
1115 /* Create got.conf(5). */
1116 gotconfig_path = got_repo_get_path_gotconfig(repo);
1117 if (gotconfig_path == NULL) {
1118 err = got_error_from_errno("got_repo_get_path_gotconfig");
1119 goto done;
1121 gotconfig_file = fopen(gotconfig_path, "a");
1122 if (gotconfig_file == NULL) {
1123 err = got_error_from_errno2("fopen", gotconfig_path);
1124 goto done;
1126 if (asprintf(&gotconfig,
1127 "remote \"%s\" {\n"
1128 "\tserver %s\n"
1129 "\tprotocol %s\n"
1130 "%s%s%s"
1131 "\trepository \"%s\"\n"
1132 "%s"
1133 "}\n",
1134 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1135 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1136 remote_repo_path,
1137 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1138 err = got_error_from_errno("asprintf");
1139 goto done;
1141 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1142 if (n != strlen(gotconfig)) {
1143 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1144 goto done;
1147 done:
1148 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1149 err = got_error_from_errno2("fclose", gotconfig_path);
1150 free(gotconfig_path);
1151 return err;
1154 static const struct got_error *
1155 create_gitconfig(const char *git_url, const char *default_branch,
1156 int fetch_all_branches, int mirror_references, struct got_repository *repo)
1158 const struct got_error *err = NULL;
1159 char *gitconfig_path = NULL;
1160 char *gitconfig = NULL;
1161 FILE *gitconfig_file = NULL;
1162 ssize_t n;
1164 /* Create a config file Git can understand. */
1165 gitconfig_path = got_repo_get_path_gitconfig(repo);
1166 if (gitconfig_path == NULL) {
1167 err = got_error_from_errno("got_repo_get_path_gitconfig");
1168 goto done;
1170 gitconfig_file = fopen(gitconfig_path, "a");
1171 if (gitconfig_file == NULL) {
1172 err = got_error_from_errno2("fopen", gitconfig_path);
1173 goto done;
1175 if (mirror_references) {
1176 if (asprintf(&gitconfig,
1177 "[remote \"%s\"]\n"
1178 "\turl = %s\n"
1179 "\tfetch = +refs/*:refs/*\n"
1180 "\tmirror = true\n",
1181 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1182 err = got_error_from_errno("asprintf");
1183 goto done;
1185 } else if (fetch_all_branches) {
1186 if (asprintf(&gitconfig,
1187 "[remote \"%s\"]\n"
1188 "\turl = %s\n"
1189 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1190 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1191 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1192 err = got_error_from_errno("asprintf");
1193 goto done;
1195 } else {
1196 const char *branchname;
1199 * If the server specified a default branch, use just that one.
1200 * Otherwise fall back to fetching all branches on next fetch.
1202 if (default_branch) {
1203 branchname = default_branch;
1204 if (strncmp(branchname, "refs/heads/", 11) == 0)
1205 branchname += 11;
1206 } else
1207 branchname = "*"; /* fall back to all branches */
1208 if (asprintf(&gitconfig,
1209 "[remote \"%s\"]\n"
1210 "\turl = %s\n"
1211 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1212 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1213 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1214 branchname) == -1) {
1215 err = got_error_from_errno("asprintf");
1216 goto done;
1219 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1220 if (n != strlen(gitconfig)) {
1221 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1222 goto done;
1224 done:
1225 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1226 err = got_error_from_errno2("fclose", gitconfig_path);
1227 free(gitconfig_path);
1228 return err;
1231 static const struct got_error *
1232 create_config_files(const char *proto, const char *host, const char *port,
1233 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1234 int mirror_references, struct got_pathlist_head *symrefs,
1235 struct got_pathlist_head *wanted_branches, struct got_repository *repo)
1237 const struct got_error *err = NULL;
1238 const char *default_branch = NULL;
1239 struct got_pathlist_entry *pe;
1242 * If we asked for a set of wanted branches then use the first
1243 * one of those.
1245 if (!TAILQ_EMPTY(wanted_branches)) {
1246 pe = TAILQ_FIRST(wanted_branches);
1247 default_branch = pe->path;
1248 } else {
1249 /* First HEAD ref listed by server is the default branch. */
1250 TAILQ_FOREACH(pe, symrefs, entry) {
1251 const char *refname = pe->path;
1252 const char *target = pe->data;
1254 if (strcmp(refname, GOT_REF_HEAD) != 0)
1255 continue;
1257 default_branch = target;
1258 break;
1262 /* Create got.conf(5). */
1263 err = create_gotconfig(proto, host, port, remote_repo_path,
1264 fetch_all_branches, mirror_references, repo);
1265 if (err)
1266 return err;
1268 /* Create a config file Git can understand. */
1269 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1270 mirror_references, repo);
1273 static const struct got_error *
1274 cmd_clone(int argc, char *argv[])
1276 const struct got_error *error = NULL;
1277 const char *uri, *dirname;
1278 char *proto, *host, *port, *repo_name, *server_path;
1279 char *default_destdir = NULL, *id_str = NULL;
1280 const char *repo_path;
1281 struct got_repository *repo = NULL;
1282 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1283 struct got_pathlist_entry *pe;
1284 struct got_object_id *pack_hash = NULL;
1285 int ch, fetchfd = -1, fetchstatus;
1286 pid_t fetchpid = -1;
1287 struct got_fetch_progress_arg fpa;
1288 char *git_url = NULL;
1289 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1290 int list_refs_only = 0;
1292 TAILQ_INIT(&refs);
1293 TAILQ_INIT(&symrefs);
1294 TAILQ_INIT(&wanted_branches);
1295 TAILQ_INIT(&wanted_refs);
1297 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1298 switch (ch) {
1299 case 'a':
1300 fetch_all_branches = 1;
1301 break;
1302 case 'b':
1303 error = got_pathlist_append(&wanted_branches,
1304 optarg, NULL);
1305 if (error)
1306 return error;
1307 break;
1308 case 'l':
1309 list_refs_only = 1;
1310 break;
1311 case 'm':
1312 mirror_references = 1;
1313 break;
1314 case 'v':
1315 if (verbosity < 0)
1316 verbosity = 0;
1317 else if (verbosity < 3)
1318 verbosity++;
1319 break;
1320 case 'q':
1321 verbosity = -1;
1322 break;
1323 case 'R':
1324 error = got_pathlist_append(&wanted_refs,
1325 optarg, NULL);
1326 if (error)
1327 return error;
1328 break;
1329 default:
1330 usage_clone();
1331 break;
1334 argc -= optind;
1335 argv += optind;
1337 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1338 errx(1, "-a and -b options are mutually exclusive");
1339 if (list_refs_only) {
1340 if (!TAILQ_EMPTY(&wanted_branches))
1341 errx(1, "-l and -b options are mutually exclusive");
1342 if (fetch_all_branches)
1343 errx(1, "-l and -a options are mutually exclusive");
1344 if (mirror_references)
1345 errx(1, "-l and -m options are mutually exclusive");
1346 if (verbosity == -1)
1347 errx(1, "-l and -q options are mutually exclusive");
1348 if (!TAILQ_EMPTY(&wanted_refs))
1349 errx(1, "-l and -R options are mutually exclusive");
1352 uri = argv[0];
1354 if (argc == 1)
1355 dirname = NULL;
1356 else if (argc == 2)
1357 dirname = argv[1];
1358 else
1359 usage_clone();
1361 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1362 &repo_name, uri);
1363 if (error)
1364 goto done;
1366 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1367 host, port ? ":" : "", port ? port : "",
1368 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1369 error = got_error_from_errno("asprintf");
1370 goto done;
1373 if (strcmp(proto, "git") == 0) {
1374 #ifndef PROFILE
1375 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1376 "sendfd dns inet unveil", NULL) == -1)
1377 err(1, "pledge");
1378 #endif
1379 } else if (strcmp(proto, "git+ssh") == 0 ||
1380 strcmp(proto, "ssh") == 0) {
1381 #ifndef PROFILE
1382 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1383 "sendfd unveil", NULL) == -1)
1384 err(1, "pledge");
1385 #endif
1386 } else if (strcmp(proto, "http") == 0 ||
1387 strcmp(proto, "git+http") == 0) {
1388 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1389 goto done;
1390 } else {
1391 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1392 goto done;
1394 if (dirname == NULL) {
1395 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1396 error = got_error_from_errno("asprintf");
1397 goto done;
1399 repo_path = default_destdir;
1400 } else
1401 repo_path = dirname;
1403 if (!list_refs_only) {
1404 error = got_path_mkdir(repo_path);
1405 if (error &&
1406 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1407 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1408 goto done;
1409 if (!got_path_dir_is_empty(repo_path)) {
1410 error = got_error_path(repo_path,
1411 GOT_ERR_DIR_NOT_EMPTY);
1412 goto done;
1416 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1417 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1418 error = got_error_from_errno2("unveil",
1419 GOT_FETCH_PATH_SSH);
1420 goto done;
1423 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1424 if (error)
1425 goto done;
1427 if (verbosity >= 0)
1428 printf("Connecting to %s%s%s\n", host,
1429 port ? ":" : "", port ? port : "");
1431 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1432 server_path, verbosity);
1433 if (error)
1434 goto done;
1436 if (!list_refs_only) {
1437 error = got_repo_init(repo_path);
1438 if (error)
1439 goto done;
1440 error = got_repo_open(&repo, repo_path, NULL);
1441 if (error)
1442 goto done;
1445 fpa.last_scaled_size[0] = '\0';
1446 fpa.last_p_indexed = -1;
1447 fpa.last_p_resolved = -1;
1448 fpa.verbosity = verbosity;
1449 fpa.create_configs = 1;
1450 fpa.configs_created = 0;
1451 fpa.repo = repo;
1452 fpa.config_info.symrefs = &symrefs;
1453 fpa.config_info.wanted_branches = &wanted_branches;
1454 fpa.config_info.proto = proto;
1455 fpa.config_info.host = host;
1456 fpa.config_info.port = port;
1457 fpa.config_info.remote_repo_path = server_path;
1458 fpa.config_info.git_url = git_url;
1459 fpa.config_info.fetch_all_branches = fetch_all_branches;
1460 fpa.config_info.mirror_references = mirror_references;
1461 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1462 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1463 fetch_all_branches, &wanted_branches, &wanted_refs,
1464 list_refs_only, verbosity, fetchfd, repo,
1465 fetch_progress, &fpa);
1466 if (error)
1467 goto done;
1469 if (list_refs_only) {
1470 error = list_remote_refs(&symrefs, &refs);
1471 goto done;
1474 error = got_object_id_str(&id_str, pack_hash);
1475 if (error)
1476 goto done;
1477 if (verbosity >= 0)
1478 printf("\nFetched %s.pack\n", id_str);
1479 free(id_str);
1481 /* Set up references provided with the pack file. */
1482 TAILQ_FOREACH(pe, &refs, entry) {
1483 const char *refname = pe->path;
1484 struct got_object_id *id = pe->data;
1485 char *remote_refname;
1487 if (is_wanted_ref(&wanted_refs, refname) &&
1488 !mirror_references) {
1489 error = create_wanted_ref(refname, id,
1490 GOT_FETCH_DEFAULT_REMOTE_NAME,
1491 verbosity - 1, repo);
1492 if (error)
1493 goto done;
1494 continue;
1497 error = create_ref(refname, id, verbosity - 1, repo);
1498 if (error)
1499 goto done;
1501 if (mirror_references)
1502 continue;
1504 if (strncmp("refs/heads/", refname, 11) != 0)
1505 continue;
1507 if (asprintf(&remote_refname,
1508 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1509 refname + 11) == -1) {
1510 error = got_error_from_errno("asprintf");
1511 goto done;
1513 error = create_ref(remote_refname, id, verbosity - 1, repo);
1514 free(remote_refname);
1515 if (error)
1516 goto done;
1519 /* Set the HEAD reference if the server provided one. */
1520 TAILQ_FOREACH(pe, &symrefs, entry) {
1521 struct got_reference *target_ref;
1522 const char *refname = pe->path;
1523 const char *target = pe->data;
1524 char *remote_refname = NULL, *remote_target = NULL;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 error = got_ref_open(&target_ref, repo, target, 0);
1530 if (error) {
1531 if (error->code == GOT_ERR_NOT_REF) {
1532 error = NULL;
1533 continue;
1535 goto done;
1538 error = create_symref(refname, target_ref, verbosity, repo);
1539 got_ref_close(target_ref);
1540 if (error)
1541 goto done;
1543 if (mirror_references)
1544 continue;
1546 if (strncmp("refs/heads/", target, 11) != 0)
1547 continue;
1549 if (asprintf(&remote_refname,
1550 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1551 refname) == -1) {
1552 error = got_error_from_errno("asprintf");
1553 goto done;
1555 if (asprintf(&remote_target,
1556 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1557 target + 11) == -1) {
1558 error = got_error_from_errno("asprintf");
1559 free(remote_refname);
1560 goto done;
1562 error = got_ref_open(&target_ref, repo, remote_target, 0);
1563 if (error) {
1564 free(remote_refname);
1565 free(remote_target);
1566 if (error->code == GOT_ERR_NOT_REF) {
1567 error = NULL;
1568 continue;
1570 goto done;
1572 error = create_symref(remote_refname, target_ref,
1573 verbosity - 1, repo);
1574 free(remote_refname);
1575 free(remote_target);
1576 got_ref_close(target_ref);
1577 if (error)
1578 goto done;
1580 if (pe == NULL) {
1582 * We failed to set the HEAD reference. If we asked for
1583 * a set of wanted branches use the first of one of those
1584 * which could be fetched instead.
1586 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1587 const char *target = pe->path;
1588 struct got_reference *target_ref;
1590 error = got_ref_open(&target_ref, repo, target, 0);
1591 if (error) {
1592 if (error->code == GOT_ERR_NOT_REF) {
1593 error = NULL;
1594 continue;
1596 goto done;
1599 error = create_symref(GOT_REF_HEAD, target_ref,
1600 verbosity, repo);
1601 got_ref_close(target_ref);
1602 if (error)
1603 goto done;
1604 break;
1608 if (verbosity >= 0)
1609 printf("Created %s repository '%s'\n",
1610 mirror_references ? "mirrored" : "cloned", repo_path);
1611 done:
1612 if (fetchpid > 0) {
1613 if (kill(fetchpid, SIGTERM) == -1)
1614 error = got_error_from_errno("kill");
1615 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1616 error = got_error_from_errno("waitpid");
1618 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1619 error = got_error_from_errno("close");
1620 if (repo)
1621 got_repo_close(repo);
1622 TAILQ_FOREACH(pe, &refs, entry) {
1623 free((void *)pe->path);
1624 free(pe->data);
1626 got_pathlist_free(&refs);
1627 TAILQ_FOREACH(pe, &symrefs, entry) {
1628 free((void *)pe->path);
1629 free(pe->data);
1631 got_pathlist_free(&symrefs);
1632 got_pathlist_free(&wanted_branches);
1633 got_pathlist_free(&wanted_refs);
1634 free(pack_hash);
1635 free(proto);
1636 free(host);
1637 free(port);
1638 free(server_path);
1639 free(repo_name);
1640 free(default_destdir);
1641 free(git_url);
1642 return error;
1645 static const struct got_error *
1646 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1647 int replace_tags, int verbosity, struct got_repository *repo)
1649 const struct got_error *err = NULL;
1650 char *new_id_str = NULL;
1651 struct got_object_id *old_id = NULL;
1653 err = got_object_id_str(&new_id_str, new_id);
1654 if (err)
1655 goto done;
1657 if (!replace_tags &&
1658 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1659 err = got_ref_resolve(&old_id, repo, ref);
1660 if (err)
1661 goto done;
1662 if (got_object_id_cmp(old_id, new_id) == 0)
1663 goto done;
1664 if (verbosity >= 0) {
1665 printf("Rejecting update of existing tag %s: %s\n",
1666 got_ref_get_name(ref), new_id_str);
1668 goto done;
1671 if (got_ref_is_symbolic(ref)) {
1672 if (verbosity >= 0) {
1673 printf("Replacing reference %s: %s\n",
1674 got_ref_get_name(ref),
1675 got_ref_get_symref_target(ref));
1677 err = got_ref_change_symref_to_ref(ref, new_id);
1678 if (err)
1679 goto done;
1680 err = got_ref_write(ref, repo);
1681 if (err)
1682 goto done;
1683 } else {
1684 err = got_ref_resolve(&old_id, repo, ref);
1685 if (err)
1686 goto done;
1687 if (got_object_id_cmp(old_id, new_id) == 0)
1688 goto done;
1690 err = got_ref_change_ref(ref, new_id);
1691 if (err)
1692 goto done;
1693 err = got_ref_write(ref, repo);
1694 if (err)
1695 goto done;
1698 if (verbosity >= 0)
1699 printf("Updated %s: %s\n", got_ref_get_name(ref),
1700 new_id_str);
1701 done:
1702 free(old_id);
1703 free(new_id_str);
1704 return err;
1707 static const struct got_error *
1708 update_symref(const char *refname, struct got_reference *target_ref,
1709 int verbosity, struct got_repository *repo)
1711 const struct got_error *err = NULL, *unlock_err;
1712 struct got_reference *symref;
1713 int symref_is_locked = 0;
1715 err = got_ref_open(&symref, repo, refname, 1);
1716 if (err) {
1717 if (err->code != GOT_ERR_NOT_REF)
1718 return err;
1719 err = got_ref_alloc_symref(&symref, refname, target_ref);
1720 if (err)
1721 goto done;
1723 err = got_ref_write(symref, repo);
1724 if (err)
1725 goto done;
1727 if (verbosity >= 0)
1728 printf("Created reference %s: %s\n",
1729 got_ref_get_name(symref),
1730 got_ref_get_symref_target(symref));
1731 } else {
1732 symref_is_locked = 1;
1734 if (strcmp(got_ref_get_symref_target(symref),
1735 got_ref_get_name(target_ref)) == 0)
1736 goto done;
1738 err = got_ref_change_symref(symref,
1739 got_ref_get_name(target_ref));
1740 if (err)
1741 goto done;
1743 err = got_ref_write(symref, repo);
1744 if (err)
1745 goto done;
1747 if (verbosity >= 0)
1748 printf("Updated %s: %s\n", got_ref_get_name(symref),
1749 got_ref_get_symref_target(symref));
1752 done:
1753 if (symref_is_locked) {
1754 unlock_err = got_ref_unlock(symref);
1755 if (unlock_err && err == NULL)
1756 err = unlock_err;
1758 got_ref_close(symref);
1759 return err;
1762 __dead static void
1763 usage_fetch(void)
1765 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1766 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1767 "[remote-repository-name]\n",
1768 getprogname());
1769 exit(1);
1772 static const struct got_error *
1773 delete_missing_ref(struct got_reference *ref,
1774 int verbosity, struct got_repository *repo)
1776 const struct got_error *err = NULL;
1777 struct got_object_id *id = NULL;
1778 char *id_str = NULL;
1780 if (got_ref_is_symbolic(ref)) {
1781 err = got_ref_delete(ref, repo);
1782 if (err)
1783 return err;
1784 if (verbosity >= 0) {
1785 printf("Deleted reference %s: %s\n",
1786 got_ref_get_name(ref),
1787 got_ref_get_symref_target(ref));
1789 } else {
1790 err = got_ref_resolve(&id, repo, ref);
1791 if (err)
1792 return err;
1793 err = got_object_id_str(&id_str, id);
1794 if (err)
1795 goto done;
1797 err = got_ref_delete(ref, repo);
1798 if (err)
1799 goto done;
1800 if (verbosity >= 0) {
1801 printf("Deleted reference %s: %s\n",
1802 got_ref_get_name(ref), id_str);
1805 done:
1806 free(id);
1807 free(id_str);
1808 return NULL;
1811 static const struct got_error *
1812 delete_missing_refs(struct got_pathlist_head *their_refs,
1813 struct got_pathlist_head *their_symrefs,
1814 const struct got_remote_repo *remote,
1815 int verbosity, struct got_repository *repo)
1817 const struct got_error *err = NULL, *unlock_err;
1818 struct got_reflist_head my_refs;
1819 struct got_reflist_entry *re;
1820 struct got_pathlist_entry *pe;
1821 char *remote_namespace = NULL;
1822 char *local_refname = NULL;
1824 SIMPLEQ_INIT(&my_refs);
1826 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1827 == -1)
1828 return got_error_from_errno("asprintf");
1830 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1831 if (err)
1832 goto done;
1834 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1835 const char *refname = got_ref_get_name(re->ref);
1837 if (!remote->mirror_references) {
1838 if (strncmp(refname, remote_namespace,
1839 strlen(remote_namespace)) == 0) {
1840 if (strcmp(refname + strlen(remote_namespace),
1841 GOT_REF_HEAD) == 0)
1842 continue;
1843 if (asprintf(&local_refname, "refs/heads/%s",
1844 refname + strlen(remote_namespace)) == -1) {
1845 err = got_error_from_errno("asprintf");
1846 goto done;
1848 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1849 continue;
1852 TAILQ_FOREACH(pe, their_refs, entry) {
1853 if (strcmp(local_refname, pe->path) == 0)
1854 break;
1856 if (pe != NULL)
1857 continue;
1859 TAILQ_FOREACH(pe, their_symrefs, entry) {
1860 if (strcmp(local_refname, pe->path) == 0)
1861 break;
1863 if (pe != NULL)
1864 continue;
1866 err = delete_missing_ref(re->ref, verbosity, repo);
1867 if (err)
1868 break;
1870 if (local_refname) {
1871 struct got_reference *ref;
1872 err = got_ref_open(&ref, repo, local_refname, 1);
1873 if (err) {
1874 if (err->code != GOT_ERR_NOT_REF)
1875 break;
1876 free(local_refname);
1877 local_refname = NULL;
1878 continue;
1880 err = delete_missing_ref(ref, verbosity, repo);
1881 if (err)
1882 break;
1883 unlock_err = got_ref_unlock(ref);
1884 got_ref_close(ref);
1885 if (unlock_err && err == NULL) {
1886 err = unlock_err;
1887 break;
1890 free(local_refname);
1891 local_refname = NULL;
1894 done:
1895 free(remote_namespace);
1896 free(local_refname);
1897 return err;
1900 static const struct got_error *
1901 update_wanted_ref(const char *refname, struct got_object_id *id,
1902 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1904 const struct got_error *err, *unlock_err;
1905 char *remote_refname;
1906 struct got_reference *ref;
1908 if (strncmp("refs/", refname, 5) == 0)
1909 refname += 5;
1911 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1912 remote_repo_name, refname) == -1)
1913 return got_error_from_errno("asprintf");
1915 err = got_ref_open(&ref, repo, remote_refname, 1);
1916 if (err) {
1917 if (err->code != GOT_ERR_NOT_REF)
1918 goto done;
1919 err = create_ref(remote_refname, id, verbosity, repo);
1920 } else {
1921 err = update_ref(ref, id, 0, verbosity, repo);
1922 unlock_err = got_ref_unlock(ref);
1923 if (unlock_err && err == NULL)
1924 err = unlock_err;
1925 got_ref_close(ref);
1927 done:
1928 free(remote_refname);
1929 return err;
1932 static const struct got_error *
1933 cmd_fetch(int argc, char *argv[])
1935 const struct got_error *error = NULL, *unlock_err;
1936 char *cwd = NULL, *repo_path = NULL;
1937 const char *remote_name;
1938 char *proto = NULL, *host = NULL, *port = NULL;
1939 char *repo_name = NULL, *server_path = NULL;
1940 const struct got_remote_repo *remotes, *remote = NULL;
1941 int nremotes;
1942 char *id_str = NULL;
1943 struct got_repository *repo = NULL;
1944 struct got_worktree *worktree = NULL;
1945 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1946 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1947 struct got_pathlist_entry *pe;
1948 struct got_object_id *pack_hash = NULL;
1949 int i, ch, fetchfd = -1, fetchstatus;
1950 pid_t fetchpid = -1;
1951 struct got_fetch_progress_arg fpa;
1952 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1953 int delete_refs = 0, replace_tags = 0;
1955 TAILQ_INIT(&refs);
1956 TAILQ_INIT(&symrefs);
1957 TAILQ_INIT(&wanted_branches);
1958 TAILQ_INIT(&wanted_refs);
1960 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1961 switch (ch) {
1962 case 'a':
1963 fetch_all_branches = 1;
1964 break;
1965 case 'b':
1966 error = got_pathlist_append(&wanted_branches,
1967 optarg, NULL);
1968 if (error)
1969 return error;
1970 break;
1971 case 'd':
1972 delete_refs = 1;
1973 break;
1974 case 'l':
1975 list_refs_only = 1;
1976 break;
1977 case 'r':
1978 repo_path = realpath(optarg, NULL);
1979 if (repo_path == NULL)
1980 return got_error_from_errno2("realpath",
1981 optarg);
1982 got_path_strip_trailing_slashes(repo_path);
1983 break;
1984 case 't':
1985 replace_tags = 1;
1986 break;
1987 case 'v':
1988 if (verbosity < 0)
1989 verbosity = 0;
1990 else if (verbosity < 3)
1991 verbosity++;
1992 break;
1993 case 'q':
1994 verbosity = -1;
1995 break;
1996 case 'R':
1997 error = got_pathlist_append(&wanted_refs,
1998 optarg, NULL);
1999 if (error)
2000 return error;
2001 break;
2002 default:
2003 usage_fetch();
2004 break;
2007 argc -= optind;
2008 argv += optind;
2010 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2011 errx(1, "-a and -b options are mutually exclusive");
2012 if (list_refs_only) {
2013 if (!TAILQ_EMPTY(&wanted_branches))
2014 errx(1, "-l and -b options are mutually exclusive");
2015 if (fetch_all_branches)
2016 errx(1, "-l and -a options are mutually exclusive");
2017 if (delete_refs)
2018 errx(1, "-l and -d options are mutually exclusive");
2019 if (verbosity == -1)
2020 errx(1, "-l and -q options are mutually exclusive");
2023 if (argc == 0)
2024 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2025 else if (argc == 1)
2026 remote_name = argv[0];
2027 else
2028 usage_fetch();
2030 cwd = getcwd(NULL, 0);
2031 if (cwd == NULL) {
2032 error = got_error_from_errno("getcwd");
2033 goto done;
2036 if (repo_path == NULL) {
2037 error = got_worktree_open(&worktree, cwd);
2038 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2039 goto done;
2040 else
2041 error = NULL;
2042 if (worktree) {
2043 repo_path =
2044 strdup(got_worktree_get_repo_path(worktree));
2045 if (repo_path == NULL)
2046 error = got_error_from_errno("strdup");
2047 if (error)
2048 goto done;
2049 } else {
2050 repo_path = strdup(cwd);
2051 if (repo_path == NULL) {
2052 error = got_error_from_errno("strdup");
2053 goto done;
2058 error = got_repo_open(&repo, repo_path, NULL);
2059 if (error)
2060 goto done;
2062 if (worktree) {
2063 worktree_conf = got_worktree_get_gotconfig(worktree);
2064 if (worktree_conf) {
2065 got_gotconfig_get_remotes(&nremotes, &remotes,
2066 worktree_conf);
2067 for (i = 0; i < nremotes; i++) {
2068 remote = &remotes[i];
2069 if (strcmp(remote->name, remote_name) == 0)
2070 break;
2074 if (remote == NULL) {
2075 repo_conf = got_repo_get_gotconfig(repo);
2076 if (repo_conf) {
2077 got_gotconfig_get_remotes(&nremotes, &remotes,
2078 repo_conf);
2079 for (i = 0; i < nremotes; i++) {
2080 remote = &remotes[i];
2081 if (strcmp(remote->name, remote_name) == 0)
2082 break;
2086 if (remote == NULL) {
2087 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2088 for (i = 0; i < nremotes; i++) {
2089 remote = &remotes[i];
2090 if (strcmp(remote->name, remote_name) == 0)
2091 break;
2094 if (remote == NULL) {
2095 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2096 goto done;
2099 if (TAILQ_EMPTY(&wanted_branches) && remote->nbranches > 0) {
2100 for (i = 0; i < remote->nbranches; i++) {
2101 got_pathlist_append(&wanted_branches,
2102 remote->branches[i], NULL);
2107 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
2108 &repo_name, remote->url);
2109 if (error)
2110 goto done;
2112 if (strcmp(proto, "git") == 0) {
2113 #ifndef PROFILE
2114 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2115 "sendfd dns inet unveil", NULL) == -1)
2116 err(1, "pledge");
2117 #endif
2118 } else if (strcmp(proto, "git+ssh") == 0 ||
2119 strcmp(proto, "ssh") == 0) {
2120 #ifndef PROFILE
2121 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2122 "sendfd unveil", NULL) == -1)
2123 err(1, "pledge");
2124 #endif
2125 } else if (strcmp(proto, "http") == 0 ||
2126 strcmp(proto, "git+http") == 0) {
2127 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2128 goto done;
2129 } else {
2130 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2131 goto done;
2134 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
2135 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
2136 error = got_error_from_errno2("unveil",
2137 GOT_FETCH_PATH_SSH);
2138 goto done;
2141 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2142 if (error)
2143 goto done;
2145 if (verbosity >= 0)
2146 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2147 port ? ":" : "", port ? port : "");
2149 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2150 server_path, verbosity);
2151 if (error)
2152 goto done;
2154 fpa.last_scaled_size[0] = '\0';
2155 fpa.last_p_indexed = -1;
2156 fpa.last_p_resolved = -1;
2157 fpa.verbosity = verbosity;
2158 fpa.repo = repo;
2159 fpa.create_configs = 0;
2160 fpa.configs_created = 0;
2161 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2162 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2163 remote->mirror_references, fetch_all_branches, &wanted_branches,
2164 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2165 fetch_progress, &fpa);
2166 if (error)
2167 goto done;
2169 if (list_refs_only) {
2170 error = list_remote_refs(&symrefs, &refs);
2171 goto done;
2174 if (pack_hash == NULL) {
2175 if (verbosity >= 0)
2176 printf("Already up-to-date\n");
2177 } else if (verbosity >= 0) {
2178 error = got_object_id_str(&id_str, pack_hash);
2179 if (error)
2180 goto done;
2181 printf("\nFetched %s.pack\n", id_str);
2182 free(id_str);
2183 id_str = NULL;
2186 /* Update references provided with the pack file. */
2187 TAILQ_FOREACH(pe, &refs, entry) {
2188 const char *refname = pe->path;
2189 struct got_object_id *id = pe->data;
2190 struct got_reference *ref;
2191 char *remote_refname;
2193 if (is_wanted_ref(&wanted_refs, refname) &&
2194 !remote->mirror_references) {
2195 error = update_wanted_ref(refname, id,
2196 remote->name, verbosity, repo);
2197 if (error)
2198 goto done;
2199 continue;
2202 if (remote->mirror_references ||
2203 strncmp("refs/tags/", refname, 10) == 0) {
2204 error = got_ref_open(&ref, repo, refname, 1);
2205 if (error) {
2206 if (error->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 error = create_ref(refname, id, verbosity,
2209 repo);
2210 if (error)
2211 goto done;
2212 } else {
2213 error = update_ref(ref, id, replace_tags,
2214 verbosity, repo);
2215 unlock_err = got_ref_unlock(ref);
2216 if (unlock_err && error == NULL)
2217 error = unlock_err;
2218 got_ref_close(ref);
2219 if (error)
2220 goto done;
2222 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2223 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2224 remote_name, refname + 11) == -1) {
2225 error = got_error_from_errno("asprintf");
2226 goto done;
2229 error = got_ref_open(&ref, repo, remote_refname, 1);
2230 if (error) {
2231 if (error->code != GOT_ERR_NOT_REF)
2232 goto done;
2233 error = create_ref(remote_refname, id,
2234 verbosity, repo);
2235 if (error)
2236 goto done;
2237 } else {
2238 error = update_ref(ref, id, replace_tags,
2239 verbosity, repo);
2240 unlock_err = got_ref_unlock(ref);
2241 if (unlock_err && error == NULL)
2242 error = unlock_err;
2243 got_ref_close(ref);
2244 if (error)
2245 goto done;
2248 /* Also create a local branch if none exists yet. */
2249 error = got_ref_open(&ref, repo, refname, 1);
2250 if (error) {
2251 if (error->code != GOT_ERR_NOT_REF)
2252 goto done;
2253 error = create_ref(refname, id, verbosity,
2254 repo);
2255 if (error)
2256 goto done;
2257 } else {
2258 unlock_err = got_ref_unlock(ref);
2259 if (unlock_err && error == NULL)
2260 error = unlock_err;
2261 got_ref_close(ref);
2265 if (delete_refs) {
2266 error = delete_missing_refs(&refs, &symrefs, remote,
2267 verbosity, repo);
2268 if (error)
2269 goto done;
2272 if (!remote->mirror_references) {
2273 /* Update remote HEAD reference if the server provided one. */
2274 TAILQ_FOREACH(pe, &symrefs, entry) {
2275 struct got_reference *target_ref;
2276 const char *refname = pe->path;
2277 const char *target = pe->data;
2278 char *remote_refname = NULL, *remote_target = NULL;
2280 if (strcmp(refname, GOT_REF_HEAD) != 0)
2281 continue;
2283 if (strncmp("refs/heads/", target, 11) != 0)
2284 continue;
2286 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2287 remote->name, refname) == -1) {
2288 error = got_error_from_errno("asprintf");
2289 goto done;
2291 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2292 remote->name, target + 11) == -1) {
2293 error = got_error_from_errno("asprintf");
2294 free(remote_refname);
2295 goto done;
2298 error = got_ref_open(&target_ref, repo, remote_target,
2299 0);
2300 if (error) {
2301 free(remote_refname);
2302 free(remote_target);
2303 if (error->code == GOT_ERR_NOT_REF) {
2304 error = NULL;
2305 continue;
2307 goto done;
2309 error = update_symref(remote_refname, target_ref,
2310 verbosity, repo);
2311 free(remote_refname);
2312 free(remote_target);
2313 got_ref_close(target_ref);
2314 if (error)
2315 goto done;
2318 done:
2319 if (fetchpid > 0) {
2320 if (kill(fetchpid, SIGTERM) == -1)
2321 error = got_error_from_errno("kill");
2322 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2323 error = got_error_from_errno("waitpid");
2325 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2326 error = got_error_from_errno("close");
2327 if (repo)
2328 got_repo_close(repo);
2329 if (worktree)
2330 got_worktree_close(worktree);
2331 TAILQ_FOREACH(pe, &refs, entry) {
2332 free((void *)pe->path);
2333 free(pe->data);
2335 got_pathlist_free(&refs);
2336 TAILQ_FOREACH(pe, &symrefs, entry) {
2337 free((void *)pe->path);
2338 free(pe->data);
2340 got_pathlist_free(&symrefs);
2341 got_pathlist_free(&wanted_branches);
2342 got_pathlist_free(&wanted_refs);
2343 free(id_str);
2344 free(cwd);
2345 free(repo_path);
2346 free(pack_hash);
2347 free(proto);
2348 free(host);
2349 free(port);
2350 free(server_path);
2351 free(repo_name);
2352 return error;
2356 __dead static void
2357 usage_checkout(void)
2359 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2360 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2361 exit(1);
2364 static void
2365 show_worktree_base_ref_warning(void)
2367 fprintf(stderr, "%s: warning: could not create a reference "
2368 "to the work tree's base commit; the commit could be "
2369 "garbage-collected by Git; making the repository "
2370 "writable and running 'got update' will prevent this\n",
2371 getprogname());
2374 struct got_checkout_progress_arg {
2375 const char *worktree_path;
2376 int had_base_commit_ref_error;
2379 static const struct got_error *
2380 checkout_progress(void *arg, unsigned char status, const char *path)
2382 struct got_checkout_progress_arg *a = arg;
2384 /* Base commit bump happens silently. */
2385 if (status == GOT_STATUS_BUMP_BASE)
2386 return NULL;
2388 if (status == GOT_STATUS_BASE_REF_ERR) {
2389 a->had_base_commit_ref_error = 1;
2390 return NULL;
2393 while (path[0] == '/')
2394 path++;
2396 printf("%c %s/%s\n", status, a->worktree_path, path);
2397 return NULL;
2400 static const struct got_error *
2401 check_cancelled(void *arg)
2403 if (sigint_received || sigpipe_received)
2404 return got_error(GOT_ERR_CANCELLED);
2405 return NULL;
2408 static const struct got_error *
2409 check_linear_ancestry(struct got_object_id *commit_id,
2410 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2411 struct got_repository *repo)
2413 const struct got_error *err = NULL;
2414 struct got_object_id *yca_id;
2416 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2417 commit_id, base_commit_id, repo, check_cancelled, NULL);
2418 if (err)
2419 return err;
2421 if (yca_id == NULL)
2422 return got_error(GOT_ERR_ANCESTRY);
2425 * Require a straight line of history between the target commit
2426 * and the work tree's base commit.
2428 * Non-linear situations such as this require a rebase:
2430 * (commit) D F (base_commit)
2431 * \ /
2432 * C E
2433 * \ /
2434 * B (yca)
2435 * |
2436 * A
2438 * 'got update' only handles linear cases:
2439 * Update forwards in time: A (base/yca) - B - C - D (commit)
2440 * Update backwards in time: D (base) - C - B - A (commit/yca)
2442 if (allow_forwards_in_time_only) {
2443 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2444 return got_error(GOT_ERR_ANCESTRY);
2445 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2446 got_object_id_cmp(base_commit_id, yca_id) != 0)
2447 return got_error(GOT_ERR_ANCESTRY);
2449 free(yca_id);
2450 return NULL;
2453 static const struct got_error *
2454 check_same_branch(struct got_object_id *commit_id,
2455 struct got_reference *head_ref, struct got_object_id *yca_id,
2456 struct got_repository *repo)
2458 const struct got_error *err = NULL;
2459 struct got_commit_graph *graph = NULL;
2460 struct got_object_id *head_commit_id = NULL;
2461 int is_same_branch = 0;
2463 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2464 if (err)
2465 goto done;
2467 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2468 is_same_branch = 1;
2469 goto done;
2471 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2472 is_same_branch = 1;
2473 goto done;
2476 err = got_commit_graph_open(&graph, "/", 1);
2477 if (err)
2478 goto done;
2480 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2481 check_cancelled, NULL);
2482 if (err)
2483 goto done;
2485 for (;;) {
2486 struct got_object_id *id;
2487 err = got_commit_graph_iter_next(&id, graph, repo,
2488 check_cancelled, NULL);
2489 if (err) {
2490 if (err->code == GOT_ERR_ITER_COMPLETED)
2491 err = NULL;
2492 break;
2495 if (id) {
2496 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2497 break;
2498 if (got_object_id_cmp(id, commit_id) == 0) {
2499 is_same_branch = 1;
2500 break;
2504 done:
2505 if (graph)
2506 got_commit_graph_close(graph);
2507 free(head_commit_id);
2508 if (!err && !is_same_branch)
2509 err = got_error(GOT_ERR_ANCESTRY);
2510 return err;
2513 static const struct got_error *
2514 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2516 static char msg[512];
2517 const char *branch_name;
2519 if (got_ref_is_symbolic(ref))
2520 branch_name = got_ref_get_symref_target(ref);
2521 else
2522 branch_name = got_ref_get_name(ref);
2524 if (strncmp("refs/heads/", branch_name, 11) == 0)
2525 branch_name += 11;
2527 snprintf(msg, sizeof(msg),
2528 "target commit is not contained in branch '%s'; "
2529 "the branch to use must be specified with -b; "
2530 "if necessary a new branch can be created for "
2531 "this commit with 'got branch -c %s BRANCH_NAME'",
2532 branch_name, commit_id_str);
2534 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2537 static const struct got_error *
2538 cmd_checkout(int argc, char *argv[])
2540 const struct got_error *error = NULL;
2541 struct got_repository *repo = NULL;
2542 struct got_reference *head_ref = NULL;
2543 struct got_worktree *worktree = NULL;
2544 char *repo_path = NULL;
2545 char *worktree_path = NULL;
2546 const char *path_prefix = "";
2547 const char *branch_name = GOT_REF_HEAD;
2548 char *commit_id_str = NULL;
2549 char *cwd = NULL, *path = NULL;
2550 int ch, same_path_prefix, allow_nonempty = 0;
2551 struct got_pathlist_head paths;
2552 struct got_checkout_progress_arg cpa;
2554 TAILQ_INIT(&paths);
2556 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2557 switch (ch) {
2558 case 'b':
2559 branch_name = optarg;
2560 break;
2561 case 'c':
2562 commit_id_str = strdup(optarg);
2563 if (commit_id_str == NULL)
2564 return got_error_from_errno("strdup");
2565 break;
2566 case 'E':
2567 allow_nonempty = 1;
2568 break;
2569 case 'p':
2570 path_prefix = optarg;
2571 break;
2572 default:
2573 usage_checkout();
2574 /* NOTREACHED */
2578 argc -= optind;
2579 argv += optind;
2581 #ifndef PROFILE
2582 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2583 "unveil", NULL) == -1)
2584 err(1, "pledge");
2585 #endif
2586 if (argc == 1) {
2587 char *base, *dotgit;
2588 repo_path = realpath(argv[0], NULL);
2589 if (repo_path == NULL)
2590 return got_error_from_errno2("realpath", argv[0]);
2591 cwd = getcwd(NULL, 0);
2592 if (cwd == NULL) {
2593 error = got_error_from_errno("getcwd");
2594 goto done;
2596 if (path_prefix[0])
2597 path = strdup(path_prefix);
2598 else
2599 path = strdup(repo_path);
2600 if (path == NULL) {
2601 error = got_error_from_errno("strdup");
2602 goto done;
2604 base = basename(path);
2605 if (base == NULL) {
2606 error = got_error_from_errno2("basename", path);
2607 goto done;
2609 dotgit = strstr(base, ".git");
2610 if (dotgit)
2611 *dotgit = '\0';
2612 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2613 error = got_error_from_errno("asprintf");
2614 goto done;
2616 } else if (argc == 2) {
2617 repo_path = realpath(argv[0], NULL);
2618 if (repo_path == NULL) {
2619 error = got_error_from_errno2("realpath", argv[0]);
2620 goto done;
2622 worktree_path = realpath(argv[1], NULL);
2623 if (worktree_path == NULL) {
2624 if (errno != ENOENT) {
2625 error = got_error_from_errno2("realpath",
2626 argv[1]);
2627 goto done;
2629 worktree_path = strdup(argv[1]);
2630 if (worktree_path == NULL) {
2631 error = got_error_from_errno("strdup");
2632 goto done;
2635 } else
2636 usage_checkout();
2638 got_path_strip_trailing_slashes(repo_path);
2639 got_path_strip_trailing_slashes(worktree_path);
2641 error = got_repo_open(&repo, repo_path, NULL);
2642 if (error != NULL)
2643 goto done;
2645 /* Pre-create work tree path for unveil(2) */
2646 error = got_path_mkdir(worktree_path);
2647 if (error) {
2648 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2649 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2650 goto done;
2651 if (!allow_nonempty &&
2652 !got_path_dir_is_empty(worktree_path)) {
2653 error = got_error_path(worktree_path,
2654 GOT_ERR_DIR_NOT_EMPTY);
2655 goto done;
2659 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2660 if (error)
2661 goto done;
2663 error = got_ref_open(&head_ref, repo, branch_name, 0);
2664 if (error != NULL)
2665 goto done;
2667 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2668 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2669 goto done;
2671 error = got_worktree_open(&worktree, worktree_path);
2672 if (error != NULL)
2673 goto done;
2675 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2676 path_prefix);
2677 if (error != NULL)
2678 goto done;
2679 if (!same_path_prefix) {
2680 error = got_error(GOT_ERR_PATH_PREFIX);
2681 goto done;
2684 if (commit_id_str) {
2685 struct got_object_id *commit_id;
2686 error = got_repo_match_object_id(&commit_id, NULL,
2687 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2688 if (error)
2689 goto done;
2690 error = check_linear_ancestry(commit_id,
2691 got_worktree_get_base_commit_id(worktree), 0, repo);
2692 if (error != NULL) {
2693 free(commit_id);
2694 if (error->code == GOT_ERR_ANCESTRY) {
2695 error = checkout_ancestry_error(
2696 head_ref, commit_id_str);
2698 goto done;
2700 error = check_same_branch(commit_id, head_ref, NULL, repo);
2701 if (error) {
2702 if (error->code == GOT_ERR_ANCESTRY) {
2703 error = checkout_ancestry_error(
2704 head_ref, commit_id_str);
2706 goto done;
2708 error = got_worktree_set_base_commit_id(worktree, repo,
2709 commit_id);
2710 free(commit_id);
2711 if (error)
2712 goto done;
2715 error = got_pathlist_append(&paths, "", NULL);
2716 if (error)
2717 goto done;
2718 cpa.worktree_path = worktree_path;
2719 cpa.had_base_commit_ref_error = 0;
2720 error = got_worktree_checkout_files(worktree, &paths, repo,
2721 checkout_progress, &cpa, check_cancelled, NULL);
2722 if (error != NULL)
2723 goto done;
2725 printf("Now shut up and hack\n");
2726 if (cpa.had_base_commit_ref_error)
2727 show_worktree_base_ref_warning();
2728 done:
2729 got_pathlist_free(&paths);
2730 free(commit_id_str);
2731 free(repo_path);
2732 free(worktree_path);
2733 free(cwd);
2734 free(path);
2735 return error;
2738 struct got_update_progress_arg {
2739 int did_something;
2740 int conflicts;
2741 int obstructed;
2742 int not_updated;
2745 void
2746 print_update_progress_stats(struct got_update_progress_arg *upa)
2748 if (!upa->did_something)
2749 return;
2751 if (upa->conflicts > 0)
2752 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2753 if (upa->obstructed > 0)
2754 printf("File paths obstructed by a non-regular file: %d\n",
2755 upa->obstructed);
2756 if (upa->not_updated > 0)
2757 printf("Files not updated because of existing merge "
2758 "conflicts: %d\n", upa->not_updated);
2761 __dead static void
2762 usage_update(void)
2764 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2765 getprogname());
2766 exit(1);
2769 static const struct got_error *
2770 update_progress(void *arg, unsigned char status, const char *path)
2772 struct got_update_progress_arg *upa = arg;
2774 if (status == GOT_STATUS_EXISTS ||
2775 status == GOT_STATUS_BASE_REF_ERR)
2776 return NULL;
2778 upa->did_something = 1;
2780 /* Base commit bump happens silently. */
2781 if (status == GOT_STATUS_BUMP_BASE)
2782 return NULL;
2784 if (status == GOT_STATUS_CONFLICT)
2785 upa->conflicts++;
2786 if (status == GOT_STATUS_OBSTRUCTED)
2787 upa->obstructed++;
2788 if (status == GOT_STATUS_CANNOT_UPDATE)
2789 upa->not_updated++;
2791 while (path[0] == '/')
2792 path++;
2793 printf("%c %s\n", status, path);
2794 return NULL;
2797 static const struct got_error *
2798 switch_head_ref(struct got_reference *head_ref,
2799 struct got_object_id *commit_id, struct got_worktree *worktree,
2800 struct got_repository *repo)
2802 const struct got_error *err = NULL;
2803 char *base_id_str;
2804 int ref_has_moved = 0;
2806 /* Trivial case: switching between two different references. */
2807 if (strcmp(got_ref_get_name(head_ref),
2808 got_worktree_get_head_ref_name(worktree)) != 0) {
2809 printf("Switching work tree from %s to %s\n",
2810 got_worktree_get_head_ref_name(worktree),
2811 got_ref_get_name(head_ref));
2812 return got_worktree_set_head_ref(worktree, head_ref);
2815 err = check_linear_ancestry(commit_id,
2816 got_worktree_get_base_commit_id(worktree), 0, repo);
2817 if (err) {
2818 if (err->code != GOT_ERR_ANCESTRY)
2819 return err;
2820 ref_has_moved = 1;
2822 if (!ref_has_moved)
2823 return NULL;
2825 /* Switching to a rebased branch with the same reference name. */
2826 err = got_object_id_str(&base_id_str,
2827 got_worktree_get_base_commit_id(worktree));
2828 if (err)
2829 return err;
2830 printf("Reference %s now points at a different branch\n",
2831 got_worktree_get_head_ref_name(worktree));
2832 printf("Switching work tree from %s to %s\n", base_id_str,
2833 got_worktree_get_head_ref_name(worktree));
2834 return NULL;
2837 static const struct got_error *
2838 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2840 const struct got_error *err;
2841 int in_progress;
2843 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2844 if (err)
2845 return err;
2846 if (in_progress)
2847 return got_error(GOT_ERR_REBASING);
2849 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2850 if (err)
2851 return err;
2852 if (in_progress)
2853 return got_error(GOT_ERR_HISTEDIT_BUSY);
2855 return NULL;
2858 static const struct got_error *
2859 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2860 char *argv[], struct got_worktree *worktree)
2862 const struct got_error *err = NULL;
2863 char *path;
2864 int i;
2866 if (argc == 0) {
2867 path = strdup("");
2868 if (path == NULL)
2869 return got_error_from_errno("strdup");
2870 return got_pathlist_append(paths, path, NULL);
2873 for (i = 0; i < argc; i++) {
2874 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2875 if (err)
2876 break;
2877 err = got_pathlist_append(paths, path, NULL);
2878 if (err) {
2879 free(path);
2880 break;
2884 return err;
2887 static const struct got_error *
2888 wrap_not_worktree_error(const struct got_error *orig_err,
2889 const char *cmdname, const char *path)
2891 const struct got_error *err;
2892 struct got_repository *repo;
2893 static char msg[512];
2895 err = got_repo_open(&repo, path, NULL);
2896 if (err)
2897 return orig_err;
2899 snprintf(msg, sizeof(msg),
2900 "'got %s' needs a work tree in addition to a git repository\n"
2901 "Work trees can be checked out from this Git repository with "
2902 "'got checkout'.\n"
2903 "The got(1) manual page contains more information.", cmdname);
2904 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2905 got_repo_close(repo);
2906 return err;
2909 static const struct got_error *
2910 cmd_update(int argc, char *argv[])
2912 const struct got_error *error = NULL;
2913 struct got_repository *repo = NULL;
2914 struct got_worktree *worktree = NULL;
2915 char *worktree_path = NULL;
2916 struct got_object_id *commit_id = NULL;
2917 char *commit_id_str = NULL;
2918 const char *branch_name = NULL;
2919 struct got_reference *head_ref = NULL;
2920 struct got_pathlist_head paths;
2921 struct got_pathlist_entry *pe;
2922 int ch;
2923 struct got_update_progress_arg upa;
2925 TAILQ_INIT(&paths);
2927 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2928 switch (ch) {
2929 case 'b':
2930 branch_name = optarg;
2931 break;
2932 case 'c':
2933 commit_id_str = strdup(optarg);
2934 if (commit_id_str == NULL)
2935 return got_error_from_errno("strdup");
2936 break;
2937 default:
2938 usage_update();
2939 /* NOTREACHED */
2943 argc -= optind;
2944 argv += optind;
2946 #ifndef PROFILE
2947 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2948 "unveil", NULL) == -1)
2949 err(1, "pledge");
2950 #endif
2951 worktree_path = getcwd(NULL, 0);
2952 if (worktree_path == NULL) {
2953 error = got_error_from_errno("getcwd");
2954 goto done;
2956 error = got_worktree_open(&worktree, worktree_path);
2957 if (error) {
2958 if (error->code == GOT_ERR_NOT_WORKTREE)
2959 error = wrap_not_worktree_error(error, "update",
2960 worktree_path);
2961 goto done;
2964 error = check_rebase_or_histedit_in_progress(worktree);
2965 if (error)
2966 goto done;
2968 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2969 NULL);
2970 if (error != NULL)
2971 goto done;
2973 error = apply_unveil(got_repo_get_path(repo), 0,
2974 got_worktree_get_root_path(worktree));
2975 if (error)
2976 goto done;
2978 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2979 if (error)
2980 goto done;
2982 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2983 got_worktree_get_head_ref_name(worktree), 0);
2984 if (error != NULL)
2985 goto done;
2986 if (commit_id_str == NULL) {
2987 error = got_ref_resolve(&commit_id, repo, head_ref);
2988 if (error != NULL)
2989 goto done;
2990 error = got_object_id_str(&commit_id_str, commit_id);
2991 if (error != NULL)
2992 goto done;
2993 } else {
2994 error = got_repo_match_object_id(&commit_id, NULL,
2995 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2996 free(commit_id_str);
2997 commit_id_str = NULL;
2998 if (error)
2999 goto done;
3000 error = got_object_id_str(&commit_id_str, commit_id);
3001 if (error)
3002 goto done;
3005 if (branch_name) {
3006 struct got_object_id *head_commit_id;
3007 TAILQ_FOREACH(pe, &paths, entry) {
3008 if (pe->path_len == 0)
3009 continue;
3010 error = got_error_msg(GOT_ERR_BAD_PATH,
3011 "switching between branches requires that "
3012 "the entire work tree gets updated");
3013 goto done;
3015 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3016 if (error)
3017 goto done;
3018 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3019 repo);
3020 free(head_commit_id);
3021 if (error != NULL)
3022 goto done;
3023 error = check_same_branch(commit_id, head_ref, NULL, repo);
3024 if (error)
3025 goto done;
3026 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3027 if (error)
3028 goto done;
3029 } else {
3030 error = check_linear_ancestry(commit_id,
3031 got_worktree_get_base_commit_id(worktree), 0, repo);
3032 if (error != NULL) {
3033 if (error->code == GOT_ERR_ANCESTRY)
3034 error = got_error(GOT_ERR_BRANCH_MOVED);
3035 goto done;
3037 error = check_same_branch(commit_id, head_ref, NULL, repo);
3038 if (error)
3039 goto done;
3042 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3043 commit_id) != 0) {
3044 error = got_worktree_set_base_commit_id(worktree, repo,
3045 commit_id);
3046 if (error)
3047 goto done;
3050 memset(&upa, 0, sizeof(upa));
3051 error = got_worktree_checkout_files(worktree, &paths, repo,
3052 update_progress, &upa, check_cancelled, NULL);
3053 if (error != NULL)
3054 goto done;
3056 if (upa.did_something)
3057 printf("Updated to commit %s\n", commit_id_str);
3058 else
3059 printf("Already up-to-date\n");
3060 print_update_progress_stats(&upa);
3061 done:
3062 free(worktree_path);
3063 TAILQ_FOREACH(pe, &paths, entry)
3064 free((char *)pe->path);
3065 got_pathlist_free(&paths);
3066 free(commit_id);
3067 free(commit_id_str);
3068 return error;
3071 static const struct got_error *
3072 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3073 const char *path, int diff_context, int ignore_whitespace,
3074 struct got_repository *repo)
3076 const struct got_error *err = NULL;
3077 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3079 if (blob_id1) {
3080 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3081 if (err)
3082 goto done;
3085 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3086 if (err)
3087 goto done;
3089 while (path[0] == '/')
3090 path++;
3091 err = got_diff_blob(blob1, blob2, path, path, diff_context,
3092 ignore_whitespace, stdout);
3093 done:
3094 if (blob1)
3095 got_object_blob_close(blob1);
3096 got_object_blob_close(blob2);
3097 return err;
3100 static const struct got_error *
3101 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3102 const char *path, int diff_context, int ignore_whitespace,
3103 struct got_repository *repo)
3105 const struct got_error *err = NULL;
3106 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3107 struct got_diff_blob_output_unidiff_arg arg;
3109 if (tree_id1) {
3110 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3111 if (err)
3112 goto done;
3115 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3116 if (err)
3117 goto done;
3119 arg.diff_context = diff_context;
3120 arg.ignore_whitespace = ignore_whitespace;
3121 arg.outfile = stdout;
3122 while (path[0] == '/')
3123 path++;
3124 err = got_diff_tree(tree1, tree2, path, path, repo,
3125 got_diff_blob_output_unidiff, &arg, 1);
3126 done:
3127 if (tree1)
3128 got_object_tree_close(tree1);
3129 if (tree2)
3130 got_object_tree_close(tree2);
3131 return err;
3134 static const struct got_error *
3135 get_changed_paths(struct got_pathlist_head *paths,
3136 struct got_commit_object *commit, struct got_repository *repo)
3138 const struct got_error *err = NULL;
3139 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3140 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3141 struct got_object_qid *qid;
3143 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3144 if (qid != NULL) {
3145 struct got_commit_object *pcommit;
3146 err = got_object_open_as_commit(&pcommit, repo,
3147 qid->id);
3148 if (err)
3149 return err;
3151 tree_id1 = got_object_commit_get_tree_id(pcommit);
3152 got_object_commit_close(pcommit);
3156 if (tree_id1) {
3157 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3158 if (err)
3159 goto done;
3162 tree_id2 = got_object_commit_get_tree_id(commit);
3163 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3164 if (err)
3165 goto done;
3167 err = got_diff_tree(tree1, tree2, "", "", repo,
3168 got_diff_tree_collect_changed_paths, paths, 0);
3169 done:
3170 if (tree1)
3171 got_object_tree_close(tree1);
3172 if (tree2)
3173 got_object_tree_close(tree2);
3174 return err;
3177 static const struct got_error *
3178 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3179 const char *path, int diff_context, struct got_repository *repo)
3181 const struct got_error *err = NULL;
3182 struct got_commit_object *pcommit = NULL;
3183 char *id_str1 = NULL, *id_str2 = NULL;
3184 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3185 struct got_object_qid *qid;
3187 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3188 if (qid != NULL) {
3189 err = got_object_open_as_commit(&pcommit, repo,
3190 qid->id);
3191 if (err)
3192 return err;
3195 if (path && path[0] != '\0') {
3196 int obj_type;
3197 err = got_object_id_by_path(&obj_id2, repo, id, path);
3198 if (err)
3199 goto done;
3200 err = got_object_id_str(&id_str2, obj_id2);
3201 if (err) {
3202 free(obj_id2);
3203 goto done;
3205 if (pcommit) {
3206 err = got_object_id_by_path(&obj_id1, repo,
3207 qid->id, path);
3208 if (err) {
3209 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3210 free(obj_id2);
3211 goto done;
3213 } else {
3214 err = got_object_id_str(&id_str1, obj_id1);
3215 if (err) {
3216 free(obj_id2);
3217 goto done;
3221 err = got_object_get_type(&obj_type, repo, obj_id2);
3222 if (err) {
3223 free(obj_id2);
3224 goto done;
3226 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3227 switch (obj_type) {
3228 case GOT_OBJ_TYPE_BLOB:
3229 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3230 0, repo);
3231 break;
3232 case GOT_OBJ_TYPE_TREE:
3233 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3234 0, repo);
3235 break;
3236 default:
3237 err = got_error(GOT_ERR_OBJ_TYPE);
3238 break;
3240 free(obj_id1);
3241 free(obj_id2);
3242 } else {
3243 obj_id2 = got_object_commit_get_tree_id(commit);
3244 err = got_object_id_str(&id_str2, obj_id2);
3245 if (err)
3246 goto done;
3247 obj_id1 = got_object_commit_get_tree_id(pcommit);
3248 err = got_object_id_str(&id_str1, obj_id1);
3249 if (err)
3250 goto done;
3251 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3252 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3254 done:
3255 free(id_str1);
3256 free(id_str2);
3257 if (pcommit)
3258 got_object_commit_close(pcommit);
3259 return err;
3262 static char *
3263 get_datestr(time_t *time, char *datebuf)
3265 struct tm mytm, *tm;
3266 char *p, *s;
3268 tm = gmtime_r(time, &mytm);
3269 if (tm == NULL)
3270 return NULL;
3271 s = asctime_r(tm, datebuf);
3272 if (s == NULL)
3273 return NULL;
3274 p = strchr(s, '\n');
3275 if (p)
3276 *p = '\0';
3277 return s;
3280 static const struct got_error *
3281 match_logmsg(int *have_match, struct got_object_id *id,
3282 struct got_commit_object *commit, regex_t *regex)
3284 const struct got_error *err = NULL;
3285 regmatch_t regmatch;
3286 char *id_str = NULL, *logmsg = NULL;
3288 *have_match = 0;
3290 err = got_object_id_str(&id_str, id);
3291 if (err)
3292 return err;
3294 err = got_object_commit_get_logmsg(&logmsg, commit);
3295 if (err)
3296 goto done;
3298 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3299 *have_match = 1;
3300 done:
3301 free(id_str);
3302 free(logmsg);
3303 return err;
3306 static void
3307 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3308 regex_t *regex)
3310 regmatch_t regmatch;
3311 struct got_pathlist_entry *pe;
3313 *have_match = 0;
3315 TAILQ_FOREACH(pe, changed_paths, entry) {
3316 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3317 *have_match = 1;
3318 break;
3323 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3325 static const struct got_error *
3326 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3327 struct got_repository *repo, const char *path,
3328 struct got_pathlist_head *changed_paths, int show_patch,
3329 int diff_context, struct got_reflist_head *refs)
3331 const struct got_error *err = NULL;
3332 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3333 char datebuf[26];
3334 time_t committer_time;
3335 const char *author, *committer;
3336 char *refs_str = NULL;
3337 struct got_reflist_entry *re;
3339 SIMPLEQ_FOREACH(re, refs, entry) {
3340 char *s;
3341 const char *name;
3342 struct got_tag_object *tag = NULL;
3343 struct got_object_id *ref_id;
3344 int cmp;
3346 name = got_ref_get_name(re->ref);
3347 if (strcmp(name, GOT_REF_HEAD) == 0)
3348 continue;
3349 if (strncmp(name, "refs/", 5) == 0)
3350 name += 5;
3351 if (strncmp(name, "got/", 4) == 0)
3352 continue;
3353 if (strncmp(name, "heads/", 6) == 0)
3354 name += 6;
3355 if (strncmp(name, "remotes/", 8) == 0) {
3356 name += 8;
3357 s = strstr(name, "/" GOT_REF_HEAD);
3358 if (s != NULL && s[strlen(s)] == '\0')
3359 continue;
3361 err = got_ref_resolve(&ref_id, repo, re->ref);
3362 if (err)
3363 return err;
3364 if (strncmp(name, "tags/", 5) == 0) {
3365 err = got_object_open_as_tag(&tag, repo, ref_id);
3366 if (err) {
3367 if (err->code != GOT_ERR_OBJ_TYPE) {
3368 free(ref_id);
3369 return err;
3371 /* Ref points at something other than a tag. */
3372 err = NULL;
3373 tag = NULL;
3376 cmp = got_object_id_cmp(tag ?
3377 got_object_tag_get_object_id(tag) : ref_id, id);
3378 free(ref_id);
3379 if (tag)
3380 got_object_tag_close(tag);
3381 if (cmp != 0)
3382 continue;
3383 s = refs_str;
3384 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3385 name) == -1) {
3386 err = got_error_from_errno("asprintf");
3387 free(s);
3388 return err;
3390 free(s);
3392 err = got_object_id_str(&id_str, id);
3393 if (err)
3394 return err;
3396 printf(GOT_COMMIT_SEP_STR);
3397 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3398 refs_str ? refs_str : "", refs_str ? ")" : "");
3399 free(id_str);
3400 id_str = NULL;
3401 free(refs_str);
3402 refs_str = NULL;
3403 printf("from: %s\n", got_object_commit_get_author(commit));
3404 committer_time = got_object_commit_get_committer_time(commit);
3405 datestr = get_datestr(&committer_time, datebuf);
3406 if (datestr)
3407 printf("date: %s UTC\n", datestr);
3408 author = got_object_commit_get_author(commit);
3409 committer = got_object_commit_get_committer(commit);
3410 if (strcmp(author, committer) != 0)
3411 printf("via: %s\n", committer);
3412 if (got_object_commit_get_nparents(commit) > 1) {
3413 const struct got_object_id_queue *parent_ids;
3414 struct got_object_qid *qid;
3415 int n = 1;
3416 parent_ids = got_object_commit_get_parent_ids(commit);
3417 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3418 err = got_object_id_str(&id_str, qid->id);
3419 if (err)
3420 return err;
3421 printf("parent %d: %s\n", n++, id_str);
3422 free(id_str);
3426 err = got_object_commit_get_logmsg(&logmsg0, commit);
3427 if (err)
3428 return err;
3430 logmsg = logmsg0;
3431 do {
3432 line = strsep(&logmsg, "\n");
3433 if (line)
3434 printf(" %s\n", line);
3435 } while (line);
3436 free(logmsg0);
3438 if (changed_paths) {
3439 struct got_pathlist_entry *pe;
3440 TAILQ_FOREACH(pe, changed_paths, entry) {
3441 struct got_diff_changed_path *cp = pe->data;
3442 printf(" %c %s\n", cp->status, pe->path);
3444 printf("\n");
3446 if (show_patch) {
3447 err = print_patch(commit, id, path, diff_context, repo);
3448 if (err == 0)
3449 printf("\n");
3452 if (fflush(stdout) != 0 && err == NULL)
3453 err = got_error_from_errno("fflush");
3454 return err;
3457 static const struct got_error *
3458 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3459 struct got_repository *repo, const char *path, int show_changed_paths,
3460 int show_patch, const char *search_pattern, int diff_context, int limit,
3461 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3463 const struct got_error *err;
3464 struct got_commit_graph *graph;
3465 regex_t regex;
3466 int have_match;
3467 struct got_object_id_queue reversed_commits;
3468 struct got_object_qid *qid;
3469 struct got_commit_object *commit;
3470 struct got_pathlist_head changed_paths;
3471 struct got_pathlist_entry *pe;
3473 SIMPLEQ_INIT(&reversed_commits);
3474 TAILQ_INIT(&changed_paths);
3476 if (search_pattern && regcomp(&regex, search_pattern,
3477 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3478 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3480 err = got_commit_graph_open(&graph, path, !log_branches);
3481 if (err)
3482 return err;
3483 err = got_commit_graph_iter_start(graph, root_id, repo,
3484 check_cancelled, NULL);
3485 if (err)
3486 goto done;
3487 for (;;) {
3488 struct got_object_id *id;
3490 if (sigint_received || sigpipe_received)
3491 break;
3493 err = got_commit_graph_iter_next(&id, graph, repo,
3494 check_cancelled, NULL);
3495 if (err) {
3496 if (err->code == GOT_ERR_ITER_COMPLETED)
3497 err = NULL;
3498 break;
3500 if (id == NULL)
3501 break;
3503 err = got_object_open_as_commit(&commit, repo, id);
3504 if (err)
3505 break;
3507 if (show_changed_paths && !reverse_display_order) {
3508 err = get_changed_paths(&changed_paths, commit, repo);
3509 if (err)
3510 break;
3513 if (search_pattern) {
3514 err = match_logmsg(&have_match, id, commit, &regex);
3515 if (err) {
3516 got_object_commit_close(commit);
3517 break;
3519 if (have_match == 0 && show_changed_paths)
3520 match_changed_paths(&have_match,
3521 &changed_paths, &regex);
3522 if (have_match == 0) {
3523 got_object_commit_close(commit);
3524 TAILQ_FOREACH(pe, &changed_paths, entry) {
3525 free((char *)pe->path);
3526 free(pe->data);
3528 got_pathlist_free(&changed_paths);
3529 continue;
3533 if (reverse_display_order) {
3534 err = got_object_qid_alloc(&qid, id);
3535 if (err)
3536 break;
3537 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3538 got_object_commit_close(commit);
3539 } else {
3540 err = print_commit(commit, id, repo, path,
3541 show_changed_paths ? &changed_paths : NULL,
3542 show_patch, diff_context, refs);
3543 got_object_commit_close(commit);
3544 if (err)
3545 break;
3547 if ((limit && --limit == 0) ||
3548 (end_id && got_object_id_cmp(id, end_id) == 0))
3549 break;
3551 TAILQ_FOREACH(pe, &changed_paths, entry) {
3552 free((char *)pe->path);
3553 free(pe->data);
3555 got_pathlist_free(&changed_paths);
3557 if (reverse_display_order) {
3558 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3559 err = got_object_open_as_commit(&commit, repo, qid->id);
3560 if (err)
3561 break;
3562 if (show_changed_paths) {
3563 err = get_changed_paths(&changed_paths,
3564 commit, repo);
3565 if (err)
3566 break;
3568 err = print_commit(commit, qid->id, repo, path,
3569 show_changed_paths ? &changed_paths : NULL,
3570 show_patch, diff_context, refs);
3571 got_object_commit_close(commit);
3572 if (err)
3573 break;
3574 TAILQ_FOREACH(pe, &changed_paths, entry) {
3575 free((char *)pe->path);
3576 free(pe->data);
3578 got_pathlist_free(&changed_paths);
3581 done:
3582 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3583 qid = SIMPLEQ_FIRST(&reversed_commits);
3584 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3585 got_object_qid_free(qid);
3587 TAILQ_FOREACH(pe, &changed_paths, entry) {
3588 free((char *)pe->path);
3589 free(pe->data);
3591 got_pathlist_free(&changed_paths);
3592 if (search_pattern)
3593 regfree(&regex);
3594 got_commit_graph_close(graph);
3595 return err;
3598 __dead static void
3599 usage_log(void)
3601 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3602 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3603 "[-R] [path]\n", getprogname());
3604 exit(1);
3607 static int
3608 get_default_log_limit(void)
3610 const char *got_default_log_limit;
3611 long long n;
3612 const char *errstr;
3614 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3615 if (got_default_log_limit == NULL)
3616 return 0;
3617 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3618 if (errstr != NULL)
3619 return 0;
3620 return n;
3623 static const struct got_error *
3624 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3625 struct got_repository *repo)
3627 const struct got_error *err = NULL;
3628 struct got_reference *ref;
3630 *id = NULL;
3632 err = got_ref_open(&ref, repo, commit_arg, 0);
3633 if (err == NULL) {
3634 int obj_type;
3635 err = got_ref_resolve(id, repo, ref);
3636 got_ref_close(ref);
3637 if (err)
3638 return err;
3639 err = got_object_get_type(&obj_type, repo, *id);
3640 if (err)
3641 return err;
3642 if (obj_type == GOT_OBJ_TYPE_TAG) {
3643 struct got_tag_object *tag;
3644 err = got_object_open_as_tag(&tag, repo, *id);
3645 if (err)
3646 return err;
3647 if (got_object_tag_get_object_type(tag) !=
3648 GOT_OBJ_TYPE_COMMIT) {
3649 got_object_tag_close(tag);
3650 return got_error(GOT_ERR_OBJ_TYPE);
3652 free(*id);
3653 *id = got_object_id_dup(
3654 got_object_tag_get_object_id(tag));
3655 if (*id == NULL)
3656 err = got_error_from_errno(
3657 "got_object_id_dup");
3658 got_object_tag_close(tag);
3659 if (err)
3660 return err;
3661 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3662 return got_error(GOT_ERR_OBJ_TYPE);
3663 } else {
3664 err = got_repo_match_object_id_prefix(id, commit_arg,
3665 GOT_OBJ_TYPE_COMMIT, repo);
3668 return err;
3671 static const struct got_error *
3672 cmd_log(int argc, char *argv[])
3674 const struct got_error *error;
3675 struct got_repository *repo = NULL;
3676 struct got_worktree *worktree = NULL;
3677 struct got_object_id *start_id = NULL, *end_id = NULL;
3678 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3679 const char *start_commit = NULL, *end_commit = NULL;
3680 const char *search_pattern = NULL;
3681 int diff_context = -1, ch;
3682 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3683 int reverse_display_order = 0;
3684 const char *errstr;
3685 struct got_reflist_head refs;
3687 SIMPLEQ_INIT(&refs);
3689 #ifndef PROFILE
3690 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3691 NULL)
3692 == -1)
3693 err(1, "pledge");
3694 #endif
3696 limit = get_default_log_limit();
3698 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3699 switch (ch) {
3700 case 'p':
3701 show_patch = 1;
3702 break;
3703 case 'P':
3704 show_changed_paths = 1;
3705 break;
3706 case 'c':
3707 start_commit = optarg;
3708 break;
3709 case 'C':
3710 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3711 &errstr);
3712 if (errstr != NULL)
3713 err(1, "-C option %s", errstr);
3714 break;
3715 case 'l':
3716 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3717 if (errstr != NULL)
3718 err(1, "-l option %s", errstr);
3719 break;
3720 case 'b':
3721 log_branches = 1;
3722 break;
3723 case 'r':
3724 repo_path = realpath(optarg, NULL);
3725 if (repo_path == NULL)
3726 return got_error_from_errno2("realpath",
3727 optarg);
3728 got_path_strip_trailing_slashes(repo_path);
3729 break;
3730 case 'R':
3731 reverse_display_order = 1;
3732 break;
3733 case 's':
3734 search_pattern = optarg;
3735 break;
3736 case 'x':
3737 end_commit = optarg;
3738 break;
3739 default:
3740 usage_log();
3741 /* NOTREACHED */
3745 argc -= optind;
3746 argv += optind;
3748 if (diff_context == -1)
3749 diff_context = 3;
3750 else if (!show_patch)
3751 errx(1, "-C requires -p");
3753 cwd = getcwd(NULL, 0);
3754 if (cwd == NULL) {
3755 error = got_error_from_errno("getcwd");
3756 goto done;
3759 if (repo_path == NULL) {
3760 error = got_worktree_open(&worktree, cwd);
3761 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3762 goto done;
3763 error = NULL;
3766 if (argc == 0) {
3767 path = strdup("");
3768 if (path == NULL) {
3769 error = got_error_from_errno("strdup");
3770 goto done;
3772 } else if (argc == 1) {
3773 if (worktree) {
3774 error = got_worktree_resolve_path(&path, worktree,
3775 argv[0]);
3776 if (error)
3777 goto done;
3778 } else {
3779 path = strdup(argv[0]);
3780 if (path == NULL) {
3781 error = got_error_from_errno("strdup");
3782 goto done;
3785 } else
3786 usage_log();
3788 if (repo_path == NULL) {
3789 repo_path = worktree ?
3790 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3792 if (repo_path == NULL) {
3793 error = got_error_from_errno("strdup");
3794 goto done;
3797 error = got_repo_open(&repo, repo_path, NULL);
3798 if (error != NULL)
3799 goto done;
3801 error = apply_unveil(got_repo_get_path(repo), 1,
3802 worktree ? got_worktree_get_root_path(worktree) : NULL);
3803 if (error)
3804 goto done;
3806 if (start_commit == NULL) {
3807 struct got_reference *head_ref;
3808 struct got_commit_object *commit = NULL;
3809 error = got_ref_open(&head_ref, repo,
3810 worktree ? got_worktree_get_head_ref_name(worktree)
3811 : GOT_REF_HEAD, 0);
3812 if (error != NULL)
3813 goto done;
3814 error = got_ref_resolve(&start_id, repo, head_ref);
3815 got_ref_close(head_ref);
3816 if (error != NULL)
3817 goto done;
3818 error = got_object_open_as_commit(&commit, repo,
3819 start_id);
3820 if (error != NULL)
3821 goto done;
3822 got_object_commit_close(commit);
3823 } else {
3824 error = resolve_commit_arg(&start_id, start_commit, repo);
3825 if (error != NULL)
3826 goto done;
3828 if (end_commit != NULL) {
3829 error = resolve_commit_arg(&end_id, end_commit, repo);
3830 if (error != NULL)
3831 goto done;
3834 if (worktree) {
3835 const char *prefix = got_worktree_get_path_prefix(worktree);
3836 char *p;
3837 if (asprintf(&p, "%s%s%s", prefix,
3838 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3839 error = got_error_from_errno("asprintf");
3840 goto done;
3842 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3843 free(p);
3844 } else
3845 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3846 if (error != NULL)
3847 goto done;
3848 if (in_repo_path) {
3849 free(path);
3850 path = in_repo_path;
3853 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3854 if (error)
3855 goto done;
3857 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3858 show_patch, search_pattern, diff_context, limit, log_branches,
3859 reverse_display_order, &refs);
3860 done:
3861 free(path);
3862 free(repo_path);
3863 free(cwd);
3864 if (worktree)
3865 got_worktree_close(worktree);
3866 if (repo) {
3867 const struct got_error *repo_error;
3868 repo_error = got_repo_close(repo);
3869 if (error == NULL)
3870 error = repo_error;
3872 got_ref_list_free(&refs);
3873 return error;
3876 __dead static void
3877 usage_diff(void)
3879 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3880 "[-w] [object1 object2 | path]\n", getprogname());
3881 exit(1);
3884 struct print_diff_arg {
3885 struct got_repository *repo;
3886 struct got_worktree *worktree;
3887 int diff_context;
3888 const char *id_str;
3889 int header_shown;
3890 int diff_staged;
3891 int ignore_whitespace;
3895 * Create a file which contains the target path of a symlink so we can feed
3896 * it as content to the diff engine.
3898 static const struct got_error *
3899 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3900 const char *abspath)
3902 const struct got_error *err = NULL;
3903 char target_path[PATH_MAX];
3904 ssize_t target_len, outlen;
3906 *fd = -1;
3908 if (dirfd != -1) {
3909 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3910 if (target_len == -1)
3911 return got_error_from_errno2("readlinkat", abspath);
3912 } else {
3913 target_len = readlink(abspath, target_path, PATH_MAX);
3914 if (target_len == -1)
3915 return got_error_from_errno2("readlink", abspath);
3918 *fd = got_opentempfd();
3919 if (*fd == -1)
3920 return got_error_from_errno("got_opentempfd");
3922 outlen = write(*fd, target_path, target_len);
3923 if (outlen == -1) {
3924 err = got_error_from_errno("got_opentempfd");
3925 goto done;
3928 if (lseek(*fd, 0, SEEK_SET) == -1) {
3929 err = got_error_from_errno2("lseek", abspath);
3930 goto done;
3932 done:
3933 if (err) {
3934 close(*fd);
3935 *fd = -1;
3937 return err;
3940 static const struct got_error *
3941 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3942 const char *path, struct got_object_id *blob_id,
3943 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3944 int dirfd, const char *de_name)
3946 struct print_diff_arg *a = arg;
3947 const struct got_error *err = NULL;
3948 struct got_blob_object *blob1 = NULL;
3949 int fd = -1;
3950 FILE *f2 = NULL;
3951 char *abspath = NULL, *label1 = NULL;
3952 struct stat sb;
3954 if (a->diff_staged) {
3955 if (staged_status != GOT_STATUS_MODIFY &&
3956 staged_status != GOT_STATUS_ADD &&
3957 staged_status != GOT_STATUS_DELETE)
3958 return NULL;
3959 } else {
3960 if (staged_status == GOT_STATUS_DELETE)
3961 return NULL;
3962 if (status == GOT_STATUS_NONEXISTENT)
3963 return got_error_set_errno(ENOENT, path);
3964 if (status != GOT_STATUS_MODIFY &&
3965 status != GOT_STATUS_ADD &&
3966 status != GOT_STATUS_DELETE &&
3967 status != GOT_STATUS_CONFLICT)
3968 return NULL;
3971 if (!a->header_shown) {
3972 printf("diff %s %s%s\n", a->id_str,
3973 got_worktree_get_root_path(a->worktree),
3974 a->diff_staged ? " (staged changes)" : "");
3975 a->header_shown = 1;
3978 if (a->diff_staged) {
3979 const char *label1 = NULL, *label2 = NULL;
3980 switch (staged_status) {
3981 case GOT_STATUS_MODIFY:
3982 label1 = path;
3983 label2 = path;
3984 break;
3985 case GOT_STATUS_ADD:
3986 label2 = path;
3987 break;
3988 case GOT_STATUS_DELETE:
3989 label1 = path;
3990 break;
3991 default:
3992 return got_error(GOT_ERR_FILE_STATUS);
3994 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3995 label1, label2, a->diff_context, a->ignore_whitespace,
3996 a->repo, stdout);
3999 if (staged_status == GOT_STATUS_ADD ||
4000 staged_status == GOT_STATUS_MODIFY) {
4001 char *id_str;
4002 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4003 8192);
4004 if (err)
4005 goto done;
4006 err = got_object_id_str(&id_str, staged_blob_id);
4007 if (err)
4008 goto done;
4009 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4010 err = got_error_from_errno("asprintf");
4011 free(id_str);
4012 goto done;
4014 free(id_str);
4015 } else if (status != GOT_STATUS_ADD) {
4016 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4017 if (err)
4018 goto done;
4021 if (status != GOT_STATUS_DELETE) {
4022 if (asprintf(&abspath, "%s/%s",
4023 got_worktree_get_root_path(a->worktree), path) == -1) {
4024 err = got_error_from_errno("asprintf");
4025 goto done;
4028 if (dirfd != -1) {
4029 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4030 if (fd == -1) {
4031 if (errno != ELOOP) {
4032 err = got_error_from_errno2("openat",
4033 abspath);
4034 goto done;
4036 err = get_symlink_target_file(&fd, dirfd,
4037 de_name, abspath);
4038 if (err)
4039 goto done;
4041 } else {
4042 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4043 if (fd == -1) {
4044 if (errno != ELOOP) {
4045 err = got_error_from_errno2("open",
4046 abspath);
4047 goto done;
4049 err = get_symlink_target_file(&fd, dirfd,
4050 de_name, abspath);
4051 if (err)
4052 goto done;
4055 if (fstat(fd, &sb) == -1) {
4056 err = got_error_from_errno2("fstat", abspath);
4057 goto done;
4059 f2 = fdopen(fd, "r");
4060 if (f2 == NULL) {
4061 err = got_error_from_errno2("fdopen", abspath);
4062 goto done;
4064 fd = -1;
4065 } else
4066 sb.st_size = 0;
4068 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4069 a->diff_context, a->ignore_whitespace, stdout);
4070 done:
4071 if (blob1)
4072 got_object_blob_close(blob1);
4073 if (f2 && fclose(f2) == EOF && err == NULL)
4074 err = got_error_from_errno("fclose");
4075 if (fd != -1 && close(fd) == -1 && err == NULL)
4076 err = got_error_from_errno("close");
4077 free(abspath);
4078 return err;
4081 static const struct got_error *
4082 cmd_diff(int argc, char *argv[])
4084 const struct got_error *error;
4085 struct got_repository *repo = NULL;
4086 struct got_worktree *worktree = NULL;
4087 char *cwd = NULL, *repo_path = NULL;
4088 struct got_object_id *id1 = NULL, *id2 = NULL;
4089 const char *id_str1 = NULL, *id_str2 = NULL;
4090 char *label1 = NULL, *label2 = NULL;
4091 int type1, type2;
4092 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4093 const char *errstr;
4094 char *path = NULL;
4096 #ifndef PROFILE
4097 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4098 NULL) == -1)
4099 err(1, "pledge");
4100 #endif
4102 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
4103 switch (ch) {
4104 case 'C':
4105 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4106 &errstr);
4107 if (errstr != NULL)
4108 err(1, "-C option %s", errstr);
4109 break;
4110 case 'r':
4111 repo_path = realpath(optarg, NULL);
4112 if (repo_path == NULL)
4113 return got_error_from_errno2("realpath",
4114 optarg);
4115 got_path_strip_trailing_slashes(repo_path);
4116 break;
4117 case 's':
4118 diff_staged = 1;
4119 break;
4120 case 'w':
4121 ignore_whitespace = 1;
4122 break;
4123 default:
4124 usage_diff();
4125 /* NOTREACHED */
4129 argc -= optind;
4130 argv += optind;
4132 cwd = getcwd(NULL, 0);
4133 if (cwd == NULL) {
4134 error = got_error_from_errno("getcwd");
4135 goto done;
4137 if (argc <= 1) {
4138 if (repo_path)
4139 errx(1,
4140 "-r option can't be used when diffing a work tree");
4141 error = got_worktree_open(&worktree, cwd);
4142 if (error) {
4143 if (error->code == GOT_ERR_NOT_WORKTREE)
4144 error = wrap_not_worktree_error(error, "diff",
4145 cwd);
4146 goto done;
4148 repo_path = strdup(got_worktree_get_repo_path(worktree));
4149 if (repo_path == NULL) {
4150 error = got_error_from_errno("strdup");
4151 goto done;
4153 if (argc == 1) {
4154 error = got_worktree_resolve_path(&path, worktree,
4155 argv[0]);
4156 if (error)
4157 goto done;
4158 } else {
4159 path = strdup("");
4160 if (path == NULL) {
4161 error = got_error_from_errno("strdup");
4162 goto done;
4165 } else if (argc == 2) {
4166 if (diff_staged)
4167 errx(1, "-s option can't be used when diffing "
4168 "objects in repository");
4169 id_str1 = argv[0];
4170 id_str2 = argv[1];
4171 if (repo_path == NULL) {
4172 error = got_worktree_open(&worktree, cwd);
4173 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4174 goto done;
4175 if (worktree) {
4176 repo_path = strdup(
4177 got_worktree_get_repo_path(worktree));
4178 if (repo_path == NULL) {
4179 error = got_error_from_errno("strdup");
4180 goto done;
4182 } else {
4183 repo_path = strdup(cwd);
4184 if (repo_path == NULL) {
4185 error = got_error_from_errno("strdup");
4186 goto done;
4190 } else
4191 usage_diff();
4193 error = got_repo_open(&repo, repo_path, NULL);
4194 free(repo_path);
4195 if (error != NULL)
4196 goto done;
4198 error = apply_unveil(got_repo_get_path(repo), 1,
4199 worktree ? got_worktree_get_root_path(worktree) : NULL);
4200 if (error)
4201 goto done;
4203 if (argc <= 1) {
4204 struct print_diff_arg arg;
4205 struct got_pathlist_head paths;
4206 char *id_str;
4208 TAILQ_INIT(&paths);
4210 error = got_object_id_str(&id_str,
4211 got_worktree_get_base_commit_id(worktree));
4212 if (error)
4213 goto done;
4214 arg.repo = repo;
4215 arg.worktree = worktree;
4216 arg.diff_context = diff_context;
4217 arg.id_str = id_str;
4218 arg.header_shown = 0;
4219 arg.diff_staged = diff_staged;
4220 arg.ignore_whitespace = ignore_whitespace;
4222 error = got_pathlist_append(&paths, path, NULL);
4223 if (error)
4224 goto done;
4226 error = got_worktree_status(worktree, &paths, repo, print_diff,
4227 &arg, check_cancelled, NULL);
4228 free(id_str);
4229 got_pathlist_free(&paths);
4230 goto done;
4233 error = got_repo_match_object_id(&id1, &label1, id_str1,
4234 GOT_OBJ_TYPE_ANY, 1, repo);
4235 if (error)
4236 goto done;
4238 error = got_repo_match_object_id(&id2, &label2, id_str2,
4239 GOT_OBJ_TYPE_ANY, 1, repo);
4240 if (error)
4241 goto done;
4243 error = got_object_get_type(&type1, repo, id1);
4244 if (error)
4245 goto done;
4247 error = got_object_get_type(&type2, repo, id2);
4248 if (error)
4249 goto done;
4251 if (type1 != type2) {
4252 error = got_error(GOT_ERR_OBJ_TYPE);
4253 goto done;
4256 switch (type1) {
4257 case GOT_OBJ_TYPE_BLOB:
4258 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4259 diff_context, ignore_whitespace, repo, stdout);
4260 break;
4261 case GOT_OBJ_TYPE_TREE:
4262 error = got_diff_objects_as_trees(id1, id2, "", "",
4263 diff_context, ignore_whitespace, repo, stdout);
4264 break;
4265 case GOT_OBJ_TYPE_COMMIT:
4266 printf("diff %s %s\n", label1, label2);
4267 error = got_diff_objects_as_commits(id1, id2, diff_context,
4268 ignore_whitespace, repo, stdout);
4269 break;
4270 default:
4271 error = got_error(GOT_ERR_OBJ_TYPE);
4273 done:
4274 free(label1);
4275 free(label2);
4276 free(id1);
4277 free(id2);
4278 free(path);
4279 if (worktree)
4280 got_worktree_close(worktree);
4281 if (repo) {
4282 const struct got_error *repo_error;
4283 repo_error = got_repo_close(repo);
4284 if (error == NULL)
4285 error = repo_error;
4287 return error;
4290 __dead static void
4291 usage_blame(void)
4293 fprintf(stderr,
4294 "usage: %s blame [-c commit] [-r repository-path] path\n",
4295 getprogname());
4296 exit(1);
4299 struct blame_line {
4300 int annotated;
4301 char *id_str;
4302 char *committer;
4303 char datebuf[11]; /* YYYY-MM-DD + NUL */
4306 struct blame_cb_args {
4307 struct blame_line *lines;
4308 int nlines;
4309 int nlines_prec;
4310 int lineno_cur;
4311 off_t *line_offsets;
4312 FILE *f;
4313 struct got_repository *repo;
4316 static const struct got_error *
4317 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4319 const struct got_error *err = NULL;
4320 struct blame_cb_args *a = arg;
4321 struct blame_line *bline;
4322 char *line = NULL;
4323 size_t linesize = 0;
4324 struct got_commit_object *commit = NULL;
4325 off_t offset;
4326 struct tm tm;
4327 time_t committer_time;
4329 if (nlines != a->nlines ||
4330 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4331 return got_error(GOT_ERR_RANGE);
4333 if (sigint_received)
4334 return got_error(GOT_ERR_ITER_COMPLETED);
4336 if (lineno == -1)
4337 return NULL; /* no change in this commit */
4339 /* Annotate this line. */
4340 bline = &a->lines[lineno - 1];
4341 if (bline->annotated)
4342 return NULL;
4343 err = got_object_id_str(&bline->id_str, id);
4344 if (err)
4345 return err;
4347 err = got_object_open_as_commit(&commit, a->repo, id);
4348 if (err)
4349 goto done;
4351 bline->committer = strdup(got_object_commit_get_committer(commit));
4352 if (bline->committer == NULL) {
4353 err = got_error_from_errno("strdup");
4354 goto done;
4357 committer_time = got_object_commit_get_committer_time(commit);
4358 if (localtime_r(&committer_time, &tm) == NULL)
4359 return got_error_from_errno("localtime_r");
4360 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4361 &tm) >= sizeof(bline->datebuf)) {
4362 err = got_error(GOT_ERR_NO_SPACE);
4363 goto done;
4365 bline->annotated = 1;
4367 /* Print lines annotated so far. */
4368 bline = &a->lines[a->lineno_cur - 1];
4369 if (!bline->annotated)
4370 goto done;
4372 offset = a->line_offsets[a->lineno_cur - 1];
4373 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4374 err = got_error_from_errno("fseeko");
4375 goto done;
4378 while (bline->annotated) {
4379 char *smallerthan, *at, *nl, *committer;
4380 size_t len;
4382 if (getline(&line, &linesize, a->f) == -1) {
4383 if (ferror(a->f))
4384 err = got_error_from_errno("getline");
4385 break;
4388 committer = bline->committer;
4389 smallerthan = strchr(committer, '<');
4390 if (smallerthan && smallerthan[1] != '\0')
4391 committer = smallerthan + 1;
4392 at = strchr(committer, '@');
4393 if (at)
4394 *at = '\0';
4395 len = strlen(committer);
4396 if (len >= 9)
4397 committer[8] = '\0';
4399 nl = strchr(line, '\n');
4400 if (nl)
4401 *nl = '\0';
4402 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4403 bline->id_str, bline->datebuf, committer, line);
4405 a->lineno_cur++;
4406 bline = &a->lines[a->lineno_cur - 1];
4408 done:
4409 if (commit)
4410 got_object_commit_close(commit);
4411 free(line);
4412 return err;
4415 static const struct got_error *
4416 cmd_blame(int argc, char *argv[])
4418 const struct got_error *error;
4419 struct got_repository *repo = NULL;
4420 struct got_worktree *worktree = NULL;
4421 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4422 char *link_target = NULL;
4423 struct got_object_id *obj_id = NULL;
4424 struct got_object_id *commit_id = NULL;
4425 struct got_blob_object *blob = NULL;
4426 char *commit_id_str = NULL;
4427 struct blame_cb_args bca;
4428 int ch, obj_type, i;
4429 size_t filesize;
4431 memset(&bca, 0, sizeof(bca));
4433 #ifndef PROFILE
4434 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4435 NULL) == -1)
4436 err(1, "pledge");
4437 #endif
4439 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4440 switch (ch) {
4441 case 'c':
4442 commit_id_str = optarg;
4443 break;
4444 case 'r':
4445 repo_path = realpath(optarg, NULL);
4446 if (repo_path == NULL)
4447 return got_error_from_errno2("realpath",
4448 optarg);
4449 got_path_strip_trailing_slashes(repo_path);
4450 break;
4451 default:
4452 usage_blame();
4453 /* NOTREACHED */
4457 argc -= optind;
4458 argv += optind;
4460 if (argc == 1)
4461 path = argv[0];
4462 else
4463 usage_blame();
4465 cwd = getcwd(NULL, 0);
4466 if (cwd == NULL) {
4467 error = got_error_from_errno("getcwd");
4468 goto done;
4470 if (repo_path == NULL) {
4471 error = got_worktree_open(&worktree, cwd);
4472 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4473 goto done;
4474 else
4475 error = NULL;
4476 if (worktree) {
4477 repo_path =
4478 strdup(got_worktree_get_repo_path(worktree));
4479 if (repo_path == NULL) {
4480 error = got_error_from_errno("strdup");
4481 if (error)
4482 goto done;
4484 } else {
4485 repo_path = strdup(cwd);
4486 if (repo_path == NULL) {
4487 error = got_error_from_errno("strdup");
4488 goto done;
4493 error = got_repo_open(&repo, repo_path, NULL);
4494 if (error != NULL)
4495 goto done;
4497 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4498 if (error)
4499 goto done;
4501 if (worktree) {
4502 const char *prefix = got_worktree_get_path_prefix(worktree);
4503 char *p, *worktree_subdir = cwd +
4504 strlen(got_worktree_get_root_path(worktree));
4505 if (asprintf(&p, "%s%s%s%s%s",
4506 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4507 worktree_subdir, worktree_subdir[0] ? "/" : "",
4508 path) == -1) {
4509 error = got_error_from_errno("asprintf");
4510 goto done;
4512 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4513 free(p);
4514 } else {
4515 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4517 if (error)
4518 goto done;
4520 if (commit_id_str == NULL) {
4521 struct got_reference *head_ref;
4522 error = got_ref_open(&head_ref, repo, worktree ?
4523 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4524 if (error != NULL)
4525 goto done;
4526 error = got_ref_resolve(&commit_id, repo, head_ref);
4527 got_ref_close(head_ref);
4528 if (error != NULL)
4529 goto done;
4530 } else {
4531 error = got_repo_match_object_id(&commit_id, NULL,
4532 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4533 if (error)
4534 goto done;
4537 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4538 commit_id, repo);
4539 if (error)
4540 goto done;
4542 error = got_object_id_by_path(&obj_id, repo, commit_id,
4543 link_target ? link_target : in_repo_path);
4544 if (error)
4545 goto done;
4547 error = got_object_get_type(&obj_type, repo, obj_id);
4548 if (error)
4549 goto done;
4551 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4552 error = got_error_path(link_target ? link_target : in_repo_path,
4553 GOT_ERR_OBJ_TYPE);
4554 goto done;
4557 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4558 if (error)
4559 goto done;
4560 bca.f = got_opentemp();
4561 if (bca.f == NULL) {
4562 error = got_error_from_errno("got_opentemp");
4563 goto done;
4565 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4566 &bca.line_offsets, bca.f, blob);
4567 if (error || bca.nlines == 0)
4568 goto done;
4570 /* Don't include \n at EOF in the blame line count. */
4571 if (bca.line_offsets[bca.nlines - 1] == filesize)
4572 bca.nlines--;
4574 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4575 if (bca.lines == NULL) {
4576 error = got_error_from_errno("calloc");
4577 goto done;
4579 bca.lineno_cur = 1;
4580 bca.nlines_prec = 0;
4581 i = bca.nlines;
4582 while (i > 0) {
4583 i /= 10;
4584 bca.nlines_prec++;
4586 bca.repo = repo;
4588 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4589 repo, blame_cb, &bca, check_cancelled, NULL);
4590 done:
4591 free(in_repo_path);
4592 free(link_target);
4593 free(repo_path);
4594 free(cwd);
4595 free(commit_id);
4596 free(obj_id);
4597 if (blob)
4598 got_object_blob_close(blob);
4599 if (worktree)
4600 got_worktree_close(worktree);
4601 if (repo) {
4602 const struct got_error *repo_error;
4603 repo_error = got_repo_close(repo);
4604 if (error == NULL)
4605 error = repo_error;
4607 if (bca.lines) {
4608 for (i = 0; i < bca.nlines; i++) {
4609 struct blame_line *bline = &bca.lines[i];
4610 free(bline->id_str);
4611 free(bline->committer);
4613 free(bca.lines);
4615 free(bca.line_offsets);
4616 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4617 error = got_error_from_errno("fclose");
4618 return error;
4621 __dead static void
4622 usage_tree(void)
4624 fprintf(stderr,
4625 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4626 getprogname());
4627 exit(1);
4630 static const struct got_error *
4631 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4632 const char *root_path, struct got_repository *repo)
4634 const struct got_error *err = NULL;
4635 int is_root_path = (strcmp(path, root_path) == 0);
4636 const char *modestr = "";
4637 mode_t mode = got_tree_entry_get_mode(te);
4638 char *link_target = NULL;
4640 path += strlen(root_path);
4641 while (path[0] == '/')
4642 path++;
4644 if (got_object_tree_entry_is_submodule(te))
4645 modestr = "$";
4646 else if (S_ISLNK(mode)) {
4647 int i;
4649 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4650 if (err)
4651 return err;
4652 for (i = 0; i < strlen(link_target); i++) {
4653 if (!isprint((unsigned char)link_target[i]))
4654 link_target[i] = '?';
4657 modestr = "@";
4659 else if (S_ISDIR(mode))
4660 modestr = "/";
4661 else if (mode & S_IXUSR)
4662 modestr = "*";
4664 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4665 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4666 link_target ? " -> ": "", link_target ? link_target : "");
4668 free(link_target);
4669 return NULL;
4672 static const struct got_error *
4673 print_tree(const char *path, struct got_object_id *commit_id,
4674 int show_ids, int recurse, const char *root_path,
4675 struct got_repository *repo)
4677 const struct got_error *err = NULL;
4678 struct got_object_id *tree_id = NULL;
4679 struct got_tree_object *tree = NULL;
4680 int nentries, i;
4682 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4683 if (err)
4684 goto done;
4686 err = got_object_open_as_tree(&tree, repo, tree_id);
4687 if (err)
4688 goto done;
4689 nentries = got_object_tree_get_nentries(tree);
4690 for (i = 0; i < nentries; i++) {
4691 struct got_tree_entry *te;
4692 char *id = NULL;
4694 if (sigint_received || sigpipe_received)
4695 break;
4697 te = got_object_tree_get_entry(tree, i);
4698 if (show_ids) {
4699 char *id_str;
4700 err = got_object_id_str(&id_str,
4701 got_tree_entry_get_id(te));
4702 if (err)
4703 goto done;
4704 if (asprintf(&id, "%s ", id_str) == -1) {
4705 err = got_error_from_errno("asprintf");
4706 free(id_str);
4707 goto done;
4709 free(id_str);
4711 err = print_entry(te, id, path, root_path, repo);
4712 free(id);
4713 if (err)
4714 goto done;
4716 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4717 char *child_path;
4718 if (asprintf(&child_path, "%s%s%s", path,
4719 path[0] == '/' && path[1] == '\0' ? "" : "/",
4720 got_tree_entry_get_name(te)) == -1) {
4721 err = got_error_from_errno("asprintf");
4722 goto done;
4724 err = print_tree(child_path, commit_id, show_ids, 1,
4725 root_path, repo);
4726 free(child_path);
4727 if (err)
4728 goto done;
4731 done:
4732 if (tree)
4733 got_object_tree_close(tree);
4734 free(tree_id);
4735 return err;
4738 static const struct got_error *
4739 cmd_tree(int argc, char *argv[])
4741 const struct got_error *error;
4742 struct got_repository *repo = NULL;
4743 struct got_worktree *worktree = NULL;
4744 const char *path, *refname = NULL;
4745 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4746 struct got_object_id *commit_id = NULL;
4747 char *commit_id_str = NULL;
4748 int show_ids = 0, recurse = 0;
4749 int ch;
4751 #ifndef PROFILE
4752 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4753 NULL) == -1)
4754 err(1, "pledge");
4755 #endif
4757 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4758 switch (ch) {
4759 case 'c':
4760 commit_id_str = optarg;
4761 break;
4762 case 'r':
4763 repo_path = realpath(optarg, NULL);
4764 if (repo_path == NULL)
4765 return got_error_from_errno2("realpath",
4766 optarg);
4767 got_path_strip_trailing_slashes(repo_path);
4768 break;
4769 case 'i':
4770 show_ids = 1;
4771 break;
4772 case 'R':
4773 recurse = 1;
4774 break;
4775 default:
4776 usage_tree();
4777 /* NOTREACHED */
4781 argc -= optind;
4782 argv += optind;
4784 if (argc == 1)
4785 path = argv[0];
4786 else if (argc > 1)
4787 usage_tree();
4788 else
4789 path = NULL;
4791 cwd = getcwd(NULL, 0);
4792 if (cwd == NULL) {
4793 error = got_error_from_errno("getcwd");
4794 goto done;
4796 if (repo_path == NULL) {
4797 error = got_worktree_open(&worktree, cwd);
4798 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4799 goto done;
4800 else
4801 error = NULL;
4802 if (worktree) {
4803 repo_path =
4804 strdup(got_worktree_get_repo_path(worktree));
4805 if (repo_path == NULL)
4806 error = got_error_from_errno("strdup");
4807 if (error)
4808 goto done;
4809 } else {
4810 repo_path = strdup(cwd);
4811 if (repo_path == NULL) {
4812 error = got_error_from_errno("strdup");
4813 goto done;
4818 error = got_repo_open(&repo, repo_path, NULL);
4819 if (error != NULL)
4820 goto done;
4822 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4823 if (error)
4824 goto done;
4826 if (path == NULL) {
4827 if (worktree) {
4828 char *p, *worktree_subdir = cwd +
4829 strlen(got_worktree_get_root_path(worktree));
4830 if (asprintf(&p, "%s/%s",
4831 got_worktree_get_path_prefix(worktree),
4832 worktree_subdir) == -1) {
4833 error = got_error_from_errno("asprintf");
4834 goto done;
4836 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4837 free(p);
4838 if (error)
4839 goto done;
4840 } else
4841 path = "/";
4843 if (in_repo_path == NULL) {
4844 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4845 if (error != NULL)
4846 goto done;
4849 if (commit_id_str == NULL) {
4850 struct got_reference *head_ref;
4851 if (worktree)
4852 refname = got_worktree_get_head_ref_name(worktree);
4853 else
4854 refname = GOT_REF_HEAD;
4855 error = got_ref_open(&head_ref, repo, refname, 0);
4856 if (error != NULL)
4857 goto done;
4858 error = got_ref_resolve(&commit_id, repo, head_ref);
4859 got_ref_close(head_ref);
4860 if (error != NULL)
4861 goto done;
4862 } else {
4863 error = got_repo_match_object_id(&commit_id, NULL,
4864 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4865 if (error)
4866 goto done;
4869 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4870 in_repo_path, repo);
4871 done:
4872 free(in_repo_path);
4873 free(repo_path);
4874 free(cwd);
4875 free(commit_id);
4876 if (worktree)
4877 got_worktree_close(worktree);
4878 if (repo) {
4879 const struct got_error *repo_error;
4880 repo_error = got_repo_close(repo);
4881 if (error == NULL)
4882 error = repo_error;
4884 return error;
4887 __dead static void
4888 usage_status(void)
4890 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4891 getprogname());
4892 exit(1);
4895 static const struct got_error *
4896 print_status(void *arg, unsigned char status, unsigned char staged_status,
4897 const char *path, struct got_object_id *blob_id,
4898 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4899 int dirfd, const char *de_name)
4901 if (status == staged_status && (status == GOT_STATUS_DELETE))
4902 status = GOT_STATUS_NO_CHANGE;
4903 if (arg) {
4904 char *status_codes = arg;
4905 size_t ncodes = strlen(status_codes);
4906 int i;
4907 for (i = 0; i < ncodes ; i++) {
4908 if (status == status_codes[i] ||
4909 staged_status == status_codes[i])
4910 break;
4912 if (i == ncodes)
4913 return NULL;
4915 printf("%c%c %s\n", status, staged_status, path);
4916 return NULL;
4919 static const struct got_error *
4920 cmd_status(int argc, char *argv[])
4922 const struct got_error *error = NULL;
4923 struct got_repository *repo = NULL;
4924 struct got_worktree *worktree = NULL;
4925 char *cwd = NULL, *status_codes = NULL;;
4926 struct got_pathlist_head paths;
4927 struct got_pathlist_entry *pe;
4928 int ch, i;
4930 TAILQ_INIT(&paths);
4932 while ((ch = getopt(argc, argv, "s:")) != -1) {
4933 switch (ch) {
4934 case 's':
4935 for (i = 0; i < strlen(optarg); i++) {
4936 switch (optarg[i]) {
4937 case GOT_STATUS_MODIFY:
4938 case GOT_STATUS_ADD:
4939 case GOT_STATUS_DELETE:
4940 case GOT_STATUS_CONFLICT:
4941 case GOT_STATUS_MISSING:
4942 case GOT_STATUS_OBSTRUCTED:
4943 case GOT_STATUS_UNVERSIONED:
4944 case GOT_STATUS_MODE_CHANGE:
4945 case GOT_STATUS_NONEXISTENT:
4946 break;
4947 default:
4948 errx(1, "invalid status code '%c'",
4949 optarg[i]);
4952 status_codes = optarg;
4953 break;
4954 default:
4955 usage_status();
4956 /* NOTREACHED */
4960 argc -= optind;
4961 argv += optind;
4963 #ifndef PROFILE
4964 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4965 NULL) == -1)
4966 err(1, "pledge");
4967 #endif
4968 cwd = getcwd(NULL, 0);
4969 if (cwd == NULL) {
4970 error = got_error_from_errno("getcwd");
4971 goto done;
4974 error = got_worktree_open(&worktree, cwd);
4975 if (error) {
4976 if (error->code == GOT_ERR_NOT_WORKTREE)
4977 error = wrap_not_worktree_error(error, "status", cwd);
4978 goto done;
4981 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4982 NULL);
4983 if (error != NULL)
4984 goto done;
4986 error = apply_unveil(got_repo_get_path(repo), 1,
4987 got_worktree_get_root_path(worktree));
4988 if (error)
4989 goto done;
4991 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4992 if (error)
4993 goto done;
4995 error = got_worktree_status(worktree, &paths, repo, print_status,
4996 status_codes, check_cancelled, NULL);
4997 done:
4998 TAILQ_FOREACH(pe, &paths, entry)
4999 free((char *)pe->path);
5000 got_pathlist_free(&paths);
5001 free(cwd);
5002 return error;
5005 __dead static void
5006 usage_ref(void)
5008 fprintf(stderr,
5009 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5010 "[-d] [name]\n",
5011 getprogname());
5012 exit(1);
5015 static const struct got_error *
5016 list_refs(struct got_repository *repo, const char *refname)
5018 static const struct got_error *err = NULL;
5019 struct got_reflist_head refs;
5020 struct got_reflist_entry *re;
5022 SIMPLEQ_INIT(&refs);
5023 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5024 if (err)
5025 return err;
5027 SIMPLEQ_FOREACH(re, &refs, entry) {
5028 char *refstr;
5029 refstr = got_ref_to_str(re->ref);
5030 if (refstr == NULL)
5031 return got_error_from_errno("got_ref_to_str");
5032 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5033 free(refstr);
5036 got_ref_list_free(&refs);
5037 return NULL;
5040 static const struct got_error *
5041 delete_ref(struct got_repository *repo, const char *refname)
5043 const struct got_error *err = NULL;
5044 struct got_reference *ref;
5046 err = got_ref_open(&ref, repo, refname, 0);
5047 if (err)
5048 return err;
5050 err = got_ref_delete(ref, repo);
5051 got_ref_close(ref);
5052 return err;
5055 static const struct got_error *
5056 add_ref(struct got_repository *repo, const char *refname, const char *target)
5058 const struct got_error *err = NULL;
5059 struct got_object_id *id;
5060 struct got_reference *ref = NULL;
5063 * Don't let the user create a reference name with a leading '-'.
5064 * While technically a valid reference name, this case is usually
5065 * an unintended typo.
5067 if (refname[0] == '-')
5068 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5070 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5071 repo);
5072 if (err) {
5073 struct got_reference *target_ref;
5075 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5076 return err;
5077 err = got_ref_open(&target_ref, repo, target, 0);
5078 if (err)
5079 return err;
5080 err = got_ref_resolve(&id, repo, target_ref);
5081 got_ref_close(target_ref);
5082 if (err)
5083 return err;
5086 err = got_ref_alloc(&ref, refname, id);
5087 if (err)
5088 goto done;
5090 err = got_ref_write(ref, repo);
5091 done:
5092 if (ref)
5093 got_ref_close(ref);
5094 free(id);
5095 return err;
5098 static const struct got_error *
5099 add_symref(struct got_repository *repo, const char *refname, const char *target)
5101 const struct got_error *err = NULL;
5102 struct got_reference *ref = NULL;
5103 struct got_reference *target_ref = NULL;
5106 * Don't let the user create a reference name with a leading '-'.
5107 * While technically a valid reference name, this case is usually
5108 * an unintended typo.
5110 if (refname[0] == '-')
5111 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5113 err = got_ref_open(&target_ref, repo, target, 0);
5114 if (err)
5115 return err;
5117 err = got_ref_alloc_symref(&ref, refname, target_ref);
5118 if (err)
5119 goto done;
5121 err = got_ref_write(ref, repo);
5122 done:
5123 if (target_ref)
5124 got_ref_close(target_ref);
5125 if (ref)
5126 got_ref_close(ref);
5127 return err;
5130 static const struct got_error *
5131 cmd_ref(int argc, char *argv[])
5133 const struct got_error *error = NULL;
5134 struct got_repository *repo = NULL;
5135 struct got_worktree *worktree = NULL;
5136 char *cwd = NULL, *repo_path = NULL;
5137 int ch, do_list = 0, do_delete = 0;
5138 const char *obj_arg = NULL, *symref_target= NULL;
5139 char *refname = NULL;
5141 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5142 switch (ch) {
5143 case 'c':
5144 obj_arg = optarg;
5145 break;
5146 case 'd':
5147 do_delete = 1;
5148 break;
5149 case 'r':
5150 repo_path = realpath(optarg, NULL);
5151 if (repo_path == NULL)
5152 return got_error_from_errno2("realpath",
5153 optarg);
5154 got_path_strip_trailing_slashes(repo_path);
5155 break;
5156 case 'l':
5157 do_list = 1;
5158 break;
5159 case 's':
5160 symref_target = optarg;
5161 break;
5162 default:
5163 usage_ref();
5164 /* NOTREACHED */
5168 if (obj_arg && do_list)
5169 errx(1, "-c and -l options are mutually exclusive");
5170 if (obj_arg && do_delete)
5171 errx(1, "-c and -d options are mutually exclusive");
5172 if (obj_arg && symref_target)
5173 errx(1, "-c and -s options are mutually exclusive");
5174 if (symref_target && do_delete)
5175 errx(1, "-s and -d options are mutually exclusive");
5176 if (symref_target && do_list)
5177 errx(1, "-s and -l options are mutually exclusive");
5178 if (do_delete && do_list)
5179 errx(1, "-d and -l options are mutually exclusive");
5181 argc -= optind;
5182 argv += optind;
5184 if (do_list) {
5185 if (argc != 0 && argc != 1)
5186 usage_ref();
5187 if (argc == 1) {
5188 refname = strdup(argv[0]);
5189 if (refname == NULL) {
5190 error = got_error_from_errno("strdup");
5191 goto done;
5194 } else {
5195 if (argc != 1)
5196 usage_ref();
5197 refname = strdup(argv[0]);
5198 if (refname == NULL) {
5199 error = got_error_from_errno("strdup");
5200 goto done;
5204 if (refname)
5205 got_path_strip_trailing_slashes(refname);
5207 #ifndef PROFILE
5208 if (do_list) {
5209 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5210 NULL) == -1)
5211 err(1, "pledge");
5212 } else {
5213 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5214 "sendfd unveil", NULL) == -1)
5215 err(1, "pledge");
5217 #endif
5218 cwd = getcwd(NULL, 0);
5219 if (cwd == NULL) {
5220 error = got_error_from_errno("getcwd");
5221 goto done;
5224 if (repo_path == NULL) {
5225 error = got_worktree_open(&worktree, cwd);
5226 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5227 goto done;
5228 else
5229 error = NULL;
5230 if (worktree) {
5231 repo_path =
5232 strdup(got_worktree_get_repo_path(worktree));
5233 if (repo_path == NULL)
5234 error = got_error_from_errno("strdup");
5235 if (error)
5236 goto done;
5237 } else {
5238 repo_path = strdup(cwd);
5239 if (repo_path == NULL) {
5240 error = got_error_from_errno("strdup");
5241 goto done;
5246 error = got_repo_open(&repo, repo_path, NULL);
5247 if (error != NULL)
5248 goto done;
5250 error = apply_unveil(got_repo_get_path(repo), do_list,
5251 worktree ? got_worktree_get_root_path(worktree) : NULL);
5252 if (error)
5253 goto done;
5255 if (do_list)
5256 error = list_refs(repo, refname);
5257 else if (do_delete)
5258 error = delete_ref(repo, refname);
5259 else if (symref_target)
5260 error = add_symref(repo, refname, symref_target);
5261 else {
5262 if (obj_arg == NULL)
5263 usage_ref();
5264 error = add_ref(repo, refname, obj_arg);
5266 done:
5267 free(refname);
5268 if (repo)
5269 got_repo_close(repo);
5270 if (worktree)
5271 got_worktree_close(worktree);
5272 free(cwd);
5273 free(repo_path);
5274 return error;
5277 __dead static void
5278 usage_branch(void)
5280 fprintf(stderr,
5281 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5282 "[name]\n", getprogname());
5283 exit(1);
5286 static const struct got_error *
5287 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5288 struct got_reference *ref)
5290 const struct got_error *err = NULL;
5291 const char *refname, *marker = " ";
5292 char *refstr;
5294 refname = got_ref_get_name(ref);
5295 if (worktree && strcmp(refname,
5296 got_worktree_get_head_ref_name(worktree)) == 0) {
5297 struct got_object_id *id = NULL;
5299 err = got_ref_resolve(&id, repo, ref);
5300 if (err)
5301 return err;
5302 if (got_object_id_cmp(id,
5303 got_worktree_get_base_commit_id(worktree)) == 0)
5304 marker = "* ";
5305 else
5306 marker = "~ ";
5307 free(id);
5310 if (strncmp(refname, "refs/heads/", 11) == 0)
5311 refname += 11;
5312 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5313 refname += 18;
5315 refstr = got_ref_to_str(ref);
5316 if (refstr == NULL)
5317 return got_error_from_errno("got_ref_to_str");
5319 printf("%s%s: %s\n", marker, refname, refstr);
5320 free(refstr);
5321 return NULL;
5324 static const struct got_error *
5325 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5327 const char *refname;
5329 if (worktree == NULL)
5330 return got_error(GOT_ERR_NOT_WORKTREE);
5332 refname = got_worktree_get_head_ref_name(worktree);
5334 if (strncmp(refname, "refs/heads/", 11) == 0)
5335 refname += 11;
5336 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5337 refname += 18;
5339 printf("%s\n", refname);
5341 return NULL;
5344 static const struct got_error *
5345 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5347 static const struct got_error *err = NULL;
5348 struct got_reflist_head refs;
5349 struct got_reflist_entry *re;
5350 struct got_reference *temp_ref = NULL;
5351 int rebase_in_progress, histedit_in_progress;
5353 SIMPLEQ_INIT(&refs);
5355 if (worktree) {
5356 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5357 worktree);
5358 if (err)
5359 return err;
5361 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5362 worktree);
5363 if (err)
5364 return err;
5366 if (rebase_in_progress || histedit_in_progress) {
5367 err = got_ref_open(&temp_ref, repo,
5368 got_worktree_get_head_ref_name(worktree), 0);
5369 if (err)
5370 return err;
5371 list_branch(repo, worktree, temp_ref);
5372 got_ref_close(temp_ref);
5376 err = got_ref_list(&refs, repo, "refs/heads",
5377 got_ref_cmp_by_name, NULL);
5378 if (err)
5379 return err;
5381 SIMPLEQ_FOREACH(re, &refs, entry)
5382 list_branch(repo, worktree, re->ref);
5384 got_ref_list_free(&refs);
5385 return NULL;
5388 static const struct got_error *
5389 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5390 const char *branch_name)
5392 const struct got_error *err = NULL;
5393 struct got_reference *ref = NULL;
5394 char *refname;
5396 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5397 return got_error_from_errno("asprintf");
5399 err = got_ref_open(&ref, repo, refname, 0);
5400 if (err)
5401 goto done;
5403 if (worktree &&
5404 strcmp(got_worktree_get_head_ref_name(worktree),
5405 got_ref_get_name(ref)) == 0) {
5406 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5407 "will not delete this work tree's current branch");
5408 goto done;
5411 err = got_ref_delete(ref, repo);
5412 done:
5413 if (ref)
5414 got_ref_close(ref);
5415 free(refname);
5416 return err;
5419 static const struct got_error *
5420 add_branch(struct got_repository *repo, const char *branch_name,
5421 struct got_object_id *base_commit_id)
5423 const struct got_error *err = NULL;
5424 struct got_reference *ref = NULL;
5425 char *base_refname = NULL, *refname = NULL;
5428 * Don't let the user create a branch name with a leading '-'.
5429 * While technically a valid reference name, this case is usually
5430 * an unintended typo.
5432 if (branch_name[0] == '-')
5433 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5435 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5436 err = got_error_from_errno("asprintf");
5437 goto done;
5440 err = got_ref_open(&ref, repo, refname, 0);
5441 if (err == NULL) {
5442 err = got_error(GOT_ERR_BRANCH_EXISTS);
5443 goto done;
5444 } else if (err->code != GOT_ERR_NOT_REF)
5445 goto done;
5447 err = got_ref_alloc(&ref, refname, base_commit_id);
5448 if (err)
5449 goto done;
5451 err = got_ref_write(ref, repo);
5452 done:
5453 if (ref)
5454 got_ref_close(ref);
5455 free(base_refname);
5456 free(refname);
5457 return err;
5460 static const struct got_error *
5461 cmd_branch(int argc, char *argv[])
5463 const struct got_error *error = NULL;
5464 struct got_repository *repo = NULL;
5465 struct got_worktree *worktree = NULL;
5466 char *cwd = NULL, *repo_path = NULL;
5467 int ch, do_list = 0, do_show = 0, do_update = 1;
5468 const char *delref = NULL, *commit_id_arg = NULL;
5469 struct got_reference *ref = NULL;
5470 struct got_pathlist_head paths;
5471 struct got_pathlist_entry *pe;
5472 struct got_object_id *commit_id = NULL;
5473 char *commit_id_str = NULL;
5475 TAILQ_INIT(&paths);
5477 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5478 switch (ch) {
5479 case 'c':
5480 commit_id_arg = optarg;
5481 break;
5482 case 'd':
5483 delref = optarg;
5484 break;
5485 case 'r':
5486 repo_path = realpath(optarg, NULL);
5487 if (repo_path == NULL)
5488 return got_error_from_errno2("realpath",
5489 optarg);
5490 got_path_strip_trailing_slashes(repo_path);
5491 break;
5492 case 'l':
5493 do_list = 1;
5494 break;
5495 case 'n':
5496 do_update = 0;
5497 break;
5498 default:
5499 usage_branch();
5500 /* NOTREACHED */
5504 if (do_list && delref)
5505 errx(1, "-l and -d options are mutually exclusive");
5507 argc -= optind;
5508 argv += optind;
5510 if (!do_list && !delref && argc == 0)
5511 do_show = 1;
5513 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5514 errx(1, "-c option can only be used when creating a branch");
5516 if (do_list || delref) {
5517 if (argc > 0)
5518 usage_branch();
5519 } else if (!do_show && argc != 1)
5520 usage_branch();
5522 #ifndef PROFILE
5523 if (do_list || do_show) {
5524 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5525 NULL) == -1)
5526 err(1, "pledge");
5527 } else {
5528 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5529 "sendfd unveil", NULL) == -1)
5530 err(1, "pledge");
5532 #endif
5533 cwd = getcwd(NULL, 0);
5534 if (cwd == NULL) {
5535 error = got_error_from_errno("getcwd");
5536 goto done;
5539 if (repo_path == NULL) {
5540 error = got_worktree_open(&worktree, cwd);
5541 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5542 goto done;
5543 else
5544 error = NULL;
5545 if (worktree) {
5546 repo_path =
5547 strdup(got_worktree_get_repo_path(worktree));
5548 if (repo_path == NULL)
5549 error = got_error_from_errno("strdup");
5550 if (error)
5551 goto done;
5552 } else {
5553 repo_path = strdup(cwd);
5554 if (repo_path == NULL) {
5555 error = got_error_from_errno("strdup");
5556 goto done;
5561 error = got_repo_open(&repo, repo_path, NULL);
5562 if (error != NULL)
5563 goto done;
5565 error = apply_unveil(got_repo_get_path(repo), do_list,
5566 worktree ? got_worktree_get_root_path(worktree) : NULL);
5567 if (error)
5568 goto done;
5570 if (do_show)
5571 error = show_current_branch(repo, worktree);
5572 else if (do_list)
5573 error = list_branches(repo, worktree);
5574 else if (delref)
5575 error = delete_branch(repo, worktree, delref);
5576 else {
5577 if (commit_id_arg == NULL)
5578 commit_id_arg = worktree ?
5579 got_worktree_get_head_ref_name(worktree) :
5580 GOT_REF_HEAD;
5581 error = got_repo_match_object_id(&commit_id, NULL,
5582 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5583 if (error)
5584 goto done;
5585 error = add_branch(repo, argv[0], commit_id);
5586 if (error)
5587 goto done;
5588 if (worktree && do_update) {
5589 struct got_update_progress_arg upa;
5590 char *branch_refname = NULL;
5592 error = got_object_id_str(&commit_id_str, commit_id);
5593 if (error)
5594 goto done;
5595 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5596 worktree);
5597 if (error)
5598 goto done;
5599 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5600 == -1) {
5601 error = got_error_from_errno("asprintf");
5602 goto done;
5604 error = got_ref_open(&ref, repo, branch_refname, 0);
5605 free(branch_refname);
5606 if (error)
5607 goto done;
5608 error = switch_head_ref(ref, commit_id, worktree,
5609 repo);
5610 if (error)
5611 goto done;
5612 error = got_worktree_set_base_commit_id(worktree, repo,
5613 commit_id);
5614 if (error)
5615 goto done;
5616 memset(&upa, 0, sizeof(upa));
5617 error = got_worktree_checkout_files(worktree, &paths,
5618 repo, update_progress, &upa, check_cancelled,
5619 NULL);
5620 if (error)
5621 goto done;
5622 if (upa.did_something)
5623 printf("Updated to commit %s\n", commit_id_str);
5624 print_update_progress_stats(&upa);
5627 done:
5628 if (ref)
5629 got_ref_close(ref);
5630 if (repo)
5631 got_repo_close(repo);
5632 if (worktree)
5633 got_worktree_close(worktree);
5634 free(cwd);
5635 free(repo_path);
5636 free(commit_id);
5637 free(commit_id_str);
5638 TAILQ_FOREACH(pe, &paths, entry)
5639 free((char *)pe->path);
5640 got_pathlist_free(&paths);
5641 return error;
5645 __dead static void
5646 usage_tag(void)
5648 fprintf(stderr,
5649 "usage: %s tag [-c commit] [-r repository] [-l] "
5650 "[-m message] name\n", getprogname());
5651 exit(1);
5654 #if 0
5655 static const struct got_error *
5656 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5658 const struct got_error *err = NULL;
5659 struct got_reflist_entry *re, *se, *new;
5660 struct got_object_id *re_id, *se_id;
5661 struct got_tag_object *re_tag, *se_tag;
5662 time_t re_time, se_time;
5664 SIMPLEQ_FOREACH(re, tags, entry) {
5665 se = SIMPLEQ_FIRST(sorted);
5666 if (se == NULL) {
5667 err = got_reflist_entry_dup(&new, re);
5668 if (err)
5669 return err;
5670 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5671 continue;
5672 } else {
5673 err = got_ref_resolve(&re_id, repo, re->ref);
5674 if (err)
5675 break;
5676 err = got_object_open_as_tag(&re_tag, repo, re_id);
5677 free(re_id);
5678 if (err)
5679 break;
5680 re_time = got_object_tag_get_tagger_time(re_tag);
5681 got_object_tag_close(re_tag);
5684 while (se) {
5685 err = got_ref_resolve(&se_id, repo, re->ref);
5686 if (err)
5687 break;
5688 err = got_object_open_as_tag(&se_tag, repo, se_id);
5689 free(se_id);
5690 if (err)
5691 break;
5692 se_time = got_object_tag_get_tagger_time(se_tag);
5693 got_object_tag_close(se_tag);
5695 if (se_time > re_time) {
5696 err = got_reflist_entry_dup(&new, re);
5697 if (err)
5698 return err;
5699 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5700 break;
5702 se = SIMPLEQ_NEXT(se, entry);
5703 continue;
5706 done:
5707 return err;
5709 #endif
5711 static const struct got_error *
5712 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5714 static const struct got_error *err = NULL;
5715 struct got_reflist_head refs;
5716 struct got_reflist_entry *re;
5718 SIMPLEQ_INIT(&refs);
5720 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5721 if (err)
5722 return err;
5724 SIMPLEQ_FOREACH(re, &refs, entry) {
5725 const char *refname;
5726 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5727 char datebuf[26];
5728 const char *tagger;
5729 time_t tagger_time;
5730 struct got_object_id *id;
5731 struct got_tag_object *tag;
5732 struct got_commit_object *commit = NULL;
5734 refname = got_ref_get_name(re->ref);
5735 if (strncmp(refname, "refs/tags/", 10) != 0)
5736 continue;
5737 refname += 10;
5738 refstr = got_ref_to_str(re->ref);
5739 if (refstr == NULL) {
5740 err = got_error_from_errno("got_ref_to_str");
5741 break;
5743 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5744 free(refstr);
5746 err = got_ref_resolve(&id, repo, re->ref);
5747 if (err)
5748 break;
5749 err = got_object_open_as_tag(&tag, repo, id);
5750 if (err) {
5751 if (err->code != GOT_ERR_OBJ_TYPE) {
5752 free(id);
5753 break;
5755 /* "lightweight" tag */
5756 err = got_object_open_as_commit(&commit, repo, id);
5757 if (err) {
5758 free(id);
5759 break;
5761 tagger = got_object_commit_get_committer(commit);
5762 tagger_time =
5763 got_object_commit_get_committer_time(commit);
5764 err = got_object_id_str(&id_str, id);
5765 free(id);
5766 if (err)
5767 break;
5768 } else {
5769 free(id);
5770 tagger = got_object_tag_get_tagger(tag);
5771 tagger_time = got_object_tag_get_tagger_time(tag);
5772 err = got_object_id_str(&id_str,
5773 got_object_tag_get_object_id(tag));
5774 if (err)
5775 break;
5777 printf("from: %s\n", tagger);
5778 datestr = get_datestr(&tagger_time, datebuf);
5779 if (datestr)
5780 printf("date: %s UTC\n", datestr);
5781 if (commit)
5782 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5783 else {
5784 switch (got_object_tag_get_object_type(tag)) {
5785 case GOT_OBJ_TYPE_BLOB:
5786 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5787 id_str);
5788 break;
5789 case GOT_OBJ_TYPE_TREE:
5790 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5791 id_str);
5792 break;
5793 case GOT_OBJ_TYPE_COMMIT:
5794 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5795 id_str);
5796 break;
5797 case GOT_OBJ_TYPE_TAG:
5798 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5799 id_str);
5800 break;
5801 default:
5802 break;
5805 free(id_str);
5806 if (commit) {
5807 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5808 if (err)
5809 break;
5810 got_object_commit_close(commit);
5811 } else {
5812 tagmsg0 = strdup(got_object_tag_get_message(tag));
5813 got_object_tag_close(tag);
5814 if (tagmsg0 == NULL) {
5815 err = got_error_from_errno("strdup");
5816 break;
5820 tagmsg = tagmsg0;
5821 do {
5822 line = strsep(&tagmsg, "\n");
5823 if (line)
5824 printf(" %s\n", line);
5825 } while (line);
5826 free(tagmsg0);
5829 got_ref_list_free(&refs);
5830 return NULL;
5833 static const struct got_error *
5834 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5835 const char *tag_name, const char *repo_path)
5837 const struct got_error *err = NULL;
5838 char *template = NULL, *initial_content = NULL;
5839 char *editor = NULL;
5840 int initial_content_len;
5841 int fd = -1;
5843 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5844 err = got_error_from_errno("asprintf");
5845 goto done;
5848 initial_content_len = asprintf(&initial_content,
5849 "\n# tagging commit %s as %s\n",
5850 commit_id_str, tag_name);
5851 if (initial_content_len == -1) {
5852 err = got_error_from_errno("asprintf");
5853 goto done;
5856 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5857 if (err)
5858 goto done;
5860 if (write(fd, initial_content, initial_content_len) == -1) {
5861 err = got_error_from_errno2("write", *tagmsg_path);
5862 goto done;
5865 err = get_editor(&editor);
5866 if (err)
5867 goto done;
5868 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5869 done:
5870 free(initial_content);
5871 free(template);
5872 free(editor);
5874 if (fd != -1 && close(fd) == -1 && err == NULL)
5875 err = got_error_from_errno2("close", *tagmsg_path);
5877 /* Editor is done; we can now apply unveil(2) */
5878 if (err == NULL)
5879 err = apply_unveil(repo_path, 0, NULL);
5880 if (err) {
5881 free(*tagmsg);
5882 *tagmsg = NULL;
5884 return err;
5887 static const struct got_error *
5888 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5889 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5891 const struct got_error *err = NULL;
5892 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5893 char *label = NULL, *commit_id_str = NULL;
5894 struct got_reference *ref = NULL;
5895 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5896 char *tagmsg_path = NULL, *tag_id_str = NULL;
5897 int preserve_tagmsg = 0;
5900 * Don't let the user create a tag name with a leading '-'.
5901 * While technically a valid reference name, this case is usually
5902 * an unintended typo.
5904 if (tag_name[0] == '-')
5905 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5907 err = get_author(&tagger, repo, worktree);
5908 if (err)
5909 return err;
5911 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5912 GOT_OBJ_TYPE_COMMIT, 1, repo);
5913 if (err)
5914 goto done;
5916 err = got_object_id_str(&commit_id_str, commit_id);
5917 if (err)
5918 goto done;
5920 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5921 refname = strdup(tag_name);
5922 if (refname == NULL) {
5923 err = got_error_from_errno("strdup");
5924 goto done;
5926 tag_name += 10;
5927 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5928 err = got_error_from_errno("asprintf");
5929 goto done;
5932 err = got_ref_open(&ref, repo, refname, 0);
5933 if (err == NULL) {
5934 err = got_error(GOT_ERR_TAG_EXISTS);
5935 goto done;
5936 } else if (err->code != GOT_ERR_NOT_REF)
5937 goto done;
5939 if (tagmsg_arg == NULL) {
5940 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5941 tag_name, got_repo_get_path(repo));
5942 if (err) {
5943 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5944 tagmsg_path != NULL)
5945 preserve_tagmsg = 1;
5946 goto done;
5950 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5951 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5952 if (err) {
5953 if (tagmsg_path)
5954 preserve_tagmsg = 1;
5955 goto done;
5958 err = got_ref_alloc(&ref, refname, tag_id);
5959 if (err) {
5960 if (tagmsg_path)
5961 preserve_tagmsg = 1;
5962 goto done;
5965 err = got_ref_write(ref, repo);
5966 if (err) {
5967 if (tagmsg_path)
5968 preserve_tagmsg = 1;
5969 goto done;
5972 err = got_object_id_str(&tag_id_str, tag_id);
5973 if (err) {
5974 if (tagmsg_path)
5975 preserve_tagmsg = 1;
5976 goto done;
5978 printf("Created tag %s\n", tag_id_str);
5979 done:
5980 if (preserve_tagmsg) {
5981 fprintf(stderr, "%s: tag message preserved in %s\n",
5982 getprogname(), tagmsg_path);
5983 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5984 err = got_error_from_errno2("unlink", tagmsg_path);
5985 free(tag_id_str);
5986 if (ref)
5987 got_ref_close(ref);
5988 free(commit_id);
5989 free(commit_id_str);
5990 free(refname);
5991 free(tagmsg);
5992 free(tagmsg_path);
5993 free(tagger);
5994 return err;
5997 static const struct got_error *
5998 cmd_tag(int argc, char *argv[])
6000 const struct got_error *error = NULL;
6001 struct got_repository *repo = NULL;
6002 struct got_worktree *worktree = NULL;
6003 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6004 char *gitconfig_path = NULL;
6005 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6006 int ch, do_list = 0;
6008 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6009 switch (ch) {
6010 case 'c':
6011 commit_id_arg = optarg;
6012 break;
6013 case 'm':
6014 tagmsg = optarg;
6015 break;
6016 case 'r':
6017 repo_path = realpath(optarg, NULL);
6018 if (repo_path == NULL)
6019 return got_error_from_errno2("realpath",
6020 optarg);
6021 got_path_strip_trailing_slashes(repo_path);
6022 break;
6023 case 'l':
6024 do_list = 1;
6025 break;
6026 default:
6027 usage_tag();
6028 /* NOTREACHED */
6032 argc -= optind;
6033 argv += optind;
6035 if (do_list) {
6036 if (commit_id_arg != NULL)
6037 errx(1,
6038 "-c option can only be used when creating a tag");
6039 if (tagmsg)
6040 errx(1, "-l and -m options are mutually exclusive");
6041 if (argc > 0)
6042 usage_tag();
6043 } else if (argc != 1)
6044 usage_tag();
6046 tag_name = argv[0];
6048 #ifndef PROFILE
6049 if (do_list) {
6050 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6051 NULL) == -1)
6052 err(1, "pledge");
6053 } else {
6054 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6055 "sendfd unveil", NULL) == -1)
6056 err(1, "pledge");
6058 #endif
6059 cwd = getcwd(NULL, 0);
6060 if (cwd == NULL) {
6061 error = got_error_from_errno("getcwd");
6062 goto done;
6065 if (repo_path == NULL) {
6066 error = got_worktree_open(&worktree, cwd);
6067 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6068 goto done;
6069 else
6070 error = NULL;
6071 if (worktree) {
6072 repo_path =
6073 strdup(got_worktree_get_repo_path(worktree));
6074 if (repo_path == NULL)
6075 error = got_error_from_errno("strdup");
6076 if (error)
6077 goto done;
6078 } else {
6079 repo_path = strdup(cwd);
6080 if (repo_path == NULL) {
6081 error = got_error_from_errno("strdup");
6082 goto done;
6087 if (do_list) {
6088 error = got_repo_open(&repo, repo_path, NULL);
6089 if (error != NULL)
6090 goto done;
6091 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6092 if (error)
6093 goto done;
6094 error = list_tags(repo, worktree);
6095 } else {
6096 error = get_gitconfig_path(&gitconfig_path);
6097 if (error)
6098 goto done;
6099 error = got_repo_open(&repo, repo_path, gitconfig_path);
6100 if (error != NULL)
6101 goto done;
6103 if (tagmsg) {
6104 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6105 if (error)
6106 goto done;
6109 if (commit_id_arg == NULL) {
6110 struct got_reference *head_ref;
6111 struct got_object_id *commit_id;
6112 error = got_ref_open(&head_ref, repo,
6113 worktree ? got_worktree_get_head_ref_name(worktree)
6114 : GOT_REF_HEAD, 0);
6115 if (error)
6116 goto done;
6117 error = got_ref_resolve(&commit_id, repo, head_ref);
6118 got_ref_close(head_ref);
6119 if (error)
6120 goto done;
6121 error = got_object_id_str(&commit_id_str, commit_id);
6122 free(commit_id);
6123 if (error)
6124 goto done;
6127 error = add_tag(repo, worktree, tag_name,
6128 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6130 done:
6131 if (repo)
6132 got_repo_close(repo);
6133 if (worktree)
6134 got_worktree_close(worktree);
6135 free(cwd);
6136 free(repo_path);
6137 free(gitconfig_path);
6138 free(commit_id_str);
6139 return error;
6142 __dead static void
6143 usage_add(void)
6145 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6146 getprogname());
6147 exit(1);
6150 static const struct got_error *
6151 add_progress(void *arg, unsigned char status, const char *path)
6153 while (path[0] == '/')
6154 path++;
6155 printf("%c %s\n", status, path);
6156 return NULL;
6159 static const struct got_error *
6160 cmd_add(int argc, char *argv[])
6162 const struct got_error *error = NULL;
6163 struct got_repository *repo = NULL;
6164 struct got_worktree *worktree = NULL;
6165 char *cwd = NULL;
6166 struct got_pathlist_head paths;
6167 struct got_pathlist_entry *pe;
6168 int ch, can_recurse = 0, no_ignores = 0;
6170 TAILQ_INIT(&paths);
6172 while ((ch = getopt(argc, argv, "IR")) != -1) {
6173 switch (ch) {
6174 case 'I':
6175 no_ignores = 1;
6176 break;
6177 case 'R':
6178 can_recurse = 1;
6179 break;
6180 default:
6181 usage_add();
6182 /* NOTREACHED */
6186 argc -= optind;
6187 argv += optind;
6189 #ifndef PROFILE
6190 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6191 NULL) == -1)
6192 err(1, "pledge");
6193 #endif
6194 if (argc < 1)
6195 usage_add();
6197 cwd = getcwd(NULL, 0);
6198 if (cwd == NULL) {
6199 error = got_error_from_errno("getcwd");
6200 goto done;
6203 error = got_worktree_open(&worktree, cwd);
6204 if (error) {
6205 if (error->code == GOT_ERR_NOT_WORKTREE)
6206 error = wrap_not_worktree_error(error, "add", cwd);
6207 goto done;
6210 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6211 NULL);
6212 if (error != NULL)
6213 goto done;
6215 error = apply_unveil(got_repo_get_path(repo), 1,
6216 got_worktree_get_root_path(worktree));
6217 if (error)
6218 goto done;
6220 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6221 if (error)
6222 goto done;
6224 if (!can_recurse && no_ignores) {
6225 error = got_error_msg(GOT_ERR_BAD_PATH,
6226 "disregarding ignores requires -R option");
6227 goto done;
6231 if (!can_recurse) {
6232 char *ondisk_path;
6233 struct stat sb;
6234 TAILQ_FOREACH(pe, &paths, entry) {
6235 if (asprintf(&ondisk_path, "%s/%s",
6236 got_worktree_get_root_path(worktree),
6237 pe->path) == -1) {
6238 error = got_error_from_errno("asprintf");
6239 goto done;
6241 if (lstat(ondisk_path, &sb) == -1) {
6242 if (errno == ENOENT) {
6243 free(ondisk_path);
6244 continue;
6246 error = got_error_from_errno2("lstat",
6247 ondisk_path);
6248 free(ondisk_path);
6249 goto done;
6251 free(ondisk_path);
6252 if (S_ISDIR(sb.st_mode)) {
6253 error = got_error_msg(GOT_ERR_BAD_PATH,
6254 "adding directories requires -R option");
6255 goto done;
6260 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6261 NULL, repo, no_ignores);
6262 done:
6263 if (repo)
6264 got_repo_close(repo);
6265 if (worktree)
6266 got_worktree_close(worktree);
6267 TAILQ_FOREACH(pe, &paths, entry)
6268 free((char *)pe->path);
6269 got_pathlist_free(&paths);
6270 free(cwd);
6271 return error;
6274 __dead static void
6275 usage_remove(void)
6277 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6278 "path ...\n", getprogname());
6279 exit(1);
6282 static const struct got_error *
6283 print_remove_status(void *arg, unsigned char status,
6284 unsigned char staged_status, const char *path)
6286 while (path[0] == '/')
6287 path++;
6288 if (status == GOT_STATUS_NONEXISTENT)
6289 return NULL;
6290 if (status == staged_status && (status == GOT_STATUS_DELETE))
6291 status = GOT_STATUS_NO_CHANGE;
6292 printf("%c%c %s\n", status, staged_status, path);
6293 return NULL;
6296 static const struct got_error *
6297 cmd_remove(int argc, char *argv[])
6299 const struct got_error *error = NULL;
6300 struct got_worktree *worktree = NULL;
6301 struct got_repository *repo = NULL;
6302 const char *status_codes = NULL;
6303 char *cwd = NULL;
6304 struct got_pathlist_head paths;
6305 struct got_pathlist_entry *pe;
6306 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6308 TAILQ_INIT(&paths);
6310 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6311 switch (ch) {
6312 case 'f':
6313 delete_local_mods = 1;
6314 break;
6315 case 'k':
6316 keep_on_disk = 1;
6317 break;
6318 case 'R':
6319 can_recurse = 1;
6320 break;
6321 case 's':
6322 for (i = 0; i < strlen(optarg); i++) {
6323 switch (optarg[i]) {
6324 case GOT_STATUS_MODIFY:
6325 delete_local_mods = 1;
6326 break;
6327 case GOT_STATUS_MISSING:
6328 break;
6329 default:
6330 errx(1, "invalid status code '%c'",
6331 optarg[i]);
6334 status_codes = optarg;
6335 break;
6336 default:
6337 usage_remove();
6338 /* NOTREACHED */
6342 argc -= optind;
6343 argv += optind;
6345 #ifndef PROFILE
6346 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6347 NULL) == -1)
6348 err(1, "pledge");
6349 #endif
6350 if (argc < 1)
6351 usage_remove();
6353 cwd = getcwd(NULL, 0);
6354 if (cwd == NULL) {
6355 error = got_error_from_errno("getcwd");
6356 goto done;
6358 error = got_worktree_open(&worktree, cwd);
6359 if (error) {
6360 if (error->code == GOT_ERR_NOT_WORKTREE)
6361 error = wrap_not_worktree_error(error, "remove", cwd);
6362 goto done;
6365 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6366 NULL);
6367 if (error)
6368 goto done;
6370 error = apply_unveil(got_repo_get_path(repo), 1,
6371 got_worktree_get_root_path(worktree));
6372 if (error)
6373 goto done;
6375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6376 if (error)
6377 goto done;
6379 if (!can_recurse) {
6380 char *ondisk_path;
6381 struct stat sb;
6382 TAILQ_FOREACH(pe, &paths, entry) {
6383 if (asprintf(&ondisk_path, "%s/%s",
6384 got_worktree_get_root_path(worktree),
6385 pe->path) == -1) {
6386 error = got_error_from_errno("asprintf");
6387 goto done;
6389 if (lstat(ondisk_path, &sb) == -1) {
6390 if (errno == ENOENT) {
6391 free(ondisk_path);
6392 continue;
6394 error = got_error_from_errno2("lstat",
6395 ondisk_path);
6396 free(ondisk_path);
6397 goto done;
6399 free(ondisk_path);
6400 if (S_ISDIR(sb.st_mode)) {
6401 error = got_error_msg(GOT_ERR_BAD_PATH,
6402 "removing directories requires -R option");
6403 goto done;
6408 error = got_worktree_schedule_delete(worktree, &paths,
6409 delete_local_mods, status_codes, print_remove_status, NULL,
6410 repo, keep_on_disk);
6411 done:
6412 if (repo)
6413 got_repo_close(repo);
6414 if (worktree)
6415 got_worktree_close(worktree);
6416 TAILQ_FOREACH(pe, &paths, entry)
6417 free((char *)pe->path);
6418 got_pathlist_free(&paths);
6419 free(cwd);
6420 return error;
6423 __dead static void
6424 usage_revert(void)
6426 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6427 "path ...\n", getprogname());
6428 exit(1);
6431 static const struct got_error *
6432 revert_progress(void *arg, unsigned char status, const char *path)
6434 if (status == GOT_STATUS_UNVERSIONED)
6435 return NULL;
6437 while (path[0] == '/')
6438 path++;
6439 printf("%c %s\n", status, path);
6440 return NULL;
6443 struct choose_patch_arg {
6444 FILE *patch_script_file;
6445 const char *action;
6448 static const struct got_error *
6449 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6450 int nchanges, const char *action)
6452 char *line = NULL;
6453 size_t linesize = 0;
6454 ssize_t linelen;
6456 switch (status) {
6457 case GOT_STATUS_ADD:
6458 printf("A %s\n%s this addition? [y/n] ", path, action);
6459 break;
6460 case GOT_STATUS_DELETE:
6461 printf("D %s\n%s this deletion? [y/n] ", path, action);
6462 break;
6463 case GOT_STATUS_MODIFY:
6464 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6465 return got_error_from_errno("fseek");
6466 printf(GOT_COMMIT_SEP_STR);
6467 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6468 printf("%s", line);
6469 if (ferror(patch_file))
6470 return got_error_from_errno("getline");
6471 printf(GOT_COMMIT_SEP_STR);
6472 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6473 path, n, nchanges, action);
6474 break;
6475 default:
6476 return got_error_path(path, GOT_ERR_FILE_STATUS);
6479 return NULL;
6482 static const struct got_error *
6483 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6484 FILE *patch_file, int n, int nchanges)
6486 const struct got_error *err = NULL;
6487 char *line = NULL;
6488 size_t linesize = 0;
6489 ssize_t linelen;
6490 int resp = ' ';
6491 struct choose_patch_arg *a = arg;
6493 *choice = GOT_PATCH_CHOICE_NONE;
6495 if (a->patch_script_file) {
6496 char *nl;
6497 err = show_change(status, path, patch_file, n, nchanges,
6498 a->action);
6499 if (err)
6500 return err;
6501 linelen = getline(&line, &linesize, a->patch_script_file);
6502 if (linelen == -1) {
6503 if (ferror(a->patch_script_file))
6504 return got_error_from_errno("getline");
6505 return NULL;
6507 nl = strchr(line, '\n');
6508 if (nl)
6509 *nl = '\0';
6510 if (strcmp(line, "y") == 0) {
6511 *choice = GOT_PATCH_CHOICE_YES;
6512 printf("y\n");
6513 } else if (strcmp(line, "n") == 0) {
6514 *choice = GOT_PATCH_CHOICE_NO;
6515 printf("n\n");
6516 } else if (strcmp(line, "q") == 0 &&
6517 status == GOT_STATUS_MODIFY) {
6518 *choice = GOT_PATCH_CHOICE_QUIT;
6519 printf("q\n");
6520 } else
6521 printf("invalid response '%s'\n", line);
6522 free(line);
6523 return NULL;
6526 while (resp != 'y' && resp != 'n' && resp != 'q') {
6527 err = show_change(status, path, patch_file, n, nchanges,
6528 a->action);
6529 if (err)
6530 return err;
6531 resp = getchar();
6532 if (resp == '\n')
6533 resp = getchar();
6534 if (status == GOT_STATUS_MODIFY) {
6535 if (resp != 'y' && resp != 'n' && resp != 'q') {
6536 printf("invalid response '%c'\n", resp);
6537 resp = ' ';
6539 } else if (resp != 'y' && resp != 'n') {
6540 printf("invalid response '%c'\n", resp);
6541 resp = ' ';
6545 if (resp == 'y')
6546 *choice = GOT_PATCH_CHOICE_YES;
6547 else if (resp == 'n')
6548 *choice = GOT_PATCH_CHOICE_NO;
6549 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6550 *choice = GOT_PATCH_CHOICE_QUIT;
6552 return NULL;
6556 static const struct got_error *
6557 cmd_revert(int argc, char *argv[])
6559 const struct got_error *error = NULL;
6560 struct got_worktree *worktree = NULL;
6561 struct got_repository *repo = NULL;
6562 char *cwd = NULL, *path = NULL;
6563 struct got_pathlist_head paths;
6564 struct got_pathlist_entry *pe;
6565 int ch, can_recurse = 0, pflag = 0;
6566 FILE *patch_script_file = NULL;
6567 const char *patch_script_path = NULL;
6568 struct choose_patch_arg cpa;
6570 TAILQ_INIT(&paths);
6572 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6573 switch (ch) {
6574 case 'p':
6575 pflag = 1;
6576 break;
6577 case 'F':
6578 patch_script_path = optarg;
6579 break;
6580 case 'R':
6581 can_recurse = 1;
6582 break;
6583 default:
6584 usage_revert();
6585 /* NOTREACHED */
6589 argc -= optind;
6590 argv += optind;
6592 #ifndef PROFILE
6593 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6594 "unveil", NULL) == -1)
6595 err(1, "pledge");
6596 #endif
6597 if (argc < 1)
6598 usage_revert();
6599 if (patch_script_path && !pflag)
6600 errx(1, "-F option can only be used together with -p option");
6602 cwd = getcwd(NULL, 0);
6603 if (cwd == NULL) {
6604 error = got_error_from_errno("getcwd");
6605 goto done;
6607 error = got_worktree_open(&worktree, cwd);
6608 if (error) {
6609 if (error->code == GOT_ERR_NOT_WORKTREE)
6610 error = wrap_not_worktree_error(error, "revert", cwd);
6611 goto done;
6614 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6615 NULL);
6616 if (error != NULL)
6617 goto done;
6619 if (patch_script_path) {
6620 patch_script_file = fopen(patch_script_path, "r");
6621 if (patch_script_file == NULL) {
6622 error = got_error_from_errno2("fopen",
6623 patch_script_path);
6624 goto done;
6627 error = apply_unveil(got_repo_get_path(repo), 1,
6628 got_worktree_get_root_path(worktree));
6629 if (error)
6630 goto done;
6632 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6633 if (error)
6634 goto done;
6636 if (!can_recurse) {
6637 char *ondisk_path;
6638 struct stat sb;
6639 TAILQ_FOREACH(pe, &paths, entry) {
6640 if (asprintf(&ondisk_path, "%s/%s",
6641 got_worktree_get_root_path(worktree),
6642 pe->path) == -1) {
6643 error = got_error_from_errno("asprintf");
6644 goto done;
6646 if (lstat(ondisk_path, &sb) == -1) {
6647 if (errno == ENOENT) {
6648 free(ondisk_path);
6649 continue;
6651 error = got_error_from_errno2("lstat",
6652 ondisk_path);
6653 free(ondisk_path);
6654 goto done;
6656 free(ondisk_path);
6657 if (S_ISDIR(sb.st_mode)) {
6658 error = got_error_msg(GOT_ERR_BAD_PATH,
6659 "reverting directories requires -R option");
6660 goto done;
6665 cpa.patch_script_file = patch_script_file;
6666 cpa.action = "revert";
6667 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6668 pflag ? choose_patch : NULL, &cpa, repo);
6669 done:
6670 if (patch_script_file && fclose(patch_script_file) == EOF &&
6671 error == NULL)
6672 error = got_error_from_errno2("fclose", patch_script_path);
6673 if (repo)
6674 got_repo_close(repo);
6675 if (worktree)
6676 got_worktree_close(worktree);
6677 free(path);
6678 free(cwd);
6679 return error;
6682 __dead static void
6683 usage_commit(void)
6685 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6686 getprogname());
6687 exit(1);
6690 struct collect_commit_logmsg_arg {
6691 const char *cmdline_log;
6692 const char *editor;
6693 const char *worktree_path;
6694 const char *branch_name;
6695 const char *repo_path;
6696 char *logmsg_path;
6700 static const struct got_error *
6701 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6702 void *arg)
6704 char *initial_content = NULL;
6705 struct got_pathlist_entry *pe;
6706 const struct got_error *err = NULL;
6707 char *template = NULL;
6708 struct collect_commit_logmsg_arg *a = arg;
6709 int initial_content_len;
6710 int fd = -1;
6711 size_t len;
6713 /* if a message was specified on the command line, just use it */
6714 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6715 len = strlen(a->cmdline_log) + 1;
6716 *logmsg = malloc(len + 1);
6717 if (*logmsg == NULL)
6718 return got_error_from_errno("malloc");
6719 strlcpy(*logmsg, a->cmdline_log, len);
6720 return NULL;
6723 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6724 return got_error_from_errno("asprintf");
6726 initial_content_len = asprintf(&initial_content,
6727 "\n# changes to be committed on branch %s:\n",
6728 a->branch_name);
6729 if (initial_content_len == -1)
6730 return got_error_from_errno("asprintf");
6732 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6733 if (err)
6734 goto done;
6736 if (write(fd, initial_content, initial_content_len) == -1) {
6737 err = got_error_from_errno2("write", a->logmsg_path);
6738 goto done;
6741 TAILQ_FOREACH(pe, commitable_paths, entry) {
6742 struct got_commitable *ct = pe->data;
6743 dprintf(fd, "# %c %s\n",
6744 got_commitable_get_status(ct),
6745 got_commitable_get_path(ct));
6748 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6749 done:
6750 free(initial_content);
6751 free(template);
6753 if (fd != -1 && close(fd) == -1 && err == NULL)
6754 err = got_error_from_errno2("close", a->logmsg_path);
6756 /* Editor is done; we can now apply unveil(2) */
6757 if (err == NULL)
6758 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6759 if (err) {
6760 free(*logmsg);
6761 *logmsg = NULL;
6763 return err;
6766 static const struct got_error *
6767 cmd_commit(int argc, char *argv[])
6769 const struct got_error *error = NULL;
6770 struct got_worktree *worktree = NULL;
6771 struct got_repository *repo = NULL;
6772 char *cwd = NULL, *id_str = NULL;
6773 struct got_object_id *id = NULL;
6774 const char *logmsg = NULL;
6775 struct collect_commit_logmsg_arg cl_arg;
6776 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6777 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6778 int allow_bad_symlinks = 0;
6779 struct got_pathlist_head paths;
6781 TAILQ_INIT(&paths);
6782 cl_arg.logmsg_path = NULL;
6784 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6785 switch (ch) {
6786 case 'm':
6787 logmsg = optarg;
6788 break;
6789 case 'S':
6790 allow_bad_symlinks = 1;
6791 break;
6792 default:
6793 usage_commit();
6794 /* NOTREACHED */
6798 argc -= optind;
6799 argv += optind;
6801 #ifndef PROFILE
6802 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6803 "unveil", NULL) == -1)
6804 err(1, "pledge");
6805 #endif
6806 cwd = getcwd(NULL, 0);
6807 if (cwd == NULL) {
6808 error = got_error_from_errno("getcwd");
6809 goto done;
6811 error = got_worktree_open(&worktree, cwd);
6812 if (error) {
6813 if (error->code == GOT_ERR_NOT_WORKTREE)
6814 error = wrap_not_worktree_error(error, "commit", cwd);
6815 goto done;
6818 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6819 if (error)
6820 goto done;
6821 if (rebase_in_progress) {
6822 error = got_error(GOT_ERR_REBASING);
6823 goto done;
6826 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6827 worktree);
6828 if (error)
6829 goto done;
6831 error = get_gitconfig_path(&gitconfig_path);
6832 if (error)
6833 goto done;
6834 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6835 gitconfig_path);
6836 if (error != NULL)
6837 goto done;
6839 error = get_author(&author, repo, worktree);
6840 if (error)
6841 return error;
6844 * unveil(2) traverses exec(2); if an editor is used we have
6845 * to apply unveil after the log message has been written.
6847 if (logmsg == NULL || strlen(logmsg) == 0)
6848 error = get_editor(&editor);
6849 else
6850 error = apply_unveil(got_repo_get_path(repo), 0,
6851 got_worktree_get_root_path(worktree));
6852 if (error)
6853 goto done;
6855 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6856 if (error)
6857 goto done;
6859 cl_arg.editor = editor;
6860 cl_arg.cmdline_log = logmsg;
6861 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6862 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6863 if (!histedit_in_progress) {
6864 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6865 error = got_error(GOT_ERR_COMMIT_BRANCH);
6866 goto done;
6868 cl_arg.branch_name += 11;
6870 cl_arg.repo_path = got_repo_get_path(repo);
6871 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6872 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6873 print_status, NULL, repo);
6874 if (error) {
6875 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6876 cl_arg.logmsg_path != NULL)
6877 preserve_logmsg = 1;
6878 goto done;
6881 error = got_object_id_str(&id_str, id);
6882 if (error)
6883 goto done;
6884 printf("Created commit %s\n", id_str);
6885 done:
6886 if (preserve_logmsg) {
6887 fprintf(stderr, "%s: log message preserved in %s\n",
6888 getprogname(), cl_arg.logmsg_path);
6889 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6890 error == NULL)
6891 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6892 free(cl_arg.logmsg_path);
6893 if (repo)
6894 got_repo_close(repo);
6895 if (worktree)
6896 got_worktree_close(worktree);
6897 free(cwd);
6898 free(id_str);
6899 free(gitconfig_path);
6900 free(editor);
6901 free(author);
6902 return error;
6905 __dead static void
6906 usage_cherrypick(void)
6908 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6909 exit(1);
6912 static const struct got_error *
6913 cmd_cherrypick(int argc, char *argv[])
6915 const struct got_error *error = NULL;
6916 struct got_worktree *worktree = NULL;
6917 struct got_repository *repo = NULL;
6918 char *cwd = NULL, *commit_id_str = NULL;
6919 struct got_object_id *commit_id = NULL;
6920 struct got_commit_object *commit = NULL;
6921 struct got_object_qid *pid;
6922 struct got_reference *head_ref = NULL;
6923 int ch;
6924 struct got_update_progress_arg upa;
6926 while ((ch = getopt(argc, argv, "")) != -1) {
6927 switch (ch) {
6928 default:
6929 usage_cherrypick();
6930 /* NOTREACHED */
6934 argc -= optind;
6935 argv += optind;
6937 #ifndef PROFILE
6938 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6939 "unveil", NULL) == -1)
6940 err(1, "pledge");
6941 #endif
6942 if (argc != 1)
6943 usage_cherrypick();
6945 cwd = getcwd(NULL, 0);
6946 if (cwd == NULL) {
6947 error = got_error_from_errno("getcwd");
6948 goto done;
6950 error = got_worktree_open(&worktree, cwd);
6951 if (error) {
6952 if (error->code == GOT_ERR_NOT_WORKTREE)
6953 error = wrap_not_worktree_error(error, "cherrypick",
6954 cwd);
6955 goto done;
6958 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6959 NULL);
6960 if (error != NULL)
6961 goto done;
6963 error = apply_unveil(got_repo_get_path(repo), 0,
6964 got_worktree_get_root_path(worktree));
6965 if (error)
6966 goto done;
6968 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6969 GOT_OBJ_TYPE_COMMIT, repo);
6970 if (error != NULL) {
6971 struct got_reference *ref;
6972 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6973 goto done;
6974 error = got_ref_open(&ref, repo, argv[0], 0);
6975 if (error != NULL)
6976 goto done;
6977 error = got_ref_resolve(&commit_id, repo, ref);
6978 got_ref_close(ref);
6979 if (error != NULL)
6980 goto done;
6982 error = got_object_id_str(&commit_id_str, commit_id);
6983 if (error)
6984 goto done;
6986 error = got_ref_open(&head_ref, repo,
6987 got_worktree_get_head_ref_name(worktree), 0);
6988 if (error != NULL)
6989 goto done;
6991 error = check_same_branch(commit_id, head_ref, NULL, repo);
6992 if (error) {
6993 if (error->code != GOT_ERR_ANCESTRY)
6994 goto done;
6995 error = NULL;
6996 } else {
6997 error = got_error(GOT_ERR_SAME_BRANCH);
6998 goto done;
7001 error = got_object_open_as_commit(&commit, repo, commit_id);
7002 if (error)
7003 goto done;
7004 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7005 memset(&upa, 0, sizeof(upa));
7006 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7007 commit_id, repo, update_progress, &upa, check_cancelled,
7008 NULL);
7009 if (error != NULL)
7010 goto done;
7012 if (upa.did_something)
7013 printf("Merged commit %s\n", commit_id_str);
7014 print_update_progress_stats(&upa);
7015 done:
7016 if (commit)
7017 got_object_commit_close(commit);
7018 free(commit_id_str);
7019 if (head_ref)
7020 got_ref_close(head_ref);
7021 if (worktree)
7022 got_worktree_close(worktree);
7023 if (repo)
7024 got_repo_close(repo);
7025 return error;
7028 __dead static void
7029 usage_backout(void)
7031 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
7032 exit(1);
7035 static const struct got_error *
7036 cmd_backout(int argc, char *argv[])
7038 const struct got_error *error = NULL;
7039 struct got_worktree *worktree = NULL;
7040 struct got_repository *repo = NULL;
7041 char *cwd = NULL, *commit_id_str = NULL;
7042 struct got_object_id *commit_id = NULL;
7043 struct got_commit_object *commit = NULL;
7044 struct got_object_qid *pid;
7045 struct got_reference *head_ref = NULL;
7046 int ch;
7047 struct got_update_progress_arg upa;
7049 while ((ch = getopt(argc, argv, "")) != -1) {
7050 switch (ch) {
7051 default:
7052 usage_backout();
7053 /* NOTREACHED */
7057 argc -= optind;
7058 argv += optind;
7060 #ifndef PROFILE
7061 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7062 "unveil", NULL) == -1)
7063 err(1, "pledge");
7064 #endif
7065 if (argc != 1)
7066 usage_backout();
7068 cwd = getcwd(NULL, 0);
7069 if (cwd == NULL) {
7070 error = got_error_from_errno("getcwd");
7071 goto done;
7073 error = got_worktree_open(&worktree, cwd);
7074 if (error) {
7075 if (error->code == GOT_ERR_NOT_WORKTREE)
7076 error = wrap_not_worktree_error(error, "backout", cwd);
7077 goto done;
7080 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7081 NULL);
7082 if (error != NULL)
7083 goto done;
7085 error = apply_unveil(got_repo_get_path(repo), 0,
7086 got_worktree_get_root_path(worktree));
7087 if (error)
7088 goto done;
7090 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7091 GOT_OBJ_TYPE_COMMIT, repo);
7092 if (error != NULL) {
7093 struct got_reference *ref;
7094 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7095 goto done;
7096 error = got_ref_open(&ref, repo, argv[0], 0);
7097 if (error != NULL)
7098 goto done;
7099 error = got_ref_resolve(&commit_id, repo, ref);
7100 got_ref_close(ref);
7101 if (error != NULL)
7102 goto done;
7104 error = got_object_id_str(&commit_id_str, commit_id);
7105 if (error)
7106 goto done;
7108 error = got_ref_open(&head_ref, repo,
7109 got_worktree_get_head_ref_name(worktree), 0);
7110 if (error != NULL)
7111 goto done;
7113 error = check_same_branch(commit_id, head_ref, NULL, repo);
7114 if (error)
7115 goto done;
7117 error = got_object_open_as_commit(&commit, repo, commit_id);
7118 if (error)
7119 goto done;
7120 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
7121 if (pid == NULL) {
7122 error = got_error(GOT_ERR_ROOT_COMMIT);
7123 goto done;
7126 memset(&upa, 0, sizeof(upa));
7127 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
7128 update_progress, &upa, check_cancelled, NULL);
7129 if (error != NULL)
7130 goto done;
7132 if (upa.did_something)
7133 printf("Backed out commit %s\n", commit_id_str);
7134 print_update_progress_stats(&upa);
7135 done:
7136 if (commit)
7137 got_object_commit_close(commit);
7138 free(commit_id_str);
7139 if (head_ref)
7140 got_ref_close(head_ref);
7141 if (worktree)
7142 got_worktree_close(worktree);
7143 if (repo)
7144 got_repo_close(repo);
7145 return error;
7148 __dead static void
7149 usage_rebase(void)
7151 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7152 getprogname());
7153 exit(1);
7156 void
7157 trim_logmsg(char *logmsg, int limit)
7159 char *nl;
7160 size_t len;
7162 len = strlen(logmsg);
7163 if (len > limit)
7164 len = limit;
7165 logmsg[len] = '\0';
7166 nl = strchr(logmsg, '\n');
7167 if (nl)
7168 *nl = '\0';
7171 static const struct got_error *
7172 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7174 const struct got_error *err;
7175 char *logmsg0 = NULL;
7176 const char *s;
7178 err = got_object_commit_get_logmsg(&logmsg0, commit);
7179 if (err)
7180 return err;
7182 s = logmsg0;
7183 while (isspace((unsigned char)s[0]))
7184 s++;
7186 *logmsg = strdup(s);
7187 if (*logmsg == NULL) {
7188 err = got_error_from_errno("strdup");
7189 goto done;
7192 trim_logmsg(*logmsg, limit);
7193 done:
7194 free(logmsg0);
7195 return err;
7198 static const struct got_error *
7199 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7201 const struct got_error *err;
7202 struct got_commit_object *commit = NULL;
7203 char *id_str = NULL, *logmsg = NULL;
7205 err = got_object_open_as_commit(&commit, repo, id);
7206 if (err)
7207 return err;
7209 err = got_object_id_str(&id_str, id);
7210 if (err)
7211 goto done;
7213 id_str[12] = '\0';
7215 err = get_short_logmsg(&logmsg, 42, commit);
7216 if (err)
7217 goto done;
7219 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7220 done:
7221 free(id_str);
7222 got_object_commit_close(commit);
7223 free(logmsg);
7224 return err;
7227 static const struct got_error *
7228 show_rebase_progress(struct got_commit_object *commit,
7229 struct got_object_id *old_id, struct got_object_id *new_id)
7231 const struct got_error *err;
7232 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7234 err = got_object_id_str(&old_id_str, old_id);
7235 if (err)
7236 goto done;
7238 if (new_id) {
7239 err = got_object_id_str(&new_id_str, new_id);
7240 if (err)
7241 goto done;
7244 old_id_str[12] = '\0';
7245 if (new_id_str)
7246 new_id_str[12] = '\0';
7248 err = get_short_logmsg(&logmsg, 42, commit);
7249 if (err)
7250 goto done;
7252 printf("%s -> %s: %s\n", old_id_str,
7253 new_id_str ? new_id_str : "no-op change", logmsg);
7254 done:
7255 free(old_id_str);
7256 free(new_id_str);
7257 free(logmsg);
7258 return err;
7261 static const struct got_error *
7262 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7263 struct got_reference *branch, struct got_reference *new_base_branch,
7264 struct got_reference *tmp_branch, struct got_repository *repo)
7266 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7267 return got_worktree_rebase_complete(worktree, fileindex,
7268 new_base_branch, tmp_branch, branch, repo);
7271 static const struct got_error *
7272 rebase_commit(struct got_pathlist_head *merged_paths,
7273 struct got_worktree *worktree, struct got_fileindex *fileindex,
7274 struct got_reference *tmp_branch,
7275 struct got_object_id *commit_id, struct got_repository *repo)
7277 const struct got_error *error;
7278 struct got_commit_object *commit;
7279 struct got_object_id *new_commit_id;
7281 error = got_object_open_as_commit(&commit, repo, commit_id);
7282 if (error)
7283 return error;
7285 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7286 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7287 if (error) {
7288 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7289 goto done;
7290 error = show_rebase_progress(commit, commit_id, NULL);
7291 } else {
7292 error = show_rebase_progress(commit, commit_id, new_commit_id);
7293 free(new_commit_id);
7295 done:
7296 got_object_commit_close(commit);
7297 return error;
7300 struct check_path_prefix_arg {
7301 const char *path_prefix;
7302 size_t len;
7303 int errcode;
7306 static const struct got_error *
7307 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7308 struct got_blob_object *blob2, struct got_object_id *id1,
7309 struct got_object_id *id2, const char *path1, const char *path2,
7310 mode_t mode1, mode_t mode2, struct got_repository *repo)
7312 struct check_path_prefix_arg *a = arg;
7314 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7315 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7316 return got_error(a->errcode);
7318 return NULL;
7321 static const struct got_error *
7322 check_path_prefix(struct got_object_id *parent_id,
7323 struct got_object_id *commit_id, const char *path_prefix,
7324 int errcode, struct got_repository *repo)
7326 const struct got_error *err;
7327 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7328 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7329 struct check_path_prefix_arg cpp_arg;
7331 if (got_path_is_root_dir(path_prefix))
7332 return NULL;
7334 err = got_object_open_as_commit(&commit, repo, commit_id);
7335 if (err)
7336 goto done;
7338 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7339 if (err)
7340 goto done;
7342 err = got_object_open_as_tree(&tree1, repo,
7343 got_object_commit_get_tree_id(parent_commit));
7344 if (err)
7345 goto done;
7347 err = got_object_open_as_tree(&tree2, repo,
7348 got_object_commit_get_tree_id(commit));
7349 if (err)
7350 goto done;
7352 cpp_arg.path_prefix = path_prefix;
7353 while (cpp_arg.path_prefix[0] == '/')
7354 cpp_arg.path_prefix++;
7355 cpp_arg.len = strlen(cpp_arg.path_prefix);
7356 cpp_arg.errcode = errcode;
7357 err = got_diff_tree(tree1, tree2, "", "", repo,
7358 check_path_prefix_in_diff, &cpp_arg, 0);
7359 done:
7360 if (tree1)
7361 got_object_tree_close(tree1);
7362 if (tree2)
7363 got_object_tree_close(tree2);
7364 if (commit)
7365 got_object_commit_close(commit);
7366 if (parent_commit)
7367 got_object_commit_close(parent_commit);
7368 return err;
7371 static const struct got_error *
7372 collect_commits(struct got_object_id_queue *commits,
7373 struct got_object_id *initial_commit_id,
7374 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7375 const char *path_prefix, int path_prefix_errcode,
7376 struct got_repository *repo)
7378 const struct got_error *err = NULL;
7379 struct got_commit_graph *graph = NULL;
7380 struct got_object_id *parent_id = NULL;
7381 struct got_object_qid *qid;
7382 struct got_object_id *commit_id = initial_commit_id;
7384 err = got_commit_graph_open(&graph, "/", 1);
7385 if (err)
7386 return err;
7388 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7389 check_cancelled, NULL);
7390 if (err)
7391 goto done;
7392 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7393 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7394 check_cancelled, NULL);
7395 if (err) {
7396 if (err->code == GOT_ERR_ITER_COMPLETED) {
7397 err = got_error_msg(GOT_ERR_ANCESTRY,
7398 "ran out of commits to rebase before "
7399 "youngest common ancestor commit has "
7400 "been reached?!?");
7402 goto done;
7403 } else {
7404 err = check_path_prefix(parent_id, commit_id,
7405 path_prefix, path_prefix_errcode, repo);
7406 if (err)
7407 goto done;
7409 err = got_object_qid_alloc(&qid, commit_id);
7410 if (err)
7411 goto done;
7412 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7413 commit_id = parent_id;
7416 done:
7417 got_commit_graph_close(graph);
7418 return err;
7421 static const struct got_error *
7422 cmd_rebase(int argc, char *argv[])
7424 const struct got_error *error = NULL;
7425 struct got_worktree *worktree = NULL;
7426 struct got_repository *repo = NULL;
7427 struct got_fileindex *fileindex = NULL;
7428 char *cwd = NULL;
7429 struct got_reference *branch = NULL;
7430 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7431 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7432 struct got_object_id *resume_commit_id = NULL;
7433 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7434 struct got_commit_object *commit = NULL;
7435 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7436 int histedit_in_progress = 0;
7437 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7438 struct got_object_id_queue commits;
7439 struct got_pathlist_head merged_paths;
7440 const struct got_object_id_queue *parent_ids;
7441 struct got_object_qid *qid, *pid;
7443 SIMPLEQ_INIT(&commits);
7444 TAILQ_INIT(&merged_paths);
7446 while ((ch = getopt(argc, argv, "ac")) != -1) {
7447 switch (ch) {
7448 case 'a':
7449 abort_rebase = 1;
7450 break;
7451 case 'c':
7452 continue_rebase = 1;
7453 break;
7454 default:
7455 usage_rebase();
7456 /* NOTREACHED */
7460 argc -= optind;
7461 argv += optind;
7463 #ifndef PROFILE
7464 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7465 "unveil", NULL) == -1)
7466 err(1, "pledge");
7467 #endif
7468 if (abort_rebase && continue_rebase)
7469 usage_rebase();
7470 else if (abort_rebase || continue_rebase) {
7471 if (argc != 0)
7472 usage_rebase();
7473 } else if (argc != 1)
7474 usage_rebase();
7476 cwd = getcwd(NULL, 0);
7477 if (cwd == NULL) {
7478 error = got_error_from_errno("getcwd");
7479 goto done;
7481 error = got_worktree_open(&worktree, cwd);
7482 if (error) {
7483 if (error->code == GOT_ERR_NOT_WORKTREE)
7484 error = wrap_not_worktree_error(error, "rebase", cwd);
7485 goto done;
7488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7489 NULL);
7490 if (error != NULL)
7491 goto done;
7493 error = apply_unveil(got_repo_get_path(repo), 0,
7494 got_worktree_get_root_path(worktree));
7495 if (error)
7496 goto done;
7498 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7499 worktree);
7500 if (error)
7501 goto done;
7502 if (histedit_in_progress) {
7503 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7504 goto done;
7507 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7508 if (error)
7509 goto done;
7511 if (abort_rebase) {
7512 struct got_update_progress_arg upa;
7513 if (!rebase_in_progress) {
7514 error = got_error(GOT_ERR_NOT_REBASING);
7515 goto done;
7517 error = got_worktree_rebase_continue(&resume_commit_id,
7518 &new_base_branch, &tmp_branch, &branch, &fileindex,
7519 worktree, repo);
7520 if (error)
7521 goto done;
7522 printf("Switching work tree to %s\n",
7523 got_ref_get_symref_target(new_base_branch));
7524 memset(&upa, 0, sizeof(upa));
7525 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7526 new_base_branch, update_progress, &upa);
7527 if (error)
7528 goto done;
7529 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7530 print_update_progress_stats(&upa);
7531 goto done; /* nothing else to do */
7534 if (continue_rebase) {
7535 if (!rebase_in_progress) {
7536 error = got_error(GOT_ERR_NOT_REBASING);
7537 goto done;
7539 error = got_worktree_rebase_continue(&resume_commit_id,
7540 &new_base_branch, &tmp_branch, &branch, &fileindex,
7541 worktree, repo);
7542 if (error)
7543 goto done;
7545 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7546 resume_commit_id, repo);
7547 if (error)
7548 goto done;
7550 yca_id = got_object_id_dup(resume_commit_id);
7551 if (yca_id == NULL) {
7552 error = got_error_from_errno("got_object_id_dup");
7553 goto done;
7555 } else {
7556 error = got_ref_open(&branch, repo, argv[0], 0);
7557 if (error != NULL)
7558 goto done;
7561 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7562 if (error)
7563 goto done;
7565 if (!continue_rebase) {
7566 struct got_object_id *base_commit_id;
7568 base_commit_id = got_worktree_get_base_commit_id(worktree);
7569 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7570 base_commit_id, branch_head_commit_id, repo,
7571 check_cancelled, NULL);
7572 if (error)
7573 goto done;
7574 if (yca_id == NULL) {
7575 error = got_error_msg(GOT_ERR_ANCESTRY,
7576 "specified branch shares no common ancestry "
7577 "with work tree's branch");
7578 goto done;
7581 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7582 if (error) {
7583 if (error->code != GOT_ERR_ANCESTRY)
7584 goto done;
7585 error = NULL;
7586 } else {
7587 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7588 "specified branch resolves to a commit which "
7589 "is already contained in work tree's branch");
7590 goto done;
7592 error = got_worktree_rebase_prepare(&new_base_branch,
7593 &tmp_branch, &fileindex, worktree, branch, repo);
7594 if (error)
7595 goto done;
7598 commit_id = branch_head_commit_id;
7599 error = got_object_open_as_commit(&commit, repo, commit_id);
7600 if (error)
7601 goto done;
7603 parent_ids = got_object_commit_get_parent_ids(commit);
7604 pid = SIMPLEQ_FIRST(parent_ids);
7605 if (pid == NULL) {
7606 if (!continue_rebase) {
7607 struct got_update_progress_arg upa;
7608 memset(&upa, 0, sizeof(upa));
7609 error = got_worktree_rebase_abort(worktree, fileindex,
7610 repo, new_base_branch, update_progress, &upa);
7611 if (error)
7612 goto done;
7613 printf("Rebase of %s aborted\n",
7614 got_ref_get_name(branch));
7615 print_update_progress_stats(&upa);
7618 error = got_error(GOT_ERR_EMPTY_REBASE);
7619 goto done;
7621 error = collect_commits(&commits, commit_id, pid->id,
7622 yca_id, got_worktree_get_path_prefix(worktree),
7623 GOT_ERR_REBASE_PATH, repo);
7624 got_object_commit_close(commit);
7625 commit = NULL;
7626 if (error)
7627 goto done;
7629 if (SIMPLEQ_EMPTY(&commits)) {
7630 if (continue_rebase) {
7631 error = rebase_complete(worktree, fileindex,
7632 branch, new_base_branch, tmp_branch, repo);
7633 goto done;
7634 } else {
7635 /* Fast-forward the reference of the branch. */
7636 struct got_object_id *new_head_commit_id;
7637 char *id_str;
7638 error = got_ref_resolve(&new_head_commit_id, repo,
7639 new_base_branch);
7640 if (error)
7641 goto done;
7642 error = got_object_id_str(&id_str, new_head_commit_id);
7643 printf("Forwarding %s to commit %s\n",
7644 got_ref_get_name(branch), id_str);
7645 free(id_str);
7646 error = got_ref_change_ref(branch,
7647 new_head_commit_id);
7648 if (error)
7649 goto done;
7653 pid = NULL;
7654 SIMPLEQ_FOREACH(qid, &commits, entry) {
7655 struct got_update_progress_arg upa;
7657 commit_id = qid->id;
7658 parent_id = pid ? pid->id : yca_id;
7659 pid = qid;
7661 memset(&upa, 0, sizeof(upa));
7662 error = got_worktree_rebase_merge_files(&merged_paths,
7663 worktree, fileindex, parent_id, commit_id, repo,
7664 update_progress, &upa, check_cancelled, NULL);
7665 if (error)
7666 goto done;
7668 print_update_progress_stats(&upa);
7669 if (upa.conflicts > 0)
7670 rebase_status = GOT_STATUS_CONFLICT;
7672 if (rebase_status == GOT_STATUS_CONFLICT) {
7673 error = show_rebase_merge_conflict(qid->id, repo);
7674 if (error)
7675 goto done;
7676 got_worktree_rebase_pathlist_free(&merged_paths);
7677 break;
7680 error = rebase_commit(&merged_paths, worktree, fileindex,
7681 tmp_branch, commit_id, repo);
7682 got_worktree_rebase_pathlist_free(&merged_paths);
7683 if (error)
7684 goto done;
7687 if (rebase_status == GOT_STATUS_CONFLICT) {
7688 error = got_worktree_rebase_postpone(worktree, fileindex);
7689 if (error)
7690 goto done;
7691 error = got_error_msg(GOT_ERR_CONFLICTS,
7692 "conflicts must be resolved before rebasing can continue");
7693 } else
7694 error = rebase_complete(worktree, fileindex, branch,
7695 new_base_branch, tmp_branch, repo);
7696 done:
7697 got_object_id_queue_free(&commits);
7698 free(branch_head_commit_id);
7699 free(resume_commit_id);
7700 free(yca_id);
7701 if (commit)
7702 got_object_commit_close(commit);
7703 if (branch)
7704 got_ref_close(branch);
7705 if (new_base_branch)
7706 got_ref_close(new_base_branch);
7707 if (tmp_branch)
7708 got_ref_close(tmp_branch);
7709 if (worktree)
7710 got_worktree_close(worktree);
7711 if (repo)
7712 got_repo_close(repo);
7713 return error;
7716 __dead static void
7717 usage_histedit(void)
7719 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7720 getprogname());
7721 exit(1);
7724 #define GOT_HISTEDIT_PICK 'p'
7725 #define GOT_HISTEDIT_EDIT 'e'
7726 #define GOT_HISTEDIT_FOLD 'f'
7727 #define GOT_HISTEDIT_DROP 'd'
7728 #define GOT_HISTEDIT_MESG 'm'
7730 static struct got_histedit_cmd {
7731 unsigned char code;
7732 const char *name;
7733 const char *desc;
7734 } got_histedit_cmds[] = {
7735 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7736 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7737 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7738 "be used" },
7739 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7740 { GOT_HISTEDIT_MESG, "mesg",
7741 "single-line log message for commit above (open editor if empty)" },
7744 struct got_histedit_list_entry {
7745 TAILQ_ENTRY(got_histedit_list_entry) entry;
7746 struct got_object_id *commit_id;
7747 const struct got_histedit_cmd *cmd;
7748 char *logmsg;
7750 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7752 static const struct got_error *
7753 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7754 FILE *f, struct got_repository *repo)
7756 const struct got_error *err = NULL;
7757 char *logmsg = NULL, *id_str = NULL;
7758 struct got_commit_object *commit = NULL;
7759 int n;
7761 err = got_object_open_as_commit(&commit, repo, commit_id);
7762 if (err)
7763 goto done;
7765 err = get_short_logmsg(&logmsg, 34, commit);
7766 if (err)
7767 goto done;
7769 err = got_object_id_str(&id_str, commit_id);
7770 if (err)
7771 goto done;
7773 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7774 if (n < 0)
7775 err = got_ferror(f, GOT_ERR_IO);
7776 done:
7777 if (commit)
7778 got_object_commit_close(commit);
7779 free(id_str);
7780 free(logmsg);
7781 return err;
7784 static const struct got_error *
7785 histedit_write_commit_list(struct got_object_id_queue *commits,
7786 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7788 const struct got_error *err = NULL;
7789 struct got_object_qid *qid;
7791 if (SIMPLEQ_EMPTY(commits))
7792 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7794 SIMPLEQ_FOREACH(qid, commits, entry) {
7795 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7796 f, repo);
7797 if (err)
7798 break;
7799 if (edit_logmsg_only) {
7800 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7801 if (n < 0) {
7802 err = got_ferror(f, GOT_ERR_IO);
7803 break;
7808 return err;
7811 static const struct got_error *
7812 write_cmd_list(FILE *f, const char *branch_name,
7813 struct got_object_id_queue *commits)
7815 const struct got_error *err = NULL;
7816 int n, i;
7817 char *id_str;
7818 struct got_object_qid *qid;
7820 qid = SIMPLEQ_FIRST(commits);
7821 err = got_object_id_str(&id_str, qid->id);
7822 if (err)
7823 return err;
7825 n = fprintf(f,
7826 "# Editing the history of branch '%s' starting at\n"
7827 "# commit %s\n"
7828 "# Commits will be processed in order from top to "
7829 "bottom of this file.\n", branch_name, id_str);
7830 if (n < 0) {
7831 err = got_ferror(f, GOT_ERR_IO);
7832 goto done;
7835 n = fprintf(f, "# Available histedit commands:\n");
7836 if (n < 0) {
7837 err = got_ferror(f, GOT_ERR_IO);
7838 goto done;
7841 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7842 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7843 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7844 cmd->desc);
7845 if (n < 0) {
7846 err = got_ferror(f, GOT_ERR_IO);
7847 break;
7850 done:
7851 free(id_str);
7852 return err;
7855 static const struct got_error *
7856 histedit_syntax_error(int lineno)
7858 static char msg[42];
7859 int ret;
7861 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7862 lineno);
7863 if (ret == -1 || ret >= sizeof(msg))
7864 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7866 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7869 static const struct got_error *
7870 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7871 char *logmsg, struct got_repository *repo)
7873 const struct got_error *err;
7874 struct got_commit_object *folded_commit = NULL;
7875 char *id_str, *folded_logmsg = NULL;
7877 err = got_object_id_str(&id_str, hle->commit_id);
7878 if (err)
7879 return err;
7881 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7882 if (err)
7883 goto done;
7885 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7886 if (err)
7887 goto done;
7888 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7889 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7890 folded_logmsg) == -1) {
7891 err = got_error_from_errno("asprintf");
7893 done:
7894 if (folded_commit)
7895 got_object_commit_close(folded_commit);
7896 free(id_str);
7897 free(folded_logmsg);
7898 return err;
7901 static struct got_histedit_list_entry *
7902 get_folded_commits(struct got_histedit_list_entry *hle)
7904 struct got_histedit_list_entry *prev, *folded = NULL;
7906 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7907 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7908 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7909 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7910 folded = prev;
7911 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7914 return folded;
7917 static const struct got_error *
7918 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7919 struct got_repository *repo)
7921 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7922 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7923 const struct got_error *err = NULL;
7924 struct got_commit_object *commit = NULL;
7925 int logmsg_len;
7926 int fd;
7927 struct got_histedit_list_entry *folded = NULL;
7929 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7930 if (err)
7931 return err;
7933 folded = get_folded_commits(hle);
7934 if (folded) {
7935 while (folded != hle) {
7936 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7937 folded = TAILQ_NEXT(folded, entry);
7938 continue;
7940 err = append_folded_commit_msg(&new_msg, folded,
7941 logmsg, repo);
7942 if (err)
7943 goto done;
7944 free(logmsg);
7945 logmsg = new_msg;
7946 folded = TAILQ_NEXT(folded, entry);
7950 err = got_object_id_str(&id_str, hle->commit_id);
7951 if (err)
7952 goto done;
7953 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7954 if (err)
7955 goto done;
7956 logmsg_len = asprintf(&new_msg,
7957 "%s\n# original log message of commit %s: %s",
7958 logmsg ? logmsg : "", id_str, orig_logmsg);
7959 if (logmsg_len == -1) {
7960 err = got_error_from_errno("asprintf");
7961 goto done;
7963 free(logmsg);
7964 logmsg = new_msg;
7966 err = got_object_id_str(&id_str, hle->commit_id);
7967 if (err)
7968 goto done;
7970 err = got_opentemp_named_fd(&logmsg_path, &fd,
7971 GOT_TMPDIR_STR "/got-logmsg");
7972 if (err)
7973 goto done;
7975 write(fd, logmsg, logmsg_len);
7976 close(fd);
7978 err = get_editor(&editor);
7979 if (err)
7980 goto done;
7982 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7983 if (err) {
7984 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7985 goto done;
7986 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7988 done:
7989 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7990 err = got_error_from_errno2("unlink", logmsg_path);
7991 free(logmsg_path);
7992 free(logmsg);
7993 free(orig_logmsg);
7994 free(editor);
7995 if (commit)
7996 got_object_commit_close(commit);
7997 return err;
8000 static const struct got_error *
8001 histedit_parse_list(struct got_histedit_list *histedit_cmds,
8002 FILE *f, struct got_repository *repo)
8004 const struct got_error *err = NULL;
8005 char *line = NULL, *p, *end;
8006 size_t size;
8007 ssize_t len;
8008 int lineno = 0, i;
8009 const struct got_histedit_cmd *cmd;
8010 struct got_object_id *commit_id = NULL;
8011 struct got_histedit_list_entry *hle = NULL;
8013 for (;;) {
8014 len = getline(&line, &size, f);
8015 if (len == -1) {
8016 const struct got_error *getline_err;
8017 if (feof(f))
8018 break;
8019 getline_err = got_error_from_errno("getline");
8020 err = got_ferror(f, getline_err->code);
8021 break;
8023 lineno++;
8024 p = line;
8025 while (isspace((unsigned char)p[0]))
8026 p++;
8027 if (p[0] == '#' || p[0] == '\0') {
8028 free(line);
8029 line = NULL;
8030 continue;
8032 cmd = NULL;
8033 for (i = 0; i < nitems(got_histedit_cmds); i++) {
8034 cmd = &got_histedit_cmds[i];
8035 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
8036 isspace((unsigned char)p[strlen(cmd->name)])) {
8037 p += strlen(cmd->name);
8038 break;
8040 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
8041 p++;
8042 break;
8045 if (i == nitems(got_histedit_cmds)) {
8046 err = histedit_syntax_error(lineno);
8047 break;
8049 while (isspace((unsigned char)p[0]))
8050 p++;
8051 if (cmd->code == GOT_HISTEDIT_MESG) {
8052 if (hle == NULL || hle->logmsg != NULL) {
8053 err = got_error(GOT_ERR_HISTEDIT_CMD);
8054 break;
8056 if (p[0] == '\0') {
8057 err = histedit_edit_logmsg(hle, repo);
8058 if (err)
8059 break;
8060 } else {
8061 hle->logmsg = strdup(p);
8062 if (hle->logmsg == NULL) {
8063 err = got_error_from_errno("strdup");
8064 break;
8067 free(line);
8068 line = NULL;
8069 continue;
8070 } else {
8071 end = p;
8072 while (end[0] && !isspace((unsigned char)end[0]))
8073 end++;
8074 *end = '\0';
8076 err = got_object_resolve_id_str(&commit_id, repo, p);
8077 if (err) {
8078 /* override error code */
8079 err = histedit_syntax_error(lineno);
8080 break;
8083 hle = malloc(sizeof(*hle));
8084 if (hle == NULL) {
8085 err = got_error_from_errno("malloc");
8086 break;
8088 hle->cmd = cmd;
8089 hle->commit_id = commit_id;
8090 hle->logmsg = NULL;
8091 commit_id = NULL;
8092 free(line);
8093 line = NULL;
8094 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
8097 free(line);
8098 free(commit_id);
8099 return err;
8102 static const struct got_error *
8103 histedit_check_script(struct got_histedit_list *histedit_cmds,
8104 struct got_object_id_queue *commits, struct got_repository *repo)
8106 const struct got_error *err = NULL;
8107 struct got_object_qid *qid;
8108 struct got_histedit_list_entry *hle;
8109 static char msg[92];
8110 char *id_str;
8112 if (TAILQ_EMPTY(histedit_cmds))
8113 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
8114 "histedit script contains no commands");
8115 if (SIMPLEQ_EMPTY(commits))
8116 return got_error(GOT_ERR_EMPTY_HISTEDIT);
8118 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8119 struct got_histedit_list_entry *hle2;
8120 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
8121 if (hle == hle2)
8122 continue;
8123 if (got_object_id_cmp(hle->commit_id,
8124 hle2->commit_id) != 0)
8125 continue;
8126 err = got_object_id_str(&id_str, hle->commit_id);
8127 if (err)
8128 return err;
8129 snprintf(msg, sizeof(msg), "commit %s is listed "
8130 "more than once in histedit script", id_str);
8131 free(id_str);
8132 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8136 SIMPLEQ_FOREACH(qid, commits, entry) {
8137 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8138 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
8139 break;
8141 if (hle == NULL) {
8142 err = got_object_id_str(&id_str, qid->id);
8143 if (err)
8144 return err;
8145 snprintf(msg, sizeof(msg),
8146 "commit %s missing from histedit script", id_str);
8147 free(id_str);
8148 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8152 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8153 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8154 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8155 "last commit in histedit script cannot be folded");
8157 return NULL;
8160 static const struct got_error *
8161 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8162 const char *path, struct got_object_id_queue *commits,
8163 struct got_repository *repo)
8165 const struct got_error *err = NULL;
8166 char *editor;
8167 FILE *f = NULL;
8169 err = get_editor(&editor);
8170 if (err)
8171 return err;
8173 if (spawn_editor(editor, path) == -1) {
8174 err = got_error_from_errno("failed spawning editor");
8175 goto done;
8178 f = fopen(path, "r");
8179 if (f == NULL) {
8180 err = got_error_from_errno("fopen");
8181 goto done;
8183 err = histedit_parse_list(histedit_cmds, f, repo);
8184 if (err)
8185 goto done;
8187 err = histedit_check_script(histedit_cmds, commits, repo);
8188 done:
8189 if (f && fclose(f) != 0 && err == NULL)
8190 err = got_error_from_errno("fclose");
8191 free(editor);
8192 return err;
8195 static const struct got_error *
8196 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8197 struct got_object_id_queue *, const char *, const char *,
8198 struct got_repository *);
8200 static const struct got_error *
8201 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8202 struct got_object_id_queue *commits, const char *branch_name,
8203 int edit_logmsg_only, struct got_repository *repo)
8205 const struct got_error *err;
8206 FILE *f = NULL;
8207 char *path = NULL;
8209 err = got_opentemp_named(&path, &f, "got-histedit");
8210 if (err)
8211 return err;
8213 err = write_cmd_list(f, branch_name, commits);
8214 if (err)
8215 goto done;
8217 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8218 if (err)
8219 goto done;
8221 if (edit_logmsg_only) {
8222 rewind(f);
8223 err = histedit_parse_list(histedit_cmds, f, repo);
8224 } else {
8225 if (fclose(f) != 0) {
8226 err = got_error_from_errno("fclose");
8227 goto done;
8229 f = NULL;
8230 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8231 if (err) {
8232 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8233 err->code != GOT_ERR_HISTEDIT_CMD)
8234 goto done;
8235 err = histedit_edit_list_retry(histedit_cmds, err,
8236 commits, path, branch_name, repo);
8239 done:
8240 if (f && fclose(f) != 0 && err == NULL)
8241 err = got_error_from_errno("fclose");
8242 if (path && unlink(path) != 0 && err == NULL)
8243 err = got_error_from_errno2("unlink", path);
8244 free(path);
8245 return err;
8248 static const struct got_error *
8249 histedit_save_list(struct got_histedit_list *histedit_cmds,
8250 struct got_worktree *worktree, struct got_repository *repo)
8252 const struct got_error *err = NULL;
8253 char *path = NULL;
8254 FILE *f = NULL;
8255 struct got_histedit_list_entry *hle;
8256 struct got_commit_object *commit = NULL;
8258 err = got_worktree_get_histedit_script_path(&path, worktree);
8259 if (err)
8260 return err;
8262 f = fopen(path, "w");
8263 if (f == NULL) {
8264 err = got_error_from_errno2("fopen", path);
8265 goto done;
8267 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8268 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8269 repo);
8270 if (err)
8271 break;
8273 if (hle->logmsg) {
8274 int n = fprintf(f, "%c %s\n",
8275 GOT_HISTEDIT_MESG, hle->logmsg);
8276 if (n < 0) {
8277 err = got_ferror(f, GOT_ERR_IO);
8278 break;
8282 done:
8283 if (f && fclose(f) != 0 && err == NULL)
8284 err = got_error_from_errno("fclose");
8285 free(path);
8286 if (commit)
8287 got_object_commit_close(commit);
8288 return err;
8291 void
8292 histedit_free_list(struct got_histedit_list *histedit_cmds)
8294 struct got_histedit_list_entry *hle;
8296 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8297 TAILQ_REMOVE(histedit_cmds, hle, entry);
8298 free(hle);
8302 static const struct got_error *
8303 histedit_load_list(struct got_histedit_list *histedit_cmds,
8304 const char *path, struct got_repository *repo)
8306 const struct got_error *err = NULL;
8307 FILE *f = NULL;
8309 f = fopen(path, "r");
8310 if (f == NULL) {
8311 err = got_error_from_errno2("fopen", path);
8312 goto done;
8315 err = histedit_parse_list(histedit_cmds, f, repo);
8316 done:
8317 if (f && fclose(f) != 0 && err == NULL)
8318 err = got_error_from_errno("fclose");
8319 return err;
8322 static const struct got_error *
8323 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8324 const struct got_error *edit_err, struct got_object_id_queue *commits,
8325 const char *path, const char *branch_name, struct got_repository *repo)
8327 const struct got_error *err = NULL, *prev_err = edit_err;
8328 int resp = ' ';
8330 while (resp != 'c' && resp != 'r' && resp != 'a') {
8331 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8332 "or (a)bort: ", getprogname(), prev_err->msg);
8333 resp = getchar();
8334 if (resp == '\n')
8335 resp = getchar();
8336 if (resp == 'c') {
8337 histedit_free_list(histedit_cmds);
8338 err = histedit_run_editor(histedit_cmds, path, commits,
8339 repo);
8340 if (err) {
8341 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8342 err->code != GOT_ERR_HISTEDIT_CMD)
8343 break;
8344 prev_err = err;
8345 resp = ' ';
8346 continue;
8348 break;
8349 } else if (resp == 'r') {
8350 histedit_free_list(histedit_cmds);
8351 err = histedit_edit_script(histedit_cmds,
8352 commits, branch_name, 0, repo);
8353 if (err) {
8354 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8355 err->code != GOT_ERR_HISTEDIT_CMD)
8356 break;
8357 prev_err = err;
8358 resp = ' ';
8359 continue;
8361 break;
8362 } else if (resp == 'a') {
8363 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8364 break;
8365 } else
8366 printf("invalid response '%c'\n", resp);
8369 return err;
8372 static const struct got_error *
8373 histedit_complete(struct got_worktree *worktree,
8374 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8375 struct got_reference *branch, struct got_repository *repo)
8377 printf("Switching work tree to %s\n",
8378 got_ref_get_symref_target(branch));
8379 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8380 branch, repo);
8383 static const struct got_error *
8384 show_histedit_progress(struct got_commit_object *commit,
8385 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8387 const struct got_error *err;
8388 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8390 err = got_object_id_str(&old_id_str, hle->commit_id);
8391 if (err)
8392 goto done;
8394 if (new_id) {
8395 err = got_object_id_str(&new_id_str, new_id);
8396 if (err)
8397 goto done;
8400 old_id_str[12] = '\0';
8401 if (new_id_str)
8402 new_id_str[12] = '\0';
8404 if (hle->logmsg) {
8405 logmsg = strdup(hle->logmsg);
8406 if (logmsg == NULL) {
8407 err = got_error_from_errno("strdup");
8408 goto done;
8410 trim_logmsg(logmsg, 42);
8411 } else {
8412 err = get_short_logmsg(&logmsg, 42, commit);
8413 if (err)
8414 goto done;
8417 switch (hle->cmd->code) {
8418 case GOT_HISTEDIT_PICK:
8419 case GOT_HISTEDIT_EDIT:
8420 printf("%s -> %s: %s\n", old_id_str,
8421 new_id_str ? new_id_str : "no-op change", logmsg);
8422 break;
8423 case GOT_HISTEDIT_DROP:
8424 case GOT_HISTEDIT_FOLD:
8425 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8426 logmsg);
8427 break;
8428 default:
8429 break;
8431 done:
8432 free(old_id_str);
8433 free(new_id_str);
8434 return err;
8437 static const struct got_error *
8438 histedit_commit(struct got_pathlist_head *merged_paths,
8439 struct got_worktree *worktree, struct got_fileindex *fileindex,
8440 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8441 struct got_repository *repo)
8443 const struct got_error *err;
8444 struct got_commit_object *commit;
8445 struct got_object_id *new_commit_id;
8447 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8448 && hle->logmsg == NULL) {
8449 err = histedit_edit_logmsg(hle, repo);
8450 if (err)
8451 return err;
8454 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8455 if (err)
8456 return err;
8458 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8459 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8460 hle->logmsg, repo);
8461 if (err) {
8462 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8463 goto done;
8464 err = show_histedit_progress(commit, hle, NULL);
8465 } else {
8466 err = show_histedit_progress(commit, hle, new_commit_id);
8467 free(new_commit_id);
8469 done:
8470 got_object_commit_close(commit);
8471 return err;
8474 static const struct got_error *
8475 histedit_skip_commit(struct got_histedit_list_entry *hle,
8476 struct got_worktree *worktree, struct got_repository *repo)
8478 const struct got_error *error;
8479 struct got_commit_object *commit;
8481 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8482 repo);
8483 if (error)
8484 return error;
8486 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8487 if (error)
8488 return error;
8490 error = show_histedit_progress(commit, hle, NULL);
8491 got_object_commit_close(commit);
8492 return error;
8495 static const struct got_error *
8496 check_local_changes(void *arg, unsigned char status,
8497 unsigned char staged_status, const char *path,
8498 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8499 struct got_object_id *commit_id, int dirfd, const char *de_name)
8501 int *have_local_changes = arg;
8503 switch (status) {
8504 case GOT_STATUS_ADD:
8505 case GOT_STATUS_DELETE:
8506 case GOT_STATUS_MODIFY:
8507 case GOT_STATUS_CONFLICT:
8508 *have_local_changes = 1;
8509 return got_error(GOT_ERR_CANCELLED);
8510 default:
8511 break;
8514 switch (staged_status) {
8515 case GOT_STATUS_ADD:
8516 case GOT_STATUS_DELETE:
8517 case GOT_STATUS_MODIFY:
8518 *have_local_changes = 1;
8519 return got_error(GOT_ERR_CANCELLED);
8520 default:
8521 break;
8524 return NULL;
8527 static const struct got_error *
8528 cmd_histedit(int argc, char *argv[])
8530 const struct got_error *error = NULL;
8531 struct got_worktree *worktree = NULL;
8532 struct got_fileindex *fileindex = NULL;
8533 struct got_repository *repo = NULL;
8534 char *cwd = NULL;
8535 struct got_reference *branch = NULL;
8536 struct got_reference *tmp_branch = NULL;
8537 struct got_object_id *resume_commit_id = NULL;
8538 struct got_object_id *base_commit_id = NULL;
8539 struct got_object_id *head_commit_id = NULL;
8540 struct got_commit_object *commit = NULL;
8541 int ch, rebase_in_progress = 0;
8542 struct got_update_progress_arg upa;
8543 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8544 int edit_logmsg_only = 0;
8545 const char *edit_script_path = NULL;
8546 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8547 struct got_object_id_queue commits;
8548 struct got_pathlist_head merged_paths;
8549 const struct got_object_id_queue *parent_ids;
8550 struct got_object_qid *pid;
8551 struct got_histedit_list histedit_cmds;
8552 struct got_histedit_list_entry *hle;
8554 SIMPLEQ_INIT(&commits);
8555 TAILQ_INIT(&histedit_cmds);
8556 TAILQ_INIT(&merged_paths);
8557 memset(&upa, 0, sizeof(upa));
8559 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8560 switch (ch) {
8561 case 'a':
8562 abort_edit = 1;
8563 break;
8564 case 'c':
8565 continue_edit = 1;
8566 break;
8567 case 'F':
8568 edit_script_path = optarg;
8569 break;
8570 case 'm':
8571 edit_logmsg_only = 1;
8572 break;
8573 default:
8574 usage_histedit();
8575 /* NOTREACHED */
8579 argc -= optind;
8580 argv += optind;
8582 #ifndef PROFILE
8583 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8584 "unveil", NULL) == -1)
8585 err(1, "pledge");
8586 #endif
8587 if (abort_edit && continue_edit)
8588 errx(1, "histedit's -a and -c options are mutually exclusive");
8589 if (edit_script_path && edit_logmsg_only)
8590 errx(1, "histedit's -F and -m options are mutually exclusive");
8591 if (abort_edit && edit_logmsg_only)
8592 errx(1, "histedit's -a and -m options are mutually exclusive");
8593 if (continue_edit && edit_logmsg_only)
8594 errx(1, "histedit's -c and -m options are mutually exclusive");
8595 if (argc != 0)
8596 usage_histedit();
8599 * This command cannot apply unveil(2) in all cases because the
8600 * user may choose to run an editor to edit the histedit script
8601 * and to edit individual commit log messages.
8602 * unveil(2) traverses exec(2); if an editor is used we have to
8603 * apply unveil after edit script and log messages have been written.
8604 * XXX TODO: Make use of unveil(2) where possible.
8607 cwd = getcwd(NULL, 0);
8608 if (cwd == NULL) {
8609 error = got_error_from_errno("getcwd");
8610 goto done;
8612 error = got_worktree_open(&worktree, cwd);
8613 if (error) {
8614 if (error->code == GOT_ERR_NOT_WORKTREE)
8615 error = wrap_not_worktree_error(error, "histedit", cwd);
8616 goto done;
8619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8620 NULL);
8621 if (error != NULL)
8622 goto done;
8624 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8625 if (error)
8626 goto done;
8627 if (rebase_in_progress) {
8628 error = got_error(GOT_ERR_REBASING);
8629 goto done;
8632 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8633 if (error)
8634 goto done;
8636 if (edit_in_progress && edit_logmsg_only) {
8637 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8638 "histedit operation is in progress in this "
8639 "work tree and must be continued or aborted "
8640 "before the -m option can be used");
8641 goto done;
8644 if (edit_in_progress && abort_edit) {
8645 error = got_worktree_histedit_continue(&resume_commit_id,
8646 &tmp_branch, &branch, &base_commit_id, &fileindex,
8647 worktree, repo);
8648 if (error)
8649 goto done;
8650 printf("Switching work tree to %s\n",
8651 got_ref_get_symref_target(branch));
8652 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8653 branch, base_commit_id, update_progress, &upa);
8654 if (error)
8655 goto done;
8656 printf("Histedit of %s aborted\n",
8657 got_ref_get_symref_target(branch));
8658 print_update_progress_stats(&upa);
8659 goto done; /* nothing else to do */
8660 } else if (abort_edit) {
8661 error = got_error(GOT_ERR_NOT_HISTEDIT);
8662 goto done;
8665 if (continue_edit) {
8666 char *path;
8668 if (!edit_in_progress) {
8669 error = got_error(GOT_ERR_NOT_HISTEDIT);
8670 goto done;
8673 error = got_worktree_get_histedit_script_path(&path, worktree);
8674 if (error)
8675 goto done;
8677 error = histedit_load_list(&histedit_cmds, path, repo);
8678 free(path);
8679 if (error)
8680 goto done;
8682 error = got_worktree_histedit_continue(&resume_commit_id,
8683 &tmp_branch, &branch, &base_commit_id, &fileindex,
8684 worktree, repo);
8685 if (error)
8686 goto done;
8688 error = got_ref_resolve(&head_commit_id, repo, branch);
8689 if (error)
8690 goto done;
8692 error = got_object_open_as_commit(&commit, repo,
8693 head_commit_id);
8694 if (error)
8695 goto done;
8696 parent_ids = got_object_commit_get_parent_ids(commit);
8697 pid = SIMPLEQ_FIRST(parent_ids);
8698 if (pid == NULL) {
8699 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8700 goto done;
8702 error = collect_commits(&commits, head_commit_id, pid->id,
8703 base_commit_id, got_worktree_get_path_prefix(worktree),
8704 GOT_ERR_HISTEDIT_PATH, repo);
8705 got_object_commit_close(commit);
8706 commit = NULL;
8707 if (error)
8708 goto done;
8709 } else {
8710 if (edit_in_progress) {
8711 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8712 goto done;
8715 error = got_ref_open(&branch, repo,
8716 got_worktree_get_head_ref_name(worktree), 0);
8717 if (error != NULL)
8718 goto done;
8720 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8721 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8722 "will not edit commit history of a branch outside "
8723 "the \"refs/heads/\" reference namespace");
8724 goto done;
8727 error = got_ref_resolve(&head_commit_id, repo, branch);
8728 got_ref_close(branch);
8729 branch = NULL;
8730 if (error)
8731 goto done;
8733 error = got_object_open_as_commit(&commit, repo,
8734 head_commit_id);
8735 if (error)
8736 goto done;
8737 parent_ids = got_object_commit_get_parent_ids(commit);
8738 pid = SIMPLEQ_FIRST(parent_ids);
8739 if (pid == NULL) {
8740 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8741 goto done;
8743 error = collect_commits(&commits, head_commit_id, pid->id,
8744 got_worktree_get_base_commit_id(worktree),
8745 got_worktree_get_path_prefix(worktree),
8746 GOT_ERR_HISTEDIT_PATH, repo);
8747 got_object_commit_close(commit);
8748 commit = NULL;
8749 if (error)
8750 goto done;
8752 if (SIMPLEQ_EMPTY(&commits)) {
8753 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8754 goto done;
8757 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8758 &base_commit_id, &fileindex, worktree, repo);
8759 if (error)
8760 goto done;
8762 if (edit_script_path) {
8763 error = histedit_load_list(&histedit_cmds,
8764 edit_script_path, repo);
8765 if (error) {
8766 got_worktree_histedit_abort(worktree, fileindex,
8767 repo, branch, base_commit_id,
8768 update_progress, &upa);
8769 print_update_progress_stats(&upa);
8770 goto done;
8772 } else {
8773 const char *branch_name;
8774 branch_name = got_ref_get_symref_target(branch);
8775 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8776 branch_name += 11;
8777 error = histedit_edit_script(&histedit_cmds, &commits,
8778 branch_name, edit_logmsg_only, repo);
8779 if (error) {
8780 got_worktree_histedit_abort(worktree, fileindex,
8781 repo, branch, base_commit_id,
8782 update_progress, &upa);
8783 print_update_progress_stats(&upa);
8784 goto done;
8789 error = histedit_save_list(&histedit_cmds, worktree,
8790 repo);
8791 if (error) {
8792 got_worktree_histedit_abort(worktree, fileindex,
8793 repo, branch, base_commit_id,
8794 update_progress, &upa);
8795 print_update_progress_stats(&upa);
8796 goto done;
8801 error = histedit_check_script(&histedit_cmds, &commits, repo);
8802 if (error)
8803 goto done;
8805 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8806 if (resume_commit_id) {
8807 if (got_object_id_cmp(hle->commit_id,
8808 resume_commit_id) != 0)
8809 continue;
8811 resume_commit_id = NULL;
8812 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8813 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8814 error = histedit_skip_commit(hle, worktree,
8815 repo);
8816 if (error)
8817 goto done;
8818 } else {
8819 struct got_pathlist_head paths;
8820 int have_changes = 0;
8822 TAILQ_INIT(&paths);
8823 error = got_pathlist_append(&paths, "", NULL);
8824 if (error)
8825 goto done;
8826 error = got_worktree_status(worktree, &paths,
8827 repo, check_local_changes, &have_changes,
8828 check_cancelled, NULL);
8829 got_pathlist_free(&paths);
8830 if (error) {
8831 if (error->code != GOT_ERR_CANCELLED)
8832 goto done;
8833 if (sigint_received || sigpipe_received)
8834 goto done;
8836 if (have_changes) {
8837 error = histedit_commit(NULL, worktree,
8838 fileindex, tmp_branch, hle, repo);
8839 if (error)
8840 goto done;
8841 } else {
8842 error = got_object_open_as_commit(
8843 &commit, repo, hle->commit_id);
8844 if (error)
8845 goto done;
8846 error = show_histedit_progress(commit,
8847 hle, NULL);
8848 got_object_commit_close(commit);
8849 commit = NULL;
8850 if (error)
8851 goto done;
8854 continue;
8857 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8858 error = histedit_skip_commit(hle, worktree, repo);
8859 if (error)
8860 goto done;
8861 continue;
8864 error = got_object_open_as_commit(&commit, repo,
8865 hle->commit_id);
8866 if (error)
8867 goto done;
8868 parent_ids = got_object_commit_get_parent_ids(commit);
8869 pid = SIMPLEQ_FIRST(parent_ids);
8871 error = got_worktree_histedit_merge_files(&merged_paths,
8872 worktree, fileindex, pid->id, hle->commit_id, repo,
8873 update_progress, &upa, check_cancelled, NULL);
8874 if (error)
8875 goto done;
8876 got_object_commit_close(commit);
8877 commit = NULL;
8879 print_update_progress_stats(&upa);
8880 if (upa.conflicts > 0)
8881 rebase_status = GOT_STATUS_CONFLICT;
8883 if (rebase_status == GOT_STATUS_CONFLICT) {
8884 error = show_rebase_merge_conflict(hle->commit_id,
8885 repo);
8886 if (error)
8887 goto done;
8888 got_worktree_rebase_pathlist_free(&merged_paths);
8889 break;
8892 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8893 char *id_str;
8894 error = got_object_id_str(&id_str, hle->commit_id);
8895 if (error)
8896 goto done;
8897 printf("Stopping histedit for amending commit %s\n",
8898 id_str);
8899 free(id_str);
8900 got_worktree_rebase_pathlist_free(&merged_paths);
8901 error = got_worktree_histedit_postpone(worktree,
8902 fileindex);
8903 goto done;
8906 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8907 error = histedit_skip_commit(hle, worktree, repo);
8908 if (error)
8909 goto done;
8910 continue;
8913 error = histedit_commit(&merged_paths, worktree, fileindex,
8914 tmp_branch, hle, repo);
8915 got_worktree_rebase_pathlist_free(&merged_paths);
8916 if (error)
8917 goto done;
8920 if (rebase_status == GOT_STATUS_CONFLICT) {
8921 error = got_worktree_histedit_postpone(worktree, fileindex);
8922 if (error)
8923 goto done;
8924 error = got_error_msg(GOT_ERR_CONFLICTS,
8925 "conflicts must be resolved before histedit can continue");
8926 } else
8927 error = histedit_complete(worktree, fileindex, tmp_branch,
8928 branch, repo);
8929 done:
8930 got_object_id_queue_free(&commits);
8931 histedit_free_list(&histedit_cmds);
8932 free(head_commit_id);
8933 free(base_commit_id);
8934 free(resume_commit_id);
8935 if (commit)
8936 got_object_commit_close(commit);
8937 if (branch)
8938 got_ref_close(branch);
8939 if (tmp_branch)
8940 got_ref_close(tmp_branch);
8941 if (worktree)
8942 got_worktree_close(worktree);
8943 if (repo)
8944 got_repo_close(repo);
8945 return error;
8948 __dead static void
8949 usage_integrate(void)
8951 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8952 exit(1);
8955 static const struct got_error *
8956 cmd_integrate(int argc, char *argv[])
8958 const struct got_error *error = NULL;
8959 struct got_repository *repo = NULL;
8960 struct got_worktree *worktree = NULL;
8961 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8962 const char *branch_arg = NULL;
8963 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8964 struct got_fileindex *fileindex = NULL;
8965 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8966 int ch;
8967 struct got_update_progress_arg upa;
8969 while ((ch = getopt(argc, argv, "")) != -1) {
8970 switch (ch) {
8971 default:
8972 usage_integrate();
8973 /* NOTREACHED */
8977 argc -= optind;
8978 argv += optind;
8980 if (argc != 1)
8981 usage_integrate();
8982 branch_arg = argv[0];
8983 #ifndef PROFILE
8984 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8985 "unveil", NULL) == -1)
8986 err(1, "pledge");
8987 #endif
8988 cwd = getcwd(NULL, 0);
8989 if (cwd == NULL) {
8990 error = got_error_from_errno("getcwd");
8991 goto done;
8994 error = got_worktree_open(&worktree, cwd);
8995 if (error) {
8996 if (error->code == GOT_ERR_NOT_WORKTREE)
8997 error = wrap_not_worktree_error(error, "integrate",
8998 cwd);
8999 goto done;
9002 error = check_rebase_or_histedit_in_progress(worktree);
9003 if (error)
9004 goto done;
9006 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9007 NULL);
9008 if (error != NULL)
9009 goto done;
9011 error = apply_unveil(got_repo_get_path(repo), 0,
9012 got_worktree_get_root_path(worktree));
9013 if (error)
9014 goto done;
9016 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
9017 error = got_error_from_errno("asprintf");
9018 goto done;
9021 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
9022 &base_branch_ref, worktree, refname, repo);
9023 if (error)
9024 goto done;
9026 refname = strdup(got_ref_get_name(branch_ref));
9027 if (refname == NULL) {
9028 error = got_error_from_errno("strdup");
9029 got_worktree_integrate_abort(worktree, fileindex, repo,
9030 branch_ref, base_branch_ref);
9031 goto done;
9033 base_refname = strdup(got_ref_get_name(base_branch_ref));
9034 if (base_refname == NULL) {
9035 error = got_error_from_errno("strdup");
9036 got_worktree_integrate_abort(worktree, fileindex, repo,
9037 branch_ref, base_branch_ref);
9038 goto done;
9041 error = got_ref_resolve(&commit_id, repo, branch_ref);
9042 if (error)
9043 goto done;
9045 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
9046 if (error)
9047 goto done;
9049 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
9050 error = got_error_msg(GOT_ERR_SAME_BRANCH,
9051 "specified branch has already been integrated");
9052 got_worktree_integrate_abort(worktree, fileindex, repo,
9053 branch_ref, base_branch_ref);
9054 goto done;
9057 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
9058 if (error) {
9059 if (error->code == GOT_ERR_ANCESTRY)
9060 error = got_error(GOT_ERR_REBASE_REQUIRED);
9061 got_worktree_integrate_abort(worktree, fileindex, repo,
9062 branch_ref, base_branch_ref);
9063 goto done;
9066 memset(&upa, 0, sizeof(upa));
9067 error = got_worktree_integrate_continue(worktree, fileindex, repo,
9068 branch_ref, base_branch_ref, update_progress, &upa,
9069 check_cancelled, NULL);
9070 if (error)
9071 goto done;
9073 printf("Integrated %s into %s\n", refname, base_refname);
9074 print_update_progress_stats(&upa);
9075 done:
9076 if (repo)
9077 got_repo_close(repo);
9078 if (worktree)
9079 got_worktree_close(worktree);
9080 free(cwd);
9081 free(base_commit_id);
9082 free(commit_id);
9083 free(refname);
9084 free(base_refname);
9085 return error;
9088 __dead static void
9089 usage_stage(void)
9091 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
9092 "[-S] [file-path ...]\n",
9093 getprogname());
9094 exit(1);
9097 static const struct got_error *
9098 print_stage(void *arg, unsigned char status, unsigned char staged_status,
9099 const char *path, struct got_object_id *blob_id,
9100 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
9101 int dirfd, const char *de_name)
9103 const struct got_error *err = NULL;
9104 char *id_str = NULL;
9106 if (staged_status != GOT_STATUS_ADD &&
9107 staged_status != GOT_STATUS_MODIFY &&
9108 staged_status != GOT_STATUS_DELETE)
9109 return NULL;
9111 if (staged_status == GOT_STATUS_ADD ||
9112 staged_status == GOT_STATUS_MODIFY)
9113 err = got_object_id_str(&id_str, staged_blob_id);
9114 else
9115 err = got_object_id_str(&id_str, blob_id);
9116 if (err)
9117 return err;
9119 printf("%s %c %s\n", id_str, staged_status, path);
9120 free(id_str);
9121 return NULL;
9124 static const struct got_error *
9125 cmd_stage(int argc, char *argv[])
9127 const struct got_error *error = NULL;
9128 struct got_repository *repo = NULL;
9129 struct got_worktree *worktree = NULL;
9130 char *cwd = NULL;
9131 struct got_pathlist_head paths;
9132 struct got_pathlist_entry *pe;
9133 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
9134 FILE *patch_script_file = NULL;
9135 const char *patch_script_path = NULL;
9136 struct choose_patch_arg cpa;
9138 TAILQ_INIT(&paths);
9140 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
9141 switch (ch) {
9142 case 'l':
9143 list_stage = 1;
9144 break;
9145 case 'p':
9146 pflag = 1;
9147 break;
9148 case 'F':
9149 patch_script_path = optarg;
9150 break;
9151 case 'S':
9152 allow_bad_symlinks = 1;
9153 break;
9154 default:
9155 usage_stage();
9156 /* NOTREACHED */
9160 argc -= optind;
9161 argv += optind;
9163 #ifndef PROFILE
9164 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9165 "unveil", NULL) == -1)
9166 err(1, "pledge");
9167 #endif
9168 if (list_stage && (pflag || patch_script_path))
9169 errx(1, "-l option cannot be used with other options");
9170 if (patch_script_path && !pflag)
9171 errx(1, "-F option can only be used together with -p option");
9173 cwd = getcwd(NULL, 0);
9174 if (cwd == NULL) {
9175 error = got_error_from_errno("getcwd");
9176 goto done;
9179 error = got_worktree_open(&worktree, cwd);
9180 if (error) {
9181 if (error->code == GOT_ERR_NOT_WORKTREE)
9182 error = wrap_not_worktree_error(error, "stage", cwd);
9183 goto done;
9186 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9187 NULL);
9188 if (error != NULL)
9189 goto done;
9191 if (patch_script_path) {
9192 patch_script_file = fopen(patch_script_path, "r");
9193 if (patch_script_file == NULL) {
9194 error = got_error_from_errno2("fopen",
9195 patch_script_path);
9196 goto done;
9199 error = apply_unveil(got_repo_get_path(repo), 0,
9200 got_worktree_get_root_path(worktree));
9201 if (error)
9202 goto done;
9204 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9205 if (error)
9206 goto done;
9208 if (list_stage)
9209 error = got_worktree_status(worktree, &paths, repo,
9210 print_stage, NULL, check_cancelled, NULL);
9211 else {
9212 cpa.patch_script_file = patch_script_file;
9213 cpa.action = "stage";
9214 error = got_worktree_stage(worktree, &paths,
9215 pflag ? NULL : print_status, NULL,
9216 pflag ? choose_patch : NULL, &cpa,
9217 allow_bad_symlinks, repo);
9219 done:
9220 if (patch_script_file && fclose(patch_script_file) == EOF &&
9221 error == NULL)
9222 error = got_error_from_errno2("fclose", patch_script_path);
9223 if (repo)
9224 got_repo_close(repo);
9225 if (worktree)
9226 got_worktree_close(worktree);
9227 TAILQ_FOREACH(pe, &paths, entry)
9228 free((char *)pe->path);
9229 got_pathlist_free(&paths);
9230 free(cwd);
9231 return error;
9234 __dead static void
9235 usage_unstage(void)
9237 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9238 "[file-path ...]\n",
9239 getprogname());
9240 exit(1);
9244 static const struct got_error *
9245 cmd_unstage(int argc, char *argv[])
9247 const struct got_error *error = NULL;
9248 struct got_repository *repo = NULL;
9249 struct got_worktree *worktree = NULL;
9250 char *cwd = NULL;
9251 struct got_pathlist_head paths;
9252 struct got_pathlist_entry *pe;
9253 int ch, pflag = 0;
9254 struct got_update_progress_arg upa;
9255 FILE *patch_script_file = NULL;
9256 const char *patch_script_path = NULL;
9257 struct choose_patch_arg cpa;
9259 TAILQ_INIT(&paths);
9261 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9262 switch (ch) {
9263 case 'p':
9264 pflag = 1;
9265 break;
9266 case 'F':
9267 patch_script_path = optarg;
9268 break;
9269 default:
9270 usage_unstage();
9271 /* NOTREACHED */
9275 argc -= optind;
9276 argv += optind;
9278 #ifndef PROFILE
9279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9280 "unveil", NULL) == -1)
9281 err(1, "pledge");
9282 #endif
9283 if (patch_script_path && !pflag)
9284 errx(1, "-F option can only be used together with -p option");
9286 cwd = getcwd(NULL, 0);
9287 if (cwd == NULL) {
9288 error = got_error_from_errno("getcwd");
9289 goto done;
9292 error = got_worktree_open(&worktree, cwd);
9293 if (error) {
9294 if (error->code == GOT_ERR_NOT_WORKTREE)
9295 error = wrap_not_worktree_error(error, "unstage", cwd);
9296 goto done;
9299 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9300 NULL);
9301 if (error != NULL)
9302 goto done;
9304 if (patch_script_path) {
9305 patch_script_file = fopen(patch_script_path, "r");
9306 if (patch_script_file == NULL) {
9307 error = got_error_from_errno2("fopen",
9308 patch_script_path);
9309 goto done;
9313 error = apply_unveil(got_repo_get_path(repo), 0,
9314 got_worktree_get_root_path(worktree));
9315 if (error)
9316 goto done;
9318 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9319 if (error)
9320 goto done;
9322 cpa.patch_script_file = patch_script_file;
9323 cpa.action = "unstage";
9324 memset(&upa, 0, sizeof(upa));
9325 error = got_worktree_unstage(worktree, &paths, update_progress,
9326 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9327 if (!error)
9328 print_update_progress_stats(&upa);
9329 done:
9330 if (patch_script_file && fclose(patch_script_file) == EOF &&
9331 error == NULL)
9332 error = got_error_from_errno2("fclose", patch_script_path);
9333 if (repo)
9334 got_repo_close(repo);
9335 if (worktree)
9336 got_worktree_close(worktree);
9337 TAILQ_FOREACH(pe, &paths, entry)
9338 free((char *)pe->path);
9339 got_pathlist_free(&paths);
9340 free(cwd);
9341 return error;
9344 __dead static void
9345 usage_cat(void)
9347 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9348 "arg1 [arg2 ...]\n", getprogname());
9349 exit(1);
9352 static const struct got_error *
9353 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9355 const struct got_error *err;
9356 struct got_blob_object *blob;
9358 err = got_object_open_as_blob(&blob, repo, id, 8192);
9359 if (err)
9360 return err;
9362 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9363 got_object_blob_close(blob);
9364 return err;
9367 static const struct got_error *
9368 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9370 const struct got_error *err;
9371 struct got_tree_object *tree;
9372 int nentries, i;
9374 err = got_object_open_as_tree(&tree, repo, id);
9375 if (err)
9376 return err;
9378 nentries = got_object_tree_get_nentries(tree);
9379 for (i = 0; i < nentries; i++) {
9380 struct got_tree_entry *te;
9381 char *id_str;
9382 if (sigint_received || sigpipe_received)
9383 break;
9384 te = got_object_tree_get_entry(tree, i);
9385 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9386 if (err)
9387 break;
9388 fprintf(outfile, "%s %.7o %s\n", id_str,
9389 got_tree_entry_get_mode(te),
9390 got_tree_entry_get_name(te));
9391 free(id_str);
9394 got_object_tree_close(tree);
9395 return err;
9398 static const struct got_error *
9399 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9401 const struct got_error *err;
9402 struct got_commit_object *commit;
9403 const struct got_object_id_queue *parent_ids;
9404 struct got_object_qid *pid;
9405 char *id_str = NULL;
9406 const char *logmsg = NULL;
9408 err = got_object_open_as_commit(&commit, repo, id);
9409 if (err)
9410 return err;
9412 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9413 if (err)
9414 goto done;
9416 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9417 parent_ids = got_object_commit_get_parent_ids(commit);
9418 fprintf(outfile, "numparents %d\n",
9419 got_object_commit_get_nparents(commit));
9420 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9421 char *pid_str;
9422 err = got_object_id_str(&pid_str, pid->id);
9423 if (err)
9424 goto done;
9425 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9426 free(pid_str);
9428 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9429 got_object_commit_get_author(commit),
9430 got_object_commit_get_author_time(commit));
9432 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9433 got_object_commit_get_author(commit),
9434 got_object_commit_get_committer_time(commit));
9436 logmsg = got_object_commit_get_logmsg_raw(commit);
9437 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9438 fprintf(outfile, "%s", logmsg);
9439 done:
9440 free(id_str);
9441 got_object_commit_close(commit);
9442 return err;
9445 static const struct got_error *
9446 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9448 const struct got_error *err;
9449 struct got_tag_object *tag;
9450 char *id_str = NULL;
9451 const char *tagmsg = NULL;
9453 err = got_object_open_as_tag(&tag, repo, id);
9454 if (err)
9455 return err;
9457 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9458 if (err)
9459 goto done;
9461 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9463 switch (got_object_tag_get_object_type(tag)) {
9464 case GOT_OBJ_TYPE_BLOB:
9465 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9466 GOT_OBJ_LABEL_BLOB);
9467 break;
9468 case GOT_OBJ_TYPE_TREE:
9469 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9470 GOT_OBJ_LABEL_TREE);
9471 break;
9472 case GOT_OBJ_TYPE_COMMIT:
9473 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9474 GOT_OBJ_LABEL_COMMIT);
9475 break;
9476 case GOT_OBJ_TYPE_TAG:
9477 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9478 GOT_OBJ_LABEL_TAG);
9479 break;
9480 default:
9481 break;
9484 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9485 got_object_tag_get_name(tag));
9487 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9488 got_object_tag_get_tagger(tag),
9489 got_object_tag_get_tagger_time(tag));
9491 tagmsg = got_object_tag_get_message(tag);
9492 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9493 fprintf(outfile, "%s", tagmsg);
9494 done:
9495 free(id_str);
9496 got_object_tag_close(tag);
9497 return err;
9500 static const struct got_error *
9501 cmd_cat(int argc, char *argv[])
9503 const struct got_error *error;
9504 struct got_repository *repo = NULL;
9505 struct got_worktree *worktree = NULL;
9506 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9507 const char *commit_id_str = NULL;
9508 struct got_object_id *id = NULL, *commit_id = NULL;
9509 int ch, obj_type, i, force_path = 0;
9511 #ifndef PROFILE
9512 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9513 NULL) == -1)
9514 err(1, "pledge");
9515 #endif
9517 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9518 switch (ch) {
9519 case 'c':
9520 commit_id_str = optarg;
9521 break;
9522 case 'r':
9523 repo_path = realpath(optarg, NULL);
9524 if (repo_path == NULL)
9525 return got_error_from_errno2("realpath",
9526 optarg);
9527 got_path_strip_trailing_slashes(repo_path);
9528 break;
9529 case 'P':
9530 force_path = 1;
9531 break;
9532 default:
9533 usage_cat();
9534 /* NOTREACHED */
9538 argc -= optind;
9539 argv += optind;
9541 cwd = getcwd(NULL, 0);
9542 if (cwd == NULL) {
9543 error = got_error_from_errno("getcwd");
9544 goto done;
9546 error = got_worktree_open(&worktree, cwd);
9547 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9548 goto done;
9549 if (worktree) {
9550 if (repo_path == NULL) {
9551 repo_path = strdup(
9552 got_worktree_get_repo_path(worktree));
9553 if (repo_path == NULL) {
9554 error = got_error_from_errno("strdup");
9555 goto done;
9560 if (repo_path == NULL) {
9561 repo_path = getcwd(NULL, 0);
9562 if (repo_path == NULL)
9563 return got_error_from_errno("getcwd");
9566 error = got_repo_open(&repo, repo_path, NULL);
9567 free(repo_path);
9568 if (error != NULL)
9569 goto done;
9571 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9572 if (error)
9573 goto done;
9575 if (commit_id_str == NULL)
9576 commit_id_str = GOT_REF_HEAD;
9577 error = got_repo_match_object_id(&commit_id, NULL,
9578 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9579 if (error)
9580 goto done;
9582 for (i = 0; i < argc; i++) {
9583 if (force_path) {
9584 error = got_object_id_by_path(&id, repo, commit_id,
9585 argv[i]);
9586 if (error)
9587 break;
9588 } else {
9589 error = got_repo_match_object_id(&id, &label, argv[i],
9590 GOT_OBJ_TYPE_ANY, 0, repo);
9591 if (error) {
9592 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9593 error->code != GOT_ERR_NOT_REF)
9594 break;
9595 error = got_object_id_by_path(&id, repo,
9596 commit_id, argv[i]);
9597 if (error)
9598 break;
9602 error = got_object_get_type(&obj_type, repo, id);
9603 if (error)
9604 break;
9606 switch (obj_type) {
9607 case GOT_OBJ_TYPE_BLOB:
9608 error = cat_blob(id, repo, stdout);
9609 break;
9610 case GOT_OBJ_TYPE_TREE:
9611 error = cat_tree(id, repo, stdout);
9612 break;
9613 case GOT_OBJ_TYPE_COMMIT:
9614 error = cat_commit(id, repo, stdout);
9615 break;
9616 case GOT_OBJ_TYPE_TAG:
9617 error = cat_tag(id, repo, stdout);
9618 break;
9619 default:
9620 error = got_error(GOT_ERR_OBJ_TYPE);
9621 break;
9623 if (error)
9624 break;
9625 free(label);
9626 label = NULL;
9627 free(id);
9628 id = NULL;
9630 done:
9631 free(label);
9632 free(id);
9633 free(commit_id);
9634 if (worktree)
9635 got_worktree_close(worktree);
9636 if (repo) {
9637 const struct got_error *repo_error;
9638 repo_error = got_repo_close(repo);
9639 if (error == NULL)
9640 error = repo_error;
9642 return error;
9645 __dead static void
9646 usage_info(void)
9648 fprintf(stderr, "usage: %s info [path ...]\n",
9649 getprogname());
9650 exit(1);
9653 static const struct got_error *
9654 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9655 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9656 struct got_object_id *commit_id)
9658 const struct got_error *err = NULL;
9659 char *id_str = NULL;
9660 char datebuf[128];
9661 struct tm mytm, *tm;
9662 struct got_pathlist_head *paths = arg;
9663 struct got_pathlist_entry *pe;
9666 * Clear error indication from any of the path arguments which
9667 * would cause this file index entry to be displayed.
9669 TAILQ_FOREACH(pe, paths, entry) {
9670 if (got_path_cmp(path, pe->path, strlen(path),
9671 pe->path_len) == 0 ||
9672 got_path_is_child(path, pe->path, pe->path_len))
9673 pe->data = NULL; /* no error */
9676 printf(GOT_COMMIT_SEP_STR);
9677 if (S_ISLNK(mode))
9678 printf("symlink: %s\n", path);
9679 else if (S_ISREG(mode)) {
9680 printf("file: %s\n", path);
9681 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9682 } else if (S_ISDIR(mode))
9683 printf("directory: %s\n", path);
9684 else
9685 printf("something: %s\n", path);
9687 tm = localtime_r(&mtime, &mytm);
9688 if (tm == NULL)
9689 return NULL;
9690 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9691 return got_error(GOT_ERR_NO_SPACE);
9692 printf("timestamp: %s\n", datebuf);
9694 if (blob_id) {
9695 err = got_object_id_str(&id_str, blob_id);
9696 if (err)
9697 return err;
9698 printf("based on blob: %s\n", id_str);
9699 free(id_str);
9702 if (staged_blob_id) {
9703 err = got_object_id_str(&id_str, staged_blob_id);
9704 if (err)
9705 return err;
9706 printf("based on staged blob: %s\n", id_str);
9707 free(id_str);
9710 if (commit_id) {
9711 err = got_object_id_str(&id_str, commit_id);
9712 if (err)
9713 return err;
9714 printf("based on commit: %s\n", id_str);
9715 free(id_str);
9718 return NULL;
9721 static const struct got_error *
9722 cmd_info(int argc, char *argv[])
9724 const struct got_error *error = NULL;
9725 struct got_worktree *worktree = NULL;
9726 char *cwd = NULL, *id_str = NULL;
9727 struct got_pathlist_head paths;
9728 struct got_pathlist_entry *pe;
9729 char *uuidstr = NULL;
9730 int ch, show_files = 0;
9732 TAILQ_INIT(&paths);
9734 while ((ch = getopt(argc, argv, "")) != -1) {
9735 switch (ch) {
9736 default:
9737 usage_info();
9738 /* NOTREACHED */
9742 argc -= optind;
9743 argv += optind;
9745 #ifndef PROFILE
9746 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9747 NULL) == -1)
9748 err(1, "pledge");
9749 #endif
9750 cwd = getcwd(NULL, 0);
9751 if (cwd == NULL) {
9752 error = got_error_from_errno("getcwd");
9753 goto done;
9756 error = got_worktree_open(&worktree, cwd);
9757 if (error) {
9758 if (error->code == GOT_ERR_NOT_WORKTREE)
9759 error = wrap_not_worktree_error(error, "status", cwd);
9760 goto done;
9763 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9764 if (error)
9765 goto done;
9767 if (argc >= 1) {
9768 error = get_worktree_paths_from_argv(&paths, argc, argv,
9769 worktree);
9770 if (error)
9771 goto done;
9772 show_files = 1;
9775 error = got_object_id_str(&id_str,
9776 got_worktree_get_base_commit_id(worktree));
9777 if (error)
9778 goto done;
9780 error = got_worktree_get_uuid(&uuidstr, worktree);
9781 if (error)
9782 goto done;
9784 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9785 printf("work tree base commit: %s\n", id_str);
9786 printf("work tree path prefix: %s\n",
9787 got_worktree_get_path_prefix(worktree));
9788 printf("work tree branch reference: %s\n",
9789 got_worktree_get_head_ref_name(worktree));
9790 printf("work tree UUID: %s\n", uuidstr);
9791 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9793 if (show_files) {
9794 struct got_pathlist_entry *pe;
9795 TAILQ_FOREACH(pe, &paths, entry) {
9796 if (pe->path_len == 0)
9797 continue;
9799 * Assume this path will fail. This will be corrected
9800 * in print_path_info() in case the path does suceeed.
9802 pe->data = (void *)got_error_path(pe->path,
9803 GOT_ERR_BAD_PATH);
9805 error = got_worktree_path_info(worktree, &paths,
9806 print_path_info, &paths, check_cancelled, NULL);
9807 if (error)
9808 goto done;
9809 TAILQ_FOREACH(pe, &paths, entry) {
9810 if (pe->data != NULL) {
9811 error = pe->data; /* bad path */
9812 break;
9816 done:
9817 TAILQ_FOREACH(pe, &paths, entry)
9818 free((char *)pe->path);
9819 got_pathlist_free(&paths);
9820 free(cwd);
9821 free(id_str);
9822 free(uuidstr);
9823 return error;