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"
58 #ifndef nitems
59 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
60 #endif
62 static volatile sig_atomic_t sigint_received;
63 static volatile sig_atomic_t sigpipe_received;
65 static void
66 catch_sigint(int signo)
67 {
68 sigint_received = 1;
69 }
71 static void
72 catch_sigpipe(int signo)
73 {
74 sigpipe_received = 1;
75 }
78 struct got_cmd {
79 const char *cmd_name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 const char *cmd_alias;
83 };
85 __dead static void usage(int);
86 __dead static void usage_init(void);
87 __dead static void usage_import(void);
88 __dead static void usage_clone(void);
89 __dead static void usage_fetch(void);
90 __dead static void usage_checkout(void);
91 __dead static void usage_update(void);
92 __dead static void usage_log(void);
93 __dead static void usage_diff(void);
94 __dead static void usage_blame(void);
95 __dead static void usage_tree(void);
96 __dead static void usage_status(void);
97 __dead static void usage_ref(void);
98 __dead static void usage_branch(void);
99 __dead static void usage_tag(void);
100 __dead static void usage_add(void);
101 __dead static void usage_remove(void);
102 __dead static void usage_revert(void);
103 __dead static void usage_commit(void);
104 __dead static void usage_cherrypick(void);
105 __dead static void usage_backout(void);
106 __dead static void usage_rebase(void);
107 __dead static void usage_histedit(void);
108 __dead static void usage_integrate(void);
109 __dead static void usage_stage(void);
110 __dead static void usage_unstage(void);
111 __dead static void usage_cat(void);
113 static const struct got_error* cmd_init(int, char *[]);
114 static const struct got_error* cmd_import(int, char *[]);
115 static const struct got_error* cmd_clone(int, char *[]);
116 static const struct got_error* cmd_fetch(int, char *[]);
117 static const struct got_error* cmd_checkout(int, char *[]);
118 static const struct got_error* cmd_update(int, char *[]);
119 static const struct got_error* cmd_log(int, char *[]);
120 static const struct got_error* cmd_diff(int, char *[]);
121 static const struct got_error* cmd_blame(int, char *[]);
122 static const struct got_error* cmd_tree(int, char *[]);
123 static const struct got_error* cmd_status(int, char *[]);
124 static const struct got_error* cmd_ref(int, char *[]);
125 static const struct got_error* cmd_branch(int, char *[]);
126 static const struct got_error* cmd_tag(int, char *[]);
127 static const struct got_error* cmd_add(int, char *[]);
128 static const struct got_error* cmd_remove(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_rebase(int, char *[]);
134 static const struct got_error* cmd_histedit(int, char *[]);
135 static const struct got_error* cmd_integrate(int, char *[]);
136 static const struct got_error* cmd_stage(int, char *[]);
137 static const struct got_error* cmd_unstage(int, char *[]);
138 static const struct got_error* cmd_cat(int, char *[]);
140 static struct got_cmd got_commands[] = {
141 { "init", cmd_init, usage_init, "in" },
142 { "import", cmd_import, usage_import, "im" },
143 { "clone", cmd_clone, usage_clone, "cl" },
144 { "fetch", cmd_fetch, usage_fetch, "fe" },
145 { "checkout", cmd_checkout, usage_checkout, "co" },
146 { "update", cmd_update, usage_update, "up" },
147 { "log", cmd_log, usage_log, "" },
148 { "diff", cmd_diff, usage_diff, "di" },
149 { "blame", cmd_blame, usage_blame, "bl" },
150 { "tree", cmd_tree, usage_tree, "tr" },
151 { "status", cmd_status, usage_status, "st" },
152 { "ref", cmd_ref, usage_ref, "" },
153 { "branch", cmd_branch, usage_branch, "br" },
154 { "tag", cmd_tag, usage_tag, "" },
155 { "add", cmd_add, usage_add, "" },
156 { "remove", cmd_remove, usage_remove, "rm" },
157 { "revert", cmd_revert, usage_revert, "rv" },
158 { "commit", cmd_commit, usage_commit, "ci" },
159 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
160 { "backout", cmd_backout, usage_backout, "bo" },
161 { "rebase", cmd_rebase, usage_rebase, "rb" },
162 { "histedit", cmd_histedit, usage_histedit, "he" },
163 { "integrate", cmd_integrate, usage_integrate,"ig" },
164 { "stage", cmd_stage, usage_stage, "sg" },
165 { "unstage", cmd_unstage, usage_unstage, "ug" },
166 { "cat", cmd_cat, usage_cat, "" },
167 };
169 static void
170 list_commands(void)
172 int i;
174 fprintf(stderr, "commands:");
175 for (i = 0; i < nitems(got_commands); i++) {
176 struct got_cmd *cmd = &got_commands[i];
177 fprintf(stderr, " %s", cmd->cmd_name);
179 fputc('\n', stderr);
182 int
183 main(int argc, char *argv[])
185 struct got_cmd *cmd;
186 unsigned int i;
187 int ch;
188 int hflag = 0, Vflag = 0;
189 static struct option longopts[] = {
190 { "version", no_argument, NULL, 'V' },
191 { NULL, 0, NULL, 0}
192 };
194 setlocale(LC_CTYPE, "");
196 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
197 switch (ch) {
198 case 'h':
199 hflag = 1;
200 break;
201 case 'V':
202 Vflag = 1;
203 break;
204 default:
205 usage(hflag);
206 /* NOTREACHED */
210 argc -= optind;
211 argv += optind;
212 optind = 0;
214 if (Vflag) {
215 got_version_print_str();
216 return 1;
219 if (argc <= 0)
220 usage(hflag);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 got_commands[i].cmd_usage();
237 error = got_commands[i].cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands();
253 return 1;
256 __dead static void
257 usage(int hflag)
259 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
260 getprogname());
261 if (hflag)
262 list_commands();
263 exit(1);
266 static const struct got_error *
267 get_editor(char **abspath)
269 const struct got_error *err = NULL;
270 const char *editor;
272 *abspath = NULL;
274 editor = getenv("VISUAL");
275 if (editor == NULL)
276 editor = getenv("EDITOR");
278 if (editor) {
279 err = got_path_find_prog(abspath, editor);
280 if (err)
281 return err;
284 if (*abspath == NULL) {
285 *abspath = strdup("/bin/ed");
286 if (*abspath == NULL)
287 return got_error_from_errno("strdup");
290 return NULL;
293 static const struct got_error *
294 apply_unveil(const char *repo_path, int repo_read_only,
295 const char *worktree_path)
297 const struct got_error *err;
299 #ifdef PROFILE
300 if (unveil("gmon.out", "rwc") != 0)
301 return got_error_from_errno2("unveil", "gmon.out");
302 #endif
303 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
304 return got_error_from_errno2("unveil", repo_path);
306 if (worktree_path && unveil(worktree_path, "rwc") != 0)
307 return got_error_from_errno2("unveil", worktree_path);
309 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
310 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
312 err = got_privsep_unveil_exec_helpers();
313 if (err != NULL)
314 return err;
316 if (unveil(NULL, NULL) != 0)
317 return got_error_from_errno("unveil");
319 return NULL;
322 __dead static void
323 usage_init(void)
325 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
326 exit(1);
329 static const struct got_error *
330 cmd_init(int argc, char *argv[])
332 const struct got_error *error = NULL;
333 char *repo_path = NULL;
334 int ch;
336 while ((ch = getopt(argc, argv, "")) != -1) {
337 switch (ch) {
338 default:
339 usage_init();
340 /* NOTREACHED */
344 argc -= optind;
345 argv += optind;
347 #ifndef PROFILE
348 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
349 err(1, "pledge");
350 #endif
351 if (argc != 1)
352 usage_init();
354 repo_path = strdup(argv[0]);
355 if (repo_path == NULL)
356 return got_error_from_errno("strdup");
358 got_path_strip_trailing_slashes(repo_path);
360 error = got_path_mkdir(repo_path);
361 if (error &&
362 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
363 goto done;
365 error = apply_unveil(repo_path, 0, NULL);
366 if (error)
367 goto done;
369 error = got_repo_init(repo_path);
370 done:
371 free(repo_path);
372 return error;
375 __dead static void
376 usage_import(void)
378 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
379 "[-r repository-path] [-I pattern] path\n", getprogname());
380 exit(1);
383 int
384 spawn_editor(const char *editor, const char *file)
386 pid_t pid;
387 sig_t sighup, sigint, sigquit;
388 int st = -1;
390 sighup = signal(SIGHUP, SIG_IGN);
391 sigint = signal(SIGINT, SIG_IGN);
392 sigquit = signal(SIGQUIT, SIG_IGN);
394 switch (pid = fork()) {
395 case -1:
396 goto doneediting;
397 case 0:
398 execl(editor, editor, file, (char *)NULL);
399 _exit(127);
402 while (waitpid(pid, &st, 0) == -1)
403 if (errno != EINTR)
404 break;
406 doneediting:
407 (void)signal(SIGHUP, sighup);
408 (void)signal(SIGINT, sigint);
409 (void)signal(SIGQUIT, sigquit);
411 if (!WIFEXITED(st)) {
412 errno = EINTR;
413 return -1;
416 return WEXITSTATUS(st);
419 static const struct got_error *
420 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
421 const char *initial_content)
423 const struct got_error *err = NULL;
424 char buf[1024];
425 struct stat st, st2;
426 FILE *fp;
427 int content_changed = 0;
428 size_t len;
430 *logmsg = NULL;
432 if (stat(logmsg_path, &st) == -1)
433 return got_error_from_errno2("stat", logmsg_path);
435 if (spawn_editor(editor, logmsg_path) == -1)
436 return got_error_from_errno("failed spawning editor");
438 if (stat(logmsg_path, &st2) == -1)
439 return got_error_from_errno("stat");
441 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 *logmsg = malloc(st2.st_size + 1);
446 if (*logmsg == NULL)
447 return got_error_from_errno("malloc");
448 (*logmsg)[0] = '\0';
449 len = 0;
451 fp = fopen(logmsg_path, "r");
452 if (fp == NULL) {
453 err = got_error_from_errno("fopen");
454 goto done;
456 while (fgets(buf, sizeof(buf), fp) != NULL) {
457 if (!content_changed && strcmp(buf, initial_content) != 0)
458 content_changed = 1;
459 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
460 continue; /* remove comments and leading empty lines */
461 len = strlcat(*logmsg, buf, st2.st_size);
463 fclose(fp);
465 while (len > 0 && (*logmsg)[len - 1] == '\n') {
466 (*logmsg)[len - 1] = '\0';
467 len--;
470 if (len == 0 || !content_changed)
471 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "commit message cannot be empty, aborting");
473 done:
474 if (err) {
475 free(*logmsg);
476 *logmsg = NULL;
478 return err;
481 static const struct got_error *
482 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
483 const char *path_dir, const char *branch_name)
485 char *initial_content = NULL;
486 const struct got_error *err = NULL;
487 int fd;
489 if (asprintf(&initial_content,
490 "\n# %s to be imported to branch %s\n", path_dir,
491 branch_name) == -1)
492 return got_error_from_errno("asprintf");
494 err = got_opentemp_named_fd(logmsg_path, &fd,
495 GOT_TMPDIR_STR "/got-importmsg");
496 if (err)
497 goto done;
499 dprintf(fd, initial_content);
500 close(fd);
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
503 done:
504 free(initial_content);
505 return err;
508 static const struct got_error *
509 import_progress(void *arg, const char *path)
511 printf("A %s\n", path);
512 return NULL;
515 static const struct got_error *
516 get_author(char **author, struct got_repository *repo)
518 const struct got_error *err = NULL;
519 const char *got_author, *name, *email;
521 *author = NULL;
523 name = got_repo_get_gitconfig_author_name(repo);
524 email = got_repo_get_gitconfig_author_email(repo);
525 if (name && email) {
526 if (asprintf(author, "%s <%s>", name, email) == -1)
527 return got_error_from_errno("asprintf");
528 return NULL;
531 got_author = getenv("GOT_AUTHOR");
532 if (got_author == NULL) {
533 name = got_repo_get_global_gitconfig_author_name(repo);
534 email = got_repo_get_global_gitconfig_author_email(repo);
535 if (name && email) {
536 if (asprintf(author, "%s <%s>", name, email) == -1)
537 return got_error_from_errno("asprintf");
538 return NULL;
540 /* TODO: Look up user in password database? */
541 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
544 *author = strdup(got_author);
545 if (*author == NULL)
546 return got_error_from_errno("strdup");
548 /*
549 * Really dumb email address check; we're only doing this to
550 * avoid git's object parser breaking on commits we create.
551 */
552 while (*got_author && *got_author != '<')
553 got_author++;
554 if (*got_author != '<') {
555 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
556 goto done;
558 while (*got_author && *got_author != '@')
559 got_author++;
560 if (*got_author != '@') {
561 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
562 goto done;
564 while (*got_author && *got_author != '>')
565 got_author++;
566 if (*got_author != '>')
567 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
568 done:
569 if (err) {
570 free(*author);
571 *author = NULL;
573 return err;
576 static const struct got_error *
577 get_gitconfig_path(char **gitconfig_path)
579 const char *homedir = getenv("HOME");
581 *gitconfig_path = NULL;
582 if (homedir) {
583 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
584 return got_error_from_errno("asprintf");
587 return NULL;
590 static const struct got_error *
591 cmd_import(int argc, char *argv[])
593 const struct got_error *error = NULL;
594 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
595 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
596 const char *branch_name = "main";
597 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
598 struct got_repository *repo = NULL;
599 struct got_reference *branch_ref = NULL, *head_ref = NULL;
600 struct got_object_id *new_commit_id = NULL;
601 int ch;
602 struct got_pathlist_head ignores;
603 struct got_pathlist_entry *pe;
604 int preserve_logmsg = 0;
606 TAILQ_INIT(&ignores);
608 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
609 switch (ch) {
610 case 'b':
611 branch_name = optarg;
612 break;
613 case 'm':
614 logmsg = strdup(optarg);
615 if (logmsg == NULL) {
616 error = got_error_from_errno("strdup");
617 goto done;
619 break;
620 case 'r':
621 repo_path = realpath(optarg, NULL);
622 if (repo_path == NULL) {
623 error = got_error_from_errno2("realpath",
624 optarg);
625 goto done;
627 break;
628 case 'I':
629 if (optarg[0] == '\0')
630 break;
631 error = got_pathlist_insert(&pe, &ignores, optarg,
632 NULL);
633 if (error)
634 goto done;
635 break;
636 default:
637 usage_import();
638 /* NOTREACHED */
642 argc -= optind;
643 argv += optind;
645 #ifndef PROFILE
646 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
647 "unveil",
648 NULL) == -1)
649 err(1, "pledge");
650 #endif
651 if (argc != 1)
652 usage_import();
654 if (repo_path == NULL) {
655 repo_path = getcwd(NULL, 0);
656 if (repo_path == NULL)
657 return got_error_from_errno("getcwd");
659 got_path_strip_trailing_slashes(repo_path);
660 error = get_gitconfig_path(&gitconfig_path);
661 if (error)
662 goto done;
663 error = got_repo_open(&repo, repo_path, gitconfig_path);
664 if (error)
665 goto done;
667 error = get_author(&author, repo);
668 if (error)
669 return error;
671 /*
672 * Don't let the user create a branch name with a leading '-'.
673 * While technically a valid reference name, this case is usually
674 * an unintended typo.
675 */
676 if (branch_name[0] == '-')
677 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
679 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
680 error = got_error_from_errno("asprintf");
681 goto done;
684 error = got_ref_open(&branch_ref, repo, refname, 0);
685 if (error) {
686 if (error->code != GOT_ERR_NOT_REF)
687 goto done;
688 } else {
689 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
690 "import target branch already exists");
691 goto done;
694 path_dir = realpath(argv[0], NULL);
695 if (path_dir == NULL) {
696 error = got_error_from_errno2("realpath", argv[0]);
697 goto done;
699 got_path_strip_trailing_slashes(path_dir);
701 /*
702 * unveil(2) traverses exec(2); if an editor is used we have
703 * to apply unveil after the log message has been written.
704 */
705 if (logmsg == NULL || strlen(logmsg) == 0) {
706 error = get_editor(&editor);
707 if (error)
708 goto done;
709 free(logmsg);
710 error = collect_import_msg(&logmsg, &logmsg_path, editor,
711 path_dir, refname);
712 if (error) {
713 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
714 logmsg_path != NULL)
715 preserve_logmsg = 1;
716 goto done;
720 if (unveil(path_dir, "r") != 0) {
721 error = got_error_from_errno2("unveil", path_dir);
722 if (logmsg_path)
723 preserve_logmsg = 1;
724 goto done;
727 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
728 if (error) {
729 if (logmsg_path)
730 preserve_logmsg = 1;
731 goto done;
734 error = got_repo_import(&new_commit_id, path_dir, logmsg,
735 author, &ignores, repo, import_progress, NULL);
736 if (error) {
737 if (logmsg_path)
738 preserve_logmsg = 1;
739 goto done;
742 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
743 if (error) {
744 if (logmsg_path)
745 preserve_logmsg = 1;
746 goto done;
749 error = got_ref_write(branch_ref, repo);
750 if (error) {
751 if (logmsg_path)
752 preserve_logmsg = 1;
753 goto done;
756 error = got_object_id_str(&id_str, new_commit_id);
757 if (error) {
758 if (logmsg_path)
759 preserve_logmsg = 1;
760 goto done;
763 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
764 if (error) {
765 if (error->code != GOT_ERR_NOT_REF) {
766 if (logmsg_path)
767 preserve_logmsg = 1;
768 goto done;
771 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
772 branch_ref);
773 if (error) {
774 if (logmsg_path)
775 preserve_logmsg = 1;
776 goto done;
779 error = got_ref_write(head_ref, repo);
780 if (error) {
781 if (logmsg_path)
782 preserve_logmsg = 1;
783 goto done;
787 printf("Created branch %s with commit %s\n",
788 got_ref_get_name(branch_ref), id_str);
789 done:
790 if (preserve_logmsg) {
791 fprintf(stderr, "%s: log message preserved in %s\n",
792 getprogname(), logmsg_path);
793 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
794 error = got_error_from_errno2("unlink", logmsg_path);
795 free(logmsg);
796 free(logmsg_path);
797 free(repo_path);
798 free(editor);
799 free(refname);
800 free(new_commit_id);
801 free(id_str);
802 free(author);
803 free(gitconfig_path);
804 if (branch_ref)
805 got_ref_close(branch_ref);
806 if (head_ref)
807 got_ref_close(head_ref);
808 return error;
811 __dead static void
812 usage_clone(void)
814 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-m] [-q] [-v] "
815 "repository-url [directory]\n", getprogname());
816 exit(1);
819 struct got_fetch_progress_arg {
820 char last_scaled_size[FMT_SCALED_STRSIZE];
821 int last_p_indexed;
822 int last_p_resolved;
823 int verbosity;
824 };
826 static const struct got_error *
827 fetch_progress(void *arg, const char *message, off_t packfile_size,
828 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
830 struct got_fetch_progress_arg *a = arg;
831 char scaled_size[FMT_SCALED_STRSIZE];
832 int p_indexed, p_resolved;
833 int print_size = 0, print_indexed = 0, print_resolved = 0;
835 if (a->verbosity < 0)
836 return NULL;
838 if (message && message[0] != '\0') {
839 printf("\rserver: %s", message);
840 fflush(stdout);
841 return NULL;
844 if (packfile_size > 0 || nobj_indexed > 0) {
845 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
846 (a->last_scaled_size[0] == '\0' ||
847 strcmp(scaled_size, a->last_scaled_size)) != 0) {
848 print_size = 1;
849 if (strlcpy(a->last_scaled_size, scaled_size,
850 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
851 return got_error(GOT_ERR_NO_SPACE);
853 if (nobj_indexed > 0) {
854 p_indexed = (nobj_indexed * 100) / nobj_total;
855 if (p_indexed != a->last_p_indexed) {
856 a->last_p_indexed = p_indexed;
857 print_indexed = 1;
858 print_size = 1;
861 if (nobj_resolved > 0) {
862 p_resolved = (nobj_resolved * 100) /
863 (nobj_total - nobj_loose);
864 if (p_resolved != a->last_p_resolved) {
865 a->last_p_resolved = p_resolved;
866 print_resolved = 1;
867 print_indexed = 1;
868 print_size = 1;
873 if (print_size || print_indexed || print_resolved)
874 printf("\r");
875 if (print_size)
876 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
877 if (print_indexed)
878 printf("; indexing %d%%", p_indexed);
879 if (print_resolved)
880 printf("; resolving deltas %d%%", p_resolved);
881 if (print_size || print_indexed || print_resolved)
882 fflush(stdout);
884 return NULL;
887 static const struct got_error *
888 create_head_ref(struct got_reference *target_ref, struct got_repository *repo)
890 const struct got_error *err;
891 struct got_reference *head_symref;
893 err = got_ref_alloc_symref(&head_symref, GOT_REF_HEAD, target_ref);
894 if (err)
895 return err;
897 err = got_ref_write(head_symref, repo);
898 got_ref_close(head_symref);
899 return err;
902 static const struct got_error *
903 cmd_clone(int argc, char *argv[])
905 const struct got_error *error = NULL;
906 const char *uri, *dirname;
907 char *proto, *host, *port, *repo_name, *server_path;
908 char *default_destdir = NULL, *id_str = NULL;
909 const char *repo_path;
910 struct got_repository *repo = NULL;
911 struct got_pathlist_head refs, symrefs, wanted_branches;
912 struct got_pathlist_entry *pe;
913 struct got_object_id *pack_hash = NULL;
914 int ch, fetchfd = -1;
915 struct got_fetch_progress_arg fpa;
916 char *git_url = NULL;
917 char *gitconfig_path = NULL;
918 char *gitconfig = NULL;
919 FILE *gitconfig_file = NULL;
920 ssize_t n;
921 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
922 struct got_reference *head_symref = NULL;
924 TAILQ_INIT(&refs);
925 TAILQ_INIT(&symrefs);
926 TAILQ_INIT(&wanted_branches);
928 while ((ch = getopt(argc, argv, "ab:mvq")) != -1) {
929 switch (ch) {
930 case 'a':
931 fetch_all_branches = 1;
932 break;
933 case 'b':
934 error = got_pathlist_append(&wanted_branches,
935 optarg, NULL);
936 if (error)
937 return error;
938 break;
939 case 'm':
940 mirror_references = 1;
941 break;
942 case 'v':
943 if (verbosity < 0)
944 verbosity = 0;
945 else if (verbosity < 3)
946 verbosity++;
947 break;
948 case 'q':
949 verbosity = -1;
950 break;
951 default:
952 usage_clone();
953 break;
956 argc -= optind;
957 argv += optind;
959 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
960 errx(1, "-a and -b options are mutually exclusive\n");
962 uri = argv[0];
964 if (argc == 1)
965 dirname = NULL;
966 else if (argc == 2)
967 dirname = argv[1];
968 else
969 usage_clone();
971 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
972 &repo_name, argv[0]);
973 if (error)
974 goto done;
976 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
977 host, port ? ":" : "", port ? port : "",
978 server_path[0] != '/' ? "/" : "", server_path) == -1) {
979 error = got_error_from_errno("asprintf");
980 goto done;
983 if (strcmp(proto, "git") == 0) {
984 #ifndef PROFILE
985 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
986 "sendfd dns inet unveil", NULL) == -1)
987 err(1, "pledge");
988 #endif
989 } else if (strcmp(proto, "git+ssh") == 0 ||
990 strcmp(proto, "ssh") == 0) {
991 #ifndef PROFILE
992 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
993 "sendfd unveil", NULL) == -1)
994 err(1, "pledge");
995 #endif
996 } else if (strcmp(proto, "http") == 0 ||
997 strcmp(proto, "git+http") == 0) {
998 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
999 goto done;
1000 } else {
1001 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1002 goto done;
1004 if (dirname == NULL) {
1005 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1006 error = got_error_from_errno("asprintf");
1007 goto done;
1009 repo_path = default_destdir;
1010 } else
1011 repo_path = dirname;
1013 error = got_path_mkdir(repo_path);
1014 if (error)
1015 goto done;
1017 error = got_repo_init(repo_path);
1018 if (error)
1019 goto done;
1021 error = got_repo_open(&repo, repo_path, NULL);
1022 if (error)
1023 goto done;
1025 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1026 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1027 error = got_error_from_errno2("unveil",
1028 GOT_FETCH_PATH_SSH);
1029 goto done;
1032 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1033 if (error)
1034 goto done;
1036 error = got_fetch_connect(&fetchfd, proto, host, port, server_path,
1037 verbosity);
1038 if (error)
1039 goto done;
1041 if (verbosity >= 0)
1042 printf("Connected to %s%s%s\n", host,
1043 port ? ":" : "", port ? port : "");
1045 fpa.last_scaled_size[0] = '\0';
1046 fpa.last_p_indexed = -1;
1047 fpa.last_p_resolved = -1;
1048 fpa.verbosity = verbosity;
1049 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1050 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1051 fetch_all_branches, &wanted_branches, fetchfd,
1052 repo, fetch_progress, &fpa);
1053 if (error)
1054 goto done;
1056 error = got_object_id_str(&id_str, pack_hash);
1057 if (error)
1058 goto done;
1059 if (verbosity >= 0)
1060 printf("\nFetched %s.pack\n", id_str);
1061 free(id_str);
1063 /* Set up references provided with the pack file. */
1064 TAILQ_FOREACH(pe, &refs, entry) {
1065 const char *refname = pe->path;
1066 struct got_object_id *id = pe->data;
1067 struct got_reference *ref;
1068 char *remote_refname;
1070 error = got_ref_alloc(&ref, refname, id);
1071 if (error)
1072 goto done;
1073 error = got_ref_write(ref, repo);
1074 got_ref_close(ref);
1075 if (error)
1076 goto done;
1078 if (mirror_references)
1079 continue;
1081 if (strncmp("refs/heads/", refname, 11) != 0)
1082 continue;
1084 if (asprintf(&remote_refname,
1085 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1086 refname + 11) == -1) {
1087 error = got_error_from_errno("asprintf");
1088 goto done;
1090 error = got_ref_alloc(&ref, remote_refname, id);
1091 if (error)
1092 goto done;
1093 error = got_ref_write(ref, repo);
1094 got_ref_close(ref);
1095 if (error)
1096 goto done;
1099 /* Set the HEAD reference if the server provided one. */
1100 TAILQ_FOREACH(pe, &symrefs, entry) {
1101 struct got_reference *target_ref;
1102 const char *refname = pe->path;
1103 const char *target = pe->data;
1105 if (strcmp(refname, GOT_REF_HEAD) != 0)
1106 continue;
1108 error = got_ref_open(&target_ref, repo, target, 0);
1109 if (error) {
1110 if (error->code == GOT_ERR_NOT_REF) {
1111 error = NULL;
1112 continue;
1114 goto done;
1117 if (verbosity >= 0)
1118 printf("Setting %s to %s\n", refname, target);
1119 error = create_head_ref(target_ref, repo);
1120 got_ref_close(target_ref);
1121 if (error)
1122 goto done;
1124 if (pe == NULL) {
1126 * We failed to set the HEAD reference. If we asked for
1127 * a set of wanted branches use the first of one of those
1128 * which could be fetched instead.
1130 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1131 const char *target = pe->path;
1132 struct got_reference *target_ref;
1134 error = got_ref_open(&target_ref, repo, target, 0);
1135 if (error) {
1136 if (error->code == GOT_ERR_NOT_REF) {
1137 error = NULL;
1138 continue;
1140 goto done;
1143 if (verbosity >= 0)
1144 printf("Setting %s to %s\n", GOT_REF_HEAD,
1145 got_ref_get_name(target_ref));
1146 error = create_head_ref(target_ref, repo);
1147 got_ref_close(target_ref);
1148 if (error)
1149 goto done;
1150 break;
1154 /* Create a config file git-fetch(1) can understand. */
1155 gitconfig_path = got_repo_get_path_gitconfig(repo);
1156 if (gitconfig_path == NULL) {
1157 error = got_error_from_errno("got_repo_get_path_gitconfig");
1158 goto done;
1160 gitconfig_file = fopen(gitconfig_path, "a");
1161 if (gitconfig_file == NULL) {
1162 error = got_error_from_errno2("fopen", gitconfig_path);
1163 goto done;
1165 if (mirror_references) {
1166 if (asprintf(&gitconfig,
1167 "[remote \"%s\"]\n"
1168 "\turl = %s\n"
1169 "\tfetch = +refs/*:refs/*\n"
1170 "\tmirror = true\n",
1171 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1172 error = got_error_from_errno("asprintf");
1173 goto done;
1175 } else if (fetch_all_branches) {
1176 if (asprintf(&gitconfig,
1177 "[remote \"%s\"]\n"
1178 "\turl = %s\n"
1179 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1180 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1181 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1182 error = got_error_from_errno("asprintf");
1183 goto done;
1185 } else {
1186 const char *branchname;
1189 * If the server specified a default branch, use just that one.
1190 * Otherwise fall back to fetching all branches on next fetch.
1192 if (head_symref) {
1193 branchname = got_ref_get_symref_target(head_symref);
1194 if (strncmp(branchname, "refs/heads/", 11) == 0)
1195 branchname += 11;
1196 } else
1197 branchname = "*"; /* fall back to all branches */
1198 if (asprintf(&gitconfig,
1199 "[remote \"%s\"]\n"
1200 "\turl = %s\n"
1201 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1202 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1203 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1204 branchname) == -1) {
1205 error = got_error_from_errno("asprintf");
1206 goto done;
1209 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1210 if (n != strlen(gitconfig)) {
1211 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1212 goto done;
1216 if (verbosity >= 0)
1217 printf("Created %s repository '%s'\n",
1218 mirror_references ? "mirrored" : "cloned", repo_path);
1219 done:
1220 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1221 error = got_error_from_errno("close");
1222 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1223 error = got_error_from_errno("fclose");
1224 if (repo)
1225 got_repo_close(repo);
1226 if (head_symref)
1227 got_ref_close(head_symref);
1228 TAILQ_FOREACH(pe, &refs, entry) {
1229 free((void *)pe->path);
1230 free(pe->data);
1232 got_pathlist_free(&refs);
1233 TAILQ_FOREACH(pe, &symrefs, entry) {
1234 free((void *)pe->path);
1235 free(pe->data);
1237 got_pathlist_free(&symrefs);
1238 got_pathlist_free(&wanted_branches);
1239 free(pack_hash);
1240 free(proto);
1241 free(host);
1242 free(port);
1243 free(server_path);
1244 free(repo_name);
1245 free(default_destdir);
1246 free(gitconfig_path);
1247 free(git_url);
1248 return error;
1251 static const struct got_error *
1252 create_ref(const char *refname, struct got_object_id *id,
1253 const char *id_str, struct got_repository *repo)
1255 const struct got_error *err = NULL;
1256 struct got_reference *ref;
1258 printf("Creating %s: %s\n", refname, id_str);
1260 err = got_ref_alloc(&ref, refname, id);
1261 if (err)
1262 return err;
1264 err = got_ref_write(ref, repo);
1265 got_ref_close(ref);
1266 return err;
1269 static const struct got_error *
1270 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1271 struct got_repository *repo)
1273 const struct got_error *err = NULL;
1274 char *new_id_str = NULL;
1275 struct got_object_id *old_id = NULL;
1277 err = got_object_id_str(&new_id_str, new_id);
1278 if (err)
1279 goto done;
1281 if (got_ref_is_symbolic(ref)) {
1282 struct got_reference *new_ref;
1283 err = got_ref_alloc(&new_ref, got_ref_get_name(ref), new_id);
1284 if (err)
1285 goto done;
1286 printf("Deleting symbolic reference %s -> %s\n",
1287 got_ref_get_name(ref), got_ref_get_symref_target(ref));
1288 err = got_ref_delete(ref, repo);
1289 if (err)
1290 goto done;
1291 printf("Setting %s to %s\n", got_ref_get_name(ref),
1292 new_id_str);
1293 err = got_ref_write(new_ref, repo);
1294 if (err)
1295 goto done;
1296 } else {
1297 err = got_ref_resolve(&old_id, repo, ref);
1298 if (err)
1299 goto done;
1300 if (got_object_id_cmp(old_id, new_id) != 0) {
1301 printf("Setting %s to %s\n",
1302 got_ref_get_name(ref), new_id_str);
1303 err = got_ref_change_ref(ref, new_id);
1304 if (err)
1305 goto done;
1306 err = got_ref_write(ref, repo);
1307 if (err)
1308 goto done;
1311 done:
1312 free(old_id);
1313 free(new_id_str);
1314 return err;
1317 __dead static void
1318 usage_fetch(void)
1320 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-r repository-path] "
1321 "[-q] [-v] [remote-repository-name]\n", getprogname());
1322 exit(1);
1325 static const struct got_error *
1326 cmd_fetch(int argc, char *argv[])
1328 const struct got_error *error = NULL;
1329 char *cwd = NULL, *repo_path = NULL;
1330 const char *remote_name;
1331 char *proto = NULL, *host = NULL, *port = NULL;
1332 char *repo_name = NULL, *server_path = NULL;
1333 struct got_remote_repo *remotes, *remote = NULL;
1334 int nremotes;
1335 char *id_str = NULL;
1336 struct got_repository *repo = NULL;
1337 struct got_worktree *worktree = NULL;
1338 struct got_pathlist_head refs, symrefs, wanted_branches;
1339 struct got_pathlist_entry *pe;
1340 struct got_object_id *pack_hash = NULL;
1341 int i, ch, fetchfd = -1;
1342 struct got_fetch_progress_arg fpa;
1343 int verbosity = 0, fetch_all_branches = 0;
1345 TAILQ_INIT(&refs);
1346 TAILQ_INIT(&symrefs);
1347 TAILQ_INIT(&wanted_branches);
1349 while ((ch = getopt(argc, argv, "ab:r:vq")) != -1) {
1350 switch (ch) {
1351 case 'a':
1352 fetch_all_branches = 1;
1353 break;
1354 case 'b':
1355 error = got_pathlist_append(&wanted_branches,
1356 optarg, NULL);
1357 if (error)
1358 return error;
1359 break;
1360 case 'r':
1361 repo_path = realpath(optarg, NULL);
1362 if (repo_path == NULL)
1363 return got_error_from_errno2("realpath",
1364 optarg);
1365 got_path_strip_trailing_slashes(repo_path);
1366 break;
1367 case 'v':
1368 if (verbosity < 0)
1369 verbosity = 0;
1370 else if (verbosity < 3)
1371 verbosity++;
1372 break;
1373 case 'q':
1374 verbosity = -1;
1375 break;
1376 default:
1377 usage_fetch();
1378 break;
1381 argc -= optind;
1382 argv += optind;
1384 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1385 errx(1, "-a and -b options are mutually exclusive\n");
1387 if (argc == 0)
1388 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1389 else if (argc == 1)
1390 remote_name = argv[0];
1391 else
1392 usage_fetch();
1394 cwd = getcwd(NULL, 0);
1395 if (cwd == NULL) {
1396 error = got_error_from_errno("getcwd");
1397 goto done;
1400 if (repo_path == NULL) {
1401 error = got_worktree_open(&worktree, cwd);
1402 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1403 goto done;
1404 else
1405 error = NULL;
1406 if (worktree) {
1407 repo_path =
1408 strdup(got_worktree_get_repo_path(worktree));
1409 if (repo_path == NULL)
1410 error = got_error_from_errno("strdup");
1411 if (error)
1412 goto done;
1413 } else {
1414 repo_path = strdup(cwd);
1415 if (repo_path == NULL) {
1416 error = got_error_from_errno("strdup");
1417 goto done;
1422 error = got_repo_open(&repo, repo_path, NULL);
1423 if (error)
1424 goto done;
1426 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1427 for (i = 0; i < nremotes; i++) {
1428 remote = &remotes[i];
1429 if (strcmp(remote->name, remote_name) == 0)
1430 break;
1432 if (i == nremotes) {
1433 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1434 goto done;
1437 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1438 &repo_name, remote->url);
1439 if (error)
1440 goto done;
1442 if (strcmp(proto, "git") == 0) {
1443 #ifndef PROFILE
1444 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1445 "sendfd dns inet unveil", NULL) == -1)
1446 err(1, "pledge");
1447 #endif
1448 } else if (strcmp(proto, "git+ssh") == 0 ||
1449 strcmp(proto, "ssh") == 0) {
1450 #ifndef PROFILE
1451 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1452 "sendfd unveil", NULL) == -1)
1453 err(1, "pledge");
1454 #endif
1455 } else if (strcmp(proto, "http") == 0 ||
1456 strcmp(proto, "git+http") == 0) {
1457 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1458 goto done;
1459 } else {
1460 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1461 goto done;
1464 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1465 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1466 error = got_error_from_errno2("unveil",
1467 GOT_FETCH_PATH_SSH);
1468 goto done;
1471 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1472 if (error)
1473 goto done;
1475 error = got_fetch_connect(&fetchfd, proto, host, port, server_path,
1476 verbosity);
1477 if (error)
1478 goto done;
1480 if (verbosity >= 0)
1481 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1482 port ? ":" : "", port ? port : "");
1484 fpa.last_scaled_size[0] = '\0';
1485 fpa.last_p_indexed = -1;
1486 fpa.last_p_resolved = -1;
1487 fpa.verbosity = verbosity;
1488 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1489 remote->mirror_references, fetch_all_branches, &wanted_branches,
1490 fetchfd, repo, fetch_progress, &fpa);
1491 if (error)
1492 goto done;
1494 if (pack_hash == NULL) {
1495 if (verbosity >= 0)
1496 printf("Already up-to-date\n");
1497 goto done;
1500 if (verbosity >= 0) {
1501 error = got_object_id_str(&id_str, pack_hash);
1502 if (error)
1503 goto done;
1504 printf("\nFetched %s.pack\n", id_str);
1505 free(id_str);
1506 id_str = NULL;
1509 /* Update references provided with the pack file. */
1510 TAILQ_FOREACH(pe, &refs, entry) {
1511 const char *refname = pe->path;
1512 struct got_object_id *id = pe->data;
1513 struct got_reference *ref;
1514 char *remote_refname;
1516 error = got_object_id_str(&id_str, id);
1517 if (error)
1518 goto done;
1520 if (remote->mirror_references ||
1521 strncmp("refs/tags/", refname, 10) == 0) {
1522 error = got_ref_open(&ref, repo, refname, 0);
1523 if (error) {
1524 if (error->code != GOT_ERR_NOT_REF)
1525 goto done;
1526 error = create_ref(refname, id, id_str, repo);
1527 if (error)
1528 goto done;
1529 } else {
1530 error = update_ref(ref, id, repo);
1531 got_ref_close(ref);
1532 if (error)
1533 goto done;
1535 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1536 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1537 remote_name, refname + 11) == -1) {
1538 error = got_error_from_errno("asprintf");
1539 goto done;
1542 error = got_ref_open(&ref, repo, remote_refname, 0);
1543 if (error) {
1544 if (error->code != GOT_ERR_NOT_REF)
1545 goto done;
1546 error = create_ref(remote_refname, id, id_str,
1547 repo);
1548 if (error)
1549 goto done;
1550 } else {
1551 error = update_ref(ref, id, repo);
1552 got_ref_close(ref);
1553 if (error)
1554 goto done;
1557 /* Also create a local branch if none exists yet. */
1558 error = got_ref_open(&ref, repo, refname, 0);
1559 if (error) {
1560 if (error->code != GOT_ERR_NOT_REF)
1561 goto done;
1562 error = create_ref(refname, id, id_str, repo);
1563 if (error)
1564 goto done;
1565 } else
1566 got_ref_close(ref);
1568 free(id_str);
1569 id_str = NULL;
1571 done:
1572 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1573 error = got_error_from_errno("close");
1574 if (repo)
1575 got_repo_close(repo);
1576 if (worktree)
1577 got_worktree_close(worktree);
1578 TAILQ_FOREACH(pe, &refs, entry) {
1579 free((void *)pe->path);
1580 free(pe->data);
1582 got_pathlist_free(&refs);
1583 TAILQ_FOREACH(pe, &symrefs, entry) {
1584 free((void *)pe->path);
1585 free(pe->data);
1587 got_pathlist_free(&symrefs);
1588 got_pathlist_free(&wanted_branches);
1589 free(id_str);
1590 free(cwd);
1591 free(repo_path);
1592 free(pack_hash);
1593 free(proto);
1594 free(host);
1595 free(port);
1596 free(server_path);
1597 free(repo_name);
1598 return error;
1602 __dead static void
1603 usage_checkout(void)
1605 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
1606 "[-p prefix] repository-path [worktree-path]\n", getprogname());
1607 exit(1);
1610 static void
1611 show_worktree_base_ref_warning(void)
1613 fprintf(stderr, "%s: warning: could not create a reference "
1614 "to the work tree's base commit; the commit could be "
1615 "garbage-collected by Git; making the repository "
1616 "writable and running 'got update' will prevent this\n",
1617 getprogname());
1620 struct got_checkout_progress_arg {
1621 const char *worktree_path;
1622 int had_base_commit_ref_error;
1625 static const struct got_error *
1626 checkout_progress(void *arg, unsigned char status, const char *path)
1628 struct got_checkout_progress_arg *a = arg;
1630 /* Base commit bump happens silently. */
1631 if (status == GOT_STATUS_BUMP_BASE)
1632 return NULL;
1634 if (status == GOT_STATUS_BASE_REF_ERR) {
1635 a->had_base_commit_ref_error = 1;
1636 return NULL;
1639 while (path[0] == '/')
1640 path++;
1642 printf("%c %s/%s\n", status, a->worktree_path, path);
1643 return NULL;
1646 static const struct got_error *
1647 check_cancelled(void *arg)
1649 if (sigint_received || sigpipe_received)
1650 return got_error(GOT_ERR_CANCELLED);
1651 return NULL;
1654 static const struct got_error *
1655 check_linear_ancestry(struct got_object_id *commit_id,
1656 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
1657 struct got_repository *repo)
1659 const struct got_error *err = NULL;
1660 struct got_object_id *yca_id;
1662 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
1663 commit_id, base_commit_id, repo, check_cancelled, NULL);
1664 if (err)
1665 return err;
1667 if (yca_id == NULL)
1668 return got_error(GOT_ERR_ANCESTRY);
1671 * Require a straight line of history between the target commit
1672 * and the work tree's base commit.
1674 * Non-linear situations such as this require a rebase:
1676 * (commit) D F (base_commit)
1677 * \ /
1678 * C E
1679 * \ /
1680 * B (yca)
1681 * |
1682 * A
1684 * 'got update' only handles linear cases:
1685 * Update forwards in time: A (base/yca) - B - C - D (commit)
1686 * Update backwards in time: D (base) - C - B - A (commit/yca)
1688 if (allow_forwards_in_time_only) {
1689 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
1690 return got_error(GOT_ERR_ANCESTRY);
1691 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
1692 got_object_id_cmp(base_commit_id, yca_id) != 0)
1693 return got_error(GOT_ERR_ANCESTRY);
1695 free(yca_id);
1696 return NULL;
1699 static const struct got_error *
1700 check_same_branch(struct got_object_id *commit_id,
1701 struct got_reference *head_ref, struct got_object_id *yca_id,
1702 struct got_repository *repo)
1704 const struct got_error *err = NULL;
1705 struct got_commit_graph *graph = NULL;
1706 struct got_object_id *head_commit_id = NULL;
1707 int is_same_branch = 0;
1709 err = got_ref_resolve(&head_commit_id, repo, head_ref);
1710 if (err)
1711 goto done;
1713 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
1714 is_same_branch = 1;
1715 goto done;
1717 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
1718 is_same_branch = 1;
1719 goto done;
1722 err = got_commit_graph_open(&graph, "/", 1);
1723 if (err)
1724 goto done;
1726 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
1727 check_cancelled, NULL);
1728 if (err)
1729 goto done;
1731 for (;;) {
1732 struct got_object_id *id;
1733 err = got_commit_graph_iter_next(&id, graph, repo,
1734 check_cancelled, NULL);
1735 if (err) {
1736 if (err->code == GOT_ERR_ITER_COMPLETED)
1737 err = NULL;
1738 break;
1741 if (id) {
1742 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
1743 break;
1744 if (got_object_id_cmp(id, commit_id) == 0) {
1745 is_same_branch = 1;
1746 break;
1750 done:
1751 if (graph)
1752 got_commit_graph_close(graph);
1753 free(head_commit_id);
1754 if (!err && !is_same_branch)
1755 err = got_error(GOT_ERR_ANCESTRY);
1756 return err;
1759 static const struct got_error *
1760 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
1762 static char msg[512];
1763 const char *branch_name;
1765 if (got_ref_is_symbolic(ref))
1766 branch_name = got_ref_get_symref_target(ref);
1767 else
1768 branch_name = got_ref_get_name(ref);
1770 if (strncmp("refs/heads/", branch_name, 11) == 0)
1771 branch_name += 11;
1773 snprintf(msg, sizeof(msg),
1774 "target commit is not contained in branch '%s'; "
1775 "the branch to use must be specified with -b; "
1776 "if necessary a new branch can be created for "
1777 "this commit with 'got branch -c %s BRANCH_NAME'",
1778 branch_name, commit_id_str);
1780 return got_error_msg(GOT_ERR_ANCESTRY, msg);
1783 static const struct got_error *
1784 cmd_checkout(int argc, char *argv[])
1786 const struct got_error *error = NULL;
1787 struct got_repository *repo = NULL;
1788 struct got_reference *head_ref = NULL;
1789 struct got_worktree *worktree = NULL;
1790 char *repo_path = NULL;
1791 char *worktree_path = NULL;
1792 const char *path_prefix = "";
1793 const char *branch_name = GOT_REF_HEAD;
1794 char *commit_id_str = NULL;
1795 int ch, same_path_prefix, allow_nonempty = 0;
1796 struct got_pathlist_head paths;
1797 struct got_checkout_progress_arg cpa;
1799 TAILQ_INIT(&paths);
1801 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
1802 switch (ch) {
1803 case 'b':
1804 branch_name = optarg;
1805 break;
1806 case 'c':
1807 commit_id_str = strdup(optarg);
1808 if (commit_id_str == NULL)
1809 return got_error_from_errno("strdup");
1810 break;
1811 case 'E':
1812 allow_nonempty = 1;
1813 break;
1814 case 'p':
1815 path_prefix = optarg;
1816 break;
1817 default:
1818 usage_checkout();
1819 /* NOTREACHED */
1823 argc -= optind;
1824 argv += optind;
1826 #ifndef PROFILE
1827 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
1828 "unveil", NULL) == -1)
1829 err(1, "pledge");
1830 #endif
1831 if (argc == 1) {
1832 char *cwd, *base, *dotgit;
1833 repo_path = realpath(argv[0], NULL);
1834 if (repo_path == NULL)
1835 return got_error_from_errno2("realpath", argv[0]);
1836 cwd = getcwd(NULL, 0);
1837 if (cwd == NULL) {
1838 error = got_error_from_errno("getcwd");
1839 goto done;
1841 if (path_prefix[0]) {
1842 base = basename(path_prefix);
1843 if (base == NULL) {
1844 error = got_error_from_errno2("basename",
1845 path_prefix);
1846 goto done;
1848 } else {
1849 base = basename(repo_path);
1850 if (base == NULL) {
1851 error = got_error_from_errno2("basename",
1852 repo_path);
1853 goto done;
1856 dotgit = strstr(base, ".git");
1857 if (dotgit)
1858 *dotgit = '\0';
1859 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
1860 error = got_error_from_errno("asprintf");
1861 free(cwd);
1862 goto done;
1864 free(cwd);
1865 } else if (argc == 2) {
1866 repo_path = realpath(argv[0], NULL);
1867 if (repo_path == NULL) {
1868 error = got_error_from_errno2("realpath", argv[0]);
1869 goto done;
1871 worktree_path = realpath(argv[1], NULL);
1872 if (worktree_path == NULL) {
1873 if (errno != ENOENT) {
1874 error = got_error_from_errno2("realpath",
1875 argv[1]);
1876 goto done;
1878 worktree_path = strdup(argv[1]);
1879 if (worktree_path == NULL) {
1880 error = got_error_from_errno("strdup");
1881 goto done;
1884 } else
1885 usage_checkout();
1887 got_path_strip_trailing_slashes(repo_path);
1888 got_path_strip_trailing_slashes(worktree_path);
1890 error = got_repo_open(&repo, repo_path, NULL);
1891 if (error != NULL)
1892 goto done;
1894 /* Pre-create work tree path for unveil(2) */
1895 error = got_path_mkdir(worktree_path);
1896 if (error) {
1897 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1898 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
1899 goto done;
1900 if (!allow_nonempty &&
1901 !got_path_dir_is_empty(worktree_path)) {
1902 error = got_error_path(worktree_path,
1903 GOT_ERR_DIR_NOT_EMPTY);
1904 goto done;
1908 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
1909 if (error)
1910 goto done;
1912 error = got_ref_open(&head_ref, repo, branch_name, 0);
1913 if (error != NULL)
1914 goto done;
1916 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
1917 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
1918 goto done;
1920 error = got_worktree_open(&worktree, worktree_path);
1921 if (error != NULL)
1922 goto done;
1924 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
1925 path_prefix);
1926 if (error != NULL)
1927 goto done;
1928 if (!same_path_prefix) {
1929 error = got_error(GOT_ERR_PATH_PREFIX);
1930 goto done;
1933 if (commit_id_str) {
1934 struct got_object_id *commit_id;
1935 error = got_repo_match_object_id(&commit_id, NULL,
1936 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
1937 if (error)
1938 goto done;
1939 error = check_linear_ancestry(commit_id,
1940 got_worktree_get_base_commit_id(worktree), 0, repo);
1941 if (error != NULL) {
1942 free(commit_id);
1943 if (error->code == GOT_ERR_ANCESTRY) {
1944 error = checkout_ancestry_error(
1945 head_ref, commit_id_str);
1947 goto done;
1949 error = check_same_branch(commit_id, head_ref, NULL, repo);
1950 if (error) {
1951 if (error->code == GOT_ERR_ANCESTRY) {
1952 error = checkout_ancestry_error(
1953 head_ref, commit_id_str);
1955 goto done;
1957 error = got_worktree_set_base_commit_id(worktree, repo,
1958 commit_id);
1959 free(commit_id);
1960 if (error)
1961 goto done;
1964 error = got_pathlist_append(&paths, "", NULL);
1965 if (error)
1966 goto done;
1967 cpa.worktree_path = worktree_path;
1968 cpa.had_base_commit_ref_error = 0;
1969 error = got_worktree_checkout_files(worktree, &paths, repo,
1970 checkout_progress, &cpa, check_cancelled, NULL);
1971 if (error != NULL)
1972 goto done;
1974 printf("Now shut up and hack\n");
1975 if (cpa.had_base_commit_ref_error)
1976 show_worktree_base_ref_warning();
1977 done:
1978 got_pathlist_free(&paths);
1979 free(commit_id_str);
1980 free(repo_path);
1981 free(worktree_path);
1982 return error;
1985 __dead static void
1986 usage_update(void)
1988 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
1989 getprogname());
1990 exit(1);
1993 static const struct got_error *
1994 update_progress(void *arg, unsigned char status, const char *path)
1996 int *did_something = arg;
1998 if (status == GOT_STATUS_EXISTS ||
1999 status == GOT_STATUS_BASE_REF_ERR)
2000 return NULL;
2002 *did_something = 1;
2004 /* Base commit bump happens silently. */
2005 if (status == GOT_STATUS_BUMP_BASE)
2006 return NULL;
2008 while (path[0] == '/')
2009 path++;
2010 printf("%c %s\n", status, path);
2011 return NULL;
2014 static const struct got_error *
2015 switch_head_ref(struct got_reference *head_ref,
2016 struct got_object_id *commit_id, struct got_worktree *worktree,
2017 struct got_repository *repo)
2019 const struct got_error *err = NULL;
2020 char *base_id_str;
2021 int ref_has_moved = 0;
2023 /* Trivial case: switching between two different references. */
2024 if (strcmp(got_ref_get_name(head_ref),
2025 got_worktree_get_head_ref_name(worktree)) != 0) {
2026 printf("Switching work tree from %s to %s\n",
2027 got_worktree_get_head_ref_name(worktree),
2028 got_ref_get_name(head_ref));
2029 return got_worktree_set_head_ref(worktree, head_ref);
2032 err = check_linear_ancestry(commit_id,
2033 got_worktree_get_base_commit_id(worktree), 0, repo);
2034 if (err) {
2035 if (err->code != GOT_ERR_ANCESTRY)
2036 return err;
2037 ref_has_moved = 1;
2039 if (!ref_has_moved)
2040 return NULL;
2042 /* Switching to a rebased branch with the same reference name. */
2043 err = got_object_id_str(&base_id_str,
2044 got_worktree_get_base_commit_id(worktree));
2045 if (err)
2046 return err;
2047 printf("Reference %s now points at a different branch\n",
2048 got_worktree_get_head_ref_name(worktree));
2049 printf("Switching work tree from %s to %s\n", base_id_str,
2050 got_worktree_get_head_ref_name(worktree));
2051 return NULL;
2054 static const struct got_error *
2055 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2057 const struct got_error *err;
2058 int in_progress;
2060 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2061 if (err)
2062 return err;
2063 if (in_progress)
2064 return got_error(GOT_ERR_REBASING);
2066 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2067 if (err)
2068 return err;
2069 if (in_progress)
2070 return got_error(GOT_ERR_HISTEDIT_BUSY);
2072 return NULL;
2075 static const struct got_error *
2076 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2077 char *argv[], struct got_worktree *worktree)
2079 const struct got_error *err = NULL;
2080 char *path;
2081 int i;
2083 if (argc == 0) {
2084 path = strdup("");
2085 if (path == NULL)
2086 return got_error_from_errno("strdup");
2087 return got_pathlist_append(paths, path, NULL);
2090 for (i = 0; i < argc; i++) {
2091 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2092 if (err)
2093 break;
2094 err = got_pathlist_append(paths, path, NULL);
2095 if (err) {
2096 free(path);
2097 break;
2101 return err;
2104 static const struct got_error *
2105 cmd_update(int argc, char *argv[])
2107 const struct got_error *error = NULL;
2108 struct got_repository *repo = NULL;
2109 struct got_worktree *worktree = NULL;
2110 char *worktree_path = NULL;
2111 struct got_object_id *commit_id = NULL;
2112 char *commit_id_str = NULL;
2113 const char *branch_name = NULL;
2114 struct got_reference *head_ref = NULL;
2115 struct got_pathlist_head paths;
2116 struct got_pathlist_entry *pe;
2117 int ch, did_something = 0;
2119 TAILQ_INIT(&paths);
2121 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2122 switch (ch) {
2123 case 'b':
2124 branch_name = optarg;
2125 break;
2126 case 'c':
2127 commit_id_str = strdup(optarg);
2128 if (commit_id_str == NULL)
2129 return got_error_from_errno("strdup");
2130 break;
2131 default:
2132 usage_update();
2133 /* NOTREACHED */
2137 argc -= optind;
2138 argv += optind;
2140 #ifndef PROFILE
2141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2142 "unveil", NULL) == -1)
2143 err(1, "pledge");
2144 #endif
2145 worktree_path = getcwd(NULL, 0);
2146 if (worktree_path == NULL) {
2147 error = got_error_from_errno("getcwd");
2148 goto done;
2150 error = got_worktree_open(&worktree, worktree_path);
2151 if (error)
2152 goto done;
2154 error = check_rebase_or_histedit_in_progress(worktree);
2155 if (error)
2156 goto done;
2158 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2159 NULL);
2160 if (error != NULL)
2161 goto done;
2163 error = apply_unveil(got_repo_get_path(repo), 0,
2164 got_worktree_get_root_path(worktree));
2165 if (error)
2166 goto done;
2168 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2169 if (error)
2170 goto done;
2172 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2173 got_worktree_get_head_ref_name(worktree), 0);
2174 if (error != NULL)
2175 goto done;
2176 if (commit_id_str == NULL) {
2177 error = got_ref_resolve(&commit_id, repo, head_ref);
2178 if (error != NULL)
2179 goto done;
2180 error = got_object_id_str(&commit_id_str, commit_id);
2181 if (error != NULL)
2182 goto done;
2183 } else {
2184 error = got_repo_match_object_id(&commit_id, NULL,
2185 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2186 free(commit_id_str);
2187 commit_id_str = NULL;
2188 if (error)
2189 goto done;
2190 error = got_object_id_str(&commit_id_str, commit_id);
2191 if (error)
2192 goto done;
2195 if (branch_name) {
2196 struct got_object_id *head_commit_id;
2197 TAILQ_FOREACH(pe, &paths, entry) {
2198 if (pe->path_len == 0)
2199 continue;
2200 error = got_error_msg(GOT_ERR_BAD_PATH,
2201 "switching between branches requires that "
2202 "the entire work tree gets updated");
2203 goto done;
2205 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2206 if (error)
2207 goto done;
2208 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2209 repo);
2210 free(head_commit_id);
2211 if (error != NULL)
2212 goto done;
2213 error = check_same_branch(commit_id, head_ref, NULL, repo);
2214 if (error)
2215 goto done;
2216 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2217 if (error)
2218 goto done;
2219 } else {
2220 error = check_linear_ancestry(commit_id,
2221 got_worktree_get_base_commit_id(worktree), 0, repo);
2222 if (error != NULL) {
2223 if (error->code == GOT_ERR_ANCESTRY)
2224 error = got_error(GOT_ERR_BRANCH_MOVED);
2225 goto done;
2227 error = check_same_branch(commit_id, head_ref, NULL, repo);
2228 if (error)
2229 goto done;
2232 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2233 commit_id) != 0) {
2234 error = got_worktree_set_base_commit_id(worktree, repo,
2235 commit_id);
2236 if (error)
2237 goto done;
2240 error = got_worktree_checkout_files(worktree, &paths, repo,
2241 update_progress, &did_something, check_cancelled, NULL);
2242 if (error != NULL)
2243 goto done;
2245 if (did_something)
2246 printf("Updated to commit %s\n", commit_id_str);
2247 else
2248 printf("Already up-to-date\n");
2249 done:
2250 free(worktree_path);
2251 TAILQ_FOREACH(pe, &paths, entry)
2252 free((char *)pe->path);
2253 got_pathlist_free(&paths);
2254 free(commit_id);
2255 free(commit_id_str);
2256 return error;
2259 static const struct got_error *
2260 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2261 const char *path, int diff_context, int ignore_whitespace,
2262 struct got_repository *repo)
2264 const struct got_error *err = NULL;
2265 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2267 if (blob_id1) {
2268 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2269 if (err)
2270 goto done;
2273 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2274 if (err)
2275 goto done;
2277 while (path[0] == '/')
2278 path++;
2279 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2280 ignore_whitespace, stdout);
2281 done:
2282 if (blob1)
2283 got_object_blob_close(blob1);
2284 got_object_blob_close(blob2);
2285 return err;
2288 static const struct got_error *
2289 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2290 const char *path, int diff_context, int ignore_whitespace,
2291 struct got_repository *repo)
2293 const struct got_error *err = NULL;
2294 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2295 struct got_diff_blob_output_unidiff_arg arg;
2297 if (tree_id1) {
2298 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2299 if (err)
2300 goto done;
2303 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2304 if (err)
2305 goto done;
2307 arg.diff_context = diff_context;
2308 arg.ignore_whitespace = ignore_whitespace;
2309 arg.outfile = stdout;
2310 while (path[0] == '/')
2311 path++;
2312 err = got_diff_tree(tree1, tree2, path, path, repo,
2313 got_diff_blob_output_unidiff, &arg, 1);
2314 done:
2315 if (tree1)
2316 got_object_tree_close(tree1);
2317 if (tree2)
2318 got_object_tree_close(tree2);
2319 return err;
2322 static const struct got_error *
2323 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2324 const char *path, int diff_context, struct got_repository *repo)
2326 const struct got_error *err = NULL;
2327 struct got_commit_object *pcommit = NULL;
2328 char *id_str1 = NULL, *id_str2 = NULL;
2329 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2330 struct got_object_qid *qid;
2332 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2333 if (qid != NULL) {
2334 err = got_object_open_as_commit(&pcommit, repo,
2335 qid->id);
2336 if (err)
2337 return err;
2340 if (path && path[0] != '\0') {
2341 int obj_type;
2342 err = got_object_id_by_path(&obj_id2, repo, id, path);
2343 if (err)
2344 goto done;
2345 err = got_object_id_str(&id_str2, obj_id2);
2346 if (err) {
2347 free(obj_id2);
2348 goto done;
2350 if (pcommit) {
2351 err = got_object_id_by_path(&obj_id1, repo,
2352 qid->id, path);
2353 if (err) {
2354 free(obj_id2);
2355 goto done;
2357 err = got_object_id_str(&id_str1, obj_id1);
2358 if (err) {
2359 free(obj_id2);
2360 goto done;
2363 err = got_object_get_type(&obj_type, repo, obj_id2);
2364 if (err) {
2365 free(obj_id2);
2366 goto done;
2368 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2369 switch (obj_type) {
2370 case GOT_OBJ_TYPE_BLOB:
2371 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2372 0, repo);
2373 break;
2374 case GOT_OBJ_TYPE_TREE:
2375 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2376 0, repo);
2377 break;
2378 default:
2379 err = got_error(GOT_ERR_OBJ_TYPE);
2380 break;
2382 free(obj_id1);
2383 free(obj_id2);
2384 } else {
2385 obj_id2 = got_object_commit_get_tree_id(commit);
2386 err = got_object_id_str(&id_str2, obj_id2);
2387 if (err)
2388 goto done;
2389 obj_id1 = got_object_commit_get_tree_id(pcommit);
2390 err = got_object_id_str(&id_str1, obj_id1);
2391 if (err)
2392 goto done;
2393 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2394 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2396 done:
2397 free(id_str1);
2398 free(id_str2);
2399 if (pcommit)
2400 got_object_commit_close(pcommit);
2401 return err;
2404 static char *
2405 get_datestr(time_t *time, char *datebuf)
2407 struct tm mytm, *tm;
2408 char *p, *s;
2410 tm = gmtime_r(time, &mytm);
2411 if (tm == NULL)
2412 return NULL;
2413 s = asctime_r(tm, datebuf);
2414 if (s == NULL)
2415 return NULL;
2416 p = strchr(s, '\n');
2417 if (p)
2418 *p = '\0';
2419 return s;
2422 static const struct got_error *
2423 match_logmsg(int *have_match, struct got_object_id *id,
2424 struct got_commit_object *commit, regex_t *regex)
2426 const struct got_error *err = NULL;
2427 regmatch_t regmatch;
2428 char *id_str = NULL, *logmsg = NULL;
2430 *have_match = 0;
2432 err = got_object_id_str(&id_str, id);
2433 if (err)
2434 return err;
2436 err = got_object_commit_get_logmsg(&logmsg, commit);
2437 if (err)
2438 goto done;
2440 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2441 *have_match = 1;
2442 done:
2443 free(id_str);
2444 free(logmsg);
2445 return err;
2448 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
2450 static const struct got_error *
2451 print_commit(struct got_commit_object *commit, struct got_object_id *id,
2452 struct got_repository *repo, const char *path, int show_patch,
2453 int diff_context, struct got_reflist_head *refs)
2455 const struct got_error *err = NULL;
2456 char *id_str, *datestr, *logmsg0, *logmsg, *line;
2457 char datebuf[26];
2458 time_t committer_time;
2459 const char *author, *committer;
2460 char *refs_str = NULL;
2461 struct got_reflist_entry *re;
2463 SIMPLEQ_FOREACH(re, refs, entry) {
2464 char *s;
2465 const char *name;
2466 struct got_tag_object *tag = NULL;
2467 int cmp;
2469 name = got_ref_get_name(re->ref);
2470 if (strcmp(name, GOT_REF_HEAD) == 0)
2471 continue;
2472 if (strncmp(name, "refs/", 5) == 0)
2473 name += 5;
2474 if (strncmp(name, "got/", 4) == 0)
2475 continue;
2476 if (strncmp(name, "heads/", 6) == 0)
2477 name += 6;
2478 if (strncmp(name, "remotes/", 8) == 0)
2479 name += 8;
2480 if (strncmp(name, "tags/", 5) == 0) {
2481 err = got_object_open_as_tag(&tag, repo, re->id);
2482 if (err) {
2483 if (err->code != GOT_ERR_OBJ_TYPE)
2484 return err;
2485 /* Ref points at something other than a tag. */
2486 err = NULL;
2487 tag = NULL;
2490 cmp = got_object_id_cmp(tag ?
2491 got_object_tag_get_object_id(tag) : re->id, id);
2492 if (tag)
2493 got_object_tag_close(tag);
2494 if (cmp != 0)
2495 continue;
2496 s = refs_str;
2497 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
2498 name) == -1) {
2499 err = got_error_from_errno("asprintf");
2500 free(s);
2501 return err;
2503 free(s);
2505 err = got_object_id_str(&id_str, id);
2506 if (err)
2507 return err;
2509 printf(GOT_COMMIT_SEP_STR);
2510 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
2511 refs_str ? refs_str : "", refs_str ? ")" : "");
2512 free(id_str);
2513 id_str = NULL;
2514 free(refs_str);
2515 refs_str = NULL;
2516 printf("from: %s\n", got_object_commit_get_author(commit));
2517 committer_time = got_object_commit_get_committer_time(commit);
2518 datestr = get_datestr(&committer_time, datebuf);
2519 if (datestr)
2520 printf("date: %s UTC\n", datestr);
2521 author = got_object_commit_get_author(commit);
2522 committer = got_object_commit_get_committer(commit);
2523 if (strcmp(author, committer) != 0)
2524 printf("via: %s\n", committer);
2525 if (got_object_commit_get_nparents(commit) > 1) {
2526 const struct got_object_id_queue *parent_ids;
2527 struct got_object_qid *qid;
2528 int n = 1;
2529 parent_ids = got_object_commit_get_parent_ids(commit);
2530 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
2531 err = got_object_id_str(&id_str, qid->id);
2532 if (err)
2533 return err;
2534 printf("parent %d: %s\n", n++, id_str);
2535 free(id_str);
2539 err = got_object_commit_get_logmsg(&logmsg0, commit);
2540 if (err)
2541 return err;
2543 logmsg = logmsg0;
2544 do {
2545 line = strsep(&logmsg, "\n");
2546 if (line)
2547 printf(" %s\n", line);
2548 } while (line);
2549 free(logmsg0);
2551 if (show_patch) {
2552 err = print_patch(commit, id, path, diff_context, repo);
2553 if (err == 0)
2554 printf("\n");
2557 if (fflush(stdout) != 0 && err == NULL)
2558 err = got_error_from_errno("fflush");
2559 return err;
2562 static const struct got_error *
2563 print_commits(struct got_object_id *root_id, struct got_repository *repo,
2564 const char *path, int show_patch, const char *search_pattern,
2565 int diff_context, int limit, int log_branches,
2566 struct got_reflist_head *refs)
2568 const struct got_error *err;
2569 struct got_commit_graph *graph;
2570 regex_t regex;
2571 int have_match;
2573 if (search_pattern &&
2574 regcomp(&regex, search_pattern, REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
2575 return got_error_msg(GOT_ERR_REGEX, search_pattern);
2577 err = got_commit_graph_open(&graph, path, !log_branches);
2578 if (err)
2579 return err;
2580 err = got_commit_graph_iter_start(graph, root_id, repo,
2581 check_cancelled, NULL);
2582 if (err)
2583 goto done;
2584 for (;;) {
2585 struct got_commit_object *commit;
2586 struct got_object_id *id;
2588 if (sigint_received || sigpipe_received)
2589 break;
2591 err = got_commit_graph_iter_next(&id, graph, repo,
2592 check_cancelled, NULL);
2593 if (err) {
2594 if (err->code == GOT_ERR_ITER_COMPLETED)
2595 err = NULL;
2596 break;
2598 if (id == NULL)
2599 break;
2601 err = got_object_open_as_commit(&commit, repo, id);
2602 if (err)
2603 break;
2605 if (search_pattern) {
2606 err = match_logmsg(&have_match, id, commit, &regex);
2607 if (err) {
2608 got_object_commit_close(commit);
2609 break;
2611 if (have_match == 0) {
2612 got_object_commit_close(commit);
2613 continue;
2617 err = print_commit(commit, id, repo, path, show_patch,
2618 diff_context, refs);
2619 got_object_commit_close(commit);
2620 if (err || (limit && --limit == 0))
2621 break;
2623 done:
2624 if (search_pattern)
2625 regfree(&regex);
2626 got_commit_graph_close(graph);
2627 return err;
2630 __dead static void
2631 usage_log(void)
2633 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] [-p] "
2634 "[-s search-pattern] [-r repository-path] [path]\n", getprogname());
2635 exit(1);
2638 static int
2639 get_default_log_limit(void)
2641 const char *got_default_log_limit;
2642 long long n;
2643 const char *errstr;
2645 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
2646 if (got_default_log_limit == NULL)
2647 return 0;
2648 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
2649 if (errstr != NULL)
2650 return 0;
2651 return n;
2654 static const struct got_error *
2655 cmd_log(int argc, char *argv[])
2657 const struct got_error *error;
2658 struct got_repository *repo = NULL;
2659 struct got_worktree *worktree = NULL;
2660 struct got_commit_object *commit = NULL;
2661 struct got_object_id *id = NULL;
2662 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
2663 const char *start_commit = NULL, *search_pattern = NULL;
2664 int diff_context = -1, ch;
2665 int show_patch = 0, limit = 0, log_branches = 0;
2666 const char *errstr;
2667 struct got_reflist_head refs;
2669 SIMPLEQ_INIT(&refs);
2671 #ifndef PROFILE
2672 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
2673 NULL)
2674 == -1)
2675 err(1, "pledge");
2676 #endif
2678 limit = get_default_log_limit();
2680 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:")) != -1) {
2681 switch (ch) {
2682 case 'p':
2683 show_patch = 1;
2684 break;
2685 case 'c':
2686 start_commit = optarg;
2687 break;
2688 case 'C':
2689 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
2690 &errstr);
2691 if (errstr != NULL)
2692 err(1, "-C option %s", errstr);
2693 break;
2694 case 'l':
2695 limit = strtonum(optarg, 0, INT_MAX, &errstr);
2696 if (errstr != NULL)
2697 err(1, "-l option %s", errstr);
2698 break;
2699 case 'b':
2700 log_branches = 1;
2701 break;
2702 case 'r':
2703 repo_path = realpath(optarg, NULL);
2704 if (repo_path == NULL)
2705 return got_error_from_errno2("realpath",
2706 optarg);
2707 got_path_strip_trailing_slashes(repo_path);
2708 break;
2709 case 's':
2710 search_pattern = optarg;
2711 break;
2712 default:
2713 usage_log();
2714 /* NOTREACHED */
2718 argc -= optind;
2719 argv += optind;
2721 if (diff_context == -1)
2722 diff_context = 3;
2723 else if (!show_patch)
2724 errx(1, "-C reguires -p");
2726 cwd = getcwd(NULL, 0);
2727 if (cwd == NULL) {
2728 error = got_error_from_errno("getcwd");
2729 goto done;
2732 error = got_worktree_open(&worktree, cwd);
2733 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2734 goto done;
2735 error = NULL;
2737 if (argc == 0) {
2738 path = strdup("");
2739 if (path == NULL) {
2740 error = got_error_from_errno("strdup");
2741 goto done;
2743 } else if (argc == 1) {
2744 if (worktree) {
2745 error = got_worktree_resolve_path(&path, worktree,
2746 argv[0]);
2747 if (error)
2748 goto done;
2749 } else {
2750 path = strdup(argv[0]);
2751 if (path == NULL) {
2752 error = got_error_from_errno("strdup");
2753 goto done;
2756 } else
2757 usage_log();
2759 if (repo_path == NULL) {
2760 repo_path = worktree ?
2761 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
2763 if (repo_path == NULL) {
2764 error = got_error_from_errno("strdup");
2765 goto done;
2768 error = got_repo_open(&repo, repo_path, NULL);
2769 if (error != NULL)
2770 goto done;
2772 error = apply_unveil(got_repo_get_path(repo), 1,
2773 worktree ? got_worktree_get_root_path(worktree) : NULL);
2774 if (error)
2775 goto done;
2777 if (start_commit == NULL) {
2778 struct got_reference *head_ref;
2779 error = got_ref_open(&head_ref, repo,
2780 worktree ? got_worktree_get_head_ref_name(worktree)
2781 : GOT_REF_HEAD, 0);
2782 if (error != NULL)
2783 return error;
2784 error = got_ref_resolve(&id, repo, head_ref);
2785 got_ref_close(head_ref);
2786 if (error != NULL)
2787 return error;
2788 error = got_object_open_as_commit(&commit, repo, id);
2789 } else {
2790 struct got_reference *ref;
2791 error = got_ref_open(&ref, repo, start_commit, 0);
2792 if (error == NULL) {
2793 int obj_type;
2794 error = got_ref_resolve(&id, repo, ref);
2795 got_ref_close(ref);
2796 if (error != NULL)
2797 goto done;
2798 error = got_object_get_type(&obj_type, repo, id);
2799 if (error != NULL)
2800 goto done;
2801 if (obj_type == GOT_OBJ_TYPE_TAG) {
2802 struct got_tag_object *tag;
2803 error = got_object_open_as_tag(&tag, repo, id);
2804 if (error != NULL)
2805 goto done;
2806 if (got_object_tag_get_object_type(tag) !=
2807 GOT_OBJ_TYPE_COMMIT) {
2808 got_object_tag_close(tag);
2809 error = got_error(GOT_ERR_OBJ_TYPE);
2810 goto done;
2812 free(id);
2813 id = got_object_id_dup(
2814 got_object_tag_get_object_id(tag));
2815 if (id == NULL)
2816 error = got_error_from_errno(
2817 "got_object_id_dup");
2818 got_object_tag_close(tag);
2819 if (error)
2820 goto done;
2821 } else if (obj_type != GOT_OBJ_TYPE_COMMIT) {
2822 error = got_error(GOT_ERR_OBJ_TYPE);
2823 goto done;
2825 error = got_object_open_as_commit(&commit, repo, id);
2826 if (error != NULL)
2827 goto done;
2829 if (commit == NULL) {
2830 error = got_repo_match_object_id_prefix(&id,
2831 start_commit, GOT_OBJ_TYPE_COMMIT, repo);
2832 if (error != NULL)
2833 return error;
2836 if (error != NULL)
2837 goto done;
2839 if (worktree) {
2840 const char *prefix = got_worktree_get_path_prefix(worktree);
2841 char *p;
2842 if (asprintf(&p, "%s%s%s", prefix,
2843 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
2844 error = got_error_from_errno("asprintf");
2845 goto done;
2847 error = got_repo_map_path(&in_repo_path, repo, p, 0);
2848 free(p);
2849 } else
2850 error = got_repo_map_path(&in_repo_path, repo, path, 1);
2851 if (error != NULL)
2852 goto done;
2853 if (in_repo_path) {
2854 free(path);
2855 path = in_repo_path;
2858 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
2859 if (error)
2860 goto done;
2862 error = print_commits(id, repo, path, show_patch, search_pattern,
2863 diff_context, limit, log_branches, &refs);
2864 done:
2865 free(path);
2866 free(repo_path);
2867 free(cwd);
2868 free(id);
2869 if (worktree)
2870 got_worktree_close(worktree);
2871 if (repo) {
2872 const struct got_error *repo_error;
2873 repo_error = got_repo_close(repo);
2874 if (error == NULL)
2875 error = repo_error;
2877 got_ref_list_free(&refs);
2878 return error;
2881 __dead static void
2882 usage_diff(void)
2884 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
2885 "[-w] [object1 object2 | path]\n", getprogname());
2886 exit(1);
2889 struct print_diff_arg {
2890 struct got_repository *repo;
2891 struct got_worktree *worktree;
2892 int diff_context;
2893 const char *id_str;
2894 int header_shown;
2895 int diff_staged;
2896 int ignore_whitespace;
2899 static const struct got_error *
2900 print_diff(void *arg, unsigned char status, unsigned char staged_status,
2901 const char *path, struct got_object_id *blob_id,
2902 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
2903 int dirfd, const char *de_name)
2905 struct print_diff_arg *a = arg;
2906 const struct got_error *err = NULL;
2907 struct got_blob_object *blob1 = NULL;
2908 int fd = -1;
2909 FILE *f2 = NULL;
2910 char *abspath = NULL, *label1 = NULL;
2911 struct stat sb;
2913 if (a->diff_staged) {
2914 if (staged_status != GOT_STATUS_MODIFY &&
2915 staged_status != GOT_STATUS_ADD &&
2916 staged_status != GOT_STATUS_DELETE)
2917 return NULL;
2918 } else {
2919 if (staged_status == GOT_STATUS_DELETE)
2920 return NULL;
2921 if (status == GOT_STATUS_NONEXISTENT)
2922 return got_error_set_errno(ENOENT, path);
2923 if (status != GOT_STATUS_MODIFY &&
2924 status != GOT_STATUS_ADD &&
2925 status != GOT_STATUS_DELETE &&
2926 status != GOT_STATUS_CONFLICT)
2927 return NULL;
2930 if (!a->header_shown) {
2931 printf("diff %s %s%s\n", a->id_str,
2932 got_worktree_get_root_path(a->worktree),
2933 a->diff_staged ? " (staged changes)" : "");
2934 a->header_shown = 1;
2937 if (a->diff_staged) {
2938 const char *label1 = NULL, *label2 = NULL;
2939 switch (staged_status) {
2940 case GOT_STATUS_MODIFY:
2941 label1 = path;
2942 label2 = path;
2943 break;
2944 case GOT_STATUS_ADD:
2945 label2 = path;
2946 break;
2947 case GOT_STATUS_DELETE:
2948 label1 = path;
2949 break;
2950 default:
2951 return got_error(GOT_ERR_FILE_STATUS);
2953 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
2954 label1, label2, a->diff_context, a->ignore_whitespace,
2955 a->repo, stdout);
2958 if (staged_status == GOT_STATUS_ADD ||
2959 staged_status == GOT_STATUS_MODIFY) {
2960 char *id_str;
2961 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
2962 8192);
2963 if (err)
2964 goto done;
2965 err = got_object_id_str(&id_str, staged_blob_id);
2966 if (err)
2967 goto done;
2968 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
2969 err = got_error_from_errno("asprintf");
2970 free(id_str);
2971 goto done;
2973 free(id_str);
2974 } else if (status != GOT_STATUS_ADD) {
2975 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
2976 if (err)
2977 goto done;
2980 if (status != GOT_STATUS_DELETE) {
2981 if (asprintf(&abspath, "%s/%s",
2982 got_worktree_get_root_path(a->worktree), path) == -1) {
2983 err = got_error_from_errno("asprintf");
2984 goto done;
2987 if (dirfd != -1) {
2988 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
2989 if (fd == -1) {
2990 err = got_error_from_errno2("openat", abspath);
2991 goto done;
2993 } else {
2994 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
2995 if (fd == -1) {
2996 err = got_error_from_errno2("open", abspath);
2997 goto done;
3000 if (fstat(fd, &sb) == -1) {
3001 err = got_error_from_errno2("fstat", abspath);
3002 goto done;
3004 f2 = fdopen(fd, "r");
3005 if (f2 == NULL) {
3006 err = got_error_from_errno2("fdopen", abspath);
3007 goto done;
3009 fd = -1;
3010 } else
3011 sb.st_size = 0;
3013 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3014 a->diff_context, a->ignore_whitespace, stdout);
3015 done:
3016 if (blob1)
3017 got_object_blob_close(blob1);
3018 if (f2 && fclose(f2) == EOF && err == NULL)
3019 err = got_error_from_errno("fclose");
3020 if (fd != -1 && close(fd) == -1 && err == NULL)
3021 err = got_error_from_errno("close");
3022 free(abspath);
3023 return err;
3026 static const struct got_error *
3027 cmd_diff(int argc, char *argv[])
3029 const struct got_error *error;
3030 struct got_repository *repo = NULL;
3031 struct got_worktree *worktree = NULL;
3032 char *cwd = NULL, *repo_path = NULL;
3033 struct got_object_id *id1 = NULL, *id2 = NULL;
3034 const char *id_str1 = NULL, *id_str2 = NULL;
3035 char *label1 = NULL, *label2 = NULL;
3036 int type1, type2;
3037 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3038 const char *errstr;
3039 char *path = NULL;
3041 #ifndef PROFILE
3042 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3043 NULL) == -1)
3044 err(1, "pledge");
3045 #endif
3047 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3048 switch (ch) {
3049 case 'C':
3050 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3051 &errstr);
3052 if (errstr != NULL)
3053 err(1, "-C option %s", errstr);
3054 break;
3055 case 'r':
3056 repo_path = realpath(optarg, NULL);
3057 if (repo_path == NULL)
3058 return got_error_from_errno2("realpath",
3059 optarg);
3060 got_path_strip_trailing_slashes(repo_path);
3061 break;
3062 case 's':
3063 diff_staged = 1;
3064 break;
3065 case 'w':
3066 ignore_whitespace = 1;
3067 break;
3068 default:
3069 usage_diff();
3070 /* NOTREACHED */
3074 argc -= optind;
3075 argv += optind;
3077 cwd = getcwd(NULL, 0);
3078 if (cwd == NULL) {
3079 error = got_error_from_errno("getcwd");
3080 goto done;
3082 error = got_worktree_open(&worktree, cwd);
3083 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3084 goto done;
3085 if (argc <= 1) {
3086 if (worktree == NULL) {
3087 error = got_error(GOT_ERR_NOT_WORKTREE);
3088 goto done;
3090 if (repo_path)
3091 errx(1,
3092 "-r option can't be used when diffing a work tree");
3093 repo_path = strdup(got_worktree_get_repo_path(worktree));
3094 if (repo_path == NULL) {
3095 error = got_error_from_errno("strdup");
3096 goto done;
3098 if (argc == 1) {
3099 error = got_worktree_resolve_path(&path, worktree,
3100 argv[0]);
3101 if (error)
3102 goto done;
3103 } else {
3104 path = strdup("");
3105 if (path == NULL) {
3106 error = got_error_from_errno("strdup");
3107 goto done;
3110 } else if (argc == 2) {
3111 if (diff_staged)
3112 errx(1, "-s option can't be used when diffing "
3113 "objects in repository");
3114 id_str1 = argv[0];
3115 id_str2 = argv[1];
3116 if (worktree && repo_path == NULL) {
3117 repo_path =
3118 strdup(got_worktree_get_repo_path(worktree));
3119 if (repo_path == NULL) {
3120 error = got_error_from_errno("strdup");
3121 goto done;
3124 } else
3125 usage_diff();
3127 if (repo_path == NULL) {
3128 repo_path = getcwd(NULL, 0);
3129 if (repo_path == NULL)
3130 return got_error_from_errno("getcwd");
3133 error = got_repo_open(&repo, repo_path, NULL);
3134 free(repo_path);
3135 if (error != NULL)
3136 goto done;
3138 error = apply_unveil(got_repo_get_path(repo), 1,
3139 worktree ? got_worktree_get_root_path(worktree) : NULL);
3140 if (error)
3141 goto done;
3143 if (argc <= 1) {
3144 struct print_diff_arg arg;
3145 struct got_pathlist_head paths;
3146 char *id_str;
3148 TAILQ_INIT(&paths);
3150 error = got_object_id_str(&id_str,
3151 got_worktree_get_base_commit_id(worktree));
3152 if (error)
3153 goto done;
3154 arg.repo = repo;
3155 arg.worktree = worktree;
3156 arg.diff_context = diff_context;
3157 arg.id_str = id_str;
3158 arg.header_shown = 0;
3159 arg.diff_staged = diff_staged;
3160 arg.ignore_whitespace = ignore_whitespace;
3162 error = got_pathlist_append(&paths, path, NULL);
3163 if (error)
3164 goto done;
3166 error = got_worktree_status(worktree, &paths, repo, print_diff,
3167 &arg, check_cancelled, NULL);
3168 free(id_str);
3169 got_pathlist_free(&paths);
3170 goto done;
3173 error = got_repo_match_object_id(&id1, &label1, id_str1,
3174 GOT_OBJ_TYPE_ANY, 1, repo);
3175 if (error)
3176 goto done;
3178 error = got_repo_match_object_id(&id2, &label2, id_str2,
3179 GOT_OBJ_TYPE_ANY, 1, repo);
3180 if (error)
3181 goto done;
3183 error = got_object_get_type(&type1, repo, id1);
3184 if (error)
3185 goto done;
3187 error = got_object_get_type(&type2, repo, id2);
3188 if (error)
3189 goto done;
3191 if (type1 != type2) {
3192 error = got_error(GOT_ERR_OBJ_TYPE);
3193 goto done;
3196 switch (type1) {
3197 case GOT_OBJ_TYPE_BLOB:
3198 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3199 diff_context, ignore_whitespace, repo, stdout);
3200 break;
3201 case GOT_OBJ_TYPE_TREE:
3202 error = got_diff_objects_as_trees(id1, id2, "", "",
3203 diff_context, ignore_whitespace, repo, stdout);
3204 break;
3205 case GOT_OBJ_TYPE_COMMIT:
3206 printf("diff %s %s\n", label1, label2);
3207 error = got_diff_objects_as_commits(id1, id2, diff_context,
3208 ignore_whitespace, repo, stdout);
3209 break;
3210 default:
3211 error = got_error(GOT_ERR_OBJ_TYPE);
3213 done:
3214 free(label1);
3215 free(label2);
3216 free(id1);
3217 free(id2);
3218 free(path);
3219 if (worktree)
3220 got_worktree_close(worktree);
3221 if (repo) {
3222 const struct got_error *repo_error;
3223 repo_error = got_repo_close(repo);
3224 if (error == NULL)
3225 error = repo_error;
3227 return error;
3230 __dead static void
3231 usage_blame(void)
3233 fprintf(stderr,
3234 "usage: %s blame [-c commit] [-r repository-path] path\n",
3235 getprogname());
3236 exit(1);
3239 struct blame_line {
3240 int annotated;
3241 char *id_str;
3242 char *committer;
3243 char datebuf[11]; /* YYYY-MM-DD + NUL */
3246 struct blame_cb_args {
3247 struct blame_line *lines;
3248 int nlines;
3249 int nlines_prec;
3250 int lineno_cur;
3251 off_t *line_offsets;
3252 FILE *f;
3253 struct got_repository *repo;
3256 static const struct got_error *
3257 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3259 const struct got_error *err = NULL;
3260 struct blame_cb_args *a = arg;
3261 struct blame_line *bline;
3262 char *line = NULL;
3263 size_t linesize = 0;
3264 struct got_commit_object *commit = NULL;
3265 off_t offset;
3266 struct tm tm;
3267 time_t committer_time;
3269 if (nlines != a->nlines ||
3270 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3271 return got_error(GOT_ERR_RANGE);
3273 if (sigint_received)
3274 return got_error(GOT_ERR_ITER_COMPLETED);
3276 if (lineno == -1)
3277 return NULL; /* no change in this commit */
3279 /* Annotate this line. */
3280 bline = &a->lines[lineno - 1];
3281 if (bline->annotated)
3282 return NULL;
3283 err = got_object_id_str(&bline->id_str, id);
3284 if (err)
3285 return err;
3287 err = got_object_open_as_commit(&commit, a->repo, id);
3288 if (err)
3289 goto done;
3291 bline->committer = strdup(got_object_commit_get_committer(commit));
3292 if (bline->committer == NULL) {
3293 err = got_error_from_errno("strdup");
3294 goto done;
3297 committer_time = got_object_commit_get_committer_time(commit);
3298 if (localtime_r(&committer_time, &tm) == NULL)
3299 return got_error_from_errno("localtime_r");
3300 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3301 &tm) >= sizeof(bline->datebuf)) {
3302 err = got_error(GOT_ERR_NO_SPACE);
3303 goto done;
3305 bline->annotated = 1;
3307 /* Print lines annotated so far. */
3308 bline = &a->lines[a->lineno_cur - 1];
3309 if (!bline->annotated)
3310 goto done;
3312 offset = a->line_offsets[a->lineno_cur - 1];
3313 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3314 err = got_error_from_errno("fseeko");
3315 goto done;
3318 while (bline->annotated) {
3319 char *smallerthan, *at, *nl, *committer;
3320 size_t len;
3322 if (getline(&line, &linesize, a->f) == -1) {
3323 if (ferror(a->f))
3324 err = got_error_from_errno("getline");
3325 break;
3328 committer = bline->committer;
3329 smallerthan = strchr(committer, '<');
3330 if (smallerthan && smallerthan[1] != '\0')
3331 committer = smallerthan + 1;
3332 at = strchr(committer, '@');
3333 if (at)
3334 *at = '\0';
3335 len = strlen(committer);
3336 if (len >= 9)
3337 committer[8] = '\0';
3339 nl = strchr(line, '\n');
3340 if (nl)
3341 *nl = '\0';
3342 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3343 bline->id_str, bline->datebuf, committer, line);
3345 a->lineno_cur++;
3346 bline = &a->lines[a->lineno_cur - 1];
3348 done:
3349 if (commit)
3350 got_object_commit_close(commit);
3351 free(line);
3352 return err;
3355 static const struct got_error *
3356 cmd_blame(int argc, char *argv[])
3358 const struct got_error *error;
3359 struct got_repository *repo = NULL;
3360 struct got_worktree *worktree = NULL;
3361 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3362 struct got_object_id *obj_id = NULL;
3363 struct got_object_id *commit_id = NULL;
3364 struct got_blob_object *blob = NULL;
3365 char *commit_id_str = NULL;
3366 struct blame_cb_args bca;
3367 int ch, obj_type, i;
3368 size_t filesize;
3370 memset(&bca, 0, sizeof(bca));
3372 #ifndef PROFILE
3373 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3374 NULL) == -1)
3375 err(1, "pledge");
3376 #endif
3378 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3379 switch (ch) {
3380 case 'c':
3381 commit_id_str = optarg;
3382 break;
3383 case 'r':
3384 repo_path = realpath(optarg, NULL);
3385 if (repo_path == NULL)
3386 return got_error_from_errno2("realpath",
3387 optarg);
3388 got_path_strip_trailing_slashes(repo_path);
3389 break;
3390 default:
3391 usage_blame();
3392 /* NOTREACHED */
3396 argc -= optind;
3397 argv += optind;
3399 if (argc == 1)
3400 path = argv[0];
3401 else
3402 usage_blame();
3404 cwd = getcwd(NULL, 0);
3405 if (cwd == NULL) {
3406 error = got_error_from_errno("getcwd");
3407 goto done;
3409 if (repo_path == NULL) {
3410 error = got_worktree_open(&worktree, cwd);
3411 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3412 goto done;
3413 else
3414 error = NULL;
3415 if (worktree) {
3416 repo_path =
3417 strdup(got_worktree_get_repo_path(worktree));
3418 if (repo_path == NULL)
3419 error = got_error_from_errno("strdup");
3420 if (error)
3421 goto done;
3422 } else {
3423 repo_path = strdup(cwd);
3424 if (repo_path == NULL) {
3425 error = got_error_from_errno("strdup");
3426 goto done;
3431 error = got_repo_open(&repo, repo_path, NULL);
3432 if (error != NULL)
3433 goto done;
3435 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3436 if (error)
3437 goto done;
3439 if (worktree) {
3440 const char *prefix = got_worktree_get_path_prefix(worktree);
3441 char *p, *worktree_subdir = cwd +
3442 strlen(got_worktree_get_root_path(worktree));
3443 if (asprintf(&p, "%s%s%s%s%s",
3444 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
3445 worktree_subdir, worktree_subdir[0] ? "/" : "",
3446 path) == -1) {
3447 error = got_error_from_errno("asprintf");
3448 goto done;
3450 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3451 free(p);
3452 } else {
3453 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3455 if (error)
3456 goto done;
3458 if (commit_id_str == NULL) {
3459 struct got_reference *head_ref;
3460 error = got_ref_open(&head_ref, repo, worktree ?
3461 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
3462 if (error != NULL)
3463 goto done;
3464 error = got_ref_resolve(&commit_id, repo, head_ref);
3465 got_ref_close(head_ref);
3466 if (error != NULL)
3467 goto done;
3468 } else {
3469 error = got_repo_match_object_id(&commit_id, NULL,
3470 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3471 if (error)
3472 goto done;
3475 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
3476 if (error)
3477 goto done;
3479 error = got_object_get_type(&obj_type, repo, obj_id);
3480 if (error)
3481 goto done;
3483 if (obj_type != GOT_OBJ_TYPE_BLOB) {
3484 error = got_error(GOT_ERR_OBJ_TYPE);
3485 goto done;
3488 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
3489 if (error)
3490 goto done;
3491 bca.f = got_opentemp();
3492 if (bca.f == NULL) {
3493 error = got_error_from_errno("got_opentemp");
3494 goto done;
3496 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
3497 &bca.line_offsets, bca.f, blob);
3498 if (error || bca.nlines == 0)
3499 goto done;
3501 /* Don't include \n at EOF in the blame line count. */
3502 if (bca.line_offsets[bca.nlines - 1] == filesize)
3503 bca.nlines--;
3505 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
3506 if (bca.lines == NULL) {
3507 error = got_error_from_errno("calloc");
3508 goto done;
3510 bca.lineno_cur = 1;
3511 bca.nlines_prec = 0;
3512 i = bca.nlines;
3513 while (i > 0) {
3514 i /= 10;
3515 bca.nlines_prec++;
3517 bca.repo = repo;
3519 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
3520 check_cancelled, NULL);
3521 done:
3522 free(in_repo_path);
3523 free(repo_path);
3524 free(cwd);
3525 free(commit_id);
3526 free(obj_id);
3527 if (blob)
3528 got_object_blob_close(blob);
3529 if (worktree)
3530 got_worktree_close(worktree);
3531 if (repo) {
3532 const struct got_error *repo_error;
3533 repo_error = got_repo_close(repo);
3534 if (error == NULL)
3535 error = repo_error;
3537 if (bca.lines) {
3538 for (i = 0; i < bca.nlines; i++) {
3539 struct blame_line *bline = &bca.lines[i];
3540 free(bline->id_str);
3541 free(bline->committer);
3543 free(bca.lines);
3545 free(bca.line_offsets);
3546 if (bca.f && fclose(bca.f) == EOF && error == NULL)
3547 error = got_error_from_errno("fclose");
3548 return error;
3551 __dead static void
3552 usage_tree(void)
3554 fprintf(stderr,
3555 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
3556 getprogname());
3557 exit(1);
3560 static void
3561 print_entry(struct got_tree_entry *te, const char *id, const char *path,
3562 const char *root_path)
3564 int is_root_path = (strcmp(path, root_path) == 0);
3565 const char *modestr = "";
3566 mode_t mode = got_tree_entry_get_mode(te);
3568 path += strlen(root_path);
3569 while (path[0] == '/')
3570 path++;
3572 if (got_object_tree_entry_is_submodule(te))
3573 modestr = "$";
3574 else if (S_ISLNK(mode))
3575 modestr = "@";
3576 else if (S_ISDIR(mode))
3577 modestr = "/";
3578 else if (mode & S_IXUSR)
3579 modestr = "*";
3581 printf("%s%s%s%s%s\n", id ? id : "", path,
3582 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
3585 static const struct got_error *
3586 print_tree(const char *path, struct got_object_id *commit_id,
3587 int show_ids, int recurse, const char *root_path,
3588 struct got_repository *repo)
3590 const struct got_error *err = NULL;
3591 struct got_object_id *tree_id = NULL;
3592 struct got_tree_object *tree = NULL;
3593 int nentries, i;
3595 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
3596 if (err)
3597 goto done;
3599 err = got_object_open_as_tree(&tree, repo, tree_id);
3600 if (err)
3601 goto done;
3602 nentries = got_object_tree_get_nentries(tree);
3603 for (i = 0; i < nentries; i++) {
3604 struct got_tree_entry *te;
3605 char *id = NULL;
3607 if (sigint_received || sigpipe_received)
3608 break;
3610 te = got_object_tree_get_entry(tree, i);
3611 if (show_ids) {
3612 char *id_str;
3613 err = got_object_id_str(&id_str,
3614 got_tree_entry_get_id(te));
3615 if (err)
3616 goto done;
3617 if (asprintf(&id, "%s ", id_str) == -1) {
3618 err = got_error_from_errno("asprintf");
3619 free(id_str);
3620 goto done;
3622 free(id_str);
3624 print_entry(te, id, path, root_path);
3625 free(id);
3627 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
3628 char *child_path;
3629 if (asprintf(&child_path, "%s%s%s", path,
3630 path[0] == '/' && path[1] == '\0' ? "" : "/",
3631 got_tree_entry_get_name(te)) == -1) {
3632 err = got_error_from_errno("asprintf");
3633 goto done;
3635 err = print_tree(child_path, commit_id, show_ids, 1,
3636 root_path, repo);
3637 free(child_path);
3638 if (err)
3639 goto done;
3642 done:
3643 if (tree)
3644 got_object_tree_close(tree);
3645 free(tree_id);
3646 return err;
3649 static const struct got_error *
3650 cmd_tree(int argc, char *argv[])
3652 const struct got_error *error;
3653 struct got_repository *repo = NULL;
3654 struct got_worktree *worktree = NULL;
3655 const char *path;
3656 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3657 struct got_object_id *commit_id = NULL;
3658 char *commit_id_str = NULL;
3659 int show_ids = 0, recurse = 0;
3660 int ch;
3662 #ifndef PROFILE
3663 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3664 NULL) == -1)
3665 err(1, "pledge");
3666 #endif
3668 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
3669 switch (ch) {
3670 case 'c':
3671 commit_id_str = optarg;
3672 break;
3673 case 'r':
3674 repo_path = realpath(optarg, NULL);
3675 if (repo_path == NULL)
3676 return got_error_from_errno2("realpath",
3677 optarg);
3678 got_path_strip_trailing_slashes(repo_path);
3679 break;
3680 case 'i':
3681 show_ids = 1;
3682 break;
3683 case 'R':
3684 recurse = 1;
3685 break;
3686 default:
3687 usage_tree();
3688 /* NOTREACHED */
3692 argc -= optind;
3693 argv += optind;
3695 if (argc == 1)
3696 path = argv[0];
3697 else if (argc > 1)
3698 usage_tree();
3699 else
3700 path = NULL;
3702 cwd = getcwd(NULL, 0);
3703 if (cwd == NULL) {
3704 error = got_error_from_errno("getcwd");
3705 goto done;
3707 if (repo_path == NULL) {
3708 error = got_worktree_open(&worktree, cwd);
3709 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3710 goto done;
3711 else
3712 error = NULL;
3713 if (worktree) {
3714 repo_path =
3715 strdup(got_worktree_get_repo_path(worktree));
3716 if (repo_path == NULL)
3717 error = got_error_from_errno("strdup");
3718 if (error)
3719 goto done;
3720 } else {
3721 repo_path = strdup(cwd);
3722 if (repo_path == NULL) {
3723 error = got_error_from_errno("strdup");
3724 goto done;
3729 error = got_repo_open(&repo, repo_path, NULL);
3730 if (error != NULL)
3731 goto done;
3733 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
3734 if (error)
3735 goto done;
3737 if (path == NULL) {
3738 if (worktree) {
3739 char *p, *worktree_subdir = cwd +
3740 strlen(got_worktree_get_root_path(worktree));
3741 if (asprintf(&p, "%s/%s",
3742 got_worktree_get_path_prefix(worktree),
3743 worktree_subdir) == -1) {
3744 error = got_error_from_errno("asprintf");
3745 goto done;
3747 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3748 free(p);
3749 if (error)
3750 goto done;
3751 } else
3752 path = "/";
3754 if (in_repo_path == NULL) {
3755 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3756 if (error != NULL)
3757 goto done;
3760 if (commit_id_str == NULL) {
3761 struct got_reference *head_ref;
3762 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
3763 if (error != NULL)
3764 goto done;
3765 error = got_ref_resolve(&commit_id, repo, head_ref);
3766 got_ref_close(head_ref);
3767 if (error != NULL)
3768 goto done;
3769 } else {
3770 error = got_repo_match_object_id(&commit_id, NULL,
3771 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
3772 if (error)
3773 goto done;
3776 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
3777 in_repo_path, repo);
3778 done:
3779 free(in_repo_path);
3780 free(repo_path);
3781 free(cwd);
3782 free(commit_id);
3783 if (worktree)
3784 got_worktree_close(worktree);
3785 if (repo) {
3786 const struct got_error *repo_error;
3787 repo_error = got_repo_close(repo);
3788 if (error == NULL)
3789 error = repo_error;
3791 return error;
3794 __dead static void
3795 usage_status(void)
3797 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
3798 exit(1);
3801 static const struct got_error *
3802 print_status(void *arg, unsigned char status, unsigned char staged_status,
3803 const char *path, struct got_object_id *blob_id,
3804 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3805 int dirfd, const char *de_name)
3807 if (status == staged_status && (status == GOT_STATUS_DELETE))
3808 status = GOT_STATUS_NO_CHANGE;
3809 printf("%c%c %s\n", status, staged_status, path);
3810 return NULL;
3813 static const struct got_error *
3814 cmd_status(int argc, char *argv[])
3816 const struct got_error *error = NULL;
3817 struct got_repository *repo = NULL;
3818 struct got_worktree *worktree = NULL;
3819 char *cwd = NULL;
3820 struct got_pathlist_head paths;
3821 struct got_pathlist_entry *pe;
3822 int ch;
3824 TAILQ_INIT(&paths);
3826 while ((ch = getopt(argc, argv, "")) != -1) {
3827 switch (ch) {
3828 default:
3829 usage_status();
3830 /* NOTREACHED */
3834 argc -= optind;
3835 argv += optind;
3837 #ifndef PROFILE
3838 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3839 NULL) == -1)
3840 err(1, "pledge");
3841 #endif
3842 cwd = getcwd(NULL, 0);
3843 if (cwd == NULL) {
3844 error = got_error_from_errno("getcwd");
3845 goto done;
3848 error = got_worktree_open(&worktree, cwd);
3849 if (error != NULL)
3850 goto done;
3852 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3853 NULL);
3854 if (error != NULL)
3855 goto done;
3857 error = apply_unveil(got_repo_get_path(repo), 1,
3858 got_worktree_get_root_path(worktree));
3859 if (error)
3860 goto done;
3862 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3863 if (error)
3864 goto done;
3866 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
3867 check_cancelled, NULL);
3868 done:
3869 TAILQ_FOREACH(pe, &paths, entry)
3870 free((char *)pe->path);
3871 got_pathlist_free(&paths);
3872 free(cwd);
3873 return error;
3876 __dead static void
3877 usage_ref(void)
3879 fprintf(stderr,
3880 "usage: %s ref [-r repository] -l | -d name | [-s] name target\n",
3881 getprogname());
3882 exit(1);
3885 static const struct got_error *
3886 list_refs(struct got_repository *repo)
3888 static const struct got_error *err = NULL;
3889 struct got_reflist_head refs;
3890 struct got_reflist_entry *re;
3892 SIMPLEQ_INIT(&refs);
3893 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3894 if (err)
3895 return err;
3897 SIMPLEQ_FOREACH(re, &refs, entry) {
3898 char *refstr;
3899 refstr = got_ref_to_str(re->ref);
3900 if (refstr == NULL)
3901 return got_error_from_errno("got_ref_to_str");
3902 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
3903 free(refstr);
3906 got_ref_list_free(&refs);
3907 return NULL;
3910 static const struct got_error *
3911 delete_ref(struct got_repository *repo, const char *refname)
3913 const struct got_error *err = NULL;
3914 struct got_reference *ref;
3916 err = got_ref_open(&ref, repo, refname, 0);
3917 if (err)
3918 return err;
3920 err = got_ref_delete(ref, repo);
3921 got_ref_close(ref);
3922 return err;
3925 static const struct got_error *
3926 add_ref(struct got_repository *repo, const char *refname, const char *target)
3928 const struct got_error *err = NULL;
3929 struct got_object_id *id;
3930 struct got_reference *ref = NULL;
3933 * Don't let the user create a reference name with a leading '-'.
3934 * While technically a valid reference name, this case is usually
3935 * an unintended typo.
3937 if (refname[0] == '-')
3938 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
3940 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
3941 repo);
3942 if (err) {
3943 struct got_reference *target_ref;
3945 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
3946 return err;
3947 err = got_ref_open(&target_ref, repo, target, 0);
3948 if (err)
3949 return err;
3950 err = got_ref_resolve(&id, repo, target_ref);
3951 got_ref_close(target_ref);
3952 if (err)
3953 return err;
3956 err = got_ref_alloc(&ref, refname, id);
3957 if (err)
3958 goto done;
3960 err = got_ref_write(ref, repo);
3961 done:
3962 if (ref)
3963 got_ref_close(ref);
3964 free(id);
3965 return err;
3968 static const struct got_error *
3969 add_symref(struct got_repository *repo, const char *refname, const char *target)
3971 const struct got_error *err = NULL;
3972 struct got_reference *ref = NULL;
3973 struct got_reference *target_ref = NULL;
3976 * Don't let the user create a reference name with a leading '-'.
3977 * While technically a valid reference name, this case is usually
3978 * an unintended typo.
3980 if (refname[0] == '-')
3981 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
3983 err = got_ref_open(&target_ref, repo, target, 0);
3984 if (err)
3985 return err;
3987 err = got_ref_alloc_symref(&ref, refname, target_ref);
3988 if (err)
3989 goto done;
3991 err = got_ref_write(ref, repo);
3992 done:
3993 if (target_ref)
3994 got_ref_close(target_ref);
3995 if (ref)
3996 got_ref_close(ref);
3997 return err;
4000 static const struct got_error *
4001 cmd_ref(int argc, char *argv[])
4003 const struct got_error *error = NULL;
4004 struct got_repository *repo = NULL;
4005 struct got_worktree *worktree = NULL;
4006 char *cwd = NULL, *repo_path = NULL;
4007 int ch, do_list = 0, create_symref = 0;
4008 const char *delref = NULL;
4010 /* TODO: Add -s option for adding symbolic references. */
4011 while ((ch = getopt(argc, argv, "d:r:ls")) != -1) {
4012 switch (ch) {
4013 case 'd':
4014 delref = optarg;
4015 break;
4016 case 'r':
4017 repo_path = realpath(optarg, NULL);
4018 if (repo_path == NULL)
4019 return got_error_from_errno2("realpath",
4020 optarg);
4021 got_path_strip_trailing_slashes(repo_path);
4022 break;
4023 case 'l':
4024 do_list = 1;
4025 break;
4026 case 's':
4027 create_symref = 1;
4028 break;
4029 default:
4030 usage_ref();
4031 /* NOTREACHED */
4035 if (do_list && delref)
4036 errx(1, "-l and -d options are mutually exclusive\n");
4038 argc -= optind;
4039 argv += optind;
4041 if (do_list || delref) {
4042 if (create_symref)
4043 errx(1, "-s option cannot be used together with the "
4044 "-l or -d options");
4045 if (argc > 0)
4046 usage_ref();
4047 } else if (argc != 2)
4048 usage_ref();
4050 #ifndef PROFILE
4051 if (do_list) {
4052 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4053 NULL) == -1)
4054 err(1, "pledge");
4055 } else {
4056 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4057 "sendfd unveil", NULL) == -1)
4058 err(1, "pledge");
4060 #endif
4061 cwd = getcwd(NULL, 0);
4062 if (cwd == NULL) {
4063 error = got_error_from_errno("getcwd");
4064 goto done;
4067 if (repo_path == NULL) {
4068 error = got_worktree_open(&worktree, cwd);
4069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4070 goto done;
4071 else
4072 error = NULL;
4073 if (worktree) {
4074 repo_path =
4075 strdup(got_worktree_get_repo_path(worktree));
4076 if (repo_path == NULL)
4077 error = got_error_from_errno("strdup");
4078 if (error)
4079 goto done;
4080 } else {
4081 repo_path = strdup(cwd);
4082 if (repo_path == NULL) {
4083 error = got_error_from_errno("strdup");
4084 goto done;
4089 error = got_repo_open(&repo, repo_path, NULL);
4090 if (error != NULL)
4091 goto done;
4093 error = apply_unveil(got_repo_get_path(repo), do_list,
4094 worktree ? got_worktree_get_root_path(worktree) : NULL);
4095 if (error)
4096 goto done;
4098 if (do_list)
4099 error = list_refs(repo);
4100 else if (delref)
4101 error = delete_ref(repo, delref);
4102 else if (create_symref)
4103 error = add_symref(repo, argv[0], argv[1]);
4104 else
4105 error = add_ref(repo, argv[0], argv[1]);
4106 done:
4107 if (repo)
4108 got_repo_close(repo);
4109 if (worktree)
4110 got_worktree_close(worktree);
4111 free(cwd);
4112 free(repo_path);
4113 return error;
4116 __dead static void
4117 usage_branch(void)
4119 fprintf(stderr,
4120 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4121 "[name]\n", getprogname());
4122 exit(1);
4125 static const struct got_error *
4126 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4127 struct got_reference *ref)
4129 const struct got_error *err = NULL;
4130 const char *refname, *marker = " ";
4131 char *refstr;
4133 refname = got_ref_get_name(ref);
4134 if (worktree && strcmp(refname,
4135 got_worktree_get_head_ref_name(worktree)) == 0) {
4136 struct got_object_id *id = NULL;
4138 err = got_ref_resolve(&id, repo, ref);
4139 if (err)
4140 return err;
4141 if (got_object_id_cmp(id,
4142 got_worktree_get_base_commit_id(worktree)) == 0)
4143 marker = "* ";
4144 else
4145 marker = "~ ";
4146 free(id);
4149 if (strncmp(refname, "refs/heads/", 11) == 0)
4150 refname += 11;
4151 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4152 refname += 18;
4154 refstr = got_ref_to_str(ref);
4155 if (refstr == NULL)
4156 return got_error_from_errno("got_ref_to_str");
4158 printf("%s%s: %s\n", marker, refname, refstr);
4159 free(refstr);
4160 return NULL;
4163 static const struct got_error *
4164 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4166 const char *refname;
4168 if (worktree == NULL)
4169 return got_error(GOT_ERR_NOT_WORKTREE);
4171 refname = got_worktree_get_head_ref_name(worktree);
4173 if (strncmp(refname, "refs/heads/", 11) == 0)
4174 refname += 11;
4175 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4176 refname += 18;
4178 printf("%s\n", refname);
4180 return NULL;
4183 static const struct got_error *
4184 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4186 static const struct got_error *err = NULL;
4187 struct got_reflist_head refs;
4188 struct got_reflist_entry *re;
4189 struct got_reference *temp_ref = NULL;
4190 int rebase_in_progress, histedit_in_progress;
4192 SIMPLEQ_INIT(&refs);
4194 if (worktree) {
4195 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4196 worktree);
4197 if (err)
4198 return err;
4200 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4201 worktree);
4202 if (err)
4203 return err;
4205 if (rebase_in_progress || histedit_in_progress) {
4206 err = got_ref_open(&temp_ref, repo,
4207 got_worktree_get_head_ref_name(worktree), 0);
4208 if (err)
4209 return err;
4210 list_branch(repo, worktree, temp_ref);
4211 got_ref_close(temp_ref);
4215 err = got_ref_list(&refs, repo, "refs/heads",
4216 got_ref_cmp_by_name, NULL);
4217 if (err)
4218 return err;
4220 SIMPLEQ_FOREACH(re, &refs, entry)
4221 list_branch(repo, worktree, re->ref);
4223 got_ref_list_free(&refs);
4224 return NULL;
4227 static const struct got_error *
4228 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4229 const char *branch_name)
4231 const struct got_error *err = NULL;
4232 struct got_reference *ref = NULL;
4233 char *refname;
4235 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4236 return got_error_from_errno("asprintf");
4238 err = got_ref_open(&ref, repo, refname, 0);
4239 if (err)
4240 goto done;
4242 if (worktree &&
4243 strcmp(got_worktree_get_head_ref_name(worktree),
4244 got_ref_get_name(ref)) == 0) {
4245 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4246 "will not delete this work tree's current branch");
4247 goto done;
4250 err = got_ref_delete(ref, repo);
4251 done:
4252 if (ref)
4253 got_ref_close(ref);
4254 free(refname);
4255 return err;
4258 static const struct got_error *
4259 add_branch(struct got_repository *repo, const char *branch_name,
4260 struct got_object_id *base_commit_id)
4262 const struct got_error *err = NULL;
4263 struct got_reference *ref = NULL;
4264 char *base_refname = NULL, *refname = NULL;
4267 * Don't let the user create a branch name with a leading '-'.
4268 * While technically a valid reference name, this case is usually
4269 * an unintended typo.
4271 if (branch_name[0] == '-')
4272 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4274 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4275 err = got_error_from_errno("asprintf");
4276 goto done;
4279 err = got_ref_open(&ref, repo, refname, 0);
4280 if (err == NULL) {
4281 err = got_error(GOT_ERR_BRANCH_EXISTS);
4282 goto done;
4283 } else if (err->code != GOT_ERR_NOT_REF)
4284 goto done;
4286 err = got_ref_alloc(&ref, refname, base_commit_id);
4287 if (err)
4288 goto done;
4290 err = got_ref_write(ref, repo);
4291 done:
4292 if (ref)
4293 got_ref_close(ref);
4294 free(base_refname);
4295 free(refname);
4296 return err;
4299 static const struct got_error *
4300 cmd_branch(int argc, char *argv[])
4302 const struct got_error *error = NULL;
4303 struct got_repository *repo = NULL;
4304 struct got_worktree *worktree = NULL;
4305 char *cwd = NULL, *repo_path = NULL;
4306 int ch, do_list = 0, do_show = 0, do_update = 1;
4307 const char *delref = NULL, *commit_id_arg = NULL;
4308 struct got_reference *ref = NULL;
4309 struct got_pathlist_head paths;
4310 struct got_pathlist_entry *pe;
4311 struct got_object_id *commit_id = NULL;
4312 char *commit_id_str = NULL;
4314 TAILQ_INIT(&paths);
4316 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4317 switch (ch) {
4318 case 'c':
4319 commit_id_arg = optarg;
4320 break;
4321 case 'd':
4322 delref = optarg;
4323 break;
4324 case 'r':
4325 repo_path = realpath(optarg, NULL);
4326 if (repo_path == NULL)
4327 return got_error_from_errno2("realpath",
4328 optarg);
4329 got_path_strip_trailing_slashes(repo_path);
4330 break;
4331 case 'l':
4332 do_list = 1;
4333 break;
4334 case 'n':
4335 do_update = 0;
4336 break;
4337 default:
4338 usage_branch();
4339 /* NOTREACHED */
4343 if (do_list && delref)
4344 errx(1, "-l and -d options are mutually exclusive\n");
4346 argc -= optind;
4347 argv += optind;
4349 if (!do_list && !delref && argc == 0)
4350 do_show = 1;
4352 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4353 errx(1, "-c option can only be used when creating a branch");
4355 if (do_list || delref) {
4356 if (argc > 0)
4357 usage_branch();
4358 } else if (!do_show && argc != 1)
4359 usage_branch();
4361 #ifndef PROFILE
4362 if (do_list || do_show) {
4363 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4364 NULL) == -1)
4365 err(1, "pledge");
4366 } else {
4367 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4368 "sendfd unveil", NULL) == -1)
4369 err(1, "pledge");
4371 #endif
4372 cwd = getcwd(NULL, 0);
4373 if (cwd == NULL) {
4374 error = got_error_from_errno("getcwd");
4375 goto done;
4378 if (repo_path == NULL) {
4379 error = got_worktree_open(&worktree, cwd);
4380 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4381 goto done;
4382 else
4383 error = NULL;
4384 if (worktree) {
4385 repo_path =
4386 strdup(got_worktree_get_repo_path(worktree));
4387 if (repo_path == NULL)
4388 error = got_error_from_errno("strdup");
4389 if (error)
4390 goto done;
4391 } else {
4392 repo_path = strdup(cwd);
4393 if (repo_path == NULL) {
4394 error = got_error_from_errno("strdup");
4395 goto done;
4400 error = got_repo_open(&repo, repo_path, NULL);
4401 if (error != NULL)
4402 goto done;
4404 error = apply_unveil(got_repo_get_path(repo), do_list,
4405 worktree ? got_worktree_get_root_path(worktree) : NULL);
4406 if (error)
4407 goto done;
4409 if (do_show)
4410 error = show_current_branch(repo, worktree);
4411 else if (do_list)
4412 error = list_branches(repo, worktree);
4413 else if (delref)
4414 error = delete_branch(repo, worktree, delref);
4415 else {
4416 if (commit_id_arg == NULL)
4417 commit_id_arg = worktree ?
4418 got_worktree_get_head_ref_name(worktree) :
4419 GOT_REF_HEAD;
4420 error = got_repo_match_object_id(&commit_id, NULL,
4421 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
4422 if (error)
4423 goto done;
4424 error = add_branch(repo, argv[0], commit_id);
4425 if (error)
4426 goto done;
4427 if (worktree && do_update) {
4428 int did_something = 0;
4429 char *branch_refname = NULL;
4431 error = got_object_id_str(&commit_id_str, commit_id);
4432 if (error)
4433 goto done;
4434 error = get_worktree_paths_from_argv(&paths, 0, NULL,
4435 worktree);
4436 if (error)
4437 goto done;
4438 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
4439 == -1) {
4440 error = got_error_from_errno("asprintf");
4441 goto done;
4443 error = got_ref_open(&ref, repo, branch_refname, 0);
4444 free(branch_refname);
4445 if (error)
4446 goto done;
4447 error = switch_head_ref(ref, commit_id, worktree,
4448 repo);
4449 if (error)
4450 goto done;
4451 error = got_worktree_set_base_commit_id(worktree, repo,
4452 commit_id);
4453 if (error)
4454 goto done;
4455 error = got_worktree_checkout_files(worktree, &paths,
4456 repo, update_progress, &did_something,
4457 check_cancelled, NULL);
4458 if (error)
4459 goto done;
4460 if (did_something)
4461 printf("Updated to commit %s\n", commit_id_str);
4464 done:
4465 if (ref)
4466 got_ref_close(ref);
4467 if (repo)
4468 got_repo_close(repo);
4469 if (worktree)
4470 got_worktree_close(worktree);
4471 free(cwd);
4472 free(repo_path);
4473 free(commit_id);
4474 free(commit_id_str);
4475 TAILQ_FOREACH(pe, &paths, entry)
4476 free((char *)pe->path);
4477 got_pathlist_free(&paths);
4478 return error;
4482 __dead static void
4483 usage_tag(void)
4485 fprintf(stderr,
4486 "usage: %s tag [-c commit] [-r repository] [-l] "
4487 "[-m message] name\n", getprogname());
4488 exit(1);
4491 #if 0
4492 static const struct got_error *
4493 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
4495 const struct got_error *err = NULL;
4496 struct got_reflist_entry *re, *se, *new;
4497 struct got_object_id *re_id, *se_id;
4498 struct got_tag_object *re_tag, *se_tag;
4499 time_t re_time, se_time;
4501 SIMPLEQ_FOREACH(re, tags, entry) {
4502 se = SIMPLEQ_FIRST(sorted);
4503 if (se == NULL) {
4504 err = got_reflist_entry_dup(&new, re);
4505 if (err)
4506 return err;
4507 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
4508 continue;
4509 } else {
4510 err = got_ref_resolve(&re_id, repo, re->ref);
4511 if (err)
4512 break;
4513 err = got_object_open_as_tag(&re_tag, repo, re_id);
4514 free(re_id);
4515 if (err)
4516 break;
4517 re_time = got_object_tag_get_tagger_time(re_tag);
4518 got_object_tag_close(re_tag);
4521 while (se) {
4522 err = got_ref_resolve(&se_id, repo, re->ref);
4523 if (err)
4524 break;
4525 err = got_object_open_as_tag(&se_tag, repo, se_id);
4526 free(se_id);
4527 if (err)
4528 break;
4529 se_time = got_object_tag_get_tagger_time(se_tag);
4530 got_object_tag_close(se_tag);
4532 if (se_time > re_time) {
4533 err = got_reflist_entry_dup(&new, re);
4534 if (err)
4535 return err;
4536 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
4537 break;
4539 se = SIMPLEQ_NEXT(se, entry);
4540 continue;
4543 done:
4544 return err;
4546 #endif
4548 static const struct got_error *
4549 list_tags(struct got_repository *repo, struct got_worktree *worktree)
4551 static const struct got_error *err = NULL;
4552 struct got_reflist_head refs;
4553 struct got_reflist_entry *re;
4555 SIMPLEQ_INIT(&refs);
4557 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
4558 if (err)
4559 return err;
4561 SIMPLEQ_FOREACH(re, &refs, entry) {
4562 const char *refname;
4563 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
4564 char datebuf[26];
4565 const char *tagger;
4566 time_t tagger_time;
4567 struct got_object_id *id;
4568 struct got_tag_object *tag;
4569 struct got_commit_object *commit = NULL;
4571 refname = got_ref_get_name(re->ref);
4572 if (strncmp(refname, "refs/tags/", 10) != 0)
4573 continue;
4574 refname += 10;
4575 refstr = got_ref_to_str(re->ref);
4576 if (refstr == NULL) {
4577 err = got_error_from_errno("got_ref_to_str");
4578 break;
4580 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
4581 free(refstr);
4583 err = got_ref_resolve(&id, repo, re->ref);
4584 if (err)
4585 break;
4586 err = got_object_open_as_tag(&tag, repo, id);
4587 if (err) {
4588 if (err->code != GOT_ERR_OBJ_TYPE) {
4589 free(id);
4590 break;
4592 /* "lightweight" tag */
4593 err = got_object_open_as_commit(&commit, repo, id);
4594 if (err) {
4595 free(id);
4596 break;
4598 tagger = got_object_commit_get_committer(commit);
4599 tagger_time =
4600 got_object_commit_get_committer_time(commit);
4601 err = got_object_id_str(&id_str, id);
4602 free(id);
4603 if (err)
4604 break;
4605 } else {
4606 free(id);
4607 tagger = got_object_tag_get_tagger(tag);
4608 tagger_time = got_object_tag_get_tagger_time(tag);
4609 err = got_object_id_str(&id_str,
4610 got_object_tag_get_object_id(tag));
4611 if (err)
4612 break;
4614 printf("from: %s\n", tagger);
4615 datestr = get_datestr(&tagger_time, datebuf);
4616 if (datestr)
4617 printf("date: %s UTC\n", datestr);
4618 if (commit)
4619 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
4620 else {
4621 switch (got_object_tag_get_object_type(tag)) {
4622 case GOT_OBJ_TYPE_BLOB:
4623 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
4624 id_str);
4625 break;
4626 case GOT_OBJ_TYPE_TREE:
4627 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
4628 id_str);
4629 break;
4630 case GOT_OBJ_TYPE_COMMIT:
4631 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
4632 id_str);
4633 break;
4634 case GOT_OBJ_TYPE_TAG:
4635 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
4636 id_str);
4637 break;
4638 default:
4639 break;
4642 free(id_str);
4643 if (commit) {
4644 err = got_object_commit_get_logmsg(&tagmsg0, commit);
4645 if (err)
4646 break;
4647 got_object_commit_close(commit);
4648 } else {
4649 tagmsg0 = strdup(got_object_tag_get_message(tag));
4650 got_object_tag_close(tag);
4651 if (tagmsg0 == NULL) {
4652 err = got_error_from_errno("strdup");
4653 break;
4657 tagmsg = tagmsg0;
4658 do {
4659 line = strsep(&tagmsg, "\n");
4660 if (line)
4661 printf(" %s\n", line);
4662 } while (line);
4663 free(tagmsg0);
4666 got_ref_list_free(&refs);
4667 return NULL;
4670 static const struct got_error *
4671 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
4672 const char *tag_name, const char *repo_path)
4674 const struct got_error *err = NULL;
4675 char *template = NULL, *initial_content = NULL;
4676 char *editor = NULL;
4677 int fd = -1;
4679 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
4680 err = got_error_from_errno("asprintf");
4681 goto done;
4684 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
4685 commit_id_str, tag_name) == -1) {
4686 err = got_error_from_errno("asprintf");
4687 goto done;
4690 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
4691 if (err)
4692 goto done;
4694 dprintf(fd, initial_content);
4695 close(fd);
4697 err = get_editor(&editor);
4698 if (err)
4699 goto done;
4700 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
4701 done:
4702 free(initial_content);
4703 free(template);
4704 free(editor);
4706 /* Editor is done; we can now apply unveil(2) */
4707 if (err == NULL) {
4708 err = apply_unveil(repo_path, 0, NULL);
4709 if (err) {
4710 free(*tagmsg);
4711 *tagmsg = NULL;
4714 return err;
4717 static const struct got_error *
4718 add_tag(struct got_repository *repo, const char *tag_name,
4719 const char *commit_arg, const char *tagmsg_arg)
4721 const struct got_error *err = NULL;
4722 struct got_object_id *commit_id = NULL, *tag_id = NULL;
4723 char *label = NULL, *commit_id_str = NULL;
4724 struct got_reference *ref = NULL;
4725 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
4726 char *tagmsg_path = NULL, *tag_id_str = NULL;
4727 int preserve_tagmsg = 0;
4730 * Don't let the user create a tag name with a leading '-'.
4731 * While technically a valid reference name, this case is usually
4732 * an unintended typo.
4734 if (tag_name[0] == '-')
4735 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
4737 err = get_author(&tagger, repo);
4738 if (err)
4739 return err;
4741 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
4742 GOT_OBJ_TYPE_COMMIT, 1, repo);
4743 if (err)
4744 goto done;
4746 err = got_object_id_str(&commit_id_str, commit_id);
4747 if (err)
4748 goto done;
4750 if (strncmp("refs/tags/", tag_name, 10) == 0) {
4751 refname = strdup(tag_name);
4752 if (refname == NULL) {
4753 err = got_error_from_errno("strdup");
4754 goto done;
4756 tag_name += 10;
4757 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
4758 err = got_error_from_errno("asprintf");
4759 goto done;
4762 err = got_ref_open(&ref, repo, refname, 0);
4763 if (err == NULL) {
4764 err = got_error(GOT_ERR_TAG_EXISTS);
4765 goto done;
4766 } else if (err->code != GOT_ERR_NOT_REF)
4767 goto done;
4769 if (tagmsg_arg == NULL) {
4770 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
4771 tag_name, got_repo_get_path(repo));
4772 if (err) {
4773 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
4774 tagmsg_path != NULL)
4775 preserve_tagmsg = 1;
4776 goto done;
4780 err = got_object_tag_create(&tag_id, tag_name, commit_id,
4781 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
4782 if (err) {
4783 if (tagmsg_path)
4784 preserve_tagmsg = 1;
4785 goto done;
4788 err = got_ref_alloc(&ref, refname, tag_id);
4789 if (err) {
4790 if (tagmsg_path)
4791 preserve_tagmsg = 1;
4792 goto done;
4795 err = got_ref_write(ref, repo);
4796 if (err) {
4797 if (tagmsg_path)
4798 preserve_tagmsg = 1;
4799 goto done;
4802 err = got_object_id_str(&tag_id_str, tag_id);
4803 if (err) {
4804 if (tagmsg_path)
4805 preserve_tagmsg = 1;
4806 goto done;
4808 printf("Created tag %s\n", tag_id_str);
4809 done:
4810 if (preserve_tagmsg) {
4811 fprintf(stderr, "%s: tag message preserved in %s\n",
4812 getprogname(), tagmsg_path);
4813 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
4814 err = got_error_from_errno2("unlink", tagmsg_path);
4815 free(tag_id_str);
4816 if (ref)
4817 got_ref_close(ref);
4818 free(commit_id);
4819 free(commit_id_str);
4820 free(refname);
4821 free(tagmsg);
4822 free(tagmsg_path);
4823 free(tagger);
4824 return err;
4827 static const struct got_error *
4828 cmd_tag(int argc, char *argv[])
4830 const struct got_error *error = NULL;
4831 struct got_repository *repo = NULL;
4832 struct got_worktree *worktree = NULL;
4833 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
4834 char *gitconfig_path = NULL;
4835 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
4836 int ch, do_list = 0;
4838 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
4839 switch (ch) {
4840 case 'c':
4841 commit_id_arg = optarg;
4842 break;
4843 case 'm':
4844 tagmsg = optarg;
4845 break;
4846 case 'r':
4847 repo_path = realpath(optarg, NULL);
4848 if (repo_path == NULL)
4849 return got_error_from_errno2("realpath",
4850 optarg);
4851 got_path_strip_trailing_slashes(repo_path);
4852 break;
4853 case 'l':
4854 do_list = 1;
4855 break;
4856 default:
4857 usage_tag();
4858 /* NOTREACHED */
4862 argc -= optind;
4863 argv += optind;
4865 if (do_list) {
4866 if (commit_id_arg != NULL)
4867 errx(1, "-c option can only be used when creating a tag");
4868 if (tagmsg)
4869 errx(1, "-l and -m options are mutually exclusive");
4870 if (argc > 0)
4871 usage_tag();
4872 } else if (argc != 1)
4873 usage_tag();
4875 tag_name = argv[0];
4877 #ifndef PROFILE
4878 if (do_list) {
4879 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4880 NULL) == -1)
4881 err(1, "pledge");
4882 } else {
4883 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4884 "sendfd unveil", NULL) == -1)
4885 err(1, "pledge");
4887 #endif
4888 cwd = getcwd(NULL, 0);
4889 if (cwd == NULL) {
4890 error = got_error_from_errno("getcwd");
4891 goto done;
4894 if (repo_path == NULL) {
4895 error = got_worktree_open(&worktree, cwd);
4896 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4897 goto done;
4898 else
4899 error = NULL;
4900 if (worktree) {
4901 repo_path =
4902 strdup(got_worktree_get_repo_path(worktree));
4903 if (repo_path == NULL)
4904 error = got_error_from_errno("strdup");
4905 if (error)
4906 goto done;
4907 } else {
4908 repo_path = strdup(cwd);
4909 if (repo_path == NULL) {
4910 error = got_error_from_errno("strdup");
4911 goto done;
4916 if (do_list) {
4917 error = got_repo_open(&repo, repo_path, NULL);
4918 if (error != NULL)
4919 goto done;
4920 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4921 if (error)
4922 goto done;
4923 error = list_tags(repo, worktree);
4924 } else {
4925 error = get_gitconfig_path(&gitconfig_path);
4926 if (error)
4927 goto done;
4928 error = got_repo_open(&repo, repo_path, gitconfig_path);
4929 if (error != NULL)
4930 goto done;
4932 if (tagmsg) {
4933 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4934 if (error)
4935 goto done;
4938 if (commit_id_arg == NULL) {
4939 struct got_reference *head_ref;
4940 struct got_object_id *commit_id;
4941 error = got_ref_open(&head_ref, repo,
4942 worktree ? got_worktree_get_head_ref_name(worktree)
4943 : GOT_REF_HEAD, 0);
4944 if (error)
4945 goto done;
4946 error = got_ref_resolve(&commit_id, repo, head_ref);
4947 got_ref_close(head_ref);
4948 if (error)
4949 goto done;
4950 error = got_object_id_str(&commit_id_str, commit_id);
4951 free(commit_id);
4952 if (error)
4953 goto done;
4956 error = add_tag(repo, tag_name,
4957 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
4959 done:
4960 if (repo)
4961 got_repo_close(repo);
4962 if (worktree)
4963 got_worktree_close(worktree);
4964 free(cwd);
4965 free(repo_path);
4966 free(gitconfig_path);
4967 free(commit_id_str);
4968 return error;
4971 __dead static void
4972 usage_add(void)
4974 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
4975 getprogname());
4976 exit(1);
4979 static const struct got_error *
4980 add_progress(void *arg, unsigned char status, const char *path)
4982 while (path[0] == '/')
4983 path++;
4984 printf("%c %s\n", status, path);
4985 return NULL;
4988 static const struct got_error *
4989 cmd_add(int argc, char *argv[])
4991 const struct got_error *error = NULL;
4992 struct got_repository *repo = NULL;
4993 struct got_worktree *worktree = NULL;
4994 char *cwd = NULL;
4995 struct got_pathlist_head paths;
4996 struct got_pathlist_entry *pe;
4997 int ch, can_recurse = 0, no_ignores = 0;
4999 TAILQ_INIT(&paths);
5001 while ((ch = getopt(argc, argv, "IR")) != -1) {
5002 switch (ch) {
5003 case 'I':
5004 no_ignores = 1;
5005 break;
5006 case 'R':
5007 can_recurse = 1;
5008 break;
5009 default:
5010 usage_add();
5011 /* NOTREACHED */
5015 argc -= optind;
5016 argv += optind;
5018 #ifndef PROFILE
5019 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5020 NULL) == -1)
5021 err(1, "pledge");
5022 #endif
5023 if (argc < 1)
5024 usage_add();
5026 cwd = getcwd(NULL, 0);
5027 if (cwd == NULL) {
5028 error = got_error_from_errno("getcwd");
5029 goto done;
5032 error = got_worktree_open(&worktree, cwd);
5033 if (error)
5034 goto done;
5036 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5037 NULL);
5038 if (error != NULL)
5039 goto done;
5041 error = apply_unveil(got_repo_get_path(repo), 1,
5042 got_worktree_get_root_path(worktree));
5043 if (error)
5044 goto done;
5046 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5047 if (error)
5048 goto done;
5050 if (!can_recurse && no_ignores) {
5051 error = got_error_msg(GOT_ERR_BAD_PATH,
5052 "disregarding ignores requires -R option");
5053 goto done;
5057 if (!can_recurse) {
5058 char *ondisk_path;
5059 struct stat sb;
5060 TAILQ_FOREACH(pe, &paths, entry) {
5061 if (asprintf(&ondisk_path, "%s/%s",
5062 got_worktree_get_root_path(worktree),
5063 pe->path) == -1) {
5064 error = got_error_from_errno("asprintf");
5065 goto done;
5067 if (lstat(ondisk_path, &sb) == -1) {
5068 if (errno == ENOENT) {
5069 free(ondisk_path);
5070 continue;
5072 error = got_error_from_errno2("lstat",
5073 ondisk_path);
5074 free(ondisk_path);
5075 goto done;
5077 free(ondisk_path);
5078 if (S_ISDIR(sb.st_mode)) {
5079 error = got_error_msg(GOT_ERR_BAD_PATH,
5080 "adding directories requires -R option");
5081 goto done;
5086 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5087 NULL, repo, no_ignores);
5088 done:
5089 if (repo)
5090 got_repo_close(repo);
5091 if (worktree)
5092 got_worktree_close(worktree);
5093 TAILQ_FOREACH(pe, &paths, entry)
5094 free((char *)pe->path);
5095 got_pathlist_free(&paths);
5096 free(cwd);
5097 return error;
5100 __dead static void
5101 usage_remove(void)
5103 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5104 getprogname());
5105 exit(1);
5108 static const struct got_error *
5109 print_remove_status(void *arg, unsigned char status,
5110 unsigned char staged_status, const char *path)
5112 while (path[0] == '/')
5113 path++;
5114 if (status == GOT_STATUS_NONEXISTENT)
5115 return NULL;
5116 if (status == staged_status && (status == GOT_STATUS_DELETE))
5117 status = GOT_STATUS_NO_CHANGE;
5118 printf("%c%c %s\n", status, staged_status, path);
5119 return NULL;
5122 static const struct got_error *
5123 cmd_remove(int argc, char *argv[])
5125 const struct got_error *error = NULL;
5126 struct got_worktree *worktree = NULL;
5127 struct got_repository *repo = NULL;
5128 char *cwd = NULL;
5129 struct got_pathlist_head paths;
5130 struct got_pathlist_entry *pe;
5131 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5133 TAILQ_INIT(&paths);
5135 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5136 switch (ch) {
5137 case 'f':
5138 delete_local_mods = 1;
5139 break;
5140 case 'k':
5141 keep_on_disk = 1;
5142 break;
5143 case 'R':
5144 can_recurse = 1;
5145 break;
5146 default:
5147 usage_remove();
5148 /* NOTREACHED */
5152 argc -= optind;
5153 argv += optind;
5155 #ifndef PROFILE
5156 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5157 NULL) == -1)
5158 err(1, "pledge");
5159 #endif
5160 if (argc < 1)
5161 usage_remove();
5163 cwd = getcwd(NULL, 0);
5164 if (cwd == NULL) {
5165 error = got_error_from_errno("getcwd");
5166 goto done;
5168 error = got_worktree_open(&worktree, cwd);
5169 if (error)
5170 goto done;
5172 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5173 NULL);
5174 if (error)
5175 goto done;
5177 error = apply_unveil(got_repo_get_path(repo), 1,
5178 got_worktree_get_root_path(worktree));
5179 if (error)
5180 goto done;
5182 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5183 if (error)
5184 goto done;
5186 if (!can_recurse) {
5187 char *ondisk_path;
5188 struct stat sb;
5189 TAILQ_FOREACH(pe, &paths, entry) {
5190 if (asprintf(&ondisk_path, "%s/%s",
5191 got_worktree_get_root_path(worktree),
5192 pe->path) == -1) {
5193 error = got_error_from_errno("asprintf");
5194 goto done;
5196 if (lstat(ondisk_path, &sb) == -1) {
5197 if (errno == ENOENT) {
5198 free(ondisk_path);
5199 continue;
5201 error = got_error_from_errno2("lstat",
5202 ondisk_path);
5203 free(ondisk_path);
5204 goto done;
5206 free(ondisk_path);
5207 if (S_ISDIR(sb.st_mode)) {
5208 error = got_error_msg(GOT_ERR_BAD_PATH,
5209 "removing directories requires -R option");
5210 goto done;
5215 error = got_worktree_schedule_delete(worktree, &paths,
5216 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5217 done:
5218 if (repo)
5219 got_repo_close(repo);
5220 if (worktree)
5221 got_worktree_close(worktree);
5222 TAILQ_FOREACH(pe, &paths, entry)
5223 free((char *)pe->path);
5224 got_pathlist_free(&paths);
5225 free(cwd);
5226 return error;
5229 __dead static void
5230 usage_revert(void)
5232 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5233 "path ...\n", getprogname());
5234 exit(1);
5237 static const struct got_error *
5238 revert_progress(void *arg, unsigned char status, const char *path)
5240 if (status == GOT_STATUS_UNVERSIONED)
5241 return NULL;
5243 while (path[0] == '/')
5244 path++;
5245 printf("%c %s\n", status, path);
5246 return NULL;
5249 struct choose_patch_arg {
5250 FILE *patch_script_file;
5251 const char *action;
5254 static const struct got_error *
5255 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5256 int nchanges, const char *action)
5258 char *line = NULL;
5259 size_t linesize = 0;
5260 ssize_t linelen;
5262 switch (status) {
5263 case GOT_STATUS_ADD:
5264 printf("A %s\n%s this addition? [y/n] ", path, action);
5265 break;
5266 case GOT_STATUS_DELETE:
5267 printf("D %s\n%s this deletion? [y/n] ", path, action);
5268 break;
5269 case GOT_STATUS_MODIFY:
5270 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5271 return got_error_from_errno("fseek");
5272 printf(GOT_COMMIT_SEP_STR);
5273 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5274 printf("%s", line);
5275 if (ferror(patch_file))
5276 return got_error_from_errno("getline");
5277 printf(GOT_COMMIT_SEP_STR);
5278 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5279 path, n, nchanges, action);
5280 break;
5281 default:
5282 return got_error_path(path, GOT_ERR_FILE_STATUS);
5285 return NULL;
5288 static const struct got_error *
5289 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5290 FILE *patch_file, int n, int nchanges)
5292 const struct got_error *err = NULL;
5293 char *line = NULL;
5294 size_t linesize = 0;
5295 ssize_t linelen;
5296 int resp = ' ';
5297 struct choose_patch_arg *a = arg;
5299 *choice = GOT_PATCH_CHOICE_NONE;
5301 if (a->patch_script_file) {
5302 char *nl;
5303 err = show_change(status, path, patch_file, n, nchanges,
5304 a->action);
5305 if (err)
5306 return err;
5307 linelen = getline(&line, &linesize, a->patch_script_file);
5308 if (linelen == -1) {
5309 if (ferror(a->patch_script_file))
5310 return got_error_from_errno("getline");
5311 return NULL;
5313 nl = strchr(line, '\n');
5314 if (nl)
5315 *nl = '\0';
5316 if (strcmp(line, "y") == 0) {
5317 *choice = GOT_PATCH_CHOICE_YES;
5318 printf("y\n");
5319 } else if (strcmp(line, "n") == 0) {
5320 *choice = GOT_PATCH_CHOICE_NO;
5321 printf("n\n");
5322 } else if (strcmp(line, "q") == 0 &&
5323 status == GOT_STATUS_MODIFY) {
5324 *choice = GOT_PATCH_CHOICE_QUIT;
5325 printf("q\n");
5326 } else
5327 printf("invalid response '%s'\n", line);
5328 free(line);
5329 return NULL;
5332 while (resp != 'y' && resp != 'n' && resp != 'q') {
5333 err = show_change(status, path, patch_file, n, nchanges,
5334 a->action);
5335 if (err)
5336 return err;
5337 resp = getchar();
5338 if (resp == '\n')
5339 resp = getchar();
5340 if (status == GOT_STATUS_MODIFY) {
5341 if (resp != 'y' && resp != 'n' && resp != 'q') {
5342 printf("invalid response '%c'\n", resp);
5343 resp = ' ';
5345 } else if (resp != 'y' && resp != 'n') {
5346 printf("invalid response '%c'\n", resp);
5347 resp = ' ';
5351 if (resp == 'y')
5352 *choice = GOT_PATCH_CHOICE_YES;
5353 else if (resp == 'n')
5354 *choice = GOT_PATCH_CHOICE_NO;
5355 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
5356 *choice = GOT_PATCH_CHOICE_QUIT;
5358 return NULL;
5362 static const struct got_error *
5363 cmd_revert(int argc, char *argv[])
5365 const struct got_error *error = NULL;
5366 struct got_worktree *worktree = NULL;
5367 struct got_repository *repo = NULL;
5368 char *cwd = NULL, *path = NULL;
5369 struct got_pathlist_head paths;
5370 struct got_pathlist_entry *pe;
5371 int ch, can_recurse = 0, pflag = 0;
5372 FILE *patch_script_file = NULL;
5373 const char *patch_script_path = NULL;
5374 struct choose_patch_arg cpa;
5376 TAILQ_INIT(&paths);
5378 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
5379 switch (ch) {
5380 case 'p':
5381 pflag = 1;
5382 break;
5383 case 'F':
5384 patch_script_path = optarg;
5385 break;
5386 case 'R':
5387 can_recurse = 1;
5388 break;
5389 default:
5390 usage_revert();
5391 /* NOTREACHED */
5395 argc -= optind;
5396 argv += optind;
5398 #ifndef PROFILE
5399 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5400 "unveil", NULL) == -1)
5401 err(1, "pledge");
5402 #endif
5403 if (argc < 1)
5404 usage_revert();
5405 if (patch_script_path && !pflag)
5406 errx(1, "-F option can only be used together with -p option");
5408 cwd = getcwd(NULL, 0);
5409 if (cwd == NULL) {
5410 error = got_error_from_errno("getcwd");
5411 goto done;
5413 error = got_worktree_open(&worktree, cwd);
5414 if (error)
5415 goto done;
5417 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5418 NULL);
5419 if (error != NULL)
5420 goto done;
5422 if (patch_script_path) {
5423 patch_script_file = fopen(patch_script_path, "r");
5424 if (patch_script_file == NULL) {
5425 error = got_error_from_errno2("fopen",
5426 patch_script_path);
5427 goto done;
5430 error = apply_unveil(got_repo_get_path(repo), 1,
5431 got_worktree_get_root_path(worktree));
5432 if (error)
5433 goto done;
5435 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5436 if (error)
5437 goto done;
5439 if (!can_recurse) {
5440 char *ondisk_path;
5441 struct stat sb;
5442 TAILQ_FOREACH(pe, &paths, entry) {
5443 if (asprintf(&ondisk_path, "%s/%s",
5444 got_worktree_get_root_path(worktree),
5445 pe->path) == -1) {
5446 error = got_error_from_errno("asprintf");
5447 goto done;
5449 if (lstat(ondisk_path, &sb) == -1) {
5450 if (errno == ENOENT) {
5451 free(ondisk_path);
5452 continue;
5454 error = got_error_from_errno2("lstat",
5455 ondisk_path);
5456 free(ondisk_path);
5457 goto done;
5459 free(ondisk_path);
5460 if (S_ISDIR(sb.st_mode)) {
5461 error = got_error_msg(GOT_ERR_BAD_PATH,
5462 "reverting directories requires -R option");
5463 goto done;
5468 cpa.patch_script_file = patch_script_file;
5469 cpa.action = "revert";
5470 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
5471 pflag ? choose_patch : NULL, &cpa, repo);
5472 done:
5473 if (patch_script_file && fclose(patch_script_file) == EOF &&
5474 error == NULL)
5475 error = got_error_from_errno2("fclose", patch_script_path);
5476 if (repo)
5477 got_repo_close(repo);
5478 if (worktree)
5479 got_worktree_close(worktree);
5480 free(path);
5481 free(cwd);
5482 return error;
5485 __dead static void
5486 usage_commit(void)
5488 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
5489 getprogname());
5490 exit(1);
5493 struct collect_commit_logmsg_arg {
5494 const char *cmdline_log;
5495 const char *editor;
5496 const char *worktree_path;
5497 const char *branch_name;
5498 const char *repo_path;
5499 char *logmsg_path;
5503 static const struct got_error *
5504 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
5505 void *arg)
5507 char *initial_content = NULL;
5508 struct got_pathlist_entry *pe;
5509 const struct got_error *err = NULL;
5510 char *template = NULL;
5511 struct collect_commit_logmsg_arg *a = arg;
5512 int fd;
5513 size_t len;
5515 /* if a message was specified on the command line, just use it */
5516 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
5517 len = strlen(a->cmdline_log) + 1;
5518 *logmsg = malloc(len + 1);
5519 if (*logmsg == NULL)
5520 return got_error_from_errno("malloc");
5521 strlcpy(*logmsg, a->cmdline_log, len);
5522 return NULL;
5525 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
5526 return got_error_from_errno("asprintf");
5528 if (asprintf(&initial_content,
5529 "\n# changes to be committed on branch %s:\n",
5530 a->branch_name) == -1)
5531 return got_error_from_errno("asprintf");
5533 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
5534 if (err)
5535 goto done;
5537 dprintf(fd, initial_content);
5539 TAILQ_FOREACH(pe, commitable_paths, entry) {
5540 struct got_commitable *ct = pe->data;
5541 dprintf(fd, "# %c %s\n",
5542 got_commitable_get_status(ct),
5543 got_commitable_get_path(ct));
5545 close(fd);
5547 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
5548 done:
5549 free(initial_content);
5550 free(template);
5552 /* Editor is done; we can now apply unveil(2) */
5553 if (err == NULL) {
5554 err = apply_unveil(a->repo_path, 0, a->worktree_path);
5555 if (err) {
5556 free(*logmsg);
5557 *logmsg = NULL;
5560 return err;
5563 static const struct got_error *
5564 cmd_commit(int argc, char *argv[])
5566 const struct got_error *error = NULL;
5567 struct got_worktree *worktree = NULL;
5568 struct got_repository *repo = NULL;
5569 char *cwd = NULL, *id_str = NULL;
5570 struct got_object_id *id = NULL;
5571 const char *logmsg = NULL;
5572 struct collect_commit_logmsg_arg cl_arg;
5573 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
5574 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
5575 struct got_pathlist_head paths;
5577 TAILQ_INIT(&paths);
5578 cl_arg.logmsg_path = NULL;
5580 while ((ch = getopt(argc, argv, "m:")) != -1) {
5581 switch (ch) {
5582 case 'm':
5583 logmsg = optarg;
5584 break;
5585 default:
5586 usage_commit();
5587 /* NOTREACHED */
5591 argc -= optind;
5592 argv += optind;
5594 #ifndef PROFILE
5595 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5596 "unveil", NULL) == -1)
5597 err(1, "pledge");
5598 #endif
5599 cwd = getcwd(NULL, 0);
5600 if (cwd == NULL) {
5601 error = got_error_from_errno("getcwd");
5602 goto done;
5604 error = got_worktree_open(&worktree, cwd);
5605 if (error)
5606 goto done;
5608 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
5609 if (error)
5610 goto done;
5611 if (rebase_in_progress) {
5612 error = got_error(GOT_ERR_REBASING);
5613 goto done;
5616 error = got_worktree_histedit_in_progress(&histedit_in_progress,
5617 worktree);
5618 if (error)
5619 goto done;
5621 error = get_gitconfig_path(&gitconfig_path);
5622 if (error)
5623 goto done;
5624 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5625 gitconfig_path);
5626 if (error != NULL)
5627 goto done;
5629 error = get_author(&author, repo);
5630 if (error)
5631 return error;
5634 * unveil(2) traverses exec(2); if an editor is used we have
5635 * to apply unveil after the log message has been written.
5637 if (logmsg == NULL || strlen(logmsg) == 0)
5638 error = get_editor(&editor);
5639 else
5640 error = apply_unveil(got_repo_get_path(repo), 0,
5641 got_worktree_get_root_path(worktree));
5642 if (error)
5643 goto done;
5645 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5646 if (error)
5647 goto done;
5649 cl_arg.editor = editor;
5650 cl_arg.cmdline_log = logmsg;
5651 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
5652 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
5653 if (!histedit_in_progress) {
5654 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
5655 error = got_error(GOT_ERR_COMMIT_BRANCH);
5656 goto done;
5658 cl_arg.branch_name += 11;
5660 cl_arg.repo_path = got_repo_get_path(repo);
5661 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
5662 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
5663 if (error) {
5664 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5665 cl_arg.logmsg_path != NULL)
5666 preserve_logmsg = 1;
5667 goto done;
5670 error = got_object_id_str(&id_str, id);
5671 if (error)
5672 goto done;
5673 printf("Created commit %s\n", id_str);
5674 done:
5675 if (preserve_logmsg) {
5676 fprintf(stderr, "%s: log message preserved in %s\n",
5677 getprogname(), cl_arg.logmsg_path);
5678 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
5679 error == NULL)
5680 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
5681 free(cl_arg.logmsg_path);
5682 if (repo)
5683 got_repo_close(repo);
5684 if (worktree)
5685 got_worktree_close(worktree);
5686 free(cwd);
5687 free(id_str);
5688 free(gitconfig_path);
5689 free(editor);
5690 free(author);
5691 return error;
5694 __dead static void
5695 usage_cherrypick(void)
5697 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
5698 exit(1);
5701 static const struct got_error *
5702 cmd_cherrypick(int argc, char *argv[])
5704 const struct got_error *error = NULL;
5705 struct got_worktree *worktree = NULL;
5706 struct got_repository *repo = NULL;
5707 char *cwd = NULL, *commit_id_str = NULL;
5708 struct got_object_id *commit_id = NULL;
5709 struct got_commit_object *commit = NULL;
5710 struct got_object_qid *pid;
5711 struct got_reference *head_ref = NULL;
5712 int ch, did_something = 0;
5714 while ((ch = getopt(argc, argv, "")) != -1) {
5715 switch (ch) {
5716 default:
5717 usage_cherrypick();
5718 /* NOTREACHED */
5722 argc -= optind;
5723 argv += optind;
5725 #ifndef PROFILE
5726 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5727 "unveil", NULL) == -1)
5728 err(1, "pledge");
5729 #endif
5730 if (argc != 1)
5731 usage_cherrypick();
5733 cwd = getcwd(NULL, 0);
5734 if (cwd == NULL) {
5735 error = got_error_from_errno("getcwd");
5736 goto done;
5738 error = got_worktree_open(&worktree, cwd);
5739 if (error)
5740 goto done;
5742 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5743 NULL);
5744 if (error != NULL)
5745 goto done;
5747 error = apply_unveil(got_repo_get_path(repo), 0,
5748 got_worktree_get_root_path(worktree));
5749 if (error)
5750 goto done;
5752 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
5753 GOT_OBJ_TYPE_COMMIT, repo);
5754 if (error != NULL) {
5755 struct got_reference *ref;
5756 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
5757 goto done;
5758 error = got_ref_open(&ref, repo, argv[0], 0);
5759 if (error != NULL)
5760 goto done;
5761 error = got_ref_resolve(&commit_id, repo, ref);
5762 got_ref_close(ref);
5763 if (error != NULL)
5764 goto done;
5766 error = got_object_id_str(&commit_id_str, commit_id);
5767 if (error)
5768 goto done;
5770 error = got_ref_open(&head_ref, repo,
5771 got_worktree_get_head_ref_name(worktree), 0);
5772 if (error != NULL)
5773 goto done;
5775 error = check_same_branch(commit_id, head_ref, NULL, repo);
5776 if (error) {
5777 if (error->code != GOT_ERR_ANCESTRY)
5778 goto done;
5779 error = NULL;
5780 } else {
5781 error = got_error(GOT_ERR_SAME_BRANCH);
5782 goto done;
5785 error = got_object_open_as_commit(&commit, repo, commit_id);
5786 if (error)
5787 goto done;
5788 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
5789 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
5790 commit_id, repo, update_progress, &did_something, check_cancelled,
5791 NULL);
5792 if (error != NULL)
5793 goto done;
5795 if (did_something)
5796 printf("Merged commit %s\n", commit_id_str);
5797 done:
5798 if (commit)
5799 got_object_commit_close(commit);
5800 free(commit_id_str);
5801 if (head_ref)
5802 got_ref_close(head_ref);
5803 if (worktree)
5804 got_worktree_close(worktree);
5805 if (repo)
5806 got_repo_close(repo);
5807 return error;
5810 __dead static void
5811 usage_backout(void)
5813 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
5814 exit(1);
5817 static const struct got_error *
5818 cmd_backout(int argc, char *argv[])
5820 const struct got_error *error = NULL;
5821 struct got_worktree *worktree = NULL;
5822 struct got_repository *repo = NULL;
5823 char *cwd = NULL, *commit_id_str = NULL;
5824 struct got_object_id *commit_id = NULL;
5825 struct got_commit_object *commit = NULL;
5826 struct got_object_qid *pid;
5827 struct got_reference *head_ref = NULL;
5828 int ch, did_something = 0;
5830 while ((ch = getopt(argc, argv, "")) != -1) {
5831 switch (ch) {
5832 default:
5833 usage_backout();
5834 /* NOTREACHED */
5838 argc -= optind;
5839 argv += optind;
5841 #ifndef PROFILE
5842 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
5843 "unveil", NULL) == -1)
5844 err(1, "pledge");
5845 #endif
5846 if (argc != 1)
5847 usage_backout();
5849 cwd = getcwd(NULL, 0);
5850 if (cwd == NULL) {
5851 error = got_error_from_errno("getcwd");
5852 goto done;
5854 error = got_worktree_open(&worktree, cwd);
5855 if (error)
5856 goto done;
5858 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5859 NULL);
5860 if (error != NULL)
5861 goto done;
5863 error = apply_unveil(got_repo_get_path(repo), 0,
5864 got_worktree_get_root_path(worktree));
5865 if (error)
5866 goto done;
5868 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
5869 GOT_OBJ_TYPE_COMMIT, repo);
5870 if (error != NULL) {
5871 struct got_reference *ref;
5872 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
5873 goto done;
5874 error = got_ref_open(&ref, repo, argv[0], 0);
5875 if (error != NULL)
5876 goto done;
5877 error = got_ref_resolve(&commit_id, repo, ref);
5878 got_ref_close(ref);
5879 if (error != NULL)
5880 goto done;
5882 error = got_object_id_str(&commit_id_str, commit_id);
5883 if (error)
5884 goto done;
5886 error = got_ref_open(&head_ref, repo,
5887 got_worktree_get_head_ref_name(worktree), 0);
5888 if (error != NULL)
5889 goto done;
5891 error = check_same_branch(commit_id, head_ref, NULL, repo);
5892 if (error)
5893 goto done;
5895 error = got_object_open_as_commit(&commit, repo, commit_id);
5896 if (error)
5897 goto done;
5898 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
5899 if (pid == NULL) {
5900 error = got_error(GOT_ERR_ROOT_COMMIT);
5901 goto done;
5904 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
5905 update_progress, &did_something, check_cancelled, NULL);
5906 if (error != NULL)
5907 goto done;
5909 if (did_something)
5910 printf("Backed out commit %s\n", commit_id_str);
5911 done:
5912 if (commit)
5913 got_object_commit_close(commit);
5914 free(commit_id_str);
5915 if (head_ref)
5916 got_ref_close(head_ref);
5917 if (worktree)
5918 got_worktree_close(worktree);
5919 if (repo)
5920 got_repo_close(repo);
5921 return error;
5924 __dead static void
5925 usage_rebase(void)
5927 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
5928 getprogname());
5929 exit(1);
5932 void
5933 trim_logmsg(char *logmsg, int limit)
5935 char *nl;
5936 size_t len;
5938 len = strlen(logmsg);
5939 if (len > limit)
5940 len = limit;
5941 logmsg[len] = '\0';
5942 nl = strchr(logmsg, '\n');
5943 if (nl)
5944 *nl = '\0';
5947 static const struct got_error *
5948 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
5950 const struct got_error *err;
5951 char *logmsg0 = NULL;
5952 const char *s;
5954 err = got_object_commit_get_logmsg(&logmsg0, commit);
5955 if (err)
5956 return err;
5958 s = logmsg0;
5959 while (isspace((unsigned char)s[0]))
5960 s++;
5962 *logmsg = strdup(s);
5963 if (*logmsg == NULL) {
5964 err = got_error_from_errno("strdup");
5965 goto done;
5968 trim_logmsg(*logmsg, limit);
5969 done:
5970 free(logmsg0);
5971 return err;
5974 static const struct got_error *
5975 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
5977 const struct got_error *err;
5978 struct got_commit_object *commit = NULL;
5979 char *id_str = NULL, *logmsg = NULL;
5981 err = got_object_open_as_commit(&commit, repo, id);
5982 if (err)
5983 return err;
5985 err = got_object_id_str(&id_str, id);
5986 if (err)
5987 goto done;
5989 id_str[12] = '\0';
5991 err = get_short_logmsg(&logmsg, 42, commit);
5992 if (err)
5993 goto done;
5995 printf("%s -> merge conflict: %s\n", id_str, logmsg);
5996 done:
5997 free(id_str);
5998 got_object_commit_close(commit);
5999 free(logmsg);
6000 return err;
6003 static const struct got_error *
6004 show_rebase_progress(struct got_commit_object *commit,
6005 struct got_object_id *old_id, struct got_object_id *new_id)
6007 const struct got_error *err;
6008 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6010 err = got_object_id_str(&old_id_str, old_id);
6011 if (err)
6012 goto done;
6014 if (new_id) {
6015 err = got_object_id_str(&new_id_str, new_id);
6016 if (err)
6017 goto done;
6020 old_id_str[12] = '\0';
6021 if (new_id_str)
6022 new_id_str[12] = '\0';
6024 err = get_short_logmsg(&logmsg, 42, commit);
6025 if (err)
6026 goto done;
6028 printf("%s -> %s: %s\n", old_id_str,
6029 new_id_str ? new_id_str : "no-op change", logmsg);
6030 done:
6031 free(old_id_str);
6032 free(new_id_str);
6033 free(logmsg);
6034 return err;
6037 static const struct got_error *
6038 rebase_progress(void *arg, unsigned char status, const char *path)
6040 unsigned char *rebase_status = arg;
6042 while (path[0] == '/')
6043 path++;
6044 printf("%c %s\n", status, path);
6046 if (*rebase_status == GOT_STATUS_CONFLICT)
6047 return NULL;
6048 if (status == GOT_STATUS_CONFLICT || status == GOT_STATUS_MERGE)
6049 *rebase_status = status;
6050 return NULL;
6053 static const struct got_error *
6054 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6055 struct got_reference *branch, struct got_reference *new_base_branch,
6056 struct got_reference *tmp_branch, struct got_repository *repo)
6058 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6059 return got_worktree_rebase_complete(worktree, fileindex,
6060 new_base_branch, tmp_branch, branch, repo);
6063 static const struct got_error *
6064 rebase_commit(struct got_pathlist_head *merged_paths,
6065 struct got_worktree *worktree, struct got_fileindex *fileindex,
6066 struct got_reference *tmp_branch,
6067 struct got_object_id *commit_id, struct got_repository *repo)
6069 const struct got_error *error;
6070 struct got_commit_object *commit;
6071 struct got_object_id *new_commit_id;
6073 error = got_object_open_as_commit(&commit, repo, commit_id);
6074 if (error)
6075 return error;
6077 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6078 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6079 if (error) {
6080 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6081 goto done;
6082 error = show_rebase_progress(commit, commit_id, NULL);
6083 } else {
6084 error = show_rebase_progress(commit, commit_id, new_commit_id);
6085 free(new_commit_id);
6087 done:
6088 got_object_commit_close(commit);
6089 return error;
6092 struct check_path_prefix_arg {
6093 const char *path_prefix;
6094 size_t len;
6095 int errcode;
6098 static const struct got_error *
6099 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6100 struct got_blob_object *blob2, struct got_object_id *id1,
6101 struct got_object_id *id2, const char *path1, const char *path2,
6102 mode_t mode1, mode_t mode2, struct got_repository *repo)
6104 struct check_path_prefix_arg *a = arg;
6106 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6107 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6108 return got_error(a->errcode);
6110 return NULL;
6113 static const struct got_error *
6114 check_path_prefix(struct got_object_id *parent_id,
6115 struct got_object_id *commit_id, const char *path_prefix,
6116 int errcode, struct got_repository *repo)
6118 const struct got_error *err;
6119 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6120 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6121 struct check_path_prefix_arg cpp_arg;
6123 if (got_path_is_root_dir(path_prefix))
6124 return NULL;
6126 err = got_object_open_as_commit(&commit, repo, commit_id);
6127 if (err)
6128 goto done;
6130 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6131 if (err)
6132 goto done;
6134 err = got_object_open_as_tree(&tree1, repo,
6135 got_object_commit_get_tree_id(parent_commit));
6136 if (err)
6137 goto done;
6139 err = got_object_open_as_tree(&tree2, repo,
6140 got_object_commit_get_tree_id(commit));
6141 if (err)
6142 goto done;
6144 cpp_arg.path_prefix = path_prefix;
6145 while (cpp_arg.path_prefix[0] == '/')
6146 cpp_arg.path_prefix++;
6147 cpp_arg.len = strlen(cpp_arg.path_prefix);
6148 cpp_arg.errcode = errcode;
6149 err = got_diff_tree(tree1, tree2, "", "", repo,
6150 check_path_prefix_in_diff, &cpp_arg, 0);
6151 done:
6152 if (tree1)
6153 got_object_tree_close(tree1);
6154 if (tree2)
6155 got_object_tree_close(tree2);
6156 if (commit)
6157 got_object_commit_close(commit);
6158 if (parent_commit)
6159 got_object_commit_close(parent_commit);
6160 return err;
6163 static const struct got_error *
6164 collect_commits(struct got_object_id_queue *commits,
6165 struct got_object_id *initial_commit_id,
6166 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6167 const char *path_prefix, int path_prefix_errcode,
6168 struct got_repository *repo)
6170 const struct got_error *err = NULL;
6171 struct got_commit_graph *graph = NULL;
6172 struct got_object_id *parent_id = NULL;
6173 struct got_object_qid *qid;
6174 struct got_object_id *commit_id = initial_commit_id;
6176 err = got_commit_graph_open(&graph, "/", 1);
6177 if (err)
6178 return err;
6180 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6181 check_cancelled, NULL);
6182 if (err)
6183 goto done;
6184 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6185 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6186 check_cancelled, NULL);
6187 if (err) {
6188 if (err->code == GOT_ERR_ITER_COMPLETED) {
6189 err = got_error_msg(GOT_ERR_ANCESTRY,
6190 "ran out of commits to rebase before "
6191 "youngest common ancestor commit has "
6192 "been reached?!?");
6194 goto done;
6195 } else {
6196 err = check_path_prefix(parent_id, commit_id,
6197 path_prefix, path_prefix_errcode, repo);
6198 if (err)
6199 goto done;
6201 err = got_object_qid_alloc(&qid, commit_id);
6202 if (err)
6203 goto done;
6204 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6205 commit_id = parent_id;
6208 done:
6209 got_commit_graph_close(graph);
6210 return err;
6213 static const struct got_error *
6214 cmd_rebase(int argc, char *argv[])
6216 const struct got_error *error = NULL;
6217 struct got_worktree *worktree = NULL;
6218 struct got_repository *repo = NULL;
6219 struct got_fileindex *fileindex = NULL;
6220 char *cwd = NULL;
6221 struct got_reference *branch = NULL;
6222 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6223 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6224 struct got_object_id *resume_commit_id = NULL;
6225 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6226 struct got_commit_object *commit = NULL;
6227 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6228 int histedit_in_progress = 0;
6229 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6230 struct got_object_id_queue commits;
6231 struct got_pathlist_head merged_paths;
6232 const struct got_object_id_queue *parent_ids;
6233 struct got_object_qid *qid, *pid;
6235 SIMPLEQ_INIT(&commits);
6236 TAILQ_INIT(&merged_paths);
6238 while ((ch = getopt(argc, argv, "ac")) != -1) {
6239 switch (ch) {
6240 case 'a':
6241 abort_rebase = 1;
6242 break;
6243 case 'c':
6244 continue_rebase = 1;
6245 break;
6246 default:
6247 usage_rebase();
6248 /* NOTREACHED */
6252 argc -= optind;
6253 argv += optind;
6255 #ifndef PROFILE
6256 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6257 "unveil", NULL) == -1)
6258 err(1, "pledge");
6259 #endif
6260 if (abort_rebase && continue_rebase)
6261 usage_rebase();
6262 else if (abort_rebase || continue_rebase) {
6263 if (argc != 0)
6264 usage_rebase();
6265 } else if (argc != 1)
6266 usage_rebase();
6268 cwd = getcwd(NULL, 0);
6269 if (cwd == NULL) {
6270 error = got_error_from_errno("getcwd");
6271 goto done;
6273 error = got_worktree_open(&worktree, cwd);
6274 if (error)
6275 goto done;
6277 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6278 NULL);
6279 if (error != NULL)
6280 goto done;
6282 error = apply_unveil(got_repo_get_path(repo), 0,
6283 got_worktree_get_root_path(worktree));
6284 if (error)
6285 goto done;
6287 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6288 worktree);
6289 if (error)
6290 goto done;
6291 if (histedit_in_progress) {
6292 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6293 goto done;
6296 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6297 if (error)
6298 goto done;
6300 if (abort_rebase) {
6301 int did_something;
6302 if (!rebase_in_progress) {
6303 error = got_error(GOT_ERR_NOT_REBASING);
6304 goto done;
6306 error = got_worktree_rebase_continue(&resume_commit_id,
6307 &new_base_branch, &tmp_branch, &branch, &fileindex,
6308 worktree, repo);
6309 if (error)
6310 goto done;
6311 printf("Switching work tree to %s\n",
6312 got_ref_get_symref_target(new_base_branch));
6313 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6314 new_base_branch, update_progress, &did_something);
6315 if (error)
6316 goto done;
6317 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6318 goto done; /* nothing else to do */
6321 if (continue_rebase) {
6322 if (!rebase_in_progress) {
6323 error = got_error(GOT_ERR_NOT_REBASING);
6324 goto done;
6326 error = got_worktree_rebase_continue(&resume_commit_id,
6327 &new_base_branch, &tmp_branch, &branch, &fileindex,
6328 worktree, repo);
6329 if (error)
6330 goto done;
6332 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6333 resume_commit_id, repo);
6334 if (error)
6335 goto done;
6337 yca_id = got_object_id_dup(resume_commit_id);
6338 if (yca_id == NULL) {
6339 error = got_error_from_errno("got_object_id_dup");
6340 goto done;
6342 } else {
6343 error = got_ref_open(&branch, repo, argv[0], 0);
6344 if (error != NULL)
6345 goto done;
6348 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
6349 if (error)
6350 goto done;
6352 if (!continue_rebase) {
6353 struct got_object_id *base_commit_id;
6355 base_commit_id = got_worktree_get_base_commit_id(worktree);
6356 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
6357 base_commit_id, branch_head_commit_id, repo,
6358 check_cancelled, NULL);
6359 if (error)
6360 goto done;
6361 if (yca_id == NULL) {
6362 error = got_error_msg(GOT_ERR_ANCESTRY,
6363 "specified branch shares no common ancestry "
6364 "with work tree's branch");
6365 goto done;
6368 error = check_same_branch(base_commit_id, branch, yca_id, repo);
6369 if (error) {
6370 if (error->code != GOT_ERR_ANCESTRY)
6371 goto done;
6372 error = NULL;
6373 } else {
6374 error = got_error_msg(GOT_ERR_SAME_BRANCH,
6375 "specified branch resolves to a commit which "
6376 "is already contained in work tree's branch");
6377 goto done;
6379 error = got_worktree_rebase_prepare(&new_base_branch,
6380 &tmp_branch, &fileindex, worktree, branch, repo);
6381 if (error)
6382 goto done;
6385 commit_id = branch_head_commit_id;
6386 error = got_object_open_as_commit(&commit, repo, commit_id);
6387 if (error)
6388 goto done;
6390 parent_ids = got_object_commit_get_parent_ids(commit);
6391 pid = SIMPLEQ_FIRST(parent_ids);
6392 if (pid == NULL) {
6393 if (!continue_rebase) {
6394 int did_something;
6395 error = got_worktree_rebase_abort(worktree, fileindex,
6396 repo, new_base_branch, update_progress,
6397 &did_something);
6398 if (error)
6399 goto done;
6400 printf("Rebase of %s aborted\n",
6401 got_ref_get_name(branch));
6403 error = got_error(GOT_ERR_EMPTY_REBASE);
6404 goto done;
6406 error = collect_commits(&commits, commit_id, pid->id,
6407 yca_id, got_worktree_get_path_prefix(worktree),
6408 GOT_ERR_REBASE_PATH, repo);
6409 got_object_commit_close(commit);
6410 commit = NULL;
6411 if (error)
6412 goto done;
6414 if (SIMPLEQ_EMPTY(&commits)) {
6415 if (continue_rebase) {
6416 error = rebase_complete(worktree, fileindex,
6417 branch, new_base_branch, tmp_branch, repo);
6418 goto done;
6419 } else {
6420 /* Fast-forward the reference of the branch. */
6421 struct got_object_id *new_head_commit_id;
6422 char *id_str;
6423 error = got_ref_resolve(&new_head_commit_id, repo,
6424 new_base_branch);
6425 if (error)
6426 goto done;
6427 error = got_object_id_str(&id_str, new_head_commit_id);
6428 printf("Forwarding %s to commit %s\n",
6429 got_ref_get_name(branch), id_str);
6430 free(id_str);
6431 error = got_ref_change_ref(branch,
6432 new_head_commit_id);
6433 if (error)
6434 goto done;
6438 pid = NULL;
6439 SIMPLEQ_FOREACH(qid, &commits, entry) {
6440 commit_id = qid->id;
6441 parent_id = pid ? pid->id : yca_id;
6442 pid = qid;
6444 error = got_worktree_rebase_merge_files(&merged_paths,
6445 worktree, fileindex, parent_id, commit_id, repo,
6446 rebase_progress, &rebase_status, check_cancelled, NULL);
6447 if (error)
6448 goto done;
6450 if (rebase_status == GOT_STATUS_CONFLICT) {
6451 error = show_rebase_merge_conflict(qid->id, repo);
6452 if (error)
6453 goto done;
6454 got_worktree_rebase_pathlist_free(&merged_paths);
6455 break;
6458 error = rebase_commit(&merged_paths, worktree, fileindex,
6459 tmp_branch, commit_id, repo);
6460 got_worktree_rebase_pathlist_free(&merged_paths);
6461 if (error)
6462 goto done;
6465 if (rebase_status == GOT_STATUS_CONFLICT) {
6466 error = got_worktree_rebase_postpone(worktree, fileindex);
6467 if (error)
6468 goto done;
6469 error = got_error_msg(GOT_ERR_CONFLICTS,
6470 "conflicts must be resolved before rebasing can continue");
6471 } else
6472 error = rebase_complete(worktree, fileindex, branch,
6473 new_base_branch, tmp_branch, repo);
6474 done:
6475 got_object_id_queue_free(&commits);
6476 free(branch_head_commit_id);
6477 free(resume_commit_id);
6478 free(yca_id);
6479 if (commit)
6480 got_object_commit_close(commit);
6481 if (branch)
6482 got_ref_close(branch);
6483 if (new_base_branch)
6484 got_ref_close(new_base_branch);
6485 if (tmp_branch)
6486 got_ref_close(tmp_branch);
6487 if (worktree)
6488 got_worktree_close(worktree);
6489 if (repo)
6490 got_repo_close(repo);
6491 return error;
6494 __dead static void
6495 usage_histedit(void)
6497 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
6498 getprogname());
6499 exit(1);
6502 #define GOT_HISTEDIT_PICK 'p'
6503 #define GOT_HISTEDIT_EDIT 'e'
6504 #define GOT_HISTEDIT_FOLD 'f'
6505 #define GOT_HISTEDIT_DROP 'd'
6506 #define GOT_HISTEDIT_MESG 'm'
6508 static struct got_histedit_cmd {
6509 unsigned char code;
6510 const char *name;
6511 const char *desc;
6512 } got_histedit_cmds[] = {
6513 { GOT_HISTEDIT_PICK, "pick", "use commit" },
6514 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
6515 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
6516 "be used" },
6517 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
6518 { GOT_HISTEDIT_MESG, "mesg",
6519 "single-line log message for commit above (open editor if empty)" },
6522 struct got_histedit_list_entry {
6523 TAILQ_ENTRY(got_histedit_list_entry) entry;
6524 struct got_object_id *commit_id;
6525 const struct got_histedit_cmd *cmd;
6526 char *logmsg;
6528 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
6530 static const struct got_error *
6531 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
6532 FILE *f, struct got_repository *repo)
6534 const struct got_error *err = NULL;
6535 char *logmsg = NULL, *id_str = NULL;
6536 struct got_commit_object *commit = NULL;
6537 int n;
6539 err = got_object_open_as_commit(&commit, repo, commit_id);
6540 if (err)
6541 goto done;
6543 err = get_short_logmsg(&logmsg, 34, commit);
6544 if (err)
6545 goto done;
6547 err = got_object_id_str(&id_str, commit_id);
6548 if (err)
6549 goto done;
6551 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
6552 if (n < 0)
6553 err = got_ferror(f, GOT_ERR_IO);
6554 done:
6555 if (commit)
6556 got_object_commit_close(commit);
6557 free(id_str);
6558 free(logmsg);
6559 return err;
6562 static const struct got_error *
6563 histedit_write_commit_list(struct got_object_id_queue *commits,
6564 FILE *f, int edit_logmsg_only, struct got_repository *repo)
6566 const struct got_error *err = NULL;
6567 struct got_object_qid *qid;
6569 if (SIMPLEQ_EMPTY(commits))
6570 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6572 SIMPLEQ_FOREACH(qid, commits, entry) {
6573 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
6574 f, repo);
6575 if (err)
6576 break;
6577 if (edit_logmsg_only) {
6578 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
6579 if (n < 0) {
6580 err = got_ferror(f, GOT_ERR_IO);
6581 break;
6586 return err;
6589 static const struct got_error *
6590 write_cmd_list(FILE *f, const char *branch_name,
6591 struct got_object_id_queue *commits)
6593 const struct got_error *err = NULL;
6594 int n, i;
6595 char *id_str;
6596 struct got_object_qid *qid;
6598 qid = SIMPLEQ_FIRST(commits);
6599 err = got_object_id_str(&id_str, qid->id);
6600 if (err)
6601 return err;
6603 n = fprintf(f,
6604 "# Editing the history of branch '%s' starting at\n"
6605 "# commit %s\n"
6606 "# Commits will be processed in order from top to "
6607 "bottom of this file.\n", branch_name, id_str);
6608 if (n < 0) {
6609 err = got_ferror(f, GOT_ERR_IO);
6610 goto done;
6613 n = fprintf(f, "# Available histedit commands:\n");
6614 if (n < 0) {
6615 err = got_ferror(f, GOT_ERR_IO);
6616 goto done;
6619 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6620 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
6621 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
6622 cmd->desc);
6623 if (n < 0) {
6624 err = got_ferror(f, GOT_ERR_IO);
6625 break;
6628 done:
6629 free(id_str);
6630 return err;
6633 static const struct got_error *
6634 histedit_syntax_error(int lineno)
6636 static char msg[42];
6637 int ret;
6639 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
6640 lineno);
6641 if (ret == -1 || ret >= sizeof(msg))
6642 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
6644 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
6647 static const struct got_error *
6648 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
6649 char *logmsg, struct got_repository *repo)
6651 const struct got_error *err;
6652 struct got_commit_object *folded_commit = NULL;
6653 char *id_str, *folded_logmsg = NULL;
6655 err = got_object_id_str(&id_str, hle->commit_id);
6656 if (err)
6657 return err;
6659 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
6660 if (err)
6661 goto done;
6663 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
6664 if (err)
6665 goto done;
6666 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
6667 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
6668 folded_logmsg) == -1) {
6669 err = got_error_from_errno("asprintf");
6671 done:
6672 if (folded_commit)
6673 got_object_commit_close(folded_commit);
6674 free(id_str);
6675 free(folded_logmsg);
6676 return err;
6679 static struct got_histedit_list_entry *
6680 get_folded_commits(struct got_histedit_list_entry *hle)
6682 struct got_histedit_list_entry *prev, *folded = NULL;
6684 prev = TAILQ_PREV(hle, got_histedit_list, entry);
6685 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
6686 prev->cmd->code == GOT_HISTEDIT_DROP)) {
6687 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
6688 folded = prev;
6689 prev = TAILQ_PREV(prev, got_histedit_list, entry);
6692 return folded;
6695 static const struct got_error *
6696 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
6697 struct got_repository *repo)
6699 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
6700 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
6701 const struct got_error *err = NULL;
6702 struct got_commit_object *commit = NULL;
6703 int fd;
6704 struct got_histedit_list_entry *folded = NULL;
6706 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
6707 if (err)
6708 return err;
6710 folded = get_folded_commits(hle);
6711 if (folded) {
6712 while (folded != hle) {
6713 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
6714 folded = TAILQ_NEXT(folded, entry);
6715 continue;
6717 err = append_folded_commit_msg(&new_msg, folded,
6718 logmsg, repo);
6719 if (err)
6720 goto done;
6721 free(logmsg);
6722 logmsg = new_msg;
6723 folded = TAILQ_NEXT(folded, entry);
6727 err = got_object_id_str(&id_str, hle->commit_id);
6728 if (err)
6729 goto done;
6730 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
6731 if (err)
6732 goto done;
6733 if (asprintf(&new_msg,
6734 "%s\n# original log message of commit %s: %s",
6735 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
6736 err = got_error_from_errno("asprintf");
6737 goto done;
6739 free(logmsg);
6740 logmsg = new_msg;
6742 err = got_object_id_str(&id_str, hle->commit_id);
6743 if (err)
6744 goto done;
6746 err = got_opentemp_named_fd(&logmsg_path, &fd,
6747 GOT_TMPDIR_STR "/got-logmsg");
6748 if (err)
6749 goto done;
6751 dprintf(fd, logmsg);
6752 close(fd);
6754 err = get_editor(&editor);
6755 if (err)
6756 goto done;
6758 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
6759 if (err) {
6760 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
6761 goto done;
6762 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
6764 done:
6765 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
6766 err = got_error_from_errno2("unlink", logmsg_path);
6767 free(logmsg_path);
6768 free(logmsg);
6769 free(orig_logmsg);
6770 free(editor);
6771 if (commit)
6772 got_object_commit_close(commit);
6773 return err;
6776 static const struct got_error *
6777 histedit_parse_list(struct got_histedit_list *histedit_cmds,
6778 FILE *f, struct got_repository *repo)
6780 const struct got_error *err = NULL;
6781 char *line = NULL, *p, *end;
6782 size_t size;
6783 ssize_t len;
6784 int lineno = 0, i;
6785 const struct got_histedit_cmd *cmd;
6786 struct got_object_id *commit_id = NULL;
6787 struct got_histedit_list_entry *hle = NULL;
6789 for (;;) {
6790 len = getline(&line, &size, f);
6791 if (len == -1) {
6792 const struct got_error *getline_err;
6793 if (feof(f))
6794 break;
6795 getline_err = got_error_from_errno("getline");
6796 err = got_ferror(f, getline_err->code);
6797 break;
6799 lineno++;
6800 p = line;
6801 while (isspace((unsigned char)p[0]))
6802 p++;
6803 if (p[0] == '#' || p[0] == '\0') {
6804 free(line);
6805 line = NULL;
6806 continue;
6808 cmd = NULL;
6809 for (i = 0; i < nitems(got_histedit_cmds); i++) {
6810 cmd = &got_histedit_cmds[i];
6811 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
6812 isspace((unsigned char)p[strlen(cmd->name)])) {
6813 p += strlen(cmd->name);
6814 break;
6816 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
6817 p++;
6818 break;
6821 if (i == nitems(got_histedit_cmds)) {
6822 err = histedit_syntax_error(lineno);
6823 break;
6825 while (isspace((unsigned char)p[0]))
6826 p++;
6827 if (cmd->code == GOT_HISTEDIT_MESG) {
6828 if (hle == NULL || hle->logmsg != NULL) {
6829 err = got_error(GOT_ERR_HISTEDIT_CMD);
6830 break;
6832 if (p[0] == '\0') {
6833 err = histedit_edit_logmsg(hle, repo);
6834 if (err)
6835 break;
6836 } else {
6837 hle->logmsg = strdup(p);
6838 if (hle->logmsg == NULL) {
6839 err = got_error_from_errno("strdup");
6840 break;
6843 free(line);
6844 line = NULL;
6845 continue;
6846 } else {
6847 end = p;
6848 while (end[0] && !isspace((unsigned char)end[0]))
6849 end++;
6850 *end = '\0';
6852 err = got_object_resolve_id_str(&commit_id, repo, p);
6853 if (err) {
6854 /* override error code */
6855 err = histedit_syntax_error(lineno);
6856 break;
6859 hle = malloc(sizeof(*hle));
6860 if (hle == NULL) {
6861 err = got_error_from_errno("malloc");
6862 break;
6864 hle->cmd = cmd;
6865 hle->commit_id = commit_id;
6866 hle->logmsg = NULL;
6867 commit_id = NULL;
6868 free(line);
6869 line = NULL;
6870 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
6873 free(line);
6874 free(commit_id);
6875 return err;
6878 static const struct got_error *
6879 histedit_check_script(struct got_histedit_list *histedit_cmds,
6880 struct got_object_id_queue *commits, struct got_repository *repo)
6882 const struct got_error *err = NULL;
6883 struct got_object_qid *qid;
6884 struct got_histedit_list_entry *hle;
6885 static char msg[92];
6886 char *id_str;
6888 if (TAILQ_EMPTY(histedit_cmds))
6889 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
6890 "histedit script contains no commands");
6891 if (SIMPLEQ_EMPTY(commits))
6892 return got_error(GOT_ERR_EMPTY_HISTEDIT);
6894 TAILQ_FOREACH(hle, histedit_cmds, entry) {
6895 struct got_histedit_list_entry *hle2;
6896 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
6897 if (hle == hle2)
6898 continue;
6899 if (got_object_id_cmp(hle->commit_id,
6900 hle2->commit_id) != 0)
6901 continue;
6902 err = got_object_id_str(&id_str, hle->commit_id);
6903 if (err)
6904 return err;
6905 snprintf(msg, sizeof(msg), "commit %s is listed "
6906 "more than once in histedit script", id_str);
6907 free(id_str);
6908 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
6912 SIMPLEQ_FOREACH(qid, commits, entry) {
6913 TAILQ_FOREACH(hle, histedit_cmds, entry) {
6914 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
6915 break;
6917 if (hle == NULL) {
6918 err = got_object_id_str(&id_str, qid->id);
6919 if (err)
6920 return err;
6921 snprintf(msg, sizeof(msg),
6922 "commit %s missing from histedit script", id_str);
6923 free(id_str);
6924 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
6928 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
6929 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
6930 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
6931 "last commit in histedit script cannot be folded");
6933 return NULL;
6936 static const struct got_error *
6937 histedit_run_editor(struct got_histedit_list *histedit_cmds,
6938 const char *path, struct got_object_id_queue *commits,
6939 struct got_repository *repo)
6941 const struct got_error *err = NULL;
6942 char *editor;
6943 FILE *f = NULL;
6945 err = get_editor(&editor);
6946 if (err)
6947 return err;
6949 if (spawn_editor(editor, path) == -1) {
6950 err = got_error_from_errno("failed spawning editor");
6951 goto done;
6954 f = fopen(path, "r");
6955 if (f == NULL) {
6956 err = got_error_from_errno("fopen");
6957 goto done;
6959 err = histedit_parse_list(histedit_cmds, f, repo);
6960 if (err)
6961 goto done;
6963 err = histedit_check_script(histedit_cmds, commits, repo);
6964 done:
6965 if (f && fclose(f) != 0 && err == NULL)
6966 err = got_error_from_errno("fclose");
6967 free(editor);
6968 return err;
6971 static const struct got_error *
6972 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
6973 struct got_object_id_queue *, const char *, const char *,
6974 struct got_repository *);
6976 static const struct got_error *
6977 histedit_edit_script(struct got_histedit_list *histedit_cmds,
6978 struct got_object_id_queue *commits, const char *branch_name,
6979 int edit_logmsg_only, struct got_repository *repo)
6981 const struct got_error *err;
6982 FILE *f = NULL;
6983 char *path = NULL;
6985 err = got_opentemp_named(&path, &f, "got-histedit");
6986 if (err)
6987 return err;
6989 err = write_cmd_list(f, branch_name, commits);
6990 if (err)
6991 goto done;
6993 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
6994 if (err)
6995 goto done;
6997 if (edit_logmsg_only) {
6998 rewind(f);
6999 err = histedit_parse_list(histedit_cmds, f, repo);
7000 } else {
7001 if (fclose(f) != 0) {
7002 err = got_error_from_errno("fclose");
7003 goto done;
7005 f = NULL;
7006 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7007 if (err) {
7008 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7009 err->code != GOT_ERR_HISTEDIT_CMD)
7010 goto done;
7011 err = histedit_edit_list_retry(histedit_cmds, err,
7012 commits, path, branch_name, repo);
7015 done:
7016 if (f && fclose(f) != 0 && err == NULL)
7017 err = got_error_from_errno("fclose");
7018 if (path && unlink(path) != 0 && err == NULL)
7019 err = got_error_from_errno2("unlink", path);
7020 free(path);
7021 return err;
7024 static const struct got_error *
7025 histedit_save_list(struct got_histedit_list *histedit_cmds,
7026 struct got_worktree *worktree, struct got_repository *repo)
7028 const struct got_error *err = NULL;
7029 char *path = NULL;
7030 FILE *f = NULL;
7031 struct got_histedit_list_entry *hle;
7032 struct got_commit_object *commit = NULL;
7034 err = got_worktree_get_histedit_script_path(&path, worktree);
7035 if (err)
7036 return err;
7038 f = fopen(path, "w");
7039 if (f == NULL) {
7040 err = got_error_from_errno2("fopen", path);
7041 goto done;
7043 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7044 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7045 repo);
7046 if (err)
7047 break;
7049 if (hle->logmsg) {
7050 int n = fprintf(f, "%c %s\n",
7051 GOT_HISTEDIT_MESG, hle->logmsg);
7052 if (n < 0) {
7053 err = got_ferror(f, GOT_ERR_IO);
7054 break;
7058 done:
7059 if (f && fclose(f) != 0 && err == NULL)
7060 err = got_error_from_errno("fclose");
7061 free(path);
7062 if (commit)
7063 got_object_commit_close(commit);
7064 return err;
7067 void
7068 histedit_free_list(struct got_histedit_list *histedit_cmds)
7070 struct got_histedit_list_entry *hle;
7072 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7073 TAILQ_REMOVE(histedit_cmds, hle, entry);
7074 free(hle);
7078 static const struct got_error *
7079 histedit_load_list(struct got_histedit_list *histedit_cmds,
7080 const char *path, struct got_repository *repo)
7082 const struct got_error *err = NULL;
7083 FILE *f = NULL;
7085 f = fopen(path, "r");
7086 if (f == NULL) {
7087 err = got_error_from_errno2("fopen", path);
7088 goto done;
7091 err = histedit_parse_list(histedit_cmds, f, repo);
7092 done:
7093 if (f && fclose(f) != 0 && err == NULL)
7094 err = got_error_from_errno("fclose");
7095 return err;
7098 static const struct got_error *
7099 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7100 const struct got_error *edit_err, struct got_object_id_queue *commits,
7101 const char *path, const char *branch_name, struct got_repository *repo)
7103 const struct got_error *err = NULL, *prev_err = edit_err;
7104 int resp = ' ';
7106 while (resp != 'c' && resp != 'r' && resp != 'a') {
7107 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7108 "or (a)bort: ", getprogname(), prev_err->msg);
7109 resp = getchar();
7110 if (resp == '\n')
7111 resp = getchar();
7112 if (resp == 'c') {
7113 histedit_free_list(histedit_cmds);
7114 err = histedit_run_editor(histedit_cmds, path, commits,
7115 repo);
7116 if (err) {
7117 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7118 err->code != GOT_ERR_HISTEDIT_CMD)
7119 break;
7120 prev_err = err;
7121 resp = ' ';
7122 continue;
7124 break;
7125 } else if (resp == 'r') {
7126 histedit_free_list(histedit_cmds);
7127 err = histedit_edit_script(histedit_cmds,
7128 commits, branch_name, 0, repo);
7129 if (err) {
7130 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7131 err->code != GOT_ERR_HISTEDIT_CMD)
7132 break;
7133 prev_err = err;
7134 resp = ' ';
7135 continue;
7137 break;
7138 } else if (resp == 'a') {
7139 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7140 break;
7141 } else
7142 printf("invalid response '%c'\n", resp);
7145 return err;
7148 static const struct got_error *
7149 histedit_complete(struct got_worktree *worktree,
7150 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7151 struct got_reference *branch, struct got_repository *repo)
7153 printf("Switching work tree to %s\n",
7154 got_ref_get_symref_target(branch));
7155 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7156 branch, repo);
7159 static const struct got_error *
7160 show_histedit_progress(struct got_commit_object *commit,
7161 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7163 const struct got_error *err;
7164 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7166 err = got_object_id_str(&old_id_str, hle->commit_id);
7167 if (err)
7168 goto done;
7170 if (new_id) {
7171 err = got_object_id_str(&new_id_str, new_id);
7172 if (err)
7173 goto done;
7176 old_id_str[12] = '\0';
7177 if (new_id_str)
7178 new_id_str[12] = '\0';
7180 if (hle->logmsg) {
7181 logmsg = strdup(hle->logmsg);
7182 if (logmsg == NULL) {
7183 err = got_error_from_errno("strdup");
7184 goto done;
7186 trim_logmsg(logmsg, 42);
7187 } else {
7188 err = get_short_logmsg(&logmsg, 42, commit);
7189 if (err)
7190 goto done;
7193 switch (hle->cmd->code) {
7194 case GOT_HISTEDIT_PICK:
7195 case GOT_HISTEDIT_EDIT:
7196 printf("%s -> %s: %s\n", old_id_str,
7197 new_id_str ? new_id_str : "no-op change", logmsg);
7198 break;
7199 case GOT_HISTEDIT_DROP:
7200 case GOT_HISTEDIT_FOLD:
7201 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7202 logmsg);
7203 break;
7204 default:
7205 break;
7207 done:
7208 free(old_id_str);
7209 free(new_id_str);
7210 return err;
7213 static const struct got_error *
7214 histedit_commit(struct got_pathlist_head *merged_paths,
7215 struct got_worktree *worktree, struct got_fileindex *fileindex,
7216 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7217 struct got_repository *repo)
7219 const struct got_error *err;
7220 struct got_commit_object *commit;
7221 struct got_object_id *new_commit_id;
7223 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7224 && hle->logmsg == NULL) {
7225 err = histedit_edit_logmsg(hle, repo);
7226 if (err)
7227 return err;
7230 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7231 if (err)
7232 return err;
7234 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7235 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7236 hle->logmsg, repo);
7237 if (err) {
7238 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7239 goto done;
7240 err = show_histedit_progress(commit, hle, NULL);
7241 } else {
7242 err = show_histedit_progress(commit, hle, new_commit_id);
7243 free(new_commit_id);
7245 done:
7246 got_object_commit_close(commit);
7247 return err;
7250 static const struct got_error *
7251 histedit_skip_commit(struct got_histedit_list_entry *hle,
7252 struct got_worktree *worktree, struct got_repository *repo)
7254 const struct got_error *error;
7255 struct got_commit_object *commit;
7257 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7258 repo);
7259 if (error)
7260 return error;
7262 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7263 if (error)
7264 return error;
7266 error = show_histedit_progress(commit, hle, NULL);
7267 got_object_commit_close(commit);
7268 return error;
7271 static const struct got_error *
7272 check_local_changes(void *arg, unsigned char status,
7273 unsigned char staged_status, const char *path,
7274 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7275 struct got_object_id *commit_id, int dirfd, const char *de_name)
7277 int *have_local_changes = arg;
7279 switch (status) {
7280 case GOT_STATUS_ADD:
7281 case GOT_STATUS_DELETE:
7282 case GOT_STATUS_MODIFY:
7283 case GOT_STATUS_CONFLICT:
7284 *have_local_changes = 1;
7285 return got_error(GOT_ERR_CANCELLED);
7286 default:
7287 break;
7290 switch (staged_status) {
7291 case GOT_STATUS_ADD:
7292 case GOT_STATUS_DELETE:
7293 case GOT_STATUS_MODIFY:
7294 *have_local_changes = 1;
7295 return got_error(GOT_ERR_CANCELLED);
7296 default:
7297 break;
7300 return NULL;
7303 static const struct got_error *
7304 cmd_histedit(int argc, char *argv[])
7306 const struct got_error *error = NULL;
7307 struct got_worktree *worktree = NULL;
7308 struct got_fileindex *fileindex = NULL;
7309 struct got_repository *repo = NULL;
7310 char *cwd = NULL;
7311 struct got_reference *branch = NULL;
7312 struct got_reference *tmp_branch = NULL;
7313 struct got_object_id *resume_commit_id = NULL;
7314 struct got_object_id *base_commit_id = NULL;
7315 struct got_object_id *head_commit_id = NULL;
7316 struct got_commit_object *commit = NULL;
7317 int ch, rebase_in_progress = 0, did_something;
7318 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7319 int edit_logmsg_only = 0;
7320 const char *edit_script_path = NULL;
7321 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7322 struct got_object_id_queue commits;
7323 struct got_pathlist_head merged_paths;
7324 const struct got_object_id_queue *parent_ids;
7325 struct got_object_qid *pid;
7326 struct got_histedit_list histedit_cmds;
7327 struct got_histedit_list_entry *hle;
7329 SIMPLEQ_INIT(&commits);
7330 TAILQ_INIT(&histedit_cmds);
7331 TAILQ_INIT(&merged_paths);
7333 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7334 switch (ch) {
7335 case 'a':
7336 abort_edit = 1;
7337 break;
7338 case 'c':
7339 continue_edit = 1;
7340 break;
7341 case 'F':
7342 edit_script_path = optarg;
7343 break;
7344 case 'm':
7345 edit_logmsg_only = 1;
7346 break;
7347 default:
7348 usage_histedit();
7349 /* NOTREACHED */
7353 argc -= optind;
7354 argv += optind;
7356 #ifndef PROFILE
7357 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7358 "unveil", NULL) == -1)
7359 err(1, "pledge");
7360 #endif
7361 if (abort_edit && continue_edit)
7362 errx(1, "histedit's -a and -c options are mutually exclusive");
7363 if (edit_script_path && edit_logmsg_only)
7364 errx(1, "histedit's -F and -m options are mutually exclusive");
7365 if (abort_edit && edit_logmsg_only)
7366 errx(1, "histedit's -a and -m options are mutually exclusive");
7367 if (continue_edit && edit_logmsg_only)
7368 errx(1, "histedit's -c and -m options are mutually exclusive");
7369 if (argc != 0)
7370 usage_histedit();
7373 * This command cannot apply unveil(2) in all cases because the
7374 * user may choose to run an editor to edit the histedit script
7375 * and to edit individual commit log messages.
7376 * unveil(2) traverses exec(2); if an editor is used we have to
7377 * apply unveil after edit script and log messages have been written.
7378 * XXX TODO: Make use of unveil(2) where possible.
7381 cwd = getcwd(NULL, 0);
7382 if (cwd == NULL) {
7383 error = got_error_from_errno("getcwd");
7384 goto done;
7386 error = got_worktree_open(&worktree, cwd);
7387 if (error)
7388 goto done;
7390 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7391 NULL);
7392 if (error != NULL)
7393 goto done;
7395 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7396 if (error)
7397 goto done;
7398 if (rebase_in_progress) {
7399 error = got_error(GOT_ERR_REBASING);
7400 goto done;
7403 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
7404 if (error)
7405 goto done;
7407 if (edit_in_progress && edit_logmsg_only) {
7408 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
7409 "histedit operation is in progress in this "
7410 "work tree and must be continued or aborted "
7411 "before the -m option can be used");
7412 goto done;
7415 if (edit_in_progress && abort_edit) {
7416 error = got_worktree_histedit_continue(&resume_commit_id,
7417 &tmp_branch, &branch, &base_commit_id, &fileindex,
7418 worktree, repo);
7419 if (error)
7420 goto done;
7421 printf("Switching work tree to %s\n",
7422 got_ref_get_symref_target(branch));
7423 error = got_worktree_histedit_abort(worktree, fileindex, repo,
7424 branch, base_commit_id, update_progress, &did_something);
7425 if (error)
7426 goto done;
7427 printf("Histedit of %s aborted\n",
7428 got_ref_get_symref_target(branch));
7429 goto done; /* nothing else to do */
7430 } else if (abort_edit) {
7431 error = got_error(GOT_ERR_NOT_HISTEDIT);
7432 goto done;
7435 if (continue_edit) {
7436 char *path;
7438 if (!edit_in_progress) {
7439 error = got_error(GOT_ERR_NOT_HISTEDIT);
7440 goto done;
7443 error = got_worktree_get_histedit_script_path(&path, worktree);
7444 if (error)
7445 goto done;
7447 error = histedit_load_list(&histedit_cmds, path, repo);
7448 free(path);
7449 if (error)
7450 goto done;
7452 error = got_worktree_histedit_continue(&resume_commit_id,
7453 &tmp_branch, &branch, &base_commit_id, &fileindex,
7454 worktree, repo);
7455 if (error)
7456 goto done;
7458 error = got_ref_resolve(&head_commit_id, repo, branch);
7459 if (error)
7460 goto done;
7462 error = got_object_open_as_commit(&commit, repo,
7463 head_commit_id);
7464 if (error)
7465 goto done;
7466 parent_ids = got_object_commit_get_parent_ids(commit);
7467 pid = SIMPLEQ_FIRST(parent_ids);
7468 if (pid == NULL) {
7469 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7470 goto done;
7472 error = collect_commits(&commits, head_commit_id, pid->id,
7473 base_commit_id, got_worktree_get_path_prefix(worktree),
7474 GOT_ERR_HISTEDIT_PATH, repo);
7475 got_object_commit_close(commit);
7476 commit = NULL;
7477 if (error)
7478 goto done;
7479 } else {
7480 if (edit_in_progress) {
7481 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7482 goto done;
7485 error = got_ref_open(&branch, repo,
7486 got_worktree_get_head_ref_name(worktree), 0);
7487 if (error != NULL)
7488 goto done;
7490 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
7491 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
7492 "will not edit commit history of a branch outside "
7493 "the \"refs/heads/\" reference namespace");
7494 goto done;
7497 error = got_ref_resolve(&head_commit_id, repo, branch);
7498 got_ref_close(branch);
7499 branch = NULL;
7500 if (error)
7501 goto done;
7503 error = got_object_open_as_commit(&commit, repo,
7504 head_commit_id);
7505 if (error)
7506 goto done;
7507 parent_ids = got_object_commit_get_parent_ids(commit);
7508 pid = SIMPLEQ_FIRST(parent_ids);
7509 if (pid == NULL) {
7510 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7511 goto done;
7513 error = collect_commits(&commits, head_commit_id, pid->id,
7514 got_worktree_get_base_commit_id(worktree),
7515 got_worktree_get_path_prefix(worktree),
7516 GOT_ERR_HISTEDIT_PATH, repo);
7517 got_object_commit_close(commit);
7518 commit = NULL;
7519 if (error)
7520 goto done;
7522 if (SIMPLEQ_EMPTY(&commits)) {
7523 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
7524 goto done;
7527 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
7528 &base_commit_id, &fileindex, worktree, repo);
7529 if (error)
7530 goto done;
7532 if (edit_script_path) {
7533 error = histedit_load_list(&histedit_cmds,
7534 edit_script_path, repo);
7535 if (error) {
7536 got_worktree_histedit_abort(worktree, fileindex,
7537 repo, branch, base_commit_id,
7538 update_progress, &did_something);
7539 goto done;
7541 } else {
7542 const char *branch_name;
7543 branch_name = got_ref_get_symref_target(branch);
7544 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7545 branch_name += 11;
7546 error = histedit_edit_script(&histedit_cmds, &commits,
7547 branch_name, edit_logmsg_only, repo);
7548 if (error) {
7549 got_worktree_histedit_abort(worktree, fileindex,
7550 repo, branch, base_commit_id,
7551 update_progress, &did_something);
7552 goto done;
7557 error = histedit_save_list(&histedit_cmds, worktree,
7558 repo);
7559 if (error) {
7560 got_worktree_histedit_abort(worktree, fileindex,
7561 repo, branch, base_commit_id,
7562 update_progress, &did_something);
7563 goto done;
7568 error = histedit_check_script(&histedit_cmds, &commits, repo);
7569 if (error)
7570 goto done;
7572 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
7573 if (resume_commit_id) {
7574 if (got_object_id_cmp(hle->commit_id,
7575 resume_commit_id) != 0)
7576 continue;
7578 resume_commit_id = NULL;
7579 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
7580 hle->cmd->code == GOT_HISTEDIT_FOLD) {
7581 error = histedit_skip_commit(hle, worktree,
7582 repo);
7583 if (error)
7584 goto done;
7585 } else {
7586 struct got_pathlist_head paths;
7587 int have_changes = 0;
7589 TAILQ_INIT(&paths);
7590 error = got_pathlist_append(&paths, "", NULL);
7591 if (error)
7592 goto done;
7593 error = got_worktree_status(worktree, &paths,
7594 repo, check_local_changes, &have_changes,
7595 check_cancelled, NULL);
7596 got_pathlist_free(&paths);
7597 if (error) {
7598 if (error->code != GOT_ERR_CANCELLED)
7599 goto done;
7600 if (sigint_received || sigpipe_received)
7601 goto done;
7603 if (have_changes) {
7604 error = histedit_commit(NULL, worktree,
7605 fileindex, tmp_branch, hle, repo);
7606 if (error)
7607 goto done;
7608 } else {
7609 error = got_object_open_as_commit(
7610 &commit, repo, hle->commit_id);
7611 if (error)
7612 goto done;
7613 error = show_histedit_progress(commit,
7614 hle, NULL);
7615 got_object_commit_close(commit);
7616 commit = NULL;
7617 if (error)
7618 goto done;
7621 continue;
7624 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
7625 error = histedit_skip_commit(hle, worktree, repo);
7626 if (error)
7627 goto done;
7628 continue;
7631 error = got_object_open_as_commit(&commit, repo,
7632 hle->commit_id);
7633 if (error)
7634 goto done;
7635 parent_ids = got_object_commit_get_parent_ids(commit);
7636 pid = SIMPLEQ_FIRST(parent_ids);
7638 error = got_worktree_histedit_merge_files(&merged_paths,
7639 worktree, fileindex, pid->id, hle->commit_id, repo,
7640 rebase_progress, &rebase_status, check_cancelled, NULL);
7641 if (error)
7642 goto done;
7643 got_object_commit_close(commit);
7644 commit = NULL;
7646 if (rebase_status == GOT_STATUS_CONFLICT) {
7647 error = show_rebase_merge_conflict(hle->commit_id,
7648 repo);
7649 if (error)
7650 goto done;
7651 got_worktree_rebase_pathlist_free(&merged_paths);
7652 break;
7655 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
7656 char *id_str;
7657 error = got_object_id_str(&id_str, hle->commit_id);
7658 if (error)
7659 goto done;
7660 printf("Stopping histedit for amending commit %s\n",
7661 id_str);
7662 free(id_str);
7663 got_worktree_rebase_pathlist_free(&merged_paths);
7664 error = got_worktree_histedit_postpone(worktree,
7665 fileindex);
7666 goto done;
7669 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
7670 error = histedit_skip_commit(hle, worktree, repo);
7671 if (error)
7672 goto done;
7673 continue;
7676 error = histedit_commit(&merged_paths, worktree, fileindex,
7677 tmp_branch, hle, repo);
7678 got_worktree_rebase_pathlist_free(&merged_paths);
7679 if (error)
7680 goto done;
7683 if (rebase_status == GOT_STATUS_CONFLICT) {
7684 error = got_worktree_histedit_postpone(worktree, fileindex);
7685 if (error)
7686 goto done;
7687 error = got_error_msg(GOT_ERR_CONFLICTS,
7688 "conflicts must be resolved before histedit can continue");
7689 } else
7690 error = histedit_complete(worktree, fileindex, tmp_branch,
7691 branch, repo);
7692 done:
7693 got_object_id_queue_free(&commits);
7694 histedit_free_list(&histedit_cmds);
7695 free(head_commit_id);
7696 free(base_commit_id);
7697 free(resume_commit_id);
7698 if (commit)
7699 got_object_commit_close(commit);
7700 if (branch)
7701 got_ref_close(branch);
7702 if (tmp_branch)
7703 got_ref_close(tmp_branch);
7704 if (worktree)
7705 got_worktree_close(worktree);
7706 if (repo)
7707 got_repo_close(repo);
7708 return error;
7711 __dead static void
7712 usage_integrate(void)
7714 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
7715 exit(1);
7718 static const struct got_error *
7719 cmd_integrate(int argc, char *argv[])
7721 const struct got_error *error = NULL;
7722 struct got_repository *repo = NULL;
7723 struct got_worktree *worktree = NULL;
7724 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
7725 const char *branch_arg = NULL;
7726 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
7727 struct got_fileindex *fileindex = NULL;
7728 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
7729 int ch, did_something = 0;
7731 while ((ch = getopt(argc, argv, "")) != -1) {
7732 switch (ch) {
7733 default:
7734 usage_integrate();
7735 /* NOTREACHED */
7739 argc -= optind;
7740 argv += optind;
7742 if (argc != 1)
7743 usage_integrate();
7744 branch_arg = argv[0];
7746 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7747 "unveil", NULL) == -1)
7748 err(1, "pledge");
7750 cwd = getcwd(NULL, 0);
7751 if (cwd == NULL) {
7752 error = got_error_from_errno("getcwd");
7753 goto done;
7756 error = got_worktree_open(&worktree, cwd);
7757 if (error)
7758 goto done;
7760 error = check_rebase_or_histedit_in_progress(worktree);
7761 if (error)
7762 goto done;
7764 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7765 NULL);
7766 if (error != NULL)
7767 goto done;
7769 error = apply_unveil(got_repo_get_path(repo), 0,
7770 got_worktree_get_root_path(worktree));
7771 if (error)
7772 goto done;
7774 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
7775 error = got_error_from_errno("asprintf");
7776 goto done;
7779 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
7780 &base_branch_ref, worktree, refname, repo);
7781 if (error)
7782 goto done;
7784 refname = strdup(got_ref_get_name(branch_ref));
7785 if (refname == NULL) {
7786 error = got_error_from_errno("strdup");
7787 got_worktree_integrate_abort(worktree, fileindex, repo,
7788 branch_ref, base_branch_ref);
7789 goto done;
7791 base_refname = strdup(got_ref_get_name(base_branch_ref));
7792 if (base_refname == NULL) {
7793 error = got_error_from_errno("strdup");
7794 got_worktree_integrate_abort(worktree, fileindex, repo,
7795 branch_ref, base_branch_ref);
7796 goto done;
7799 error = got_ref_resolve(&commit_id, repo, branch_ref);
7800 if (error)
7801 goto done;
7803 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
7804 if (error)
7805 goto done;
7807 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
7808 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7809 "specified branch has already been integrated");
7810 got_worktree_integrate_abort(worktree, fileindex, repo,
7811 branch_ref, base_branch_ref);
7812 goto done;
7815 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
7816 if (error) {
7817 if (error->code == GOT_ERR_ANCESTRY)
7818 error = got_error(GOT_ERR_REBASE_REQUIRED);
7819 got_worktree_integrate_abort(worktree, fileindex, repo,
7820 branch_ref, base_branch_ref);
7821 goto done;
7824 error = got_worktree_integrate_continue(worktree, fileindex, repo,
7825 branch_ref, base_branch_ref, update_progress, &did_something,
7826 check_cancelled, NULL);
7827 if (error)
7828 goto done;
7830 printf("Integrated %s into %s\n", refname, base_refname);
7831 done:
7832 if (repo)
7833 got_repo_close(repo);
7834 if (worktree)
7835 got_worktree_close(worktree);
7836 free(cwd);
7837 free(base_commit_id);
7838 free(commit_id);
7839 free(refname);
7840 free(base_refname);
7841 return error;
7844 __dead static void
7845 usage_stage(void)
7847 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
7848 "[file-path ...]\n",
7849 getprogname());
7850 exit(1);
7853 static const struct got_error *
7854 print_stage(void *arg, unsigned char status, unsigned char staged_status,
7855 const char *path, struct got_object_id *blob_id,
7856 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
7857 int dirfd, const char *de_name)
7859 const struct got_error *err = NULL;
7860 char *id_str = NULL;
7862 if (staged_status != GOT_STATUS_ADD &&
7863 staged_status != GOT_STATUS_MODIFY &&
7864 staged_status != GOT_STATUS_DELETE)
7865 return NULL;
7867 if (staged_status == GOT_STATUS_ADD ||
7868 staged_status == GOT_STATUS_MODIFY)
7869 err = got_object_id_str(&id_str, staged_blob_id);
7870 else
7871 err = got_object_id_str(&id_str, blob_id);
7872 if (err)
7873 return err;
7875 printf("%s %c %s\n", id_str, staged_status, path);
7876 free(id_str);
7877 return NULL;
7880 static const struct got_error *
7881 cmd_stage(int argc, char *argv[])
7883 const struct got_error *error = NULL;
7884 struct got_repository *repo = NULL;
7885 struct got_worktree *worktree = NULL;
7886 char *cwd = NULL;
7887 struct got_pathlist_head paths;
7888 struct got_pathlist_entry *pe;
7889 int ch, list_stage = 0, pflag = 0;
7890 FILE *patch_script_file = NULL;
7891 const char *patch_script_path = NULL;
7892 struct choose_patch_arg cpa;
7894 TAILQ_INIT(&paths);
7896 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
7897 switch (ch) {
7898 case 'l':
7899 list_stage = 1;
7900 break;
7901 case 'p':
7902 pflag = 1;
7903 break;
7904 case 'F':
7905 patch_script_path = optarg;
7906 break;
7907 default:
7908 usage_stage();
7909 /* NOTREACHED */
7913 argc -= optind;
7914 argv += optind;
7916 #ifndef PROFILE
7917 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7918 "unveil", NULL) == -1)
7919 err(1, "pledge");
7920 #endif
7921 if (list_stage && (pflag || patch_script_path))
7922 errx(1, "-l option cannot be used with other options");
7923 if (patch_script_path && !pflag)
7924 errx(1, "-F option can only be used together with -p option");
7926 cwd = getcwd(NULL, 0);
7927 if (cwd == NULL) {
7928 error = got_error_from_errno("getcwd");
7929 goto done;
7932 error = got_worktree_open(&worktree, cwd);
7933 if (error)
7934 goto done;
7936 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7937 NULL);
7938 if (error != NULL)
7939 goto done;
7941 if (patch_script_path) {
7942 patch_script_file = fopen(patch_script_path, "r");
7943 if (patch_script_file == NULL) {
7944 error = got_error_from_errno2("fopen",
7945 patch_script_path);
7946 goto done;
7949 error = apply_unveil(got_repo_get_path(repo), 0,
7950 got_worktree_get_root_path(worktree));
7951 if (error)
7952 goto done;
7954 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7955 if (error)
7956 goto done;
7958 if (list_stage)
7959 error = got_worktree_status(worktree, &paths, repo,
7960 print_stage, NULL, check_cancelled, NULL);
7961 else {
7962 cpa.patch_script_file = patch_script_file;
7963 cpa.action = "stage";
7964 error = got_worktree_stage(worktree, &paths,
7965 pflag ? NULL : print_status, NULL,
7966 pflag ? choose_patch : NULL, &cpa, repo);
7968 done:
7969 if (patch_script_file && fclose(patch_script_file) == EOF &&
7970 error == NULL)
7971 error = got_error_from_errno2("fclose", patch_script_path);
7972 if (repo)
7973 got_repo_close(repo);
7974 if (worktree)
7975 got_worktree_close(worktree);
7976 TAILQ_FOREACH(pe, &paths, entry)
7977 free((char *)pe->path);
7978 got_pathlist_free(&paths);
7979 free(cwd);
7980 return error;
7983 __dead static void
7984 usage_unstage(void)
7986 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
7987 "[file-path ...]\n",
7988 getprogname());
7989 exit(1);
7993 static const struct got_error *
7994 cmd_unstage(int argc, char *argv[])
7996 const struct got_error *error = NULL;
7997 struct got_repository *repo = NULL;
7998 struct got_worktree *worktree = NULL;
7999 char *cwd = NULL;
8000 struct got_pathlist_head paths;
8001 struct got_pathlist_entry *pe;
8002 int ch, did_something = 0, pflag = 0;
8003 FILE *patch_script_file = NULL;
8004 const char *patch_script_path = NULL;
8005 struct choose_patch_arg cpa;
8007 TAILQ_INIT(&paths);
8009 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8010 switch (ch) {
8011 case 'p':
8012 pflag = 1;
8013 break;
8014 case 'F':
8015 patch_script_path = optarg;
8016 break;
8017 default:
8018 usage_unstage();
8019 /* NOTREACHED */
8023 argc -= optind;
8024 argv += optind;
8026 #ifndef PROFILE
8027 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8028 "unveil", NULL) == -1)
8029 err(1, "pledge");
8030 #endif
8031 if (patch_script_path && !pflag)
8032 errx(1, "-F option can only be used together with -p option");
8034 cwd = getcwd(NULL, 0);
8035 if (cwd == NULL) {
8036 error = got_error_from_errno("getcwd");
8037 goto done;
8040 error = got_worktree_open(&worktree, cwd);
8041 if (error)
8042 goto done;
8044 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8045 NULL);
8046 if (error != NULL)
8047 goto done;
8049 if (patch_script_path) {
8050 patch_script_file = fopen(patch_script_path, "r");
8051 if (patch_script_file == NULL) {
8052 error = got_error_from_errno2("fopen",
8053 patch_script_path);
8054 goto done;
8058 error = apply_unveil(got_repo_get_path(repo), 0,
8059 got_worktree_get_root_path(worktree));
8060 if (error)
8061 goto done;
8063 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8064 if (error)
8065 goto done;
8067 cpa.patch_script_file = patch_script_file;
8068 cpa.action = "unstage";
8069 error = got_worktree_unstage(worktree, &paths, update_progress,
8070 &did_something, pflag ? choose_patch : NULL, &cpa, repo);
8071 done:
8072 if (patch_script_file && fclose(patch_script_file) == EOF &&
8073 error == NULL)
8074 error = got_error_from_errno2("fclose", patch_script_path);
8075 if (repo)
8076 got_repo_close(repo);
8077 if (worktree)
8078 got_worktree_close(worktree);
8079 TAILQ_FOREACH(pe, &paths, entry)
8080 free((char *)pe->path);
8081 got_pathlist_free(&paths);
8082 free(cwd);
8083 return error;
8086 __dead static void
8087 usage_cat(void)
8089 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8090 "arg1 [arg2 ...]\n", getprogname());
8091 exit(1);
8094 static const struct got_error *
8095 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8097 const struct got_error *err;
8098 struct got_blob_object *blob;
8100 err = got_object_open_as_blob(&blob, repo, id, 8192);
8101 if (err)
8102 return err;
8104 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8105 got_object_blob_close(blob);
8106 return err;
8109 static const struct got_error *
8110 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8112 const struct got_error *err;
8113 struct got_tree_object *tree;
8114 int nentries, i;
8116 err = got_object_open_as_tree(&tree, repo, id);
8117 if (err)
8118 return err;
8120 nentries = got_object_tree_get_nentries(tree);
8121 for (i = 0; i < nentries; i++) {
8122 struct got_tree_entry *te;
8123 char *id_str;
8124 if (sigint_received || sigpipe_received)
8125 break;
8126 te = got_object_tree_get_entry(tree, i);
8127 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8128 if (err)
8129 break;
8130 fprintf(outfile, "%s %.7o %s\n", id_str,
8131 got_tree_entry_get_mode(te),
8132 got_tree_entry_get_name(te));
8133 free(id_str);
8136 got_object_tree_close(tree);
8137 return err;
8140 static const struct got_error *
8141 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8143 const struct got_error *err;
8144 struct got_commit_object *commit;
8145 const struct got_object_id_queue *parent_ids;
8146 struct got_object_qid *pid;
8147 char *id_str = NULL;
8148 const char *logmsg = NULL;
8150 err = got_object_open_as_commit(&commit, repo, id);
8151 if (err)
8152 return err;
8154 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8155 if (err)
8156 goto done;
8158 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8159 parent_ids = got_object_commit_get_parent_ids(commit);
8160 fprintf(outfile, "numparents %d\n",
8161 got_object_commit_get_nparents(commit));
8162 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8163 char *pid_str;
8164 err = got_object_id_str(&pid_str, pid->id);
8165 if (err)
8166 goto done;
8167 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8168 free(pid_str);
8170 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8171 got_object_commit_get_author(commit),
8172 got_object_commit_get_author_time(commit));
8174 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8175 got_object_commit_get_author(commit),
8176 got_object_commit_get_committer_time(commit));
8178 logmsg = got_object_commit_get_logmsg_raw(commit);
8179 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8180 fprintf(outfile, "%s", logmsg);
8181 done:
8182 free(id_str);
8183 got_object_commit_close(commit);
8184 return err;
8187 static const struct got_error *
8188 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8190 const struct got_error *err;
8191 struct got_tag_object *tag;
8192 char *id_str = NULL;
8193 const char *tagmsg = NULL;
8195 err = got_object_open_as_tag(&tag, repo, id);
8196 if (err)
8197 return err;
8199 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8200 if (err)
8201 goto done;
8203 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8205 switch (got_object_tag_get_object_type(tag)) {
8206 case GOT_OBJ_TYPE_BLOB:
8207 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8208 GOT_OBJ_LABEL_BLOB);
8209 break;
8210 case GOT_OBJ_TYPE_TREE:
8211 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8212 GOT_OBJ_LABEL_TREE);
8213 break;
8214 case GOT_OBJ_TYPE_COMMIT:
8215 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8216 GOT_OBJ_LABEL_COMMIT);
8217 break;
8218 case GOT_OBJ_TYPE_TAG:
8219 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8220 GOT_OBJ_LABEL_TAG);
8221 break;
8222 default:
8223 break;
8226 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8227 got_object_tag_get_name(tag));
8229 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8230 got_object_tag_get_tagger(tag),
8231 got_object_tag_get_tagger_time(tag));
8233 tagmsg = got_object_tag_get_message(tag);
8234 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8235 fprintf(outfile, "%s", tagmsg);
8236 done:
8237 free(id_str);
8238 got_object_tag_close(tag);
8239 return err;
8242 static const struct got_error *
8243 cmd_cat(int argc, char *argv[])
8245 const struct got_error *error;
8246 struct got_repository *repo = NULL;
8247 struct got_worktree *worktree = NULL;
8248 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8249 const char *commit_id_str = NULL;
8250 struct got_object_id *id = NULL, *commit_id = NULL;
8251 int ch, obj_type, i, force_path = 0;
8253 #ifndef PROFILE
8254 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8255 NULL) == -1)
8256 err(1, "pledge");
8257 #endif
8259 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8260 switch (ch) {
8261 case 'c':
8262 commit_id_str = optarg;
8263 break;
8264 case 'r':
8265 repo_path = realpath(optarg, NULL);
8266 if (repo_path == NULL)
8267 return got_error_from_errno2("realpath",
8268 optarg);
8269 got_path_strip_trailing_slashes(repo_path);
8270 break;
8271 case 'P':
8272 force_path = 1;
8273 break;
8274 default:
8275 usage_cat();
8276 /* NOTREACHED */
8280 argc -= optind;
8281 argv += optind;
8283 cwd = getcwd(NULL, 0);
8284 if (cwd == NULL) {
8285 error = got_error_from_errno("getcwd");
8286 goto done;
8288 error = got_worktree_open(&worktree, cwd);
8289 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8290 goto done;
8291 if (worktree) {
8292 if (repo_path == NULL) {
8293 repo_path = strdup(
8294 got_worktree_get_repo_path(worktree));
8295 if (repo_path == NULL) {
8296 error = got_error_from_errno("strdup");
8297 goto done;
8302 if (repo_path == NULL) {
8303 repo_path = getcwd(NULL, 0);
8304 if (repo_path == NULL)
8305 return got_error_from_errno("getcwd");
8308 error = got_repo_open(&repo, repo_path, NULL);
8309 free(repo_path);
8310 if (error != NULL)
8311 goto done;
8313 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8314 if (error)
8315 goto done;
8317 if (commit_id_str == NULL)
8318 commit_id_str = GOT_REF_HEAD;
8319 error = got_repo_match_object_id(&commit_id, NULL,
8320 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
8321 if (error)
8322 goto done;
8324 for (i = 0; i < argc; i++) {
8325 if (force_path) {
8326 error = got_object_id_by_path(&id, repo, commit_id,
8327 argv[i]);
8328 if (error)
8329 break;
8330 } else {
8331 error = got_repo_match_object_id(&id, &label, argv[i],
8332 GOT_OBJ_TYPE_ANY, 0, repo);
8333 if (error) {
8334 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8335 error->code != GOT_ERR_NOT_REF)
8336 break;
8337 error = got_object_id_by_path(&id, repo,
8338 commit_id, argv[i]);
8339 if (error)
8340 break;
8344 error = got_object_get_type(&obj_type, repo, id);
8345 if (error)
8346 break;
8348 switch (obj_type) {
8349 case GOT_OBJ_TYPE_BLOB:
8350 error = cat_blob(id, repo, stdout);
8351 break;
8352 case GOT_OBJ_TYPE_TREE:
8353 error = cat_tree(id, repo, stdout);
8354 break;
8355 case GOT_OBJ_TYPE_COMMIT:
8356 error = cat_commit(id, repo, stdout);
8357 break;
8358 case GOT_OBJ_TYPE_TAG:
8359 error = cat_tag(id, repo, stdout);
8360 break;
8361 default:
8362 error = got_error(GOT_ERR_OBJ_TYPE);
8363 break;
8365 if (error)
8366 break;
8367 free(label);
8368 label = NULL;
8369 free(id);
8370 id = NULL;
8372 done:
8373 free(label);
8374 free(id);
8375 free(commit_id);
8376 if (worktree)
8377 got_worktree_close(worktree);
8378 if (repo) {
8379 const struct got_error *repo_error;
8380 repo_error = got_repo_close(repo);
8381 if (error == NULL)
8382 error = repo_error;
8384 return error;