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] [-l] [-m] [-q] [-v] "
815 "[-R reference] 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_symref(const char *refname, struct got_reference *target_ref,
889 int verbosity, struct got_repository *repo)
891 const struct got_error *err;
892 struct got_reference *head_symref;
894 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
895 if (err)
896 return err;
898 err = got_ref_write(head_symref, repo);
899 got_ref_close(head_symref);
900 if (err == NULL && verbosity > 0) {
901 printf("Created reference %s: %s\n", GOT_REF_HEAD,
902 got_ref_get_name(target_ref));
904 return err;
907 static const struct got_error *
908 list_remote_refs(struct got_pathlist_head *symrefs,
909 struct got_pathlist_head *refs)
911 const struct got_error *err;
912 struct got_pathlist_entry *pe;
914 TAILQ_FOREACH(pe, symrefs, entry) {
915 const char *refname = pe->path;
916 const char *targetref = pe->data;
918 printf("%s: %s\n", refname, targetref);
921 TAILQ_FOREACH(pe, refs, entry) {
922 const char *refname = pe->path;
923 struct got_object_id *id = pe->data;
924 char *id_str;
926 err = got_object_id_str(&id_str, id);
927 if (err)
928 return err;
929 printf("%s: %s\n", refname, id_str);
930 free(id_str);
933 return NULL;
936 static const struct got_error *
937 create_ref(const char *refname, struct got_object_id *id,
938 int verbosity, struct got_repository *repo)
940 const struct got_error *err = NULL;
941 struct got_reference *ref;
942 char *id_str;
944 err = got_object_id_str(&id_str, id);
945 if (err)
946 return err;
948 err = got_ref_alloc(&ref, refname, id);
949 if (err)
950 goto done;
952 err = got_ref_write(ref, repo);
953 got_ref_close(ref);
955 if (err == NULL && verbosity >= 0)
956 printf("Created reference %s: %s\n", refname, id_str);
957 done:
958 free(id_str);
959 return err;
962 static int
963 match_wanted_ref(const char *refname, const char *wanted_ref)
965 if (strncmp(refname, "refs/", 5) != 0)
966 return 0;
967 refname += 5;
969 /*
970 * Prevent fetching of references that won't make any
971 * sense outside of the remote repository's context.
972 */
973 if (strncmp(refname, "got/", 4) == 0)
974 return 0;
975 if (strncmp(refname, "remotes/", 8) == 0)
976 return 0;
978 if (strncmp(wanted_ref, "refs/", 5) == 0)
979 wanted_ref += 5;
981 /* Allow prefix match. */
982 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
983 return 1;
985 /* Allow exact match. */
986 return (strcmp(refname, wanted_ref) == 0);
989 static int
990 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
992 struct got_pathlist_entry *pe;
994 TAILQ_FOREACH(pe, wanted_refs, entry) {
995 if (match_wanted_ref(refname, pe->path))
996 return 1;
999 return 0;
1002 static const struct got_error *
1003 create_wanted_ref(const char *refname, struct got_object_id *id,
1004 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1006 const struct got_error *err;
1007 char *remote_refname;
1009 if (strncmp("refs/", refname, 5) == 0)
1010 refname += 5;
1012 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1013 remote_repo_name, refname) == -1)
1014 return got_error_from_errno("asprintf");
1016 err = create_ref(remote_refname, id, verbosity, repo);
1017 free(remote_refname);
1018 return err;
1021 static const struct got_error *
1022 cmd_clone(int argc, char *argv[])
1024 const struct got_error *error = NULL;
1025 const char *uri, *dirname;
1026 char *proto, *host, *port, *repo_name, *server_path;
1027 char *default_destdir = NULL, *id_str = NULL;
1028 const char *repo_path;
1029 struct got_repository *repo = NULL;
1030 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1031 struct got_pathlist_entry *pe;
1032 struct got_object_id *pack_hash = NULL;
1033 int ch, fetchfd = -1, fetchstatus;
1034 pid_t fetchpid = -1;
1035 struct got_fetch_progress_arg fpa;
1036 char *git_url = NULL;
1037 char *gitconfig_path = NULL;
1038 char *gitconfig = NULL;
1039 FILE *gitconfig_file = NULL;
1040 ssize_t n;
1041 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1042 int list_refs_only = 0;
1043 struct got_reference *head_symref = NULL;
1045 TAILQ_INIT(&refs);
1046 TAILQ_INIT(&symrefs);
1047 TAILQ_INIT(&wanted_branches);
1048 TAILQ_INIT(&wanted_refs);
1050 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1051 switch (ch) {
1052 case 'a':
1053 fetch_all_branches = 1;
1054 break;
1055 case 'b':
1056 error = got_pathlist_append(&wanted_branches,
1057 optarg, NULL);
1058 if (error)
1059 return error;
1060 break;
1061 case 'l':
1062 list_refs_only = 1;
1063 break;
1064 case 'm':
1065 mirror_references = 1;
1066 break;
1067 case 'v':
1068 if (verbosity < 0)
1069 verbosity = 0;
1070 else if (verbosity < 3)
1071 verbosity++;
1072 break;
1073 case 'q':
1074 verbosity = -1;
1075 break;
1076 case 'R':
1077 error = got_pathlist_append(&wanted_refs,
1078 optarg, NULL);
1079 if (error)
1080 return error;
1081 break;
1082 default:
1083 usage_clone();
1084 break;
1087 argc -= optind;
1088 argv += optind;
1090 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1091 errx(1, "-a and -b options are mutually exclusive");
1092 if (list_refs_only) {
1093 if (!TAILQ_EMPTY(&wanted_branches))
1094 errx(1, "-l and -b options are mutually exclusive");
1095 if (fetch_all_branches)
1096 errx(1, "-l and -a options are mutually exclusive");
1097 if (mirror_references)
1098 errx(1, "-l and -m options are mutually exclusive");
1099 if (verbosity == -1)
1100 errx(1, "-l and -q options are mutually exclusive");
1101 if (!TAILQ_EMPTY(&wanted_refs))
1102 errx(1, "-l and -R options are mutually exclusive");
1105 uri = argv[0];
1107 if (argc == 1)
1108 dirname = NULL;
1109 else if (argc == 2)
1110 dirname = argv[1];
1111 else
1112 usage_clone();
1114 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1115 &repo_name, argv[0]);
1116 if (error)
1117 goto done;
1119 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1120 host, port ? ":" : "", port ? port : "",
1121 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1122 error = got_error_from_errno("asprintf");
1123 goto done;
1126 if (strcmp(proto, "git") == 0) {
1127 #ifndef PROFILE
1128 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1129 "sendfd dns inet unveil", NULL) == -1)
1130 err(1, "pledge");
1131 #endif
1132 } else if (strcmp(proto, "git+ssh") == 0 ||
1133 strcmp(proto, "ssh") == 0) {
1134 #ifndef PROFILE
1135 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1136 "sendfd unveil", NULL) == -1)
1137 err(1, "pledge");
1138 #endif
1139 } else if (strcmp(proto, "http") == 0 ||
1140 strcmp(proto, "git+http") == 0) {
1141 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1142 goto done;
1143 } else {
1144 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1145 goto done;
1147 if (dirname == NULL) {
1148 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1149 error = got_error_from_errno("asprintf");
1150 goto done;
1152 repo_path = default_destdir;
1153 } else
1154 repo_path = dirname;
1156 if (!list_refs_only) {
1157 error = got_path_mkdir(repo_path);
1158 if (error)
1159 goto done;
1161 error = got_repo_init(repo_path);
1162 if (error)
1163 goto done;
1164 error = got_repo_open(&repo, repo_path, NULL);
1165 if (error)
1166 goto done;
1169 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1170 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1171 error = got_error_from_errno2("unveil",
1172 GOT_FETCH_PATH_SSH);
1173 goto done;
1176 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1177 if (error)
1178 goto done;
1180 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1181 server_path, verbosity);
1182 if (error)
1183 goto done;
1185 if (verbosity >= 0)
1186 printf("Connected to %s%s%s\n", host,
1187 port ? ":" : "", port ? port : "");
1189 fpa.last_scaled_size[0] = '\0';
1190 fpa.last_p_indexed = -1;
1191 fpa.last_p_resolved = -1;
1192 fpa.verbosity = verbosity;
1193 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1194 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1195 fetch_all_branches, &wanted_branches, &wanted_refs,
1196 list_refs_only, verbosity, fetchfd, repo,
1197 fetch_progress, &fpa);
1198 if (error)
1199 goto done;
1201 if (list_refs_only) {
1202 error = list_remote_refs(&symrefs, &refs);
1203 goto done;
1206 error = got_object_id_str(&id_str, pack_hash);
1207 if (error)
1208 goto done;
1209 if (verbosity >= 0)
1210 printf("\nFetched %s.pack\n", id_str);
1211 free(id_str);
1213 /* Set up references provided with the pack file. */
1214 TAILQ_FOREACH(pe, &refs, entry) {
1215 const char *refname = pe->path;
1216 struct got_object_id *id = pe->data;
1217 char *remote_refname;
1219 if (is_wanted_ref(&wanted_refs, refname) &&
1220 !mirror_references) {
1221 error = create_wanted_ref(refname, id,
1222 GOT_FETCH_DEFAULT_REMOTE_NAME,
1223 verbosity - 1, repo);
1224 if (error)
1225 goto done;
1226 continue;
1229 error = create_ref(refname, id, verbosity - 1, repo);
1230 if (error)
1231 goto done;
1233 if (mirror_references)
1234 continue;
1236 if (strncmp("refs/heads/", refname, 11) != 0)
1237 continue;
1239 if (asprintf(&remote_refname,
1240 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1241 refname + 11) == -1) {
1242 error = got_error_from_errno("asprintf");
1243 goto done;
1245 error = create_ref(remote_refname, id, verbosity - 1, repo);
1246 free(remote_refname);
1247 if (error)
1248 goto done;
1251 /* Set the HEAD reference if the server provided one. */
1252 TAILQ_FOREACH(pe, &symrefs, entry) {
1253 struct got_reference *target_ref;
1254 const char *refname = pe->path;
1255 const char *target = pe->data;
1256 char *remote_refname = NULL, *remote_target = NULL;
1258 if (strcmp(refname, GOT_REF_HEAD) != 0)
1259 continue;
1261 error = got_ref_open(&target_ref, repo, target, 0);
1262 if (error) {
1263 if (error->code == GOT_ERR_NOT_REF) {
1264 error = NULL;
1265 continue;
1267 goto done;
1270 error = create_symref(refname, target_ref, verbosity, repo);
1271 got_ref_close(target_ref);
1272 if (error)
1273 goto done;
1275 if (mirror_references)
1276 continue;
1278 if (strncmp("refs/heads/", target, 11) != 0)
1279 continue;
1281 if (asprintf(&remote_refname,
1282 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1283 refname) == -1) {
1284 error = got_error_from_errno("asprintf");
1285 goto done;
1287 if (asprintf(&remote_target,
1288 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1289 target + 11) == -1) {
1290 error = got_error_from_errno("asprintf");
1291 free(remote_refname);
1292 goto done;
1294 error = got_ref_open(&target_ref, repo, remote_target, 0);
1295 if (error) {
1296 free(remote_refname);
1297 free(remote_target);
1298 if (error->code == GOT_ERR_NOT_REF) {
1299 error = NULL;
1300 continue;
1302 goto done;
1304 error = create_symref(remote_refname, target_ref,
1305 verbosity - 1, repo);
1306 free(remote_refname);
1307 free(remote_target);
1308 got_ref_close(target_ref);
1309 if (error)
1310 goto done;
1312 if (pe == NULL) {
1314 * We failed to set the HEAD reference. If we asked for
1315 * a set of wanted branches use the first of one of those
1316 * which could be fetched instead.
1318 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1319 const char *target = pe->path;
1320 struct got_reference *target_ref;
1322 error = got_ref_open(&target_ref, repo, target, 0);
1323 if (error) {
1324 if (error->code == GOT_ERR_NOT_REF) {
1325 error = NULL;
1326 continue;
1328 goto done;
1331 error = create_symref(GOT_REF_HEAD, target_ref,
1332 verbosity, repo);
1333 got_ref_close(target_ref);
1334 if (error)
1335 goto done;
1336 break;
1340 /* Create a config file git-fetch(1) can understand. */
1341 gitconfig_path = got_repo_get_path_gitconfig(repo);
1342 if (gitconfig_path == NULL) {
1343 error = got_error_from_errno("got_repo_get_path_gitconfig");
1344 goto done;
1346 gitconfig_file = fopen(gitconfig_path, "a");
1347 if (gitconfig_file == NULL) {
1348 error = got_error_from_errno2("fopen", gitconfig_path);
1349 goto done;
1351 if (mirror_references) {
1352 if (asprintf(&gitconfig,
1353 "[remote \"%s\"]\n"
1354 "\turl = %s\n"
1355 "\tfetch = +refs/*:refs/*\n"
1356 "\tmirror = true\n",
1357 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1358 error = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (fetch_all_branches) {
1362 if (asprintf(&gitconfig,
1363 "[remote \"%s\"]\n"
1364 "\turl = %s\n"
1365 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1366 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 error = got_error_from_errno("asprintf");
1369 goto done;
1371 } else {
1372 const char *branchname;
1375 * If the server specified a default branch, use just that one.
1376 * Otherwise fall back to fetching all branches on next fetch.
1378 if (head_symref) {
1379 branchname = got_ref_get_symref_target(head_symref);
1380 if (strncmp(branchname, "refs/heads/", 11) == 0)
1381 branchname += 11;
1382 } else
1383 branchname = "*"; /* fall back to all branches */
1384 if (asprintf(&gitconfig,
1385 "[remote \"%s\"]\n"
1386 "\turl = %s\n"
1387 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1388 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 error = got_error_from_errno("asprintf");
1392 goto done;
1395 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1396 if (n != strlen(gitconfig)) {
1397 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1398 goto done;
1401 if (verbosity >= 0)
1402 printf("Created %s repository '%s'\n",
1403 mirror_references ? "mirrored" : "cloned", repo_path);
1404 done:
1405 if (fetchpid > 0) {
1406 if (kill(fetchpid, SIGTERM) == -1)
1407 error = got_error_from_errno("kill");
1408 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1409 error = got_error_from_errno("waitpid");
1411 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1412 error = got_error_from_errno("close");
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1414 error = got_error_from_errno("fclose");
1415 if (repo)
1416 got_repo_close(repo);
1417 if (head_symref)
1418 got_ref_close(head_symref);
1419 TAILQ_FOREACH(pe, &refs, entry) {
1420 free((void *)pe->path);
1421 free(pe->data);
1423 got_pathlist_free(&refs);
1424 TAILQ_FOREACH(pe, &symrefs, entry) {
1425 free((void *)pe->path);
1426 free(pe->data);
1428 got_pathlist_free(&symrefs);
1429 got_pathlist_free(&wanted_branches);
1430 got_pathlist_free(&wanted_refs);
1431 free(pack_hash);
1432 free(proto);
1433 free(host);
1434 free(port);
1435 free(server_path);
1436 free(repo_name);
1437 free(default_destdir);
1438 free(gitconfig_path);
1439 free(git_url);
1440 return error;
1443 static const struct got_error *
1444 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1445 int replace_tags, int verbosity, struct got_repository *repo)
1447 const struct got_error *err = NULL;
1448 char *new_id_str = NULL;
1449 struct got_object_id *old_id = NULL;
1451 err = got_object_id_str(&new_id_str, new_id);
1452 if (err)
1453 goto done;
1455 if (!replace_tags &&
1456 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1457 err = got_ref_resolve(&old_id, repo, ref);
1458 if (err)
1459 goto done;
1460 if (got_object_id_cmp(old_id, new_id) == 0)
1461 goto done;
1462 if (verbosity >= 0) {
1463 printf("Rejecting update of existing tag %s: %s\n",
1464 got_ref_get_name(ref), new_id_str);
1466 goto done;
1469 if (got_ref_is_symbolic(ref)) {
1470 if (verbosity >= 0) {
1471 printf("Replacing reference %s: %s\n",
1472 got_ref_get_name(ref),
1473 got_ref_get_symref_target(ref));
1475 err = got_ref_change_symref_to_ref(ref, new_id);
1476 if (err)
1477 goto done;
1478 err = got_ref_write(ref, repo);
1479 if (err)
1480 goto done;
1481 } else {
1482 err = got_ref_resolve(&old_id, repo, ref);
1483 if (err)
1484 goto done;
1485 if (got_object_id_cmp(old_id, new_id) == 0)
1486 goto done;
1488 err = got_ref_change_ref(ref, new_id);
1489 if (err)
1490 goto done;
1491 err = got_ref_write(ref, repo);
1492 if (err)
1493 goto done;
1496 if (verbosity >= 0)
1497 printf("Updated reference %s: %s\n", got_ref_get_name(ref),
1498 new_id_str);
1499 done:
1500 free(old_id);
1501 free(new_id_str);
1502 return err;
1505 static const struct got_error *
1506 update_symref(const char *refname, struct got_reference *target_ref,
1507 int verbosity, struct got_repository *repo)
1509 const struct got_error *err = NULL, *unlock_err;
1510 struct got_reference *symref;
1511 int symref_is_locked = 0;
1513 err = got_ref_open(&symref, repo, refname, 1);
1514 if (err) {
1515 if (err->code != GOT_ERR_NOT_REF)
1516 return err;
1517 err = got_ref_alloc_symref(&symref, refname, target_ref);
1518 if (err)
1519 goto done;
1521 err = got_ref_write(symref, repo);
1522 if (err)
1523 goto done;
1525 if (verbosity >= 0)
1526 printf("Created reference %s: %s\n",
1527 got_ref_get_name(symref),
1528 got_ref_get_symref_target(symref));
1529 } else {
1530 symref_is_locked = 1;
1532 if (strcmp(got_ref_get_symref_target(symref),
1533 got_ref_get_name(target_ref)) == 0)
1534 goto done;
1536 err = got_ref_change_symref(symref,
1537 got_ref_get_name(target_ref));
1538 if (err)
1539 goto done;
1541 err = got_ref_write(symref, repo);
1542 if (err)
1543 goto done;
1545 if (verbosity >= 0)
1546 printf("Updated reference %s: %s\n",
1547 got_ref_get_name(symref),
1548 got_ref_get_symref_target(symref));
1551 done:
1552 if (symref_is_locked) {
1553 unlock_err = got_ref_unlock(symref);
1554 if (unlock_err && err == NULL)
1555 err = unlock_err;
1557 got_ref_close(symref);
1558 return err;
1561 __dead static void
1562 usage_fetch(void)
1564 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1565 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1566 "[remote-repository-name]\n",
1567 getprogname());
1568 exit(1);
1571 static const struct got_error *
1572 delete_missing_ref(struct got_reference *ref,
1573 int verbosity, struct got_repository *repo)
1575 const struct got_error *err = NULL;
1576 struct got_object_id *id = NULL;
1577 char *id_str = NULL;
1579 if (got_ref_is_symbolic(ref)) {
1580 err = got_ref_delete(ref, repo);
1581 if (err)
1582 return err;
1583 if (verbosity >= 0) {
1584 printf("Deleted reference %s: %s\n",
1585 got_ref_get_name(ref),
1586 got_ref_get_symref_target(ref));
1588 } else {
1589 err = got_ref_resolve(&id, repo, ref);
1590 if (err)
1591 return err;
1592 err = got_object_id_str(&id_str, id);
1593 if (err)
1594 goto done;
1596 err = got_ref_delete(ref, repo);
1597 if (err)
1598 goto done;
1599 if (verbosity >= 0) {
1600 printf("Deleted reference %s: %s\n",
1601 got_ref_get_name(ref), id_str);
1604 done:
1605 free(id);
1606 free(id_str);
1607 return NULL;
1610 static const struct got_error *
1611 delete_missing_refs(struct got_pathlist_head *their_refs,
1612 struct got_pathlist_head *their_symrefs, struct got_remote_repo *remote,
1613 int verbosity, struct got_repository *repo)
1615 const struct got_error *err = NULL, *unlock_err;
1616 struct got_reflist_head my_refs;
1617 struct got_reflist_entry *re;
1618 struct got_pathlist_entry *pe;
1619 char *remote_namespace = NULL;
1620 char *local_refname = NULL;
1622 SIMPLEQ_INIT(&my_refs);
1624 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1625 == -1)
1626 return got_error_from_errno("asprintf");
1628 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1629 if (err)
1630 goto done;
1632 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1633 const char *refname = got_ref_get_name(re->ref);
1635 if (!remote->mirror_references) {
1636 if (strncmp(refname, remote_namespace,
1637 strlen(remote_namespace)) == 0) {
1638 if (strcmp(refname + strlen(remote_namespace),
1639 GOT_REF_HEAD) == 0)
1640 continue;
1641 if (asprintf(&local_refname, "refs/heads/%s",
1642 refname + strlen(remote_namespace)) == -1) {
1643 err = got_error_from_errno("asprintf");
1644 goto done;
1646 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1647 continue;
1650 TAILQ_FOREACH(pe, their_refs, entry) {
1651 if (strcmp(local_refname, pe->path) == 0)
1652 break;
1654 if (pe != NULL)
1655 continue;
1657 TAILQ_FOREACH(pe, their_symrefs, entry) {
1658 if (strcmp(local_refname, pe->path) == 0)
1659 break;
1661 if (pe != NULL)
1662 continue;
1664 err = delete_missing_ref(re->ref, verbosity, repo);
1665 if (err)
1666 break;
1668 if (local_refname) {
1669 struct got_reference *ref;
1670 err = got_ref_open(&ref, repo, local_refname, 1);
1671 if (err) {
1672 if (err->code != GOT_ERR_NOT_REF)
1673 break;
1674 free(local_refname);
1675 local_refname = NULL;
1676 continue;
1678 err = delete_missing_ref(ref, verbosity, repo);
1679 if (err)
1680 break;
1681 unlock_err = got_ref_unlock(ref);
1682 got_ref_close(ref);
1683 if (unlock_err && err == NULL) {
1684 err = unlock_err;
1685 break;
1688 free(local_refname);
1689 local_refname = NULL;
1692 done:
1693 free(remote_namespace);
1694 free(local_refname);
1695 return err;
1698 static const struct got_error *
1699 update_wanted_ref(const char *refname, struct got_object_id *id,
1700 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1702 const struct got_error *err, *unlock_err;
1703 char *remote_refname;
1704 struct got_reference *ref;
1706 if (strncmp("refs/", refname, 5) == 0)
1707 refname += 5;
1709 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1710 remote_repo_name, refname) == -1)
1711 return got_error_from_errno("asprintf");
1713 err = got_ref_open(&ref, repo, remote_refname, 1);
1714 if (err) {
1715 if (err->code != GOT_ERR_NOT_REF)
1716 goto done;
1717 err = create_ref(remote_refname, id, verbosity, repo);
1718 } else {
1719 err = update_ref(ref, id, 0, verbosity, repo);
1720 unlock_err = got_ref_unlock(ref);
1721 if (unlock_err && err == NULL)
1722 err = unlock_err;
1723 got_ref_close(ref);
1725 done:
1726 free(remote_refname);
1727 return err;
1730 static const struct got_error *
1731 cmd_fetch(int argc, char *argv[])
1733 const struct got_error *error = NULL, *unlock_err;
1734 char *cwd = NULL, *repo_path = NULL;
1735 const char *remote_name;
1736 char *proto = NULL, *host = NULL, *port = NULL;
1737 char *repo_name = NULL, *server_path = NULL;
1738 struct got_remote_repo *remotes, *remote = NULL;
1739 int nremotes;
1740 char *id_str = NULL;
1741 struct got_repository *repo = NULL;
1742 struct got_worktree *worktree = NULL;
1743 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1744 struct got_pathlist_entry *pe;
1745 struct got_object_id *pack_hash = NULL;
1746 int i, ch, fetchfd = -1, fetchstatus;
1747 pid_t fetchpid = -1;
1748 struct got_fetch_progress_arg fpa;
1749 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1750 int delete_refs = 0, replace_tags = 0;
1752 TAILQ_INIT(&refs);
1753 TAILQ_INIT(&symrefs);
1754 TAILQ_INIT(&wanted_branches);
1755 TAILQ_INIT(&wanted_refs);
1757 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1758 switch (ch) {
1759 case 'a':
1760 fetch_all_branches = 1;
1761 break;
1762 case 'b':
1763 error = got_pathlist_append(&wanted_branches,
1764 optarg, NULL);
1765 if (error)
1766 return error;
1767 break;
1768 case 'd':
1769 delete_refs = 1;
1770 break;
1771 case 'l':
1772 list_refs_only = 1;
1773 break;
1774 case 'r':
1775 repo_path = realpath(optarg, NULL);
1776 if (repo_path == NULL)
1777 return got_error_from_errno2("realpath",
1778 optarg);
1779 got_path_strip_trailing_slashes(repo_path);
1780 break;
1781 case 't':
1782 replace_tags = 1;
1783 break;
1784 case 'v':
1785 if (verbosity < 0)
1786 verbosity = 0;
1787 else if (verbosity < 3)
1788 verbosity++;
1789 break;
1790 case 'q':
1791 verbosity = -1;
1792 break;
1793 case 'R':
1794 error = got_pathlist_append(&wanted_refs,
1795 optarg, NULL);
1796 if (error)
1797 return error;
1798 break;
1799 default:
1800 usage_fetch();
1801 break;
1804 argc -= optind;
1805 argv += optind;
1807 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1808 errx(1, "-a and -b options are mutually exclusive");
1809 if (list_refs_only) {
1810 if (!TAILQ_EMPTY(&wanted_branches))
1811 errx(1, "-l and -b options are mutually exclusive");
1812 if (fetch_all_branches)
1813 errx(1, "-l and -a options are mutually exclusive");
1814 if (delete_refs)
1815 errx(1, "-l and -d options are mutually exclusive");
1816 if (verbosity == -1)
1817 errx(1, "-l and -q options are mutually exclusive");
1820 if (argc == 0)
1821 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1822 else if (argc == 1)
1823 remote_name = argv[0];
1824 else
1825 usage_fetch();
1827 cwd = getcwd(NULL, 0);
1828 if (cwd == NULL) {
1829 error = got_error_from_errno("getcwd");
1830 goto done;
1833 if (repo_path == NULL) {
1834 error = got_worktree_open(&worktree, cwd);
1835 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1836 goto done;
1837 else
1838 error = NULL;
1839 if (worktree) {
1840 repo_path =
1841 strdup(got_worktree_get_repo_path(worktree));
1842 if (repo_path == NULL)
1843 error = got_error_from_errno("strdup");
1844 if (error)
1845 goto done;
1846 } else {
1847 repo_path = strdup(cwd);
1848 if (repo_path == NULL) {
1849 error = got_error_from_errno("strdup");
1850 goto done;
1855 error = got_repo_open(&repo, repo_path, NULL);
1856 if (error)
1857 goto done;
1859 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1860 for (i = 0; i < nremotes; i++) {
1861 remote = &remotes[i];
1862 if (strcmp(remote->name, remote_name) == 0)
1863 break;
1865 if (i == nremotes) {
1866 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1867 goto done;
1870 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1871 &repo_name, remote->url);
1872 if (error)
1873 goto done;
1875 if (strcmp(proto, "git") == 0) {
1876 #ifndef PROFILE
1877 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1878 "sendfd dns inet unveil", NULL) == -1)
1879 err(1, "pledge");
1880 #endif
1881 } else if (strcmp(proto, "git+ssh") == 0 ||
1882 strcmp(proto, "ssh") == 0) {
1883 #ifndef PROFILE
1884 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1885 "sendfd unveil", NULL) == -1)
1886 err(1, "pledge");
1887 #endif
1888 } else if (strcmp(proto, "http") == 0 ||
1889 strcmp(proto, "git+http") == 0) {
1890 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1891 goto done;
1892 } else {
1893 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1894 goto done;
1897 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1898 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1899 error = got_error_from_errno2("unveil",
1900 GOT_FETCH_PATH_SSH);
1901 goto done;
1904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
1905 if (error)
1906 goto done;
1908 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1909 server_path, verbosity);
1910 if (error)
1911 goto done;
1913 if (verbosity >= 0)
1914 printf("Connected to \"%s\" %s%s%s\n", remote->name, host,
1915 port ? ":" : "", port ? port : "");
1917 fpa.last_scaled_size[0] = '\0';
1918 fpa.last_p_indexed = -1;
1919 fpa.last_p_resolved = -1;
1920 fpa.verbosity = verbosity;
1921 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
1922 remote->mirror_references, fetch_all_branches, &wanted_branches,
1923 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
1924 fetch_progress, &fpa);
1925 if (error)
1926 goto done;
1928 if (list_refs_only) {
1929 error = list_remote_refs(&symrefs, &refs);
1930 goto done;
1933 if (pack_hash == NULL) {
1934 if (verbosity >= 0)
1935 printf("Already up-to-date\n");
1936 } else if (verbosity >= 0) {
1937 error = got_object_id_str(&id_str, pack_hash);
1938 if (error)
1939 goto done;
1940 printf("\nFetched %s.pack\n", id_str);
1941 free(id_str);
1942 id_str = NULL;
1945 /* Update references provided with the pack file. */
1946 TAILQ_FOREACH(pe, &refs, entry) {
1947 const char *refname = pe->path;
1948 struct got_object_id *id = pe->data;
1949 struct got_reference *ref;
1950 char *remote_refname;
1952 if (is_wanted_ref(&wanted_refs, refname) &&
1953 !remote->mirror_references) {
1954 error = update_wanted_ref(refname, id,
1955 remote->name, verbosity, repo);
1956 if (error)
1957 goto done;
1958 continue;
1961 if (remote->mirror_references ||
1962 strncmp("refs/tags/", refname, 10) == 0) {
1963 error = got_ref_open(&ref, repo, refname, 1);
1964 if (error) {
1965 if (error->code != GOT_ERR_NOT_REF)
1966 goto done;
1967 error = create_ref(refname, id, verbosity,
1968 repo);
1969 if (error)
1970 goto done;
1971 } else {
1972 error = update_ref(ref, id, replace_tags,
1973 verbosity, repo);
1974 unlock_err = got_ref_unlock(ref);
1975 if (unlock_err && error == NULL)
1976 error = unlock_err;
1977 got_ref_close(ref);
1978 if (error)
1979 goto done;
1981 } else if (strncmp("refs/heads/", refname, 11) == 0) {
1982 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1983 remote_name, refname + 11) == -1) {
1984 error = got_error_from_errno("asprintf");
1985 goto done;
1988 error = got_ref_open(&ref, repo, remote_refname, 1);
1989 if (error) {
1990 if (error->code != GOT_ERR_NOT_REF)
1991 goto done;
1992 error = create_ref(remote_refname, id,
1993 verbosity, repo);
1994 if (error)
1995 goto done;
1996 } else {
1997 error = update_ref(ref, id, replace_tags,
1998 verbosity, repo);
1999 unlock_err = got_ref_unlock(ref);
2000 if (unlock_err && error == NULL)
2001 error = unlock_err;
2002 got_ref_close(ref);
2003 if (error)
2004 goto done;
2007 /* Also create a local branch if none exists yet. */
2008 error = got_ref_open(&ref, repo, refname, 1);
2009 if (error) {
2010 if (error->code != GOT_ERR_NOT_REF)
2011 goto done;
2012 error = create_ref(refname, id, verbosity,
2013 repo);
2014 if (error)
2015 goto done;
2016 } else {
2017 unlock_err = got_ref_unlock(ref);
2018 if (unlock_err && error == NULL)
2019 error = unlock_err;
2020 got_ref_close(ref);
2024 if (delete_refs) {
2025 error = delete_missing_refs(&refs, &symrefs, remote,
2026 verbosity, repo);
2027 if (error)
2028 goto done;
2031 if (!remote->mirror_references) {
2032 /* Update remote HEAD reference if the server provided one. */
2033 TAILQ_FOREACH(pe, &symrefs, entry) {
2034 struct got_reference *target_ref;
2035 const char *refname = pe->path;
2036 const char *target = pe->data;
2037 char *remote_refname = NULL, *remote_target = NULL;
2039 if (strcmp(refname, GOT_REF_HEAD) != 0)
2040 continue;
2042 if (strncmp("refs/heads/", target, 11) != 0)
2043 continue;
2045 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2046 remote->name, refname) == -1) {
2047 error = got_error_from_errno("asprintf");
2048 goto done;
2050 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2051 remote->name, target + 11) == -1) {
2052 error = got_error_from_errno("asprintf");
2053 free(remote_refname);
2054 goto done;
2057 error = got_ref_open(&target_ref, repo, remote_target,
2058 0);
2059 if (error) {
2060 free(remote_refname);
2061 free(remote_target);
2062 if (error->code == GOT_ERR_NOT_REF) {
2063 error = NULL;
2064 continue;
2066 goto done;
2068 error = update_symref(remote_refname, target_ref,
2069 verbosity, repo);
2070 free(remote_refname);
2071 free(remote_target);
2072 got_ref_close(target_ref);
2073 if (error)
2074 goto done;
2077 done:
2078 if (fetchpid > 0) {
2079 if (kill(fetchpid, SIGTERM) == -1)
2080 error = got_error_from_errno("kill");
2081 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2082 error = got_error_from_errno("waitpid");
2084 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2085 error = got_error_from_errno("close");
2086 if (repo)
2087 got_repo_close(repo);
2088 if (worktree)
2089 got_worktree_close(worktree);
2090 TAILQ_FOREACH(pe, &refs, entry) {
2091 free((void *)pe->path);
2092 free(pe->data);
2094 got_pathlist_free(&refs);
2095 TAILQ_FOREACH(pe, &symrefs, entry) {
2096 free((void *)pe->path);
2097 free(pe->data);
2099 got_pathlist_free(&symrefs);
2100 got_pathlist_free(&wanted_branches);
2101 got_pathlist_free(&wanted_refs);
2102 free(id_str);
2103 free(cwd);
2104 free(repo_path);
2105 free(pack_hash);
2106 free(proto);
2107 free(host);
2108 free(port);
2109 free(server_path);
2110 free(repo_name);
2111 return error;
2115 __dead static void
2116 usage_checkout(void)
2118 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2119 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2120 exit(1);
2123 static void
2124 show_worktree_base_ref_warning(void)
2126 fprintf(stderr, "%s: warning: could not create a reference "
2127 "to the work tree's base commit; the commit could be "
2128 "garbage-collected by Git; making the repository "
2129 "writable and running 'got update' will prevent this\n",
2130 getprogname());
2133 struct got_checkout_progress_arg {
2134 const char *worktree_path;
2135 int had_base_commit_ref_error;
2138 static const struct got_error *
2139 checkout_progress(void *arg, unsigned char status, const char *path)
2141 struct got_checkout_progress_arg *a = arg;
2143 /* Base commit bump happens silently. */
2144 if (status == GOT_STATUS_BUMP_BASE)
2145 return NULL;
2147 if (status == GOT_STATUS_BASE_REF_ERR) {
2148 a->had_base_commit_ref_error = 1;
2149 return NULL;
2152 while (path[0] == '/')
2153 path++;
2155 printf("%c %s/%s\n", status, a->worktree_path, path);
2156 return NULL;
2159 static const struct got_error *
2160 check_cancelled(void *arg)
2162 if (sigint_received || sigpipe_received)
2163 return got_error(GOT_ERR_CANCELLED);
2164 return NULL;
2167 static const struct got_error *
2168 check_linear_ancestry(struct got_object_id *commit_id,
2169 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2170 struct got_repository *repo)
2172 const struct got_error *err = NULL;
2173 struct got_object_id *yca_id;
2175 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2176 commit_id, base_commit_id, repo, check_cancelled, NULL);
2177 if (err)
2178 return err;
2180 if (yca_id == NULL)
2181 return got_error(GOT_ERR_ANCESTRY);
2184 * Require a straight line of history between the target commit
2185 * and the work tree's base commit.
2187 * Non-linear situations such as this require a rebase:
2189 * (commit) D F (base_commit)
2190 * \ /
2191 * C E
2192 * \ /
2193 * B (yca)
2194 * |
2195 * A
2197 * 'got update' only handles linear cases:
2198 * Update forwards in time: A (base/yca) - B - C - D (commit)
2199 * Update backwards in time: D (base) - C - B - A (commit/yca)
2201 if (allow_forwards_in_time_only) {
2202 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2203 return got_error(GOT_ERR_ANCESTRY);
2204 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2205 got_object_id_cmp(base_commit_id, yca_id) != 0)
2206 return got_error(GOT_ERR_ANCESTRY);
2208 free(yca_id);
2209 return NULL;
2212 static const struct got_error *
2213 check_same_branch(struct got_object_id *commit_id,
2214 struct got_reference *head_ref, struct got_object_id *yca_id,
2215 struct got_repository *repo)
2217 const struct got_error *err = NULL;
2218 struct got_commit_graph *graph = NULL;
2219 struct got_object_id *head_commit_id = NULL;
2220 int is_same_branch = 0;
2222 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2223 if (err)
2224 goto done;
2226 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2227 is_same_branch = 1;
2228 goto done;
2230 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2231 is_same_branch = 1;
2232 goto done;
2235 err = got_commit_graph_open(&graph, "/", 1);
2236 if (err)
2237 goto done;
2239 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2240 check_cancelled, NULL);
2241 if (err)
2242 goto done;
2244 for (;;) {
2245 struct got_object_id *id;
2246 err = got_commit_graph_iter_next(&id, graph, repo,
2247 check_cancelled, NULL);
2248 if (err) {
2249 if (err->code == GOT_ERR_ITER_COMPLETED)
2250 err = NULL;
2251 break;
2254 if (id) {
2255 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2256 break;
2257 if (got_object_id_cmp(id, commit_id) == 0) {
2258 is_same_branch = 1;
2259 break;
2263 done:
2264 if (graph)
2265 got_commit_graph_close(graph);
2266 free(head_commit_id);
2267 if (!err && !is_same_branch)
2268 err = got_error(GOT_ERR_ANCESTRY);
2269 return err;
2272 static const struct got_error *
2273 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2275 static char msg[512];
2276 const char *branch_name;
2278 if (got_ref_is_symbolic(ref))
2279 branch_name = got_ref_get_symref_target(ref);
2280 else
2281 branch_name = got_ref_get_name(ref);
2283 if (strncmp("refs/heads/", branch_name, 11) == 0)
2284 branch_name += 11;
2286 snprintf(msg, sizeof(msg),
2287 "target commit is not contained in branch '%s'; "
2288 "the branch to use must be specified with -b; "
2289 "if necessary a new branch can be created for "
2290 "this commit with 'got branch -c %s BRANCH_NAME'",
2291 branch_name, commit_id_str);
2293 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2296 static const struct got_error *
2297 cmd_checkout(int argc, char *argv[])
2299 const struct got_error *error = NULL;
2300 struct got_repository *repo = NULL;
2301 struct got_reference *head_ref = NULL;
2302 struct got_worktree *worktree = NULL;
2303 char *repo_path = NULL;
2304 char *worktree_path = NULL;
2305 const char *path_prefix = "";
2306 const char *branch_name = GOT_REF_HEAD;
2307 char *commit_id_str = NULL;
2308 int ch, same_path_prefix, allow_nonempty = 0;
2309 struct got_pathlist_head paths;
2310 struct got_checkout_progress_arg cpa;
2312 TAILQ_INIT(&paths);
2314 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2315 switch (ch) {
2316 case 'b':
2317 branch_name = optarg;
2318 break;
2319 case 'c':
2320 commit_id_str = strdup(optarg);
2321 if (commit_id_str == NULL)
2322 return got_error_from_errno("strdup");
2323 break;
2324 case 'E':
2325 allow_nonempty = 1;
2326 break;
2327 case 'p':
2328 path_prefix = optarg;
2329 break;
2330 default:
2331 usage_checkout();
2332 /* NOTREACHED */
2336 argc -= optind;
2337 argv += optind;
2339 #ifndef PROFILE
2340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2341 "unveil", NULL) == -1)
2342 err(1, "pledge");
2343 #endif
2344 if (argc == 1) {
2345 char *cwd, *base, *dotgit;
2346 repo_path = realpath(argv[0], NULL);
2347 if (repo_path == NULL)
2348 return got_error_from_errno2("realpath", argv[0]);
2349 cwd = getcwd(NULL, 0);
2350 if (cwd == NULL) {
2351 error = got_error_from_errno("getcwd");
2352 goto done;
2354 if (path_prefix[0]) {
2355 base = basename(path_prefix);
2356 if (base == NULL) {
2357 error = got_error_from_errno2("basename",
2358 path_prefix);
2359 goto done;
2361 } else {
2362 base = basename(repo_path);
2363 if (base == NULL) {
2364 error = got_error_from_errno2("basename",
2365 repo_path);
2366 goto done;
2369 dotgit = strstr(base, ".git");
2370 if (dotgit)
2371 *dotgit = '\0';
2372 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2373 error = got_error_from_errno("asprintf");
2374 free(cwd);
2375 goto done;
2377 free(cwd);
2378 } else if (argc == 2) {
2379 repo_path = realpath(argv[0], NULL);
2380 if (repo_path == NULL) {
2381 error = got_error_from_errno2("realpath", argv[0]);
2382 goto done;
2384 worktree_path = realpath(argv[1], NULL);
2385 if (worktree_path == NULL) {
2386 if (errno != ENOENT) {
2387 error = got_error_from_errno2("realpath",
2388 argv[1]);
2389 goto done;
2391 worktree_path = strdup(argv[1]);
2392 if (worktree_path == NULL) {
2393 error = got_error_from_errno("strdup");
2394 goto done;
2397 } else
2398 usage_checkout();
2400 got_path_strip_trailing_slashes(repo_path);
2401 got_path_strip_trailing_slashes(worktree_path);
2403 error = got_repo_open(&repo, repo_path, NULL);
2404 if (error != NULL)
2405 goto done;
2407 /* Pre-create work tree path for unveil(2) */
2408 error = got_path_mkdir(worktree_path);
2409 if (error) {
2410 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2411 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2412 goto done;
2413 if (!allow_nonempty &&
2414 !got_path_dir_is_empty(worktree_path)) {
2415 error = got_error_path(worktree_path,
2416 GOT_ERR_DIR_NOT_EMPTY);
2417 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2422 if (error)
2423 goto done;
2425 error = got_ref_open(&head_ref, repo, branch_name, 0);
2426 if (error != NULL)
2427 goto done;
2429 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2430 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2431 goto done;
2433 error = got_worktree_open(&worktree, worktree_path);
2434 if (error != NULL)
2435 goto done;
2437 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2438 path_prefix);
2439 if (error != NULL)
2440 goto done;
2441 if (!same_path_prefix) {
2442 error = got_error(GOT_ERR_PATH_PREFIX);
2443 goto done;
2446 if (commit_id_str) {
2447 struct got_object_id *commit_id;
2448 error = got_repo_match_object_id(&commit_id, NULL,
2449 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2450 if (error)
2451 goto done;
2452 error = check_linear_ancestry(commit_id,
2453 got_worktree_get_base_commit_id(worktree), 0, repo);
2454 if (error != NULL) {
2455 free(commit_id);
2456 if (error->code == GOT_ERR_ANCESTRY) {
2457 error = checkout_ancestry_error(
2458 head_ref, commit_id_str);
2460 goto done;
2462 error = check_same_branch(commit_id, head_ref, NULL, repo);
2463 if (error) {
2464 if (error->code == GOT_ERR_ANCESTRY) {
2465 error = checkout_ancestry_error(
2466 head_ref, commit_id_str);
2468 goto done;
2470 error = got_worktree_set_base_commit_id(worktree, repo,
2471 commit_id);
2472 free(commit_id);
2473 if (error)
2474 goto done;
2477 error = got_pathlist_append(&paths, "", NULL);
2478 if (error)
2479 goto done;
2480 cpa.worktree_path = worktree_path;
2481 cpa.had_base_commit_ref_error = 0;
2482 error = got_worktree_checkout_files(worktree, &paths, repo,
2483 checkout_progress, &cpa, check_cancelled, NULL);
2484 if (error != NULL)
2485 goto done;
2487 printf("Now shut up and hack\n");
2488 if (cpa.had_base_commit_ref_error)
2489 show_worktree_base_ref_warning();
2490 done:
2491 got_pathlist_free(&paths);
2492 free(commit_id_str);
2493 free(repo_path);
2494 free(worktree_path);
2495 return error;
2498 struct got_update_progress_arg {
2499 int did_something;
2500 int conflicts;
2501 int obstructed;
2502 int not_updated;
2505 void
2506 print_update_progress_stats(struct got_update_progress_arg *upa)
2508 if (!upa->did_something)
2509 return;
2511 if (upa->conflicts > 0)
2512 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2513 if (upa->obstructed > 0)
2514 printf("File paths obstructed by a non-regular file: %d\n",
2515 upa->obstructed);
2516 if (upa->not_updated > 0)
2517 printf("Files not updated because of existing merge "
2518 "conflicts: %d\n", upa->not_updated);
2521 __dead static void
2522 usage_update(void)
2524 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2525 getprogname());
2526 exit(1);
2529 static const struct got_error *
2530 update_progress(void *arg, unsigned char status, const char *path)
2532 struct got_update_progress_arg *upa = arg;
2534 if (status == GOT_STATUS_EXISTS ||
2535 status == GOT_STATUS_BASE_REF_ERR)
2536 return NULL;
2538 upa->did_something = 1;
2540 /* Base commit bump happens silently. */
2541 if (status == GOT_STATUS_BUMP_BASE)
2542 return NULL;
2544 if (status == GOT_STATUS_CONFLICT)
2545 upa->conflicts++;
2546 if (status == GOT_STATUS_OBSTRUCTED)
2547 upa->obstructed++;
2548 if (status == GOT_STATUS_CANNOT_UPDATE)
2549 upa->not_updated++;
2551 while (path[0] == '/')
2552 path++;
2553 printf("%c %s\n", status, path);
2554 return NULL;
2557 static const struct got_error *
2558 switch_head_ref(struct got_reference *head_ref,
2559 struct got_object_id *commit_id, struct got_worktree *worktree,
2560 struct got_repository *repo)
2562 const struct got_error *err = NULL;
2563 char *base_id_str;
2564 int ref_has_moved = 0;
2566 /* Trivial case: switching between two different references. */
2567 if (strcmp(got_ref_get_name(head_ref),
2568 got_worktree_get_head_ref_name(worktree)) != 0) {
2569 printf("Switching work tree from %s to %s\n",
2570 got_worktree_get_head_ref_name(worktree),
2571 got_ref_get_name(head_ref));
2572 return got_worktree_set_head_ref(worktree, head_ref);
2575 err = check_linear_ancestry(commit_id,
2576 got_worktree_get_base_commit_id(worktree), 0, repo);
2577 if (err) {
2578 if (err->code != GOT_ERR_ANCESTRY)
2579 return err;
2580 ref_has_moved = 1;
2582 if (!ref_has_moved)
2583 return NULL;
2585 /* Switching to a rebased branch with the same reference name. */
2586 err = got_object_id_str(&base_id_str,
2587 got_worktree_get_base_commit_id(worktree));
2588 if (err)
2589 return err;
2590 printf("Reference %s now points at a different branch\n",
2591 got_worktree_get_head_ref_name(worktree));
2592 printf("Switching work tree from %s to %s\n", base_id_str,
2593 got_worktree_get_head_ref_name(worktree));
2594 return NULL;
2597 static const struct got_error *
2598 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2600 const struct got_error *err;
2601 int in_progress;
2603 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2604 if (err)
2605 return err;
2606 if (in_progress)
2607 return got_error(GOT_ERR_REBASING);
2609 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2610 if (err)
2611 return err;
2612 if (in_progress)
2613 return got_error(GOT_ERR_HISTEDIT_BUSY);
2615 return NULL;
2618 static const struct got_error *
2619 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2620 char *argv[], struct got_worktree *worktree)
2622 const struct got_error *err = NULL;
2623 char *path;
2624 int i;
2626 if (argc == 0) {
2627 path = strdup("");
2628 if (path == NULL)
2629 return got_error_from_errno("strdup");
2630 return got_pathlist_append(paths, path, NULL);
2633 for (i = 0; i < argc; i++) {
2634 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2635 if (err)
2636 break;
2637 err = got_pathlist_append(paths, path, NULL);
2638 if (err) {
2639 free(path);
2640 break;
2644 return err;
2647 static const struct got_error *
2648 wrap_not_worktree_error(const struct got_error *orig_err,
2649 const char *cmdname, const char *path)
2651 const struct got_error *err;
2652 struct got_repository *repo;
2653 static char msg[512];
2655 err = got_repo_open(&repo, path, NULL);
2656 if (err)
2657 return orig_err;
2659 snprintf(msg, sizeof(msg),
2660 "'got %s' needs a work tree in addition to a git repository\n"
2661 "Work trees can be checked out from this Git repository with "
2662 "'got checkout'.\n"
2663 "The got(1) manual page contains more information.", cmdname);
2664 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2665 got_repo_close(repo);
2666 return err;
2669 static const struct got_error *
2670 cmd_update(int argc, char *argv[])
2672 const struct got_error *error = NULL;
2673 struct got_repository *repo = NULL;
2674 struct got_worktree *worktree = NULL;
2675 char *worktree_path = NULL;
2676 struct got_object_id *commit_id = NULL;
2677 char *commit_id_str = NULL;
2678 const char *branch_name = NULL;
2679 struct got_reference *head_ref = NULL;
2680 struct got_pathlist_head paths;
2681 struct got_pathlist_entry *pe;
2682 int ch;
2683 struct got_update_progress_arg upa;
2685 TAILQ_INIT(&paths);
2687 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2688 switch (ch) {
2689 case 'b':
2690 branch_name = optarg;
2691 break;
2692 case 'c':
2693 commit_id_str = strdup(optarg);
2694 if (commit_id_str == NULL)
2695 return got_error_from_errno("strdup");
2696 break;
2697 default:
2698 usage_update();
2699 /* NOTREACHED */
2703 argc -= optind;
2704 argv += optind;
2706 #ifndef PROFILE
2707 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2708 "unveil", NULL) == -1)
2709 err(1, "pledge");
2710 #endif
2711 worktree_path = getcwd(NULL, 0);
2712 if (worktree_path == NULL) {
2713 error = got_error_from_errno("getcwd");
2714 goto done;
2716 error = got_worktree_open(&worktree, worktree_path);
2717 if (error) {
2718 if (error->code == GOT_ERR_NOT_WORKTREE)
2719 error = wrap_not_worktree_error(error, "update",
2720 worktree_path);
2721 goto done;
2724 error = check_rebase_or_histedit_in_progress(worktree);
2725 if (error)
2726 goto done;
2728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2729 NULL);
2730 if (error != NULL)
2731 goto done;
2733 error = apply_unveil(got_repo_get_path(repo), 0,
2734 got_worktree_get_root_path(worktree));
2735 if (error)
2736 goto done;
2738 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2739 if (error)
2740 goto done;
2742 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2743 got_worktree_get_head_ref_name(worktree), 0);
2744 if (error != NULL)
2745 goto done;
2746 if (commit_id_str == NULL) {
2747 error = got_ref_resolve(&commit_id, repo, head_ref);
2748 if (error != NULL)
2749 goto done;
2750 error = got_object_id_str(&commit_id_str, commit_id);
2751 if (error != NULL)
2752 goto done;
2753 } else {
2754 error = got_repo_match_object_id(&commit_id, NULL,
2755 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2756 free(commit_id_str);
2757 commit_id_str = NULL;
2758 if (error)
2759 goto done;
2760 error = got_object_id_str(&commit_id_str, commit_id);
2761 if (error)
2762 goto done;
2765 if (branch_name) {
2766 struct got_object_id *head_commit_id;
2767 TAILQ_FOREACH(pe, &paths, entry) {
2768 if (pe->path_len == 0)
2769 continue;
2770 error = got_error_msg(GOT_ERR_BAD_PATH,
2771 "switching between branches requires that "
2772 "the entire work tree gets updated");
2773 goto done;
2775 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2776 if (error)
2777 goto done;
2778 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2779 repo);
2780 free(head_commit_id);
2781 if (error != NULL)
2782 goto done;
2783 error = check_same_branch(commit_id, head_ref, NULL, repo);
2784 if (error)
2785 goto done;
2786 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2787 if (error)
2788 goto done;
2789 } else {
2790 error = check_linear_ancestry(commit_id,
2791 got_worktree_get_base_commit_id(worktree), 0, repo);
2792 if (error != NULL) {
2793 if (error->code == GOT_ERR_ANCESTRY)
2794 error = got_error(GOT_ERR_BRANCH_MOVED);
2795 goto done;
2797 error = check_same_branch(commit_id, head_ref, NULL, repo);
2798 if (error)
2799 goto done;
2802 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2803 commit_id) != 0) {
2804 error = got_worktree_set_base_commit_id(worktree, repo,
2805 commit_id);
2806 if (error)
2807 goto done;
2810 memset(&upa, 0, sizeof(upa));
2811 error = got_worktree_checkout_files(worktree, &paths, repo,
2812 update_progress, &upa, check_cancelled, NULL);
2813 if (error != NULL)
2814 goto done;
2816 if (upa.did_something)
2817 printf("Updated to commit %s\n", commit_id_str);
2818 else
2819 printf("Already up-to-date\n");
2820 print_update_progress_stats(&upa);
2821 done:
2822 free(worktree_path);
2823 TAILQ_FOREACH(pe, &paths, entry)
2824 free((char *)pe->path);
2825 got_pathlist_free(&paths);
2826 free(commit_id);
2827 free(commit_id_str);
2828 return error;
2831 static const struct got_error *
2832 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2833 const char *path, int diff_context, int ignore_whitespace,
2834 struct got_repository *repo)
2836 const struct got_error *err = NULL;
2837 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2839 if (blob_id1) {
2840 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2841 if (err)
2842 goto done;
2845 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2846 if (err)
2847 goto done;
2849 while (path[0] == '/')
2850 path++;
2851 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2852 ignore_whitespace, stdout);
2853 done:
2854 if (blob1)
2855 got_object_blob_close(blob1);
2856 got_object_blob_close(blob2);
2857 return err;
2860 static const struct got_error *
2861 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2862 const char *path, int diff_context, int ignore_whitespace,
2863 struct got_repository *repo)
2865 const struct got_error *err = NULL;
2866 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2867 struct got_diff_blob_output_unidiff_arg arg;
2869 if (tree_id1) {
2870 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2871 if (err)
2872 goto done;
2875 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2876 if (err)
2877 goto done;
2879 arg.diff_context = diff_context;
2880 arg.ignore_whitespace = ignore_whitespace;
2881 arg.outfile = stdout;
2882 while (path[0] == '/')
2883 path++;
2884 err = got_diff_tree(tree1, tree2, path, path, repo,
2885 got_diff_blob_output_unidiff, &arg, 1);
2886 done:
2887 if (tree1)
2888 got_object_tree_close(tree1);
2889 if (tree2)
2890 got_object_tree_close(tree2);
2891 return err;
2894 static const struct got_error *
2895 print_patch(struct got_commit_object *commit, struct got_object_id *id,
2896 const char *path, int diff_context, struct got_repository *repo)
2898 const struct got_error *err = NULL;
2899 struct got_commit_object *pcommit = NULL;
2900 char *id_str1 = NULL, *id_str2 = NULL;
2901 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
2902 struct got_object_qid *qid;
2904 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
2905 if (qid != NULL) {
2906 err = got_object_open_as_commit(&pcommit, repo,
2907 qid->id);
2908 if (err)
2909 return err;
2912 if (path && path[0] != '\0') {
2913 int obj_type;
2914 err = got_object_id_by_path(&obj_id2, repo, id, path);
2915 if (err)
2916 goto done;
2917 err = got_object_id_str(&id_str2, obj_id2);
2918 if (err) {
2919 free(obj_id2);
2920 goto done;
2922 if (pcommit) {
2923 err = got_object_id_by_path(&obj_id1, repo,
2924 qid->id, path);
2925 if (err) {
2926 free(obj_id2);
2927 goto done;
2929 err = got_object_id_str(&id_str1, obj_id1);
2930 if (err) {
2931 free(obj_id2);
2932 goto done;
2935 err = got_object_get_type(&obj_type, repo, obj_id2);
2936 if (err) {
2937 free(obj_id2);
2938 goto done;
2940 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2941 switch (obj_type) {
2942 case GOT_OBJ_TYPE_BLOB:
2943 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
2944 0, repo);
2945 break;
2946 case GOT_OBJ_TYPE_TREE:
2947 err = diff_trees(obj_id1, obj_id2, path, diff_context,
2948 0, repo);
2949 break;
2950 default:
2951 err = got_error(GOT_ERR_OBJ_TYPE);
2952 break;
2954 free(obj_id1);
2955 free(obj_id2);
2956 } else {
2957 obj_id2 = got_object_commit_get_tree_id(commit);
2958 err = got_object_id_str(&id_str2, obj_id2);
2959 if (err)
2960 goto done;
2961 obj_id1 = got_object_commit_get_tree_id(pcommit);
2962 err = got_object_id_str(&id_str1, obj_id1);
2963 if (err)
2964 goto done;
2965 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
2966 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
2968 done:
2969 free(id_str1);
2970 free(id_str2);
2971 if (pcommit)
2972 got_object_commit_close(pcommit);
2973 return err;
2976 static char *
2977 get_datestr(time_t *time, char *datebuf)
2979 struct tm mytm, *tm;
2980 char *p, *s;
2982 tm = gmtime_r(time, &mytm);
2983 if (tm == NULL)
2984 return NULL;
2985 s = asctime_r(tm, datebuf);
2986 if (s == NULL)
2987 return NULL;
2988 p = strchr(s, '\n');
2989 if (p)
2990 *p = '\0';
2991 return s;
2994 static const struct got_error *
2995 match_logmsg(int *have_match, struct got_object_id *id,
2996 struct got_commit_object *commit, regex_t *regex)
2998 const struct got_error *err = NULL;
2999 regmatch_t regmatch;
3000 char *id_str = NULL, *logmsg = NULL;
3002 *have_match = 0;
3004 err = got_object_id_str(&id_str, id);
3005 if (err)
3006 return err;
3008 err = got_object_commit_get_logmsg(&logmsg, commit);
3009 if (err)
3010 goto done;
3012 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3013 *have_match = 1;
3014 done:
3015 free(id_str);
3016 free(logmsg);
3017 return err;
3020 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3022 static const struct got_error *
3023 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3024 struct got_repository *repo, const char *path, int show_patch,
3025 int diff_context, struct got_reflist_head *refs)
3027 const struct got_error *err = NULL;
3028 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3029 char datebuf[26];
3030 time_t committer_time;
3031 const char *author, *committer;
3032 char *refs_str = NULL;
3033 struct got_reflist_entry *re;
3035 SIMPLEQ_FOREACH(re, refs, entry) {
3036 char *s;
3037 const char *name;
3038 struct got_tag_object *tag = NULL;
3039 int cmp;
3041 name = got_ref_get_name(re->ref);
3042 if (strcmp(name, GOT_REF_HEAD) == 0)
3043 continue;
3044 if (strncmp(name, "refs/", 5) == 0)
3045 name += 5;
3046 if (strncmp(name, "got/", 4) == 0)
3047 continue;
3048 if (strncmp(name, "heads/", 6) == 0)
3049 name += 6;
3050 if (strncmp(name, "remotes/", 8) == 0)
3051 name += 8;
3052 if (strncmp(name, "tags/", 5) == 0) {
3053 err = got_object_open_as_tag(&tag, repo, re->id);
3054 if (err) {
3055 if (err->code != GOT_ERR_OBJ_TYPE)
3056 return err;
3057 /* Ref points at something other than a tag. */
3058 err = NULL;
3059 tag = NULL;
3062 cmp = got_object_id_cmp(tag ?
3063 got_object_tag_get_object_id(tag) : re->id, id);
3064 if (tag)
3065 got_object_tag_close(tag);
3066 if (cmp != 0)
3067 continue;
3068 s = refs_str;
3069 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3070 name) == -1) {
3071 err = got_error_from_errno("asprintf");
3072 free(s);
3073 return err;
3075 free(s);
3077 err = got_object_id_str(&id_str, id);
3078 if (err)
3079 return err;
3081 printf(GOT_COMMIT_SEP_STR);
3082 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3083 refs_str ? refs_str : "", refs_str ? ")" : "");
3084 free(id_str);
3085 id_str = NULL;
3086 free(refs_str);
3087 refs_str = NULL;
3088 printf("from: %s\n", got_object_commit_get_author(commit));
3089 committer_time = got_object_commit_get_committer_time(commit);
3090 datestr = get_datestr(&committer_time, datebuf);
3091 if (datestr)
3092 printf("date: %s UTC\n", datestr);
3093 author = got_object_commit_get_author(commit);
3094 committer = got_object_commit_get_committer(commit);
3095 if (strcmp(author, committer) != 0)
3096 printf("via: %s\n", committer);
3097 if (got_object_commit_get_nparents(commit) > 1) {
3098 const struct got_object_id_queue *parent_ids;
3099 struct got_object_qid *qid;
3100 int n = 1;
3101 parent_ids = got_object_commit_get_parent_ids(commit);
3102 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3103 err = got_object_id_str(&id_str, qid->id);
3104 if (err)
3105 return err;
3106 printf("parent %d: %s\n", n++, id_str);
3107 free(id_str);
3111 err = got_object_commit_get_logmsg(&logmsg0, commit);
3112 if (err)
3113 return err;
3115 logmsg = logmsg0;
3116 do {
3117 line = strsep(&logmsg, "\n");
3118 if (line)
3119 printf(" %s\n", line);
3120 } while (line);
3121 free(logmsg0);
3123 if (show_patch) {
3124 err = print_patch(commit, id, path, diff_context, repo);
3125 if (err == 0)
3126 printf("\n");
3129 if (fflush(stdout) != 0 && err == NULL)
3130 err = got_error_from_errno("fflush");
3131 return err;
3134 static const struct got_error *
3135 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3136 struct got_repository *repo, const char *path, int show_patch,
3137 const char *search_pattern, int diff_context, int limit, int log_branches,
3138 struct got_reflist_head *refs)
3140 const struct got_error *err;
3141 struct got_commit_graph *graph;
3142 regex_t regex;
3143 int have_match;
3145 if (search_pattern && regcomp(&regex, search_pattern,
3146 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3147 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3149 err = got_commit_graph_open(&graph, path, !log_branches);
3150 if (err)
3151 return err;
3152 err = got_commit_graph_iter_start(graph, root_id, repo,
3153 check_cancelled, NULL);
3154 if (err)
3155 goto done;
3156 for (;;) {
3157 struct got_commit_object *commit;
3158 struct got_object_id *id;
3160 if (sigint_received || sigpipe_received)
3161 break;
3163 err = got_commit_graph_iter_next(&id, graph, repo,
3164 check_cancelled, NULL);
3165 if (err) {
3166 if (err->code == GOT_ERR_ITER_COMPLETED)
3167 err = NULL;
3168 break;
3170 if (id == NULL)
3171 break;
3173 err = got_object_open_as_commit(&commit, repo, id);
3174 if (err)
3175 break;
3177 if (search_pattern) {
3178 err = match_logmsg(&have_match, id, commit, &regex);
3179 if (err) {
3180 got_object_commit_close(commit);
3181 break;
3183 if (have_match == 0) {
3184 got_object_commit_close(commit);
3185 continue;
3189 err = print_commit(commit, id, repo, path, show_patch,
3190 diff_context, refs);
3191 got_object_commit_close(commit);
3192 if (err || (limit && --limit == 0) ||
3193 (end_id != NULL && got_object_id_cmp(id, end_id) == 0))
3194 break;
3196 done:
3197 if (search_pattern)
3198 regfree(&regex);
3199 got_commit_graph_close(graph);
3200 return err;
3203 __dead static void
3204 usage_log(void)
3206 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3207 "[-p] [-x commit] [-s search-pattern] [-r repository-path] "
3208 "[path]\n", getprogname());
3209 exit(1);
3212 static int
3213 get_default_log_limit(void)
3215 const char *got_default_log_limit;
3216 long long n;
3217 const char *errstr;
3219 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3220 if (got_default_log_limit == NULL)
3221 return 0;
3222 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3223 if (errstr != NULL)
3224 return 0;
3225 return n;
3228 static const struct got_error *
3229 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3230 struct got_repository *repo)
3232 const struct got_error *err = NULL;
3233 struct got_reference *ref;
3235 *id = NULL;
3237 err = got_ref_open(&ref, repo, commit_arg, 0);
3238 if (err == NULL) {
3239 int obj_type;
3240 err = got_ref_resolve(id, repo, ref);
3241 got_ref_close(ref);
3242 if (err)
3243 return err;
3244 err = got_object_get_type(&obj_type, repo, *id);
3245 if (err)
3246 return err;
3247 if (obj_type == GOT_OBJ_TYPE_TAG) {
3248 struct got_tag_object *tag;
3249 err = got_object_open_as_tag(&tag, repo, *id);
3250 if (err)
3251 return err;
3252 if (got_object_tag_get_object_type(tag) !=
3253 GOT_OBJ_TYPE_COMMIT) {
3254 got_object_tag_close(tag);
3255 return got_error(GOT_ERR_OBJ_TYPE);
3257 free(*id);
3258 *id = got_object_id_dup(
3259 got_object_tag_get_object_id(tag));
3260 if (*id == NULL)
3261 err = got_error_from_errno(
3262 "got_object_id_dup");
3263 got_object_tag_close(tag);
3264 if (err)
3265 return err;
3266 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3267 return got_error(GOT_ERR_OBJ_TYPE);
3268 } else {
3269 err = got_repo_match_object_id_prefix(id, commit_arg,
3270 GOT_OBJ_TYPE_COMMIT, repo);
3273 return err;
3276 static const struct got_error *
3277 cmd_log(int argc, char *argv[])
3279 const struct got_error *error;
3280 struct got_repository *repo = NULL;
3281 struct got_worktree *worktree = NULL;
3282 struct got_object_id *start_id = NULL, *end_id = NULL;
3283 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3284 const char *start_commit = NULL, *end_commit = NULL;
3285 const char *search_pattern = NULL;
3286 int diff_context = -1, ch;
3287 int show_patch = 0, limit = 0, log_branches = 0;
3288 const char *errstr;
3289 struct got_reflist_head refs;
3291 SIMPLEQ_INIT(&refs);
3293 #ifndef PROFILE
3294 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3295 NULL)
3296 == -1)
3297 err(1, "pledge");
3298 #endif
3300 limit = get_default_log_limit();
3302 while ((ch = getopt(argc, argv, "bpc:C:l:r:s:x:")) != -1) {
3303 switch (ch) {
3304 case 'p':
3305 show_patch = 1;
3306 break;
3307 case 'c':
3308 start_commit = optarg;
3309 break;
3310 case 'C':
3311 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3312 &errstr);
3313 if (errstr != NULL)
3314 err(1, "-C option %s", errstr);
3315 break;
3316 case 'l':
3317 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3318 if (errstr != NULL)
3319 err(1, "-l option %s", errstr);
3320 break;
3321 case 'b':
3322 log_branches = 1;
3323 break;
3324 case 'r':
3325 repo_path = realpath(optarg, NULL);
3326 if (repo_path == NULL)
3327 return got_error_from_errno2("realpath",
3328 optarg);
3329 got_path_strip_trailing_slashes(repo_path);
3330 break;
3331 case 's':
3332 search_pattern = optarg;
3333 break;
3334 case 'x':
3335 end_commit = optarg;
3336 break;
3337 default:
3338 usage_log();
3339 /* NOTREACHED */
3343 argc -= optind;
3344 argv += optind;
3346 if (diff_context == -1)
3347 diff_context = 3;
3348 else if (!show_patch)
3349 errx(1, "-C reguires -p");
3351 cwd = getcwd(NULL, 0);
3352 if (cwd == NULL) {
3353 error = got_error_from_errno("getcwd");
3354 goto done;
3357 error = got_worktree_open(&worktree, cwd);
3358 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3359 goto done;
3360 error = NULL;
3362 if (argc == 0) {
3363 path = strdup("");
3364 if (path == NULL) {
3365 error = got_error_from_errno("strdup");
3366 goto done;
3368 } else if (argc == 1) {
3369 if (worktree) {
3370 error = got_worktree_resolve_path(&path, worktree,
3371 argv[0]);
3372 if (error)
3373 goto done;
3374 } else {
3375 path = strdup(argv[0]);
3376 if (path == NULL) {
3377 error = got_error_from_errno("strdup");
3378 goto done;
3381 } else
3382 usage_log();
3384 if (repo_path == NULL) {
3385 repo_path = worktree ?
3386 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3388 if (repo_path == NULL) {
3389 error = got_error_from_errno("strdup");
3390 goto done;
3393 error = got_repo_open(&repo, repo_path, NULL);
3394 if (error != NULL)
3395 goto done;
3397 error = apply_unveil(got_repo_get_path(repo), 1,
3398 worktree ? got_worktree_get_root_path(worktree) : NULL);
3399 if (error)
3400 goto done;
3402 if (start_commit == NULL) {
3403 struct got_reference *head_ref;
3404 struct got_commit_object *commit = NULL;
3405 error = got_ref_open(&head_ref, repo,
3406 worktree ? got_worktree_get_head_ref_name(worktree)
3407 : GOT_REF_HEAD, 0);
3408 if (error != NULL)
3409 goto done;
3410 error = got_ref_resolve(&start_id, repo, head_ref);
3411 got_ref_close(head_ref);
3412 if (error != NULL)
3413 goto done;
3414 error = got_object_open_as_commit(&commit, repo,
3415 start_id);
3416 if (error != NULL)
3417 goto done;
3418 got_object_commit_close(commit);
3419 } else {
3420 error = resolve_commit_arg(&start_id, start_commit, repo);
3421 if (error != NULL)
3422 goto done;
3424 if (end_commit != NULL) {
3425 error = resolve_commit_arg(&end_id, end_commit, repo);
3426 if (error != NULL)
3427 goto done;
3430 if (worktree) {
3431 const char *prefix = got_worktree_get_path_prefix(worktree);
3432 char *p;
3433 if (asprintf(&p, "%s%s%s", prefix,
3434 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3435 error = got_error_from_errno("asprintf");
3436 goto done;
3438 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3439 free(p);
3440 } else
3441 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3442 if (error != NULL)
3443 goto done;
3444 if (in_repo_path) {
3445 free(path);
3446 path = in_repo_path;
3449 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3450 if (error)
3451 goto done;
3453 error = print_commits(start_id, end_id, repo, path, show_patch,
3454 search_pattern, diff_context, limit, log_branches, &refs);
3455 done:
3456 free(path);
3457 free(repo_path);
3458 free(cwd);
3459 if (worktree)
3460 got_worktree_close(worktree);
3461 if (repo) {
3462 const struct got_error *repo_error;
3463 repo_error = got_repo_close(repo);
3464 if (error == NULL)
3465 error = repo_error;
3467 got_ref_list_free(&refs);
3468 return error;
3471 __dead static void
3472 usage_diff(void)
3474 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3475 "[-w] [object1 object2 | path]\n", getprogname());
3476 exit(1);
3479 struct print_diff_arg {
3480 struct got_repository *repo;
3481 struct got_worktree *worktree;
3482 int diff_context;
3483 const char *id_str;
3484 int header_shown;
3485 int diff_staged;
3486 int ignore_whitespace;
3489 static const struct got_error *
3490 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3491 const char *path, struct got_object_id *blob_id,
3492 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3493 int dirfd, const char *de_name)
3495 struct print_diff_arg *a = arg;
3496 const struct got_error *err = NULL;
3497 struct got_blob_object *blob1 = NULL;
3498 int fd = -1;
3499 FILE *f2 = NULL;
3500 char *abspath = NULL, *label1 = NULL;
3501 struct stat sb;
3503 if (a->diff_staged) {
3504 if (staged_status != GOT_STATUS_MODIFY &&
3505 staged_status != GOT_STATUS_ADD &&
3506 staged_status != GOT_STATUS_DELETE)
3507 return NULL;
3508 } else {
3509 if (staged_status == GOT_STATUS_DELETE)
3510 return NULL;
3511 if (status == GOT_STATUS_NONEXISTENT)
3512 return got_error_set_errno(ENOENT, path);
3513 if (status != GOT_STATUS_MODIFY &&
3514 status != GOT_STATUS_ADD &&
3515 status != GOT_STATUS_DELETE &&
3516 status != GOT_STATUS_CONFLICT)
3517 return NULL;
3520 if (!a->header_shown) {
3521 printf("diff %s %s%s\n", a->id_str,
3522 got_worktree_get_root_path(a->worktree),
3523 a->diff_staged ? " (staged changes)" : "");
3524 a->header_shown = 1;
3527 if (a->diff_staged) {
3528 const char *label1 = NULL, *label2 = NULL;
3529 switch (staged_status) {
3530 case GOT_STATUS_MODIFY:
3531 label1 = path;
3532 label2 = path;
3533 break;
3534 case GOT_STATUS_ADD:
3535 label2 = path;
3536 break;
3537 case GOT_STATUS_DELETE:
3538 label1 = path;
3539 break;
3540 default:
3541 return got_error(GOT_ERR_FILE_STATUS);
3543 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3544 label1, label2, a->diff_context, a->ignore_whitespace,
3545 a->repo, stdout);
3548 if (staged_status == GOT_STATUS_ADD ||
3549 staged_status == GOT_STATUS_MODIFY) {
3550 char *id_str;
3551 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3552 8192);
3553 if (err)
3554 goto done;
3555 err = got_object_id_str(&id_str, staged_blob_id);
3556 if (err)
3557 goto done;
3558 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3559 err = got_error_from_errno("asprintf");
3560 free(id_str);
3561 goto done;
3563 free(id_str);
3564 } else if (status != GOT_STATUS_ADD) {
3565 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3566 if (err)
3567 goto done;
3570 if (status != GOT_STATUS_DELETE) {
3571 if (asprintf(&abspath, "%s/%s",
3572 got_worktree_get_root_path(a->worktree), path) == -1) {
3573 err = got_error_from_errno("asprintf");
3574 goto done;
3577 if (dirfd != -1) {
3578 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3579 if (fd == -1) {
3580 err = got_error_from_errno2("openat", abspath);
3581 goto done;
3583 } else {
3584 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3585 if (fd == -1) {
3586 err = got_error_from_errno2("open", abspath);
3587 goto done;
3590 if (fstat(fd, &sb) == -1) {
3591 err = got_error_from_errno2("fstat", abspath);
3592 goto done;
3594 f2 = fdopen(fd, "r");
3595 if (f2 == NULL) {
3596 err = got_error_from_errno2("fdopen", abspath);
3597 goto done;
3599 fd = -1;
3600 } else
3601 sb.st_size = 0;
3603 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3604 a->diff_context, a->ignore_whitespace, stdout);
3605 done:
3606 if (blob1)
3607 got_object_blob_close(blob1);
3608 if (f2 && fclose(f2) == EOF && err == NULL)
3609 err = got_error_from_errno("fclose");
3610 if (fd != -1 && close(fd) == -1 && err == NULL)
3611 err = got_error_from_errno("close");
3612 free(abspath);
3613 return err;
3616 static const struct got_error *
3617 cmd_diff(int argc, char *argv[])
3619 const struct got_error *error;
3620 struct got_repository *repo = NULL;
3621 struct got_worktree *worktree = NULL;
3622 char *cwd = NULL, *repo_path = NULL;
3623 struct got_object_id *id1 = NULL, *id2 = NULL;
3624 const char *id_str1 = NULL, *id_str2 = NULL;
3625 char *label1 = NULL, *label2 = NULL;
3626 int type1, type2;
3627 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3628 const char *errstr;
3629 char *path = NULL;
3631 #ifndef PROFILE
3632 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3633 NULL) == -1)
3634 err(1, "pledge");
3635 #endif
3637 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3638 switch (ch) {
3639 case 'C':
3640 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3641 &errstr);
3642 if (errstr != NULL)
3643 err(1, "-C option %s", errstr);
3644 break;
3645 case 'r':
3646 repo_path = realpath(optarg, NULL);
3647 if (repo_path == NULL)
3648 return got_error_from_errno2("realpath",
3649 optarg);
3650 got_path_strip_trailing_slashes(repo_path);
3651 break;
3652 case 's':
3653 diff_staged = 1;
3654 break;
3655 case 'w':
3656 ignore_whitespace = 1;
3657 break;
3658 default:
3659 usage_diff();
3660 /* NOTREACHED */
3664 argc -= optind;
3665 argv += optind;
3667 cwd = getcwd(NULL, 0);
3668 if (cwd == NULL) {
3669 error = got_error_from_errno("getcwd");
3670 goto done;
3672 if (argc <= 1) {
3673 if (repo_path)
3674 errx(1,
3675 "-r option can't be used when diffing a work tree");
3676 error = got_worktree_open(&worktree, cwd);
3677 if (error) {
3678 if (error->code == GOT_ERR_NOT_WORKTREE)
3679 error = wrap_not_worktree_error(error, "diff",
3680 cwd);
3681 goto done;
3683 repo_path = strdup(got_worktree_get_repo_path(worktree));
3684 if (repo_path == NULL) {
3685 error = got_error_from_errno("strdup");
3686 goto done;
3688 if (argc == 1) {
3689 error = got_worktree_resolve_path(&path, worktree,
3690 argv[0]);
3691 if (error)
3692 goto done;
3693 } else {
3694 path = strdup("");
3695 if (path == NULL) {
3696 error = got_error_from_errno("strdup");
3697 goto done;
3700 } else if (argc == 2) {
3701 if (diff_staged)
3702 errx(1, "-s option can't be used when diffing "
3703 "objects in repository");
3704 id_str1 = argv[0];
3705 id_str2 = argv[1];
3706 if (repo_path == NULL) {
3707 error = got_worktree_open(&worktree, cwd);
3708 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3709 goto done;
3710 if (worktree) {
3711 repo_path = strdup(
3712 got_worktree_get_repo_path(worktree));
3713 if (repo_path == NULL) {
3714 error = got_error_from_errno("strdup");
3715 goto done;
3717 } else {
3718 repo_path = strdup(cwd);
3719 if (repo_path == NULL) {
3720 error = got_error_from_errno("strdup");
3721 goto done;
3725 } else
3726 usage_diff();
3728 error = got_repo_open(&repo, repo_path, NULL);
3729 free(repo_path);
3730 if (error != NULL)
3731 goto done;
3733 error = apply_unveil(got_repo_get_path(repo), 1,
3734 worktree ? got_worktree_get_root_path(worktree) : NULL);
3735 if (error)
3736 goto done;
3738 if (argc <= 1) {
3739 struct print_diff_arg arg;
3740 struct got_pathlist_head paths;
3741 char *id_str;
3743 TAILQ_INIT(&paths);
3745 error = got_object_id_str(&id_str,
3746 got_worktree_get_base_commit_id(worktree));
3747 if (error)
3748 goto done;
3749 arg.repo = repo;
3750 arg.worktree = worktree;
3751 arg.diff_context = diff_context;
3752 arg.id_str = id_str;
3753 arg.header_shown = 0;
3754 arg.diff_staged = diff_staged;
3755 arg.ignore_whitespace = ignore_whitespace;
3757 error = got_pathlist_append(&paths, path, NULL);
3758 if (error)
3759 goto done;
3761 error = got_worktree_status(worktree, &paths, repo, print_diff,
3762 &arg, check_cancelled, NULL);
3763 free(id_str);
3764 got_pathlist_free(&paths);
3765 goto done;
3768 error = got_repo_match_object_id(&id1, &label1, id_str1,
3769 GOT_OBJ_TYPE_ANY, 1, repo);
3770 if (error)
3771 goto done;
3773 error = got_repo_match_object_id(&id2, &label2, id_str2,
3774 GOT_OBJ_TYPE_ANY, 1, repo);
3775 if (error)
3776 goto done;
3778 error = got_object_get_type(&type1, repo, id1);
3779 if (error)
3780 goto done;
3782 error = got_object_get_type(&type2, repo, id2);
3783 if (error)
3784 goto done;
3786 if (type1 != type2) {
3787 error = got_error(GOT_ERR_OBJ_TYPE);
3788 goto done;
3791 switch (type1) {
3792 case GOT_OBJ_TYPE_BLOB:
3793 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
3794 diff_context, ignore_whitespace, repo, stdout);
3795 break;
3796 case GOT_OBJ_TYPE_TREE:
3797 error = got_diff_objects_as_trees(id1, id2, "", "",
3798 diff_context, ignore_whitespace, repo, stdout);
3799 break;
3800 case GOT_OBJ_TYPE_COMMIT:
3801 printf("diff %s %s\n", label1, label2);
3802 error = got_diff_objects_as_commits(id1, id2, diff_context,
3803 ignore_whitespace, repo, stdout);
3804 break;
3805 default:
3806 error = got_error(GOT_ERR_OBJ_TYPE);
3808 done:
3809 free(label1);
3810 free(label2);
3811 free(id1);
3812 free(id2);
3813 free(path);
3814 if (worktree)
3815 got_worktree_close(worktree);
3816 if (repo) {
3817 const struct got_error *repo_error;
3818 repo_error = got_repo_close(repo);
3819 if (error == NULL)
3820 error = repo_error;
3822 return error;
3825 __dead static void
3826 usage_blame(void)
3828 fprintf(stderr,
3829 "usage: %s blame [-c commit] [-r repository-path] path\n",
3830 getprogname());
3831 exit(1);
3834 struct blame_line {
3835 int annotated;
3836 char *id_str;
3837 char *committer;
3838 char datebuf[11]; /* YYYY-MM-DD + NUL */
3841 struct blame_cb_args {
3842 struct blame_line *lines;
3843 int nlines;
3844 int nlines_prec;
3845 int lineno_cur;
3846 off_t *line_offsets;
3847 FILE *f;
3848 struct got_repository *repo;
3851 static const struct got_error *
3852 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
3854 const struct got_error *err = NULL;
3855 struct blame_cb_args *a = arg;
3856 struct blame_line *bline;
3857 char *line = NULL;
3858 size_t linesize = 0;
3859 struct got_commit_object *commit = NULL;
3860 off_t offset;
3861 struct tm tm;
3862 time_t committer_time;
3864 if (nlines != a->nlines ||
3865 (lineno != -1 && lineno < 1) || lineno > a->nlines)
3866 return got_error(GOT_ERR_RANGE);
3868 if (sigint_received)
3869 return got_error(GOT_ERR_ITER_COMPLETED);
3871 if (lineno == -1)
3872 return NULL; /* no change in this commit */
3874 /* Annotate this line. */
3875 bline = &a->lines[lineno - 1];
3876 if (bline->annotated)
3877 return NULL;
3878 err = got_object_id_str(&bline->id_str, id);
3879 if (err)
3880 return err;
3882 err = got_object_open_as_commit(&commit, a->repo, id);
3883 if (err)
3884 goto done;
3886 bline->committer = strdup(got_object_commit_get_committer(commit));
3887 if (bline->committer == NULL) {
3888 err = got_error_from_errno("strdup");
3889 goto done;
3892 committer_time = got_object_commit_get_committer_time(commit);
3893 if (localtime_r(&committer_time, &tm) == NULL)
3894 return got_error_from_errno("localtime_r");
3895 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
3896 &tm) >= sizeof(bline->datebuf)) {
3897 err = got_error(GOT_ERR_NO_SPACE);
3898 goto done;
3900 bline->annotated = 1;
3902 /* Print lines annotated so far. */
3903 bline = &a->lines[a->lineno_cur - 1];
3904 if (!bline->annotated)
3905 goto done;
3907 offset = a->line_offsets[a->lineno_cur - 1];
3908 if (fseeko(a->f, offset, SEEK_SET) == -1) {
3909 err = got_error_from_errno("fseeko");
3910 goto done;
3913 while (bline->annotated) {
3914 char *smallerthan, *at, *nl, *committer;
3915 size_t len;
3917 if (getline(&line, &linesize, a->f) == -1) {
3918 if (ferror(a->f))
3919 err = got_error_from_errno("getline");
3920 break;
3923 committer = bline->committer;
3924 smallerthan = strchr(committer, '<');
3925 if (smallerthan && smallerthan[1] != '\0')
3926 committer = smallerthan + 1;
3927 at = strchr(committer, '@');
3928 if (at)
3929 *at = '\0';
3930 len = strlen(committer);
3931 if (len >= 9)
3932 committer[8] = '\0';
3934 nl = strchr(line, '\n');
3935 if (nl)
3936 *nl = '\0';
3937 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
3938 bline->id_str, bline->datebuf, committer, line);
3940 a->lineno_cur++;
3941 bline = &a->lines[a->lineno_cur - 1];
3943 done:
3944 if (commit)
3945 got_object_commit_close(commit);
3946 free(line);
3947 return err;
3950 static const struct got_error *
3951 cmd_blame(int argc, char *argv[])
3953 const struct got_error *error;
3954 struct got_repository *repo = NULL;
3955 struct got_worktree *worktree = NULL;
3956 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
3957 struct got_object_id *obj_id = NULL;
3958 struct got_object_id *commit_id = NULL;
3959 struct got_blob_object *blob = NULL;
3960 char *commit_id_str = NULL;
3961 struct blame_cb_args bca;
3962 int ch, obj_type, i;
3963 size_t filesize;
3965 memset(&bca, 0, sizeof(bca));
3967 #ifndef PROFILE
3968 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3969 NULL) == -1)
3970 err(1, "pledge");
3971 #endif
3973 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
3974 switch (ch) {
3975 case 'c':
3976 commit_id_str = optarg;
3977 break;
3978 case 'r':
3979 repo_path = realpath(optarg, NULL);
3980 if (repo_path == NULL)
3981 return got_error_from_errno2("realpath",
3982 optarg);
3983 got_path_strip_trailing_slashes(repo_path);
3984 break;
3985 default:
3986 usage_blame();
3987 /* NOTREACHED */
3991 argc -= optind;
3992 argv += optind;
3994 if (argc == 1)
3995 path = argv[0];
3996 else
3997 usage_blame();
3999 cwd = getcwd(NULL, 0);
4000 if (cwd == NULL) {
4001 error = got_error_from_errno("getcwd");
4002 goto done;
4004 if (repo_path == NULL) {
4005 error = got_worktree_open(&worktree, cwd);
4006 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4007 goto done;
4008 else
4009 error = NULL;
4010 if (worktree) {
4011 repo_path =
4012 strdup(got_worktree_get_repo_path(worktree));
4013 if (repo_path == NULL) {
4014 error = got_error_from_errno("strdup");
4015 if (error)
4016 goto done;
4018 } else {
4019 repo_path = strdup(cwd);
4020 if (repo_path == NULL) {
4021 error = got_error_from_errno("strdup");
4022 goto done;
4027 error = got_repo_open(&repo, repo_path, NULL);
4028 if (error != NULL)
4029 goto done;
4031 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4032 if (error)
4033 goto done;
4035 if (worktree) {
4036 const char *prefix = got_worktree_get_path_prefix(worktree);
4037 char *p, *worktree_subdir = cwd +
4038 strlen(got_worktree_get_root_path(worktree));
4039 if (asprintf(&p, "%s%s%s%s%s",
4040 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4041 worktree_subdir, worktree_subdir[0] ? "/" : "",
4042 path) == -1) {
4043 error = got_error_from_errno("asprintf");
4044 goto done;
4046 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4047 free(p);
4048 } else {
4049 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4051 if (error)
4052 goto done;
4054 if (commit_id_str == NULL) {
4055 struct got_reference *head_ref;
4056 error = got_ref_open(&head_ref, repo, worktree ?
4057 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4058 if (error != NULL)
4059 goto done;
4060 error = got_ref_resolve(&commit_id, repo, head_ref);
4061 got_ref_close(head_ref);
4062 if (error != NULL)
4063 goto done;
4064 } else {
4065 error = got_repo_match_object_id(&commit_id, NULL,
4066 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4067 if (error)
4068 goto done;
4071 error = got_object_id_by_path(&obj_id, repo, commit_id, in_repo_path);
4072 if (error)
4073 goto done;
4075 error = got_object_get_type(&obj_type, repo, obj_id);
4076 if (error)
4077 goto done;
4079 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4080 error = got_error(GOT_ERR_OBJ_TYPE);
4081 goto done;
4084 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4085 if (error)
4086 goto done;
4087 bca.f = got_opentemp();
4088 if (bca.f == NULL) {
4089 error = got_error_from_errno("got_opentemp");
4090 goto done;
4092 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4093 &bca.line_offsets, bca.f, blob);
4094 if (error || bca.nlines == 0)
4095 goto done;
4097 /* Don't include \n at EOF in the blame line count. */
4098 if (bca.line_offsets[bca.nlines - 1] == filesize)
4099 bca.nlines--;
4101 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4102 if (bca.lines == NULL) {
4103 error = got_error_from_errno("calloc");
4104 goto done;
4106 bca.lineno_cur = 1;
4107 bca.nlines_prec = 0;
4108 i = bca.nlines;
4109 while (i > 0) {
4110 i /= 10;
4111 bca.nlines_prec++;
4113 bca.repo = repo;
4115 error = got_blame(in_repo_path, commit_id, repo, blame_cb, &bca,
4116 check_cancelled, NULL);
4117 done:
4118 free(in_repo_path);
4119 free(repo_path);
4120 free(cwd);
4121 free(commit_id);
4122 free(obj_id);
4123 if (blob)
4124 got_object_blob_close(blob);
4125 if (worktree)
4126 got_worktree_close(worktree);
4127 if (repo) {
4128 const struct got_error *repo_error;
4129 repo_error = got_repo_close(repo);
4130 if (error == NULL)
4131 error = repo_error;
4133 if (bca.lines) {
4134 for (i = 0; i < bca.nlines; i++) {
4135 struct blame_line *bline = &bca.lines[i];
4136 free(bline->id_str);
4137 free(bline->committer);
4139 free(bca.lines);
4141 free(bca.line_offsets);
4142 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4143 error = got_error_from_errno("fclose");
4144 return error;
4147 __dead static void
4148 usage_tree(void)
4150 fprintf(stderr,
4151 "usage: %s tree [-c commit] [-r repository-path] [-iR] path\n",
4152 getprogname());
4153 exit(1);
4156 static void
4157 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4158 const char *root_path)
4160 int is_root_path = (strcmp(path, root_path) == 0);
4161 const char *modestr = "";
4162 mode_t mode = got_tree_entry_get_mode(te);
4164 path += strlen(root_path);
4165 while (path[0] == '/')
4166 path++;
4168 if (got_object_tree_entry_is_submodule(te))
4169 modestr = "$";
4170 else if (S_ISLNK(mode))
4171 modestr = "@";
4172 else if (S_ISDIR(mode))
4173 modestr = "/";
4174 else if (mode & S_IXUSR)
4175 modestr = "*";
4177 printf("%s%s%s%s%s\n", id ? id : "", path,
4178 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr);
4181 static const struct got_error *
4182 print_tree(const char *path, struct got_object_id *commit_id,
4183 int show_ids, int recurse, const char *root_path,
4184 struct got_repository *repo)
4186 const struct got_error *err = NULL;
4187 struct got_object_id *tree_id = NULL;
4188 struct got_tree_object *tree = NULL;
4189 int nentries, i;
4191 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4192 if (err)
4193 goto done;
4195 err = got_object_open_as_tree(&tree, repo, tree_id);
4196 if (err)
4197 goto done;
4198 nentries = got_object_tree_get_nentries(tree);
4199 for (i = 0; i < nentries; i++) {
4200 struct got_tree_entry *te;
4201 char *id = NULL;
4203 if (sigint_received || sigpipe_received)
4204 break;
4206 te = got_object_tree_get_entry(tree, i);
4207 if (show_ids) {
4208 char *id_str;
4209 err = got_object_id_str(&id_str,
4210 got_tree_entry_get_id(te));
4211 if (err)
4212 goto done;
4213 if (asprintf(&id, "%s ", id_str) == -1) {
4214 err = got_error_from_errno("asprintf");
4215 free(id_str);
4216 goto done;
4218 free(id_str);
4220 print_entry(te, id, path, root_path);
4221 free(id);
4223 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4224 char *child_path;
4225 if (asprintf(&child_path, "%s%s%s", path,
4226 path[0] == '/' && path[1] == '\0' ? "" : "/",
4227 got_tree_entry_get_name(te)) == -1) {
4228 err = got_error_from_errno("asprintf");
4229 goto done;
4231 err = print_tree(child_path, commit_id, show_ids, 1,
4232 root_path, repo);
4233 free(child_path);
4234 if (err)
4235 goto done;
4238 done:
4239 if (tree)
4240 got_object_tree_close(tree);
4241 free(tree_id);
4242 return err;
4245 static const struct got_error *
4246 cmd_tree(int argc, char *argv[])
4248 const struct got_error *error;
4249 struct got_repository *repo = NULL;
4250 struct got_worktree *worktree = NULL;
4251 const char *path, *refname = NULL;
4252 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4253 struct got_object_id *commit_id = NULL;
4254 char *commit_id_str = NULL;
4255 int show_ids = 0, recurse = 0;
4256 int ch;
4258 #ifndef PROFILE
4259 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4260 NULL) == -1)
4261 err(1, "pledge");
4262 #endif
4264 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4265 switch (ch) {
4266 case 'c':
4267 commit_id_str = optarg;
4268 break;
4269 case 'r':
4270 repo_path = realpath(optarg, NULL);
4271 if (repo_path == NULL)
4272 return got_error_from_errno2("realpath",
4273 optarg);
4274 got_path_strip_trailing_slashes(repo_path);
4275 break;
4276 case 'i':
4277 show_ids = 1;
4278 break;
4279 case 'R':
4280 recurse = 1;
4281 break;
4282 default:
4283 usage_tree();
4284 /* NOTREACHED */
4288 argc -= optind;
4289 argv += optind;
4291 if (argc == 1)
4292 path = argv[0];
4293 else if (argc > 1)
4294 usage_tree();
4295 else
4296 path = NULL;
4298 cwd = getcwd(NULL, 0);
4299 if (cwd == NULL) {
4300 error = got_error_from_errno("getcwd");
4301 goto done;
4303 if (repo_path == NULL) {
4304 error = got_worktree_open(&worktree, cwd);
4305 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4306 goto done;
4307 else
4308 error = NULL;
4309 if (worktree) {
4310 repo_path =
4311 strdup(got_worktree_get_repo_path(worktree));
4312 if (repo_path == NULL)
4313 error = got_error_from_errno("strdup");
4314 if (error)
4315 goto done;
4316 } else {
4317 repo_path = strdup(cwd);
4318 if (repo_path == NULL) {
4319 error = got_error_from_errno("strdup");
4320 goto done;
4325 error = got_repo_open(&repo, repo_path, NULL);
4326 if (error != NULL)
4327 goto done;
4329 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4330 if (error)
4331 goto done;
4333 if (path == NULL) {
4334 if (worktree) {
4335 char *p, *worktree_subdir = cwd +
4336 strlen(got_worktree_get_root_path(worktree));
4337 if (asprintf(&p, "%s/%s",
4338 got_worktree_get_path_prefix(worktree),
4339 worktree_subdir) == -1) {
4340 error = got_error_from_errno("asprintf");
4341 goto done;
4343 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4344 free(p);
4345 if (error)
4346 goto done;
4347 } else
4348 path = "/";
4350 if (in_repo_path == NULL) {
4351 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4352 if (error != NULL)
4353 goto done;
4356 if (commit_id_str == NULL) {
4357 struct got_reference *head_ref;
4358 if (worktree)
4359 refname = got_worktree_get_head_ref_name(worktree);
4360 else
4361 refname = GOT_REF_HEAD;
4362 error = got_ref_open(&head_ref, repo, refname, 0);
4363 if (error != NULL)
4364 goto done;
4365 error = got_ref_resolve(&commit_id, repo, head_ref);
4366 got_ref_close(head_ref);
4367 if (error != NULL)
4368 goto done;
4369 } else {
4370 error = got_repo_match_object_id(&commit_id, NULL,
4371 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4372 if (error)
4373 goto done;
4376 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4377 in_repo_path, repo);
4378 done:
4379 free(in_repo_path);
4380 free(repo_path);
4381 free(cwd);
4382 free(commit_id);
4383 if (worktree)
4384 got_worktree_close(worktree);
4385 if (repo) {
4386 const struct got_error *repo_error;
4387 repo_error = got_repo_close(repo);
4388 if (error == NULL)
4389 error = repo_error;
4391 return error;
4394 __dead static void
4395 usage_status(void)
4397 fprintf(stderr, "usage: %s status [path ...]\n", getprogname());
4398 exit(1);
4401 static const struct got_error *
4402 print_status(void *arg, unsigned char status, unsigned char staged_status,
4403 const char *path, struct got_object_id *blob_id,
4404 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4405 int dirfd, const char *de_name)
4407 if (status == staged_status && (status == GOT_STATUS_DELETE))
4408 status = GOT_STATUS_NO_CHANGE;
4409 printf("%c%c %s\n", status, staged_status, path);
4410 return NULL;
4413 static const struct got_error *
4414 cmd_status(int argc, char *argv[])
4416 const struct got_error *error = NULL;
4417 struct got_repository *repo = NULL;
4418 struct got_worktree *worktree = NULL;
4419 char *cwd = NULL;
4420 struct got_pathlist_head paths;
4421 struct got_pathlist_entry *pe;
4422 int ch;
4424 TAILQ_INIT(&paths);
4426 while ((ch = getopt(argc, argv, "")) != -1) {
4427 switch (ch) {
4428 default:
4429 usage_status();
4430 /* NOTREACHED */
4434 argc -= optind;
4435 argv += optind;
4437 #ifndef PROFILE
4438 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4439 NULL) == -1)
4440 err(1, "pledge");
4441 #endif
4442 cwd = getcwd(NULL, 0);
4443 if (cwd == NULL) {
4444 error = got_error_from_errno("getcwd");
4445 goto done;
4448 error = got_worktree_open(&worktree, cwd);
4449 if (error) {
4450 if (error->code == GOT_ERR_NOT_WORKTREE)
4451 error = wrap_not_worktree_error(error, "status", cwd);
4452 goto done;
4455 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4456 NULL);
4457 if (error != NULL)
4458 goto done;
4460 error = apply_unveil(got_repo_get_path(repo), 1,
4461 got_worktree_get_root_path(worktree));
4462 if (error)
4463 goto done;
4465 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4466 if (error)
4467 goto done;
4469 error = got_worktree_status(worktree, &paths, repo, print_status, NULL,
4470 check_cancelled, NULL);
4471 done:
4472 TAILQ_FOREACH(pe, &paths, entry)
4473 free((char *)pe->path);
4474 got_pathlist_free(&paths);
4475 free(cwd);
4476 return error;
4479 __dead static void
4480 usage_ref(void)
4482 fprintf(stderr,
4483 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4484 "[-d] [name]\n",
4485 getprogname());
4486 exit(1);
4489 static const struct got_error *
4490 list_refs(struct got_repository *repo, const char *refname)
4492 static const struct got_error *err = NULL;
4493 struct got_reflist_head refs;
4494 struct got_reflist_entry *re;
4496 SIMPLEQ_INIT(&refs);
4497 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4498 if (err)
4499 return err;
4501 SIMPLEQ_FOREACH(re, &refs, entry) {
4502 char *refstr;
4503 refstr = got_ref_to_str(re->ref);
4504 if (refstr == NULL)
4505 return got_error_from_errno("got_ref_to_str");
4506 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4507 free(refstr);
4510 got_ref_list_free(&refs);
4511 return NULL;
4514 static const struct got_error *
4515 delete_ref(struct got_repository *repo, const char *refname)
4517 const struct got_error *err = NULL;
4518 struct got_reference *ref;
4520 err = got_ref_open(&ref, repo, refname, 0);
4521 if (err)
4522 return err;
4524 err = got_ref_delete(ref, repo);
4525 got_ref_close(ref);
4526 return err;
4529 static const struct got_error *
4530 add_ref(struct got_repository *repo, const char *refname, const char *target)
4532 const struct got_error *err = NULL;
4533 struct got_object_id *id;
4534 struct got_reference *ref = NULL;
4537 * Don't let the user create a reference name with a leading '-'.
4538 * While technically a valid reference name, this case is usually
4539 * an unintended typo.
4541 if (refname[0] == '-')
4542 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4544 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4545 repo);
4546 if (err) {
4547 struct got_reference *target_ref;
4549 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4550 return err;
4551 err = got_ref_open(&target_ref, repo, target, 0);
4552 if (err)
4553 return err;
4554 err = got_ref_resolve(&id, repo, target_ref);
4555 got_ref_close(target_ref);
4556 if (err)
4557 return err;
4560 err = got_ref_alloc(&ref, refname, id);
4561 if (err)
4562 goto done;
4564 err = got_ref_write(ref, repo);
4565 done:
4566 if (ref)
4567 got_ref_close(ref);
4568 free(id);
4569 return err;
4572 static const struct got_error *
4573 add_symref(struct got_repository *repo, const char *refname, const char *target)
4575 const struct got_error *err = NULL;
4576 struct got_reference *ref = NULL;
4577 struct got_reference *target_ref = NULL;
4580 * Don't let the user create a reference name with a leading '-'.
4581 * While technically a valid reference name, this case is usually
4582 * an unintended typo.
4584 if (refname[0] == '-')
4585 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4587 err = got_ref_open(&target_ref, repo, target, 0);
4588 if (err)
4589 return err;
4591 err = got_ref_alloc_symref(&ref, refname, target_ref);
4592 if (err)
4593 goto done;
4595 err = got_ref_write(ref, repo);
4596 done:
4597 if (target_ref)
4598 got_ref_close(target_ref);
4599 if (ref)
4600 got_ref_close(ref);
4601 return err;
4604 static const struct got_error *
4605 cmd_ref(int argc, char *argv[])
4607 const struct got_error *error = NULL;
4608 struct got_repository *repo = NULL;
4609 struct got_worktree *worktree = NULL;
4610 char *cwd = NULL, *repo_path = NULL;
4611 int ch, do_list = 0, do_delete = 0;
4612 const char *obj_arg = NULL, *symref_target= NULL;
4613 char *refname = NULL;
4615 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4616 switch (ch) {
4617 case 'c':
4618 obj_arg = optarg;
4619 break;
4620 case 'd':
4621 do_delete = 1;
4622 break;
4623 case 'r':
4624 repo_path = realpath(optarg, NULL);
4625 if (repo_path == NULL)
4626 return got_error_from_errno2("realpath",
4627 optarg);
4628 got_path_strip_trailing_slashes(repo_path);
4629 break;
4630 case 'l':
4631 do_list = 1;
4632 break;
4633 case 's':
4634 symref_target = optarg;
4635 break;
4636 default:
4637 usage_ref();
4638 /* NOTREACHED */
4642 if (obj_arg && do_list)
4643 errx(1, "-c and -l options are mutually exclusive");
4644 if (obj_arg && do_delete)
4645 errx(1, "-c and -d options are mutually exclusive");
4646 if (obj_arg && symref_target)
4647 errx(1, "-c and -s options are mutually exclusive");
4648 if (symref_target && do_delete)
4649 errx(1, "-s and -d options are mutually exclusive");
4650 if (symref_target && do_list)
4651 errx(1, "-s and -l options are mutually exclusive");
4652 if (do_delete && do_list)
4653 errx(1, "-d and -l options are mutually exclusive");
4655 argc -= optind;
4656 argv += optind;
4658 if (do_list) {
4659 if (argc != 0 && argc != 1)
4660 usage_ref();
4661 if (argc == 1) {
4662 refname = strdup(argv[0]);
4663 if (refname == NULL) {
4664 error = got_error_from_errno("strdup");
4665 goto done;
4668 } else {
4669 if (argc != 1)
4670 usage_ref();
4671 refname = strdup(argv[0]);
4672 if (refname == NULL) {
4673 error = got_error_from_errno("strdup");
4674 goto done;
4678 if (refname)
4679 got_path_strip_trailing_slashes(refname);
4681 #ifndef PROFILE
4682 if (do_list) {
4683 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4684 NULL) == -1)
4685 err(1, "pledge");
4686 } else {
4687 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
4688 "sendfd unveil", NULL) == -1)
4689 err(1, "pledge");
4691 #endif
4692 cwd = getcwd(NULL, 0);
4693 if (cwd == NULL) {
4694 error = got_error_from_errno("getcwd");
4695 goto done;
4698 if (repo_path == NULL) {
4699 error = got_worktree_open(&worktree, cwd);
4700 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4701 goto done;
4702 else
4703 error = NULL;
4704 if (worktree) {
4705 repo_path =
4706 strdup(got_worktree_get_repo_path(worktree));
4707 if (repo_path == NULL)
4708 error = got_error_from_errno("strdup");
4709 if (error)
4710 goto done;
4711 } else {
4712 repo_path = strdup(cwd);
4713 if (repo_path == NULL) {
4714 error = got_error_from_errno("strdup");
4715 goto done;
4720 error = got_repo_open(&repo, repo_path, NULL);
4721 if (error != NULL)
4722 goto done;
4724 error = apply_unveil(got_repo_get_path(repo), do_list,
4725 worktree ? got_worktree_get_root_path(worktree) : NULL);
4726 if (error)
4727 goto done;
4729 if (do_list)
4730 error = list_refs(repo, refname);
4731 else if (do_delete)
4732 error = delete_ref(repo, refname);
4733 else if (symref_target)
4734 error = add_symref(repo, refname, symref_target);
4735 else {
4736 if (obj_arg == NULL)
4737 usage_ref();
4738 error = add_ref(repo, refname, obj_arg);
4740 done:
4741 free(refname);
4742 if (repo)
4743 got_repo_close(repo);
4744 if (worktree)
4745 got_worktree_close(worktree);
4746 free(cwd);
4747 free(repo_path);
4748 return error;
4751 __dead static void
4752 usage_branch(void)
4754 fprintf(stderr,
4755 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
4756 "[name]\n", getprogname());
4757 exit(1);
4760 static const struct got_error *
4761 list_branch(struct got_repository *repo, struct got_worktree *worktree,
4762 struct got_reference *ref)
4764 const struct got_error *err = NULL;
4765 const char *refname, *marker = " ";
4766 char *refstr;
4768 refname = got_ref_get_name(ref);
4769 if (worktree && strcmp(refname,
4770 got_worktree_get_head_ref_name(worktree)) == 0) {
4771 struct got_object_id *id = NULL;
4773 err = got_ref_resolve(&id, repo, ref);
4774 if (err)
4775 return err;
4776 if (got_object_id_cmp(id,
4777 got_worktree_get_base_commit_id(worktree)) == 0)
4778 marker = "* ";
4779 else
4780 marker = "~ ";
4781 free(id);
4784 if (strncmp(refname, "refs/heads/", 11) == 0)
4785 refname += 11;
4786 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4787 refname += 18;
4789 refstr = got_ref_to_str(ref);
4790 if (refstr == NULL)
4791 return got_error_from_errno("got_ref_to_str");
4793 printf("%s%s: %s\n", marker, refname, refstr);
4794 free(refstr);
4795 return NULL;
4798 static const struct got_error *
4799 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
4801 const char *refname;
4803 if (worktree == NULL)
4804 return got_error(GOT_ERR_NOT_WORKTREE);
4806 refname = got_worktree_get_head_ref_name(worktree);
4808 if (strncmp(refname, "refs/heads/", 11) == 0)
4809 refname += 11;
4810 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
4811 refname += 18;
4813 printf("%s\n", refname);
4815 return NULL;
4818 static const struct got_error *
4819 list_branches(struct got_repository *repo, struct got_worktree *worktree)
4821 static const struct got_error *err = NULL;
4822 struct got_reflist_head refs;
4823 struct got_reflist_entry *re;
4824 struct got_reference *temp_ref = NULL;
4825 int rebase_in_progress, histedit_in_progress;
4827 SIMPLEQ_INIT(&refs);
4829 if (worktree) {
4830 err = got_worktree_rebase_in_progress(&rebase_in_progress,
4831 worktree);
4832 if (err)
4833 return err;
4835 err = got_worktree_histedit_in_progress(&histedit_in_progress,
4836 worktree);
4837 if (err)
4838 return err;
4840 if (rebase_in_progress || histedit_in_progress) {
4841 err = got_ref_open(&temp_ref, repo,
4842 got_worktree_get_head_ref_name(worktree), 0);
4843 if (err)
4844 return err;
4845 list_branch(repo, worktree, temp_ref);
4846 got_ref_close(temp_ref);
4850 err = got_ref_list(&refs, repo, "refs/heads",
4851 got_ref_cmp_by_name, NULL);
4852 if (err)
4853 return err;
4855 SIMPLEQ_FOREACH(re, &refs, entry)
4856 list_branch(repo, worktree, re->ref);
4858 got_ref_list_free(&refs);
4859 return NULL;
4862 static const struct got_error *
4863 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
4864 const char *branch_name)
4866 const struct got_error *err = NULL;
4867 struct got_reference *ref = NULL;
4868 char *refname;
4870 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
4871 return got_error_from_errno("asprintf");
4873 err = got_ref_open(&ref, repo, refname, 0);
4874 if (err)
4875 goto done;
4877 if (worktree &&
4878 strcmp(got_worktree_get_head_ref_name(worktree),
4879 got_ref_get_name(ref)) == 0) {
4880 err = got_error_msg(GOT_ERR_SAME_BRANCH,
4881 "will not delete this work tree's current branch");
4882 goto done;
4885 err = got_ref_delete(ref, repo);
4886 done:
4887 if (ref)
4888 got_ref_close(ref);
4889 free(refname);
4890 return err;
4893 static const struct got_error *
4894 add_branch(struct got_repository *repo, const char *branch_name,
4895 struct got_object_id *base_commit_id)
4897 const struct got_error *err = NULL;
4898 struct got_reference *ref = NULL;
4899 char *base_refname = NULL, *refname = NULL;
4902 * Don't let the user create a branch name with a leading '-'.
4903 * While technically a valid reference name, this case is usually
4904 * an unintended typo.
4906 if (branch_name[0] == '-')
4907 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
4909 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
4910 err = got_error_from_errno("asprintf");
4911 goto done;
4914 err = got_ref_open(&ref, repo, refname, 0);
4915 if (err == NULL) {
4916 err = got_error(GOT_ERR_BRANCH_EXISTS);
4917 goto done;
4918 } else if (err->code != GOT_ERR_NOT_REF)
4919 goto done;
4921 err = got_ref_alloc(&ref, refname, base_commit_id);
4922 if (err)
4923 goto done;
4925 err = got_ref_write(ref, repo);
4926 done:
4927 if (ref)
4928 got_ref_close(ref);
4929 free(base_refname);
4930 free(refname);
4931 return err;
4934 static const struct got_error *
4935 cmd_branch(int argc, char *argv[])
4937 const struct got_error *error = NULL;
4938 struct got_repository *repo = NULL;
4939 struct got_worktree *worktree = NULL;
4940 char *cwd = NULL, *repo_path = NULL;
4941 int ch, do_list = 0, do_show = 0, do_update = 1;
4942 const char *delref = NULL, *commit_id_arg = NULL;
4943 struct got_reference *ref = NULL;
4944 struct got_pathlist_head paths;
4945 struct got_pathlist_entry *pe;
4946 struct got_object_id *commit_id = NULL;
4947 char *commit_id_str = NULL;
4949 TAILQ_INIT(&paths);
4951 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
4952 switch (ch) {
4953 case 'c':
4954 commit_id_arg = optarg;
4955 break;
4956 case 'd':
4957 delref = optarg;
4958 break;
4959 case 'r':
4960 repo_path = realpath(optarg, NULL);
4961 if (repo_path == NULL)
4962 return got_error_from_errno2("realpath",
4963 optarg);
4964 got_path_strip_trailing_slashes(repo_path);
4965 break;
4966 case 'l':
4967 do_list = 1;
4968 break;
4969 case 'n':
4970 do_update = 0;
4971 break;
4972 default:
4973 usage_branch();
4974 /* NOTREACHED */
4978 if (do_list && delref)
4979 errx(1, "-l and -d options are mutually exclusive");
4981 argc -= optind;
4982 argv += optind;
4984 if (!do_list && !delref && argc == 0)
4985 do_show = 1;
4987 if ((do_list || delref || do_show) && commit_id_arg != NULL)
4988 errx(1, "-c option can only be used when creating a branch");
4990 if (do_list || delref) {
4991 if (argc > 0)
4992 usage_branch();
4993 } else if (!do_show && argc != 1)
4994 usage_branch();
4996 #ifndef PROFILE
4997 if (do_list || do_show) {
4998 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
4999 NULL) == -1)
5000 err(1, "pledge");
5001 } else {
5002 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5003 "sendfd unveil", NULL) == -1)
5004 err(1, "pledge");
5006 #endif
5007 cwd = getcwd(NULL, 0);
5008 if (cwd == NULL) {
5009 error = got_error_from_errno("getcwd");
5010 goto done;
5013 if (repo_path == NULL) {
5014 error = got_worktree_open(&worktree, cwd);
5015 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5016 goto done;
5017 else
5018 error = NULL;
5019 if (worktree) {
5020 repo_path =
5021 strdup(got_worktree_get_repo_path(worktree));
5022 if (repo_path == NULL)
5023 error = got_error_from_errno("strdup");
5024 if (error)
5025 goto done;
5026 } else {
5027 repo_path = strdup(cwd);
5028 if (repo_path == NULL) {
5029 error = got_error_from_errno("strdup");
5030 goto done;
5035 error = got_repo_open(&repo, repo_path, NULL);
5036 if (error != NULL)
5037 goto done;
5039 error = apply_unveil(got_repo_get_path(repo), do_list,
5040 worktree ? got_worktree_get_root_path(worktree) : NULL);
5041 if (error)
5042 goto done;
5044 if (do_show)
5045 error = show_current_branch(repo, worktree);
5046 else if (do_list)
5047 error = list_branches(repo, worktree);
5048 else if (delref)
5049 error = delete_branch(repo, worktree, delref);
5050 else {
5051 if (commit_id_arg == NULL)
5052 commit_id_arg = worktree ?
5053 got_worktree_get_head_ref_name(worktree) :
5054 GOT_REF_HEAD;
5055 error = got_repo_match_object_id(&commit_id, NULL,
5056 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5057 if (error)
5058 goto done;
5059 error = add_branch(repo, argv[0], commit_id);
5060 if (error)
5061 goto done;
5062 if (worktree && do_update) {
5063 struct got_update_progress_arg upa;
5064 char *branch_refname = NULL;
5066 error = got_object_id_str(&commit_id_str, commit_id);
5067 if (error)
5068 goto done;
5069 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5070 worktree);
5071 if (error)
5072 goto done;
5073 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5074 == -1) {
5075 error = got_error_from_errno("asprintf");
5076 goto done;
5078 error = got_ref_open(&ref, repo, branch_refname, 0);
5079 free(branch_refname);
5080 if (error)
5081 goto done;
5082 error = switch_head_ref(ref, commit_id, worktree,
5083 repo);
5084 if (error)
5085 goto done;
5086 error = got_worktree_set_base_commit_id(worktree, repo,
5087 commit_id);
5088 if (error)
5089 goto done;
5090 memset(&upa, 0, sizeof(upa));
5091 error = got_worktree_checkout_files(worktree, &paths,
5092 repo, update_progress, &upa, check_cancelled,
5093 NULL);
5094 if (error)
5095 goto done;
5096 if (upa.did_something)
5097 printf("Updated to commit %s\n", commit_id_str);
5098 print_update_progress_stats(&upa);
5101 done:
5102 if (ref)
5103 got_ref_close(ref);
5104 if (repo)
5105 got_repo_close(repo);
5106 if (worktree)
5107 got_worktree_close(worktree);
5108 free(cwd);
5109 free(repo_path);
5110 free(commit_id);
5111 free(commit_id_str);
5112 TAILQ_FOREACH(pe, &paths, entry)
5113 free((char *)pe->path);
5114 got_pathlist_free(&paths);
5115 return error;
5119 __dead static void
5120 usage_tag(void)
5122 fprintf(stderr,
5123 "usage: %s tag [-c commit] [-r repository] [-l] "
5124 "[-m message] name\n", getprogname());
5125 exit(1);
5128 #if 0
5129 static const struct got_error *
5130 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5132 const struct got_error *err = NULL;
5133 struct got_reflist_entry *re, *se, *new;
5134 struct got_object_id *re_id, *se_id;
5135 struct got_tag_object *re_tag, *se_tag;
5136 time_t re_time, se_time;
5138 SIMPLEQ_FOREACH(re, tags, entry) {
5139 se = SIMPLEQ_FIRST(sorted);
5140 if (se == NULL) {
5141 err = got_reflist_entry_dup(&new, re);
5142 if (err)
5143 return err;
5144 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5145 continue;
5146 } else {
5147 err = got_ref_resolve(&re_id, repo, re->ref);
5148 if (err)
5149 break;
5150 err = got_object_open_as_tag(&re_tag, repo, re_id);
5151 free(re_id);
5152 if (err)
5153 break;
5154 re_time = got_object_tag_get_tagger_time(re_tag);
5155 got_object_tag_close(re_tag);
5158 while (se) {
5159 err = got_ref_resolve(&se_id, repo, re->ref);
5160 if (err)
5161 break;
5162 err = got_object_open_as_tag(&se_tag, repo, se_id);
5163 free(se_id);
5164 if (err)
5165 break;
5166 se_time = got_object_tag_get_tagger_time(se_tag);
5167 got_object_tag_close(se_tag);
5169 if (se_time > re_time) {
5170 err = got_reflist_entry_dup(&new, re);
5171 if (err)
5172 return err;
5173 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5174 break;
5176 se = SIMPLEQ_NEXT(se, entry);
5177 continue;
5180 done:
5181 return err;
5183 #endif
5185 static const struct got_error *
5186 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5188 static const struct got_error *err = NULL;
5189 struct got_reflist_head refs;
5190 struct got_reflist_entry *re;
5192 SIMPLEQ_INIT(&refs);
5194 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5195 if (err)
5196 return err;
5198 SIMPLEQ_FOREACH(re, &refs, entry) {
5199 const char *refname;
5200 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5201 char datebuf[26];
5202 const char *tagger;
5203 time_t tagger_time;
5204 struct got_object_id *id;
5205 struct got_tag_object *tag;
5206 struct got_commit_object *commit = NULL;
5208 refname = got_ref_get_name(re->ref);
5209 if (strncmp(refname, "refs/tags/", 10) != 0)
5210 continue;
5211 refname += 10;
5212 refstr = got_ref_to_str(re->ref);
5213 if (refstr == NULL) {
5214 err = got_error_from_errno("got_ref_to_str");
5215 break;
5217 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5218 free(refstr);
5220 err = got_ref_resolve(&id, repo, re->ref);
5221 if (err)
5222 break;
5223 err = got_object_open_as_tag(&tag, repo, id);
5224 if (err) {
5225 if (err->code != GOT_ERR_OBJ_TYPE) {
5226 free(id);
5227 break;
5229 /* "lightweight" tag */
5230 err = got_object_open_as_commit(&commit, repo, id);
5231 if (err) {
5232 free(id);
5233 break;
5235 tagger = got_object_commit_get_committer(commit);
5236 tagger_time =
5237 got_object_commit_get_committer_time(commit);
5238 err = got_object_id_str(&id_str, id);
5239 free(id);
5240 if (err)
5241 break;
5242 } else {
5243 free(id);
5244 tagger = got_object_tag_get_tagger(tag);
5245 tagger_time = got_object_tag_get_tagger_time(tag);
5246 err = got_object_id_str(&id_str,
5247 got_object_tag_get_object_id(tag));
5248 if (err)
5249 break;
5251 printf("from: %s\n", tagger);
5252 datestr = get_datestr(&tagger_time, datebuf);
5253 if (datestr)
5254 printf("date: %s UTC\n", datestr);
5255 if (commit)
5256 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5257 else {
5258 switch (got_object_tag_get_object_type(tag)) {
5259 case GOT_OBJ_TYPE_BLOB:
5260 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5261 id_str);
5262 break;
5263 case GOT_OBJ_TYPE_TREE:
5264 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5265 id_str);
5266 break;
5267 case GOT_OBJ_TYPE_COMMIT:
5268 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5269 id_str);
5270 break;
5271 case GOT_OBJ_TYPE_TAG:
5272 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5273 id_str);
5274 break;
5275 default:
5276 break;
5279 free(id_str);
5280 if (commit) {
5281 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5282 if (err)
5283 break;
5284 got_object_commit_close(commit);
5285 } else {
5286 tagmsg0 = strdup(got_object_tag_get_message(tag));
5287 got_object_tag_close(tag);
5288 if (tagmsg0 == NULL) {
5289 err = got_error_from_errno("strdup");
5290 break;
5294 tagmsg = tagmsg0;
5295 do {
5296 line = strsep(&tagmsg, "\n");
5297 if (line)
5298 printf(" %s\n", line);
5299 } while (line);
5300 free(tagmsg0);
5303 got_ref_list_free(&refs);
5304 return NULL;
5307 static const struct got_error *
5308 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5309 const char *tag_name, const char *repo_path)
5311 const struct got_error *err = NULL;
5312 char *template = NULL, *initial_content = NULL;
5313 char *editor = NULL;
5314 int fd = -1;
5316 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5317 err = got_error_from_errno("asprintf");
5318 goto done;
5321 if (asprintf(&initial_content, "\n# tagging commit %s as %s\n",
5322 commit_id_str, tag_name) == -1) {
5323 err = got_error_from_errno("asprintf");
5324 goto done;
5327 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5328 if (err)
5329 goto done;
5331 dprintf(fd, initial_content);
5332 close(fd);
5334 err = get_editor(&editor);
5335 if (err)
5336 goto done;
5337 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5338 done:
5339 free(initial_content);
5340 free(template);
5341 free(editor);
5343 /* Editor is done; we can now apply unveil(2) */
5344 if (err == NULL) {
5345 err = apply_unveil(repo_path, 0, NULL);
5346 if (err) {
5347 free(*tagmsg);
5348 *tagmsg = NULL;
5351 return err;
5354 static const struct got_error *
5355 add_tag(struct got_repository *repo, const char *tag_name,
5356 const char *commit_arg, const char *tagmsg_arg)
5358 const struct got_error *err = NULL;
5359 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5360 char *label = NULL, *commit_id_str = NULL;
5361 struct got_reference *ref = NULL;
5362 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5363 char *tagmsg_path = NULL, *tag_id_str = NULL;
5364 int preserve_tagmsg = 0;
5367 * Don't let the user create a tag name with a leading '-'.
5368 * While technically a valid reference name, this case is usually
5369 * an unintended typo.
5371 if (tag_name[0] == '-')
5372 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5374 err = get_author(&tagger, repo);
5375 if (err)
5376 return err;
5378 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5379 GOT_OBJ_TYPE_COMMIT, 1, repo);
5380 if (err)
5381 goto done;
5383 err = got_object_id_str(&commit_id_str, commit_id);
5384 if (err)
5385 goto done;
5387 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5388 refname = strdup(tag_name);
5389 if (refname == NULL) {
5390 err = got_error_from_errno("strdup");
5391 goto done;
5393 tag_name += 10;
5394 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5395 err = got_error_from_errno("asprintf");
5396 goto done;
5399 err = got_ref_open(&ref, repo, refname, 0);
5400 if (err == NULL) {
5401 err = got_error(GOT_ERR_TAG_EXISTS);
5402 goto done;
5403 } else if (err->code != GOT_ERR_NOT_REF)
5404 goto done;
5406 if (tagmsg_arg == NULL) {
5407 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5408 tag_name, got_repo_get_path(repo));
5409 if (err) {
5410 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5411 tagmsg_path != NULL)
5412 preserve_tagmsg = 1;
5413 goto done;
5417 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5418 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5419 if (err) {
5420 if (tagmsg_path)
5421 preserve_tagmsg = 1;
5422 goto done;
5425 err = got_ref_alloc(&ref, refname, tag_id);
5426 if (err) {
5427 if (tagmsg_path)
5428 preserve_tagmsg = 1;
5429 goto done;
5432 err = got_ref_write(ref, repo);
5433 if (err) {
5434 if (tagmsg_path)
5435 preserve_tagmsg = 1;
5436 goto done;
5439 err = got_object_id_str(&tag_id_str, tag_id);
5440 if (err) {
5441 if (tagmsg_path)
5442 preserve_tagmsg = 1;
5443 goto done;
5445 printf("Created tag %s\n", tag_id_str);
5446 done:
5447 if (preserve_tagmsg) {
5448 fprintf(stderr, "%s: tag message preserved in %s\n",
5449 getprogname(), tagmsg_path);
5450 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5451 err = got_error_from_errno2("unlink", tagmsg_path);
5452 free(tag_id_str);
5453 if (ref)
5454 got_ref_close(ref);
5455 free(commit_id);
5456 free(commit_id_str);
5457 free(refname);
5458 free(tagmsg);
5459 free(tagmsg_path);
5460 free(tagger);
5461 return err;
5464 static const struct got_error *
5465 cmd_tag(int argc, char *argv[])
5467 const struct got_error *error = NULL;
5468 struct got_repository *repo = NULL;
5469 struct got_worktree *worktree = NULL;
5470 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5471 char *gitconfig_path = NULL;
5472 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5473 int ch, do_list = 0;
5475 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5476 switch (ch) {
5477 case 'c':
5478 commit_id_arg = optarg;
5479 break;
5480 case 'm':
5481 tagmsg = optarg;
5482 break;
5483 case 'r':
5484 repo_path = realpath(optarg, NULL);
5485 if (repo_path == NULL)
5486 return got_error_from_errno2("realpath",
5487 optarg);
5488 got_path_strip_trailing_slashes(repo_path);
5489 break;
5490 case 'l':
5491 do_list = 1;
5492 break;
5493 default:
5494 usage_tag();
5495 /* NOTREACHED */
5499 argc -= optind;
5500 argv += optind;
5502 if (do_list) {
5503 if (commit_id_arg != NULL)
5504 errx(1,
5505 "-c option can only be used when creating a tag");
5506 if (tagmsg)
5507 errx(1, "-l and -m options are mutually exclusive");
5508 if (argc > 0)
5509 usage_tag();
5510 } else if (argc != 1)
5511 usage_tag();
5513 tag_name = argv[0];
5515 #ifndef PROFILE
5516 if (do_list) {
5517 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5518 NULL) == -1)
5519 err(1, "pledge");
5520 } else {
5521 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5522 "sendfd unveil", NULL) == -1)
5523 err(1, "pledge");
5525 #endif
5526 cwd = getcwd(NULL, 0);
5527 if (cwd == NULL) {
5528 error = got_error_from_errno("getcwd");
5529 goto done;
5532 if (repo_path == NULL) {
5533 error = got_worktree_open(&worktree, cwd);
5534 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5535 goto done;
5536 else
5537 error = NULL;
5538 if (worktree) {
5539 repo_path =
5540 strdup(got_worktree_get_repo_path(worktree));
5541 if (repo_path == NULL)
5542 error = got_error_from_errno("strdup");
5543 if (error)
5544 goto done;
5545 } else {
5546 repo_path = strdup(cwd);
5547 if (repo_path == NULL) {
5548 error = got_error_from_errno("strdup");
5549 goto done;
5554 if (do_list) {
5555 error = got_repo_open(&repo, repo_path, NULL);
5556 if (error != NULL)
5557 goto done;
5558 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5559 if (error)
5560 goto done;
5561 error = list_tags(repo, worktree);
5562 } else {
5563 error = get_gitconfig_path(&gitconfig_path);
5564 if (error)
5565 goto done;
5566 error = got_repo_open(&repo, repo_path, gitconfig_path);
5567 if (error != NULL)
5568 goto done;
5570 if (tagmsg) {
5571 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5572 if (error)
5573 goto done;
5576 if (commit_id_arg == NULL) {
5577 struct got_reference *head_ref;
5578 struct got_object_id *commit_id;
5579 error = got_ref_open(&head_ref, repo,
5580 worktree ? got_worktree_get_head_ref_name(worktree)
5581 : GOT_REF_HEAD, 0);
5582 if (error)
5583 goto done;
5584 error = got_ref_resolve(&commit_id, repo, head_ref);
5585 got_ref_close(head_ref);
5586 if (error)
5587 goto done;
5588 error = got_object_id_str(&commit_id_str, commit_id);
5589 free(commit_id);
5590 if (error)
5591 goto done;
5594 error = add_tag(repo, tag_name,
5595 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5597 done:
5598 if (repo)
5599 got_repo_close(repo);
5600 if (worktree)
5601 got_worktree_close(worktree);
5602 free(cwd);
5603 free(repo_path);
5604 free(gitconfig_path);
5605 free(commit_id_str);
5606 return error;
5609 __dead static void
5610 usage_add(void)
5612 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5613 getprogname());
5614 exit(1);
5617 static const struct got_error *
5618 add_progress(void *arg, unsigned char status, const char *path)
5620 while (path[0] == '/')
5621 path++;
5622 printf("%c %s\n", status, path);
5623 return NULL;
5626 static const struct got_error *
5627 cmd_add(int argc, char *argv[])
5629 const struct got_error *error = NULL;
5630 struct got_repository *repo = NULL;
5631 struct got_worktree *worktree = NULL;
5632 char *cwd = NULL;
5633 struct got_pathlist_head paths;
5634 struct got_pathlist_entry *pe;
5635 int ch, can_recurse = 0, no_ignores = 0;
5637 TAILQ_INIT(&paths);
5639 while ((ch = getopt(argc, argv, "IR")) != -1) {
5640 switch (ch) {
5641 case 'I':
5642 no_ignores = 1;
5643 break;
5644 case 'R':
5645 can_recurse = 1;
5646 break;
5647 default:
5648 usage_add();
5649 /* NOTREACHED */
5653 argc -= optind;
5654 argv += optind;
5656 #ifndef PROFILE
5657 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5658 NULL) == -1)
5659 err(1, "pledge");
5660 #endif
5661 if (argc < 1)
5662 usage_add();
5664 cwd = getcwd(NULL, 0);
5665 if (cwd == NULL) {
5666 error = got_error_from_errno("getcwd");
5667 goto done;
5670 error = got_worktree_open(&worktree, cwd);
5671 if (error) {
5672 if (error->code == GOT_ERR_NOT_WORKTREE)
5673 error = wrap_not_worktree_error(error, "add", cwd);
5674 goto done;
5677 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5678 NULL);
5679 if (error != NULL)
5680 goto done;
5682 error = apply_unveil(got_repo_get_path(repo), 1,
5683 got_worktree_get_root_path(worktree));
5684 if (error)
5685 goto done;
5687 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5688 if (error)
5689 goto done;
5691 if (!can_recurse && no_ignores) {
5692 error = got_error_msg(GOT_ERR_BAD_PATH,
5693 "disregarding ignores requires -R option");
5694 goto done;
5698 if (!can_recurse) {
5699 char *ondisk_path;
5700 struct stat sb;
5701 TAILQ_FOREACH(pe, &paths, entry) {
5702 if (asprintf(&ondisk_path, "%s/%s",
5703 got_worktree_get_root_path(worktree),
5704 pe->path) == -1) {
5705 error = got_error_from_errno("asprintf");
5706 goto done;
5708 if (lstat(ondisk_path, &sb) == -1) {
5709 if (errno == ENOENT) {
5710 free(ondisk_path);
5711 continue;
5713 error = got_error_from_errno2("lstat",
5714 ondisk_path);
5715 free(ondisk_path);
5716 goto done;
5718 free(ondisk_path);
5719 if (S_ISDIR(sb.st_mode)) {
5720 error = got_error_msg(GOT_ERR_BAD_PATH,
5721 "adding directories requires -R option");
5722 goto done;
5727 error = got_worktree_schedule_add(worktree, &paths, add_progress,
5728 NULL, repo, no_ignores);
5729 done:
5730 if (repo)
5731 got_repo_close(repo);
5732 if (worktree)
5733 got_worktree_close(worktree);
5734 TAILQ_FOREACH(pe, &paths, entry)
5735 free((char *)pe->path);
5736 got_pathlist_free(&paths);
5737 free(cwd);
5738 return error;
5741 __dead static void
5742 usage_remove(void)
5744 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] path ...\n",
5745 getprogname());
5746 exit(1);
5749 static const struct got_error *
5750 print_remove_status(void *arg, unsigned char status,
5751 unsigned char staged_status, const char *path)
5753 while (path[0] == '/')
5754 path++;
5755 if (status == GOT_STATUS_NONEXISTENT)
5756 return NULL;
5757 if (status == staged_status && (status == GOT_STATUS_DELETE))
5758 status = GOT_STATUS_NO_CHANGE;
5759 printf("%c%c %s\n", status, staged_status, path);
5760 return NULL;
5763 static const struct got_error *
5764 cmd_remove(int argc, char *argv[])
5766 const struct got_error *error = NULL;
5767 struct got_worktree *worktree = NULL;
5768 struct got_repository *repo = NULL;
5769 char *cwd = NULL;
5770 struct got_pathlist_head paths;
5771 struct got_pathlist_entry *pe;
5772 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0;
5774 TAILQ_INIT(&paths);
5776 while ((ch = getopt(argc, argv, "fkR")) != -1) {
5777 switch (ch) {
5778 case 'f':
5779 delete_local_mods = 1;
5780 break;
5781 case 'k':
5782 keep_on_disk = 1;
5783 break;
5784 case 'R':
5785 can_recurse = 1;
5786 break;
5787 default:
5788 usage_remove();
5789 /* NOTREACHED */
5793 argc -= optind;
5794 argv += optind;
5796 #ifndef PROFILE
5797 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5798 NULL) == -1)
5799 err(1, "pledge");
5800 #endif
5801 if (argc < 1)
5802 usage_remove();
5804 cwd = getcwd(NULL, 0);
5805 if (cwd == NULL) {
5806 error = got_error_from_errno("getcwd");
5807 goto done;
5809 error = got_worktree_open(&worktree, cwd);
5810 if (error) {
5811 if (error->code == GOT_ERR_NOT_WORKTREE)
5812 error = wrap_not_worktree_error(error, "remove", cwd);
5813 goto done;
5816 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5817 NULL);
5818 if (error)
5819 goto done;
5821 error = apply_unveil(got_repo_get_path(repo), 1,
5822 got_worktree_get_root_path(worktree));
5823 if (error)
5824 goto done;
5826 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5827 if (error)
5828 goto done;
5830 if (!can_recurse) {
5831 char *ondisk_path;
5832 struct stat sb;
5833 TAILQ_FOREACH(pe, &paths, entry) {
5834 if (asprintf(&ondisk_path, "%s/%s",
5835 got_worktree_get_root_path(worktree),
5836 pe->path) == -1) {
5837 error = got_error_from_errno("asprintf");
5838 goto done;
5840 if (lstat(ondisk_path, &sb) == -1) {
5841 if (errno == ENOENT) {
5842 free(ondisk_path);
5843 continue;
5845 error = got_error_from_errno2("lstat",
5846 ondisk_path);
5847 free(ondisk_path);
5848 goto done;
5850 free(ondisk_path);
5851 if (S_ISDIR(sb.st_mode)) {
5852 error = got_error_msg(GOT_ERR_BAD_PATH,
5853 "removing directories requires -R option");
5854 goto done;
5859 error = got_worktree_schedule_delete(worktree, &paths,
5860 delete_local_mods, print_remove_status, NULL, repo, keep_on_disk);
5861 done:
5862 if (repo)
5863 got_repo_close(repo);
5864 if (worktree)
5865 got_worktree_close(worktree);
5866 TAILQ_FOREACH(pe, &paths, entry)
5867 free((char *)pe->path);
5868 got_pathlist_free(&paths);
5869 free(cwd);
5870 return error;
5873 __dead static void
5874 usage_revert(void)
5876 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
5877 "path ...\n", getprogname());
5878 exit(1);
5881 static const struct got_error *
5882 revert_progress(void *arg, unsigned char status, const char *path)
5884 if (status == GOT_STATUS_UNVERSIONED)
5885 return NULL;
5887 while (path[0] == '/')
5888 path++;
5889 printf("%c %s\n", status, path);
5890 return NULL;
5893 struct choose_patch_arg {
5894 FILE *patch_script_file;
5895 const char *action;
5898 static const struct got_error *
5899 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
5900 int nchanges, const char *action)
5902 char *line = NULL;
5903 size_t linesize = 0;
5904 ssize_t linelen;
5906 switch (status) {
5907 case GOT_STATUS_ADD:
5908 printf("A %s\n%s this addition? [y/n] ", path, action);
5909 break;
5910 case GOT_STATUS_DELETE:
5911 printf("D %s\n%s this deletion? [y/n] ", path, action);
5912 break;
5913 case GOT_STATUS_MODIFY:
5914 if (fseek(patch_file, 0L, SEEK_SET) == -1)
5915 return got_error_from_errno("fseek");
5916 printf(GOT_COMMIT_SEP_STR);
5917 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
5918 printf("%s", line);
5919 if (ferror(patch_file))
5920 return got_error_from_errno("getline");
5921 printf(GOT_COMMIT_SEP_STR);
5922 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
5923 path, n, nchanges, action);
5924 break;
5925 default:
5926 return got_error_path(path, GOT_ERR_FILE_STATUS);
5929 return NULL;
5932 static const struct got_error *
5933 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
5934 FILE *patch_file, int n, int nchanges)
5936 const struct got_error *err = NULL;
5937 char *line = NULL;
5938 size_t linesize = 0;
5939 ssize_t linelen;
5940 int resp = ' ';
5941 struct choose_patch_arg *a = arg;
5943 *choice = GOT_PATCH_CHOICE_NONE;
5945 if (a->patch_script_file) {
5946 char *nl;
5947 err = show_change(status, path, patch_file, n, nchanges,
5948 a->action);
5949 if (err)
5950 return err;
5951 linelen = getline(&line, &linesize, a->patch_script_file);
5952 if (linelen == -1) {
5953 if (ferror(a->patch_script_file))
5954 return got_error_from_errno("getline");
5955 return NULL;
5957 nl = strchr(line, '\n');
5958 if (nl)
5959 *nl = '\0';
5960 if (strcmp(line, "y") == 0) {
5961 *choice = GOT_PATCH_CHOICE_YES;
5962 printf("y\n");
5963 } else if (strcmp(line, "n") == 0) {
5964 *choice = GOT_PATCH_CHOICE_NO;
5965 printf("n\n");
5966 } else if (strcmp(line, "q") == 0 &&
5967 status == GOT_STATUS_MODIFY) {
5968 *choice = GOT_PATCH_CHOICE_QUIT;
5969 printf("q\n");
5970 } else
5971 printf("invalid response '%s'\n", line);
5972 free(line);
5973 return NULL;
5976 while (resp != 'y' && resp != 'n' && resp != 'q') {
5977 err = show_change(status, path, patch_file, n, nchanges,
5978 a->action);
5979 if (err)
5980 return err;
5981 resp = getchar();
5982 if (resp == '\n')
5983 resp = getchar();
5984 if (status == GOT_STATUS_MODIFY) {
5985 if (resp != 'y' && resp != 'n' && resp != 'q') {
5986 printf("invalid response '%c'\n", resp);
5987 resp = ' ';
5989 } else if (resp != 'y' && resp != 'n') {
5990 printf("invalid response '%c'\n", resp);
5991 resp = ' ';
5995 if (resp == 'y')
5996 *choice = GOT_PATCH_CHOICE_YES;
5997 else if (resp == 'n')
5998 *choice = GOT_PATCH_CHOICE_NO;
5999 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6000 *choice = GOT_PATCH_CHOICE_QUIT;
6002 return NULL;
6006 static const struct got_error *
6007 cmd_revert(int argc, char *argv[])
6009 const struct got_error *error = NULL;
6010 struct got_worktree *worktree = NULL;
6011 struct got_repository *repo = NULL;
6012 char *cwd = NULL, *path = NULL;
6013 struct got_pathlist_head paths;
6014 struct got_pathlist_entry *pe;
6015 int ch, can_recurse = 0, pflag = 0;
6016 FILE *patch_script_file = NULL;
6017 const char *patch_script_path = NULL;
6018 struct choose_patch_arg cpa;
6020 TAILQ_INIT(&paths);
6022 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6023 switch (ch) {
6024 case 'p':
6025 pflag = 1;
6026 break;
6027 case 'F':
6028 patch_script_path = optarg;
6029 break;
6030 case 'R':
6031 can_recurse = 1;
6032 break;
6033 default:
6034 usage_revert();
6035 /* NOTREACHED */
6039 argc -= optind;
6040 argv += optind;
6042 #ifndef PROFILE
6043 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6044 "unveil", NULL) == -1)
6045 err(1, "pledge");
6046 #endif
6047 if (argc < 1)
6048 usage_revert();
6049 if (patch_script_path && !pflag)
6050 errx(1, "-F option can only be used together with -p option");
6052 cwd = getcwd(NULL, 0);
6053 if (cwd == NULL) {
6054 error = got_error_from_errno("getcwd");
6055 goto done;
6057 error = got_worktree_open(&worktree, cwd);
6058 if (error) {
6059 if (error->code == GOT_ERR_NOT_WORKTREE)
6060 error = wrap_not_worktree_error(error, "revert", cwd);
6061 goto done;
6064 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6065 NULL);
6066 if (error != NULL)
6067 goto done;
6069 if (patch_script_path) {
6070 patch_script_file = fopen(patch_script_path, "r");
6071 if (patch_script_file == NULL) {
6072 error = got_error_from_errno2("fopen",
6073 patch_script_path);
6074 goto done;
6077 error = apply_unveil(got_repo_get_path(repo), 1,
6078 got_worktree_get_root_path(worktree));
6079 if (error)
6080 goto done;
6082 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6083 if (error)
6084 goto done;
6086 if (!can_recurse) {
6087 char *ondisk_path;
6088 struct stat sb;
6089 TAILQ_FOREACH(pe, &paths, entry) {
6090 if (asprintf(&ondisk_path, "%s/%s",
6091 got_worktree_get_root_path(worktree),
6092 pe->path) == -1) {
6093 error = got_error_from_errno("asprintf");
6094 goto done;
6096 if (lstat(ondisk_path, &sb) == -1) {
6097 if (errno == ENOENT) {
6098 free(ondisk_path);
6099 continue;
6101 error = got_error_from_errno2("lstat",
6102 ondisk_path);
6103 free(ondisk_path);
6104 goto done;
6106 free(ondisk_path);
6107 if (S_ISDIR(sb.st_mode)) {
6108 error = got_error_msg(GOT_ERR_BAD_PATH,
6109 "reverting directories requires -R option");
6110 goto done;
6115 cpa.patch_script_file = patch_script_file;
6116 cpa.action = "revert";
6117 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6118 pflag ? choose_patch : NULL, &cpa, repo);
6119 done:
6120 if (patch_script_file && fclose(patch_script_file) == EOF &&
6121 error == NULL)
6122 error = got_error_from_errno2("fclose", patch_script_path);
6123 if (repo)
6124 got_repo_close(repo);
6125 if (worktree)
6126 got_worktree_close(worktree);
6127 free(path);
6128 free(cwd);
6129 return error;
6132 __dead static void
6133 usage_commit(void)
6135 fprintf(stderr, "usage: %s commit [-m msg] [path ...]\n",
6136 getprogname());
6137 exit(1);
6140 struct collect_commit_logmsg_arg {
6141 const char *cmdline_log;
6142 const char *editor;
6143 const char *worktree_path;
6144 const char *branch_name;
6145 const char *repo_path;
6146 char *logmsg_path;
6150 static const struct got_error *
6151 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6152 void *arg)
6154 char *initial_content = NULL;
6155 struct got_pathlist_entry *pe;
6156 const struct got_error *err = NULL;
6157 char *template = NULL;
6158 struct collect_commit_logmsg_arg *a = arg;
6159 int fd;
6160 size_t len;
6162 /* if a message was specified on the command line, just use it */
6163 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6164 len = strlen(a->cmdline_log) + 1;
6165 *logmsg = malloc(len + 1);
6166 if (*logmsg == NULL)
6167 return got_error_from_errno("malloc");
6168 strlcpy(*logmsg, a->cmdline_log, len);
6169 return NULL;
6172 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6173 return got_error_from_errno("asprintf");
6175 if (asprintf(&initial_content,
6176 "\n# changes to be committed on branch %s:\n",
6177 a->branch_name) == -1)
6178 return got_error_from_errno("asprintf");
6180 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6181 if (err)
6182 goto done;
6184 dprintf(fd, initial_content);
6186 TAILQ_FOREACH(pe, commitable_paths, entry) {
6187 struct got_commitable *ct = pe->data;
6188 dprintf(fd, "# %c %s\n",
6189 got_commitable_get_status(ct),
6190 got_commitable_get_path(ct));
6192 close(fd);
6194 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6195 done:
6196 free(initial_content);
6197 free(template);
6199 /* Editor is done; we can now apply unveil(2) */
6200 if (err == NULL) {
6201 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6202 if (err) {
6203 free(*logmsg);
6204 *logmsg = NULL;
6207 return err;
6210 static const struct got_error *
6211 cmd_commit(int argc, char *argv[])
6213 const struct got_error *error = NULL;
6214 struct got_worktree *worktree = NULL;
6215 struct got_repository *repo = NULL;
6216 char *cwd = NULL, *id_str = NULL;
6217 struct got_object_id *id = NULL;
6218 const char *logmsg = NULL;
6219 struct collect_commit_logmsg_arg cl_arg;
6220 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6221 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6222 struct got_pathlist_head paths;
6224 TAILQ_INIT(&paths);
6225 cl_arg.logmsg_path = NULL;
6227 while ((ch = getopt(argc, argv, "m:")) != -1) {
6228 switch (ch) {
6229 case 'm':
6230 logmsg = optarg;
6231 break;
6232 default:
6233 usage_commit();
6234 /* NOTREACHED */
6238 argc -= optind;
6239 argv += optind;
6241 #ifndef PROFILE
6242 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6243 "unveil", NULL) == -1)
6244 err(1, "pledge");
6245 #endif
6246 cwd = getcwd(NULL, 0);
6247 if (cwd == NULL) {
6248 error = got_error_from_errno("getcwd");
6249 goto done;
6251 error = got_worktree_open(&worktree, cwd);
6252 if (error) {
6253 if (error->code == GOT_ERR_NOT_WORKTREE)
6254 error = wrap_not_worktree_error(error, "commit", cwd);
6255 goto done;
6258 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6259 if (error)
6260 goto done;
6261 if (rebase_in_progress) {
6262 error = got_error(GOT_ERR_REBASING);
6263 goto done;
6266 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6267 worktree);
6268 if (error)
6269 goto done;
6271 error = get_gitconfig_path(&gitconfig_path);
6272 if (error)
6273 goto done;
6274 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6275 gitconfig_path);
6276 if (error != NULL)
6277 goto done;
6279 error = get_author(&author, repo);
6280 if (error)
6281 return error;
6284 * unveil(2) traverses exec(2); if an editor is used we have
6285 * to apply unveil after the log message has been written.
6287 if (logmsg == NULL || strlen(logmsg) == 0)
6288 error = get_editor(&editor);
6289 else
6290 error = apply_unveil(got_repo_get_path(repo), 0,
6291 got_worktree_get_root_path(worktree));
6292 if (error)
6293 goto done;
6295 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6296 if (error)
6297 goto done;
6299 cl_arg.editor = editor;
6300 cl_arg.cmdline_log = logmsg;
6301 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6302 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6303 if (!histedit_in_progress) {
6304 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6305 error = got_error(GOT_ERR_COMMIT_BRANCH);
6306 goto done;
6308 cl_arg.branch_name += 11;
6310 cl_arg.repo_path = got_repo_get_path(repo);
6311 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6312 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
6313 if (error) {
6314 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6315 cl_arg.logmsg_path != NULL)
6316 preserve_logmsg = 1;
6317 goto done;
6320 error = got_object_id_str(&id_str, id);
6321 if (error)
6322 goto done;
6323 printf("Created commit %s\n", id_str);
6324 done:
6325 if (preserve_logmsg) {
6326 fprintf(stderr, "%s: log message preserved in %s\n",
6327 getprogname(), cl_arg.logmsg_path);
6328 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6329 error == NULL)
6330 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6331 free(cl_arg.logmsg_path);
6332 if (repo)
6333 got_repo_close(repo);
6334 if (worktree)
6335 got_worktree_close(worktree);
6336 free(cwd);
6337 free(id_str);
6338 free(gitconfig_path);
6339 free(editor);
6340 free(author);
6341 return error;
6344 __dead static void
6345 usage_cherrypick(void)
6347 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6348 exit(1);
6351 static const struct got_error *
6352 cmd_cherrypick(int argc, char *argv[])
6354 const struct got_error *error = NULL;
6355 struct got_worktree *worktree = NULL;
6356 struct got_repository *repo = NULL;
6357 char *cwd = NULL, *commit_id_str = NULL;
6358 struct got_object_id *commit_id = NULL;
6359 struct got_commit_object *commit = NULL;
6360 struct got_object_qid *pid;
6361 struct got_reference *head_ref = NULL;
6362 int ch;
6363 struct got_update_progress_arg upa;
6365 while ((ch = getopt(argc, argv, "")) != -1) {
6366 switch (ch) {
6367 default:
6368 usage_cherrypick();
6369 /* NOTREACHED */
6373 argc -= optind;
6374 argv += optind;
6376 #ifndef PROFILE
6377 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6378 "unveil", NULL) == -1)
6379 err(1, "pledge");
6380 #endif
6381 if (argc != 1)
6382 usage_cherrypick();
6384 cwd = getcwd(NULL, 0);
6385 if (cwd == NULL) {
6386 error = got_error_from_errno("getcwd");
6387 goto done;
6389 error = got_worktree_open(&worktree, cwd);
6390 if (error) {
6391 if (error->code == GOT_ERR_NOT_WORKTREE)
6392 error = wrap_not_worktree_error(error, "cherrypick",
6393 cwd);
6394 goto done;
6397 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6398 NULL);
6399 if (error != NULL)
6400 goto done;
6402 error = apply_unveil(got_repo_get_path(repo), 0,
6403 got_worktree_get_root_path(worktree));
6404 if (error)
6405 goto done;
6407 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6408 GOT_OBJ_TYPE_COMMIT, repo);
6409 if (error != NULL) {
6410 struct got_reference *ref;
6411 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6412 goto done;
6413 error = got_ref_open(&ref, repo, argv[0], 0);
6414 if (error != NULL)
6415 goto done;
6416 error = got_ref_resolve(&commit_id, repo, ref);
6417 got_ref_close(ref);
6418 if (error != NULL)
6419 goto done;
6421 error = got_object_id_str(&commit_id_str, commit_id);
6422 if (error)
6423 goto done;
6425 error = got_ref_open(&head_ref, repo,
6426 got_worktree_get_head_ref_name(worktree), 0);
6427 if (error != NULL)
6428 goto done;
6430 error = check_same_branch(commit_id, head_ref, NULL, repo);
6431 if (error) {
6432 if (error->code != GOT_ERR_ANCESTRY)
6433 goto done;
6434 error = NULL;
6435 } else {
6436 error = got_error(GOT_ERR_SAME_BRANCH);
6437 goto done;
6440 error = got_object_open_as_commit(&commit, repo, commit_id);
6441 if (error)
6442 goto done;
6443 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6444 memset(&upa, 0, sizeof(upa));
6445 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6446 commit_id, repo, update_progress, &upa, check_cancelled,
6447 NULL);
6448 if (error != NULL)
6449 goto done;
6451 if (upa.did_something)
6452 printf("Merged commit %s\n", commit_id_str);
6453 print_update_progress_stats(&upa);
6454 done:
6455 if (commit)
6456 got_object_commit_close(commit);
6457 free(commit_id_str);
6458 if (head_ref)
6459 got_ref_close(head_ref);
6460 if (worktree)
6461 got_worktree_close(worktree);
6462 if (repo)
6463 got_repo_close(repo);
6464 return error;
6467 __dead static void
6468 usage_backout(void)
6470 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6471 exit(1);
6474 static const struct got_error *
6475 cmd_backout(int argc, char *argv[])
6477 const struct got_error *error = NULL;
6478 struct got_worktree *worktree = NULL;
6479 struct got_repository *repo = NULL;
6480 char *cwd = NULL, *commit_id_str = NULL;
6481 struct got_object_id *commit_id = NULL;
6482 struct got_commit_object *commit = NULL;
6483 struct got_object_qid *pid;
6484 struct got_reference *head_ref = NULL;
6485 int ch;
6486 struct got_update_progress_arg upa;
6488 while ((ch = getopt(argc, argv, "")) != -1) {
6489 switch (ch) {
6490 default:
6491 usage_backout();
6492 /* NOTREACHED */
6496 argc -= optind;
6497 argv += optind;
6499 #ifndef PROFILE
6500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6501 "unveil", NULL) == -1)
6502 err(1, "pledge");
6503 #endif
6504 if (argc != 1)
6505 usage_backout();
6507 cwd = getcwd(NULL, 0);
6508 if (cwd == NULL) {
6509 error = got_error_from_errno("getcwd");
6510 goto done;
6512 error = got_worktree_open(&worktree, cwd);
6513 if (error) {
6514 if (error->code == GOT_ERR_NOT_WORKTREE)
6515 error = wrap_not_worktree_error(error, "backout", cwd);
6516 goto done;
6519 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6520 NULL);
6521 if (error != NULL)
6522 goto done;
6524 error = apply_unveil(got_repo_get_path(repo), 0,
6525 got_worktree_get_root_path(worktree));
6526 if (error)
6527 goto done;
6529 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6530 GOT_OBJ_TYPE_COMMIT, repo);
6531 if (error != NULL) {
6532 struct got_reference *ref;
6533 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6534 goto done;
6535 error = got_ref_open(&ref, repo, argv[0], 0);
6536 if (error != NULL)
6537 goto done;
6538 error = got_ref_resolve(&commit_id, repo, ref);
6539 got_ref_close(ref);
6540 if (error != NULL)
6541 goto done;
6543 error = got_object_id_str(&commit_id_str, commit_id);
6544 if (error)
6545 goto done;
6547 error = got_ref_open(&head_ref, repo,
6548 got_worktree_get_head_ref_name(worktree), 0);
6549 if (error != NULL)
6550 goto done;
6552 error = check_same_branch(commit_id, head_ref, NULL, repo);
6553 if (error)
6554 goto done;
6556 error = got_object_open_as_commit(&commit, repo, commit_id);
6557 if (error)
6558 goto done;
6559 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6560 if (pid == NULL) {
6561 error = got_error(GOT_ERR_ROOT_COMMIT);
6562 goto done;
6565 memset(&upa, 0, sizeof(upa));
6566 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6567 update_progress, &upa, check_cancelled, NULL);
6568 if (error != NULL)
6569 goto done;
6571 if (upa.did_something)
6572 printf("Backed out commit %s\n", commit_id_str);
6573 print_update_progress_stats(&upa);
6574 done:
6575 if (commit)
6576 got_object_commit_close(commit);
6577 free(commit_id_str);
6578 if (head_ref)
6579 got_ref_close(head_ref);
6580 if (worktree)
6581 got_worktree_close(worktree);
6582 if (repo)
6583 got_repo_close(repo);
6584 return error;
6587 __dead static void
6588 usage_rebase(void)
6590 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
6591 getprogname());
6592 exit(1);
6595 void
6596 trim_logmsg(char *logmsg, int limit)
6598 char *nl;
6599 size_t len;
6601 len = strlen(logmsg);
6602 if (len > limit)
6603 len = limit;
6604 logmsg[len] = '\0';
6605 nl = strchr(logmsg, '\n');
6606 if (nl)
6607 *nl = '\0';
6610 static const struct got_error *
6611 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
6613 const struct got_error *err;
6614 char *logmsg0 = NULL;
6615 const char *s;
6617 err = got_object_commit_get_logmsg(&logmsg0, commit);
6618 if (err)
6619 return err;
6621 s = logmsg0;
6622 while (isspace((unsigned char)s[0]))
6623 s++;
6625 *logmsg = strdup(s);
6626 if (*logmsg == NULL) {
6627 err = got_error_from_errno("strdup");
6628 goto done;
6631 trim_logmsg(*logmsg, limit);
6632 done:
6633 free(logmsg0);
6634 return err;
6637 static const struct got_error *
6638 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
6640 const struct got_error *err;
6641 struct got_commit_object *commit = NULL;
6642 char *id_str = NULL, *logmsg = NULL;
6644 err = got_object_open_as_commit(&commit, repo, id);
6645 if (err)
6646 return err;
6648 err = got_object_id_str(&id_str, id);
6649 if (err)
6650 goto done;
6652 id_str[12] = '\0';
6654 err = get_short_logmsg(&logmsg, 42, commit);
6655 if (err)
6656 goto done;
6658 printf("%s -> merge conflict: %s\n", id_str, logmsg);
6659 done:
6660 free(id_str);
6661 got_object_commit_close(commit);
6662 free(logmsg);
6663 return err;
6666 static const struct got_error *
6667 show_rebase_progress(struct got_commit_object *commit,
6668 struct got_object_id *old_id, struct got_object_id *new_id)
6670 const struct got_error *err;
6671 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
6673 err = got_object_id_str(&old_id_str, old_id);
6674 if (err)
6675 goto done;
6677 if (new_id) {
6678 err = got_object_id_str(&new_id_str, new_id);
6679 if (err)
6680 goto done;
6683 old_id_str[12] = '\0';
6684 if (new_id_str)
6685 new_id_str[12] = '\0';
6687 err = get_short_logmsg(&logmsg, 42, commit);
6688 if (err)
6689 goto done;
6691 printf("%s -> %s: %s\n", old_id_str,
6692 new_id_str ? new_id_str : "no-op change", logmsg);
6693 done:
6694 free(old_id_str);
6695 free(new_id_str);
6696 free(logmsg);
6697 return err;
6700 static const struct got_error *
6701 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
6702 struct got_reference *branch, struct got_reference *new_base_branch,
6703 struct got_reference *tmp_branch, struct got_repository *repo)
6705 printf("Switching work tree to %s\n", got_ref_get_name(branch));
6706 return got_worktree_rebase_complete(worktree, fileindex,
6707 new_base_branch, tmp_branch, branch, repo);
6710 static const struct got_error *
6711 rebase_commit(struct got_pathlist_head *merged_paths,
6712 struct got_worktree *worktree, struct got_fileindex *fileindex,
6713 struct got_reference *tmp_branch,
6714 struct got_object_id *commit_id, struct got_repository *repo)
6716 const struct got_error *error;
6717 struct got_commit_object *commit;
6718 struct got_object_id *new_commit_id;
6720 error = got_object_open_as_commit(&commit, repo, commit_id);
6721 if (error)
6722 return error;
6724 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
6725 worktree, fileindex, tmp_branch, commit, commit_id, repo);
6726 if (error) {
6727 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
6728 goto done;
6729 error = show_rebase_progress(commit, commit_id, NULL);
6730 } else {
6731 error = show_rebase_progress(commit, commit_id, new_commit_id);
6732 free(new_commit_id);
6734 done:
6735 got_object_commit_close(commit);
6736 return error;
6739 struct check_path_prefix_arg {
6740 const char *path_prefix;
6741 size_t len;
6742 int errcode;
6745 static const struct got_error *
6746 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
6747 struct got_blob_object *blob2, struct got_object_id *id1,
6748 struct got_object_id *id2, const char *path1, const char *path2,
6749 mode_t mode1, mode_t mode2, struct got_repository *repo)
6751 struct check_path_prefix_arg *a = arg;
6753 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
6754 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
6755 return got_error(a->errcode);
6757 return NULL;
6760 static const struct got_error *
6761 check_path_prefix(struct got_object_id *parent_id,
6762 struct got_object_id *commit_id, const char *path_prefix,
6763 int errcode, struct got_repository *repo)
6765 const struct got_error *err;
6766 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
6767 struct got_commit_object *commit = NULL, *parent_commit = NULL;
6768 struct check_path_prefix_arg cpp_arg;
6770 if (got_path_is_root_dir(path_prefix))
6771 return NULL;
6773 err = got_object_open_as_commit(&commit, repo, commit_id);
6774 if (err)
6775 goto done;
6777 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
6778 if (err)
6779 goto done;
6781 err = got_object_open_as_tree(&tree1, repo,
6782 got_object_commit_get_tree_id(parent_commit));
6783 if (err)
6784 goto done;
6786 err = got_object_open_as_tree(&tree2, repo,
6787 got_object_commit_get_tree_id(commit));
6788 if (err)
6789 goto done;
6791 cpp_arg.path_prefix = path_prefix;
6792 while (cpp_arg.path_prefix[0] == '/')
6793 cpp_arg.path_prefix++;
6794 cpp_arg.len = strlen(cpp_arg.path_prefix);
6795 cpp_arg.errcode = errcode;
6796 err = got_diff_tree(tree1, tree2, "", "", repo,
6797 check_path_prefix_in_diff, &cpp_arg, 0);
6798 done:
6799 if (tree1)
6800 got_object_tree_close(tree1);
6801 if (tree2)
6802 got_object_tree_close(tree2);
6803 if (commit)
6804 got_object_commit_close(commit);
6805 if (parent_commit)
6806 got_object_commit_close(parent_commit);
6807 return err;
6810 static const struct got_error *
6811 collect_commits(struct got_object_id_queue *commits,
6812 struct got_object_id *initial_commit_id,
6813 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
6814 const char *path_prefix, int path_prefix_errcode,
6815 struct got_repository *repo)
6817 const struct got_error *err = NULL;
6818 struct got_commit_graph *graph = NULL;
6819 struct got_object_id *parent_id = NULL;
6820 struct got_object_qid *qid;
6821 struct got_object_id *commit_id = initial_commit_id;
6823 err = got_commit_graph_open(&graph, "/", 1);
6824 if (err)
6825 return err;
6827 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
6828 check_cancelled, NULL);
6829 if (err)
6830 goto done;
6831 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
6832 err = got_commit_graph_iter_next(&parent_id, graph, repo,
6833 check_cancelled, NULL);
6834 if (err) {
6835 if (err->code == GOT_ERR_ITER_COMPLETED) {
6836 err = got_error_msg(GOT_ERR_ANCESTRY,
6837 "ran out of commits to rebase before "
6838 "youngest common ancestor commit has "
6839 "been reached?!?");
6841 goto done;
6842 } else {
6843 err = check_path_prefix(parent_id, commit_id,
6844 path_prefix, path_prefix_errcode, repo);
6845 if (err)
6846 goto done;
6848 err = got_object_qid_alloc(&qid, commit_id);
6849 if (err)
6850 goto done;
6851 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
6852 commit_id = parent_id;
6855 done:
6856 got_commit_graph_close(graph);
6857 return err;
6860 static const struct got_error *
6861 cmd_rebase(int argc, char *argv[])
6863 const struct got_error *error = NULL;
6864 struct got_worktree *worktree = NULL;
6865 struct got_repository *repo = NULL;
6866 struct got_fileindex *fileindex = NULL;
6867 char *cwd = NULL;
6868 struct got_reference *branch = NULL;
6869 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
6870 struct got_object_id *commit_id = NULL, *parent_id = NULL;
6871 struct got_object_id *resume_commit_id = NULL;
6872 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
6873 struct got_commit_object *commit = NULL;
6874 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
6875 int histedit_in_progress = 0;
6876 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
6877 struct got_object_id_queue commits;
6878 struct got_pathlist_head merged_paths;
6879 const struct got_object_id_queue *parent_ids;
6880 struct got_object_qid *qid, *pid;
6882 SIMPLEQ_INIT(&commits);
6883 TAILQ_INIT(&merged_paths);
6885 while ((ch = getopt(argc, argv, "ac")) != -1) {
6886 switch (ch) {
6887 case 'a':
6888 abort_rebase = 1;
6889 break;
6890 case 'c':
6891 continue_rebase = 1;
6892 break;
6893 default:
6894 usage_rebase();
6895 /* NOTREACHED */
6899 argc -= optind;
6900 argv += optind;
6902 #ifndef PROFILE
6903 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6904 "unveil", NULL) == -1)
6905 err(1, "pledge");
6906 #endif
6907 if (abort_rebase && continue_rebase)
6908 usage_rebase();
6909 else if (abort_rebase || continue_rebase) {
6910 if (argc != 0)
6911 usage_rebase();
6912 } else if (argc != 1)
6913 usage_rebase();
6915 cwd = getcwd(NULL, 0);
6916 if (cwd == NULL) {
6917 error = got_error_from_errno("getcwd");
6918 goto done;
6920 error = got_worktree_open(&worktree, cwd);
6921 if (error) {
6922 if (error->code == GOT_ERR_NOT_WORKTREE)
6923 error = wrap_not_worktree_error(error, "rebase", cwd);
6924 goto done;
6927 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6928 NULL);
6929 if (error != NULL)
6930 goto done;
6932 error = apply_unveil(got_repo_get_path(repo), 0,
6933 got_worktree_get_root_path(worktree));
6934 if (error)
6935 goto done;
6937 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6938 worktree);
6939 if (error)
6940 goto done;
6941 if (histedit_in_progress) {
6942 error = got_error(GOT_ERR_HISTEDIT_BUSY);
6943 goto done;
6946 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6947 if (error)
6948 goto done;
6950 if (abort_rebase) {
6951 struct got_update_progress_arg upa;
6952 if (!rebase_in_progress) {
6953 error = got_error(GOT_ERR_NOT_REBASING);
6954 goto done;
6956 error = got_worktree_rebase_continue(&resume_commit_id,
6957 &new_base_branch, &tmp_branch, &branch, &fileindex,
6958 worktree, repo);
6959 if (error)
6960 goto done;
6961 printf("Switching work tree to %s\n",
6962 got_ref_get_symref_target(new_base_branch));
6963 memset(&upa, 0, sizeof(upa));
6964 error = got_worktree_rebase_abort(worktree, fileindex, repo,
6965 new_base_branch, update_progress, &upa);
6966 if (error)
6967 goto done;
6968 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
6969 print_update_progress_stats(&upa);
6970 goto done; /* nothing else to do */
6973 if (continue_rebase) {
6974 if (!rebase_in_progress) {
6975 error = got_error(GOT_ERR_NOT_REBASING);
6976 goto done;
6978 error = got_worktree_rebase_continue(&resume_commit_id,
6979 &new_base_branch, &tmp_branch, &branch, &fileindex,
6980 worktree, repo);
6981 if (error)
6982 goto done;
6984 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
6985 resume_commit_id, repo);
6986 if (error)
6987 goto done;
6989 yca_id = got_object_id_dup(resume_commit_id);
6990 if (yca_id == NULL) {
6991 error = got_error_from_errno("got_object_id_dup");
6992 goto done;
6994 } else {
6995 error = got_ref_open(&branch, repo, argv[0], 0);
6996 if (error != NULL)
6997 goto done;
7000 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7001 if (error)
7002 goto done;
7004 if (!continue_rebase) {
7005 struct got_object_id *base_commit_id;
7007 base_commit_id = got_worktree_get_base_commit_id(worktree);
7008 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7009 base_commit_id, branch_head_commit_id, repo,
7010 check_cancelled, NULL);
7011 if (error)
7012 goto done;
7013 if (yca_id == NULL) {
7014 error = got_error_msg(GOT_ERR_ANCESTRY,
7015 "specified branch shares no common ancestry "
7016 "with work tree's branch");
7017 goto done;
7020 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7021 if (error) {
7022 if (error->code != GOT_ERR_ANCESTRY)
7023 goto done;
7024 error = NULL;
7025 } else {
7026 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7027 "specified branch resolves to a commit which "
7028 "is already contained in work tree's branch");
7029 goto done;
7031 error = got_worktree_rebase_prepare(&new_base_branch,
7032 &tmp_branch, &fileindex, worktree, branch, repo);
7033 if (error)
7034 goto done;
7037 commit_id = branch_head_commit_id;
7038 error = got_object_open_as_commit(&commit, repo, commit_id);
7039 if (error)
7040 goto done;
7042 parent_ids = got_object_commit_get_parent_ids(commit);
7043 pid = SIMPLEQ_FIRST(parent_ids);
7044 if (pid == NULL) {
7045 if (!continue_rebase) {
7046 struct got_update_progress_arg upa;
7047 memset(&upa, 0, sizeof(upa));
7048 error = got_worktree_rebase_abort(worktree, fileindex,
7049 repo, new_base_branch, update_progress, &upa);
7050 if (error)
7051 goto done;
7052 printf("Rebase of %s aborted\n",
7053 got_ref_get_name(branch));
7054 print_update_progress_stats(&upa);
7057 error = got_error(GOT_ERR_EMPTY_REBASE);
7058 goto done;
7060 error = collect_commits(&commits, commit_id, pid->id,
7061 yca_id, got_worktree_get_path_prefix(worktree),
7062 GOT_ERR_REBASE_PATH, repo);
7063 got_object_commit_close(commit);
7064 commit = NULL;
7065 if (error)
7066 goto done;
7068 if (SIMPLEQ_EMPTY(&commits)) {
7069 if (continue_rebase) {
7070 error = rebase_complete(worktree, fileindex,
7071 branch, new_base_branch, tmp_branch, repo);
7072 goto done;
7073 } else {
7074 /* Fast-forward the reference of the branch. */
7075 struct got_object_id *new_head_commit_id;
7076 char *id_str;
7077 error = got_ref_resolve(&new_head_commit_id, repo,
7078 new_base_branch);
7079 if (error)
7080 goto done;
7081 error = got_object_id_str(&id_str, new_head_commit_id);
7082 printf("Forwarding %s to commit %s\n",
7083 got_ref_get_name(branch), id_str);
7084 free(id_str);
7085 error = got_ref_change_ref(branch,
7086 new_head_commit_id);
7087 if (error)
7088 goto done;
7092 pid = NULL;
7093 SIMPLEQ_FOREACH(qid, &commits, entry) {
7094 struct got_update_progress_arg upa;
7096 commit_id = qid->id;
7097 parent_id = pid ? pid->id : yca_id;
7098 pid = qid;
7100 memset(&upa, 0, sizeof(upa));
7101 error = got_worktree_rebase_merge_files(&merged_paths,
7102 worktree, fileindex, parent_id, commit_id, repo,
7103 update_progress, &upa, check_cancelled, NULL);
7104 if (error)
7105 goto done;
7107 print_update_progress_stats(&upa);
7108 if (upa.conflicts > 0)
7109 rebase_status = GOT_STATUS_CONFLICT;
7111 if (rebase_status == GOT_STATUS_CONFLICT) {
7112 error = show_rebase_merge_conflict(qid->id, repo);
7113 if (error)
7114 goto done;
7115 got_worktree_rebase_pathlist_free(&merged_paths);
7116 break;
7119 error = rebase_commit(&merged_paths, worktree, fileindex,
7120 tmp_branch, commit_id, repo);
7121 got_worktree_rebase_pathlist_free(&merged_paths);
7122 if (error)
7123 goto done;
7126 if (rebase_status == GOT_STATUS_CONFLICT) {
7127 error = got_worktree_rebase_postpone(worktree, fileindex);
7128 if (error)
7129 goto done;
7130 error = got_error_msg(GOT_ERR_CONFLICTS,
7131 "conflicts must be resolved before rebasing can continue");
7132 } else
7133 error = rebase_complete(worktree, fileindex, branch,
7134 new_base_branch, tmp_branch, repo);
7135 done:
7136 got_object_id_queue_free(&commits);
7137 free(branch_head_commit_id);
7138 free(resume_commit_id);
7139 free(yca_id);
7140 if (commit)
7141 got_object_commit_close(commit);
7142 if (branch)
7143 got_ref_close(branch);
7144 if (new_base_branch)
7145 got_ref_close(new_base_branch);
7146 if (tmp_branch)
7147 got_ref_close(tmp_branch);
7148 if (worktree)
7149 got_worktree_close(worktree);
7150 if (repo)
7151 got_repo_close(repo);
7152 return error;
7155 __dead static void
7156 usage_histedit(void)
7158 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7159 getprogname());
7160 exit(1);
7163 #define GOT_HISTEDIT_PICK 'p'
7164 #define GOT_HISTEDIT_EDIT 'e'
7165 #define GOT_HISTEDIT_FOLD 'f'
7166 #define GOT_HISTEDIT_DROP 'd'
7167 #define GOT_HISTEDIT_MESG 'm'
7169 static struct got_histedit_cmd {
7170 unsigned char code;
7171 const char *name;
7172 const char *desc;
7173 } got_histedit_cmds[] = {
7174 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7175 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7176 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7177 "be used" },
7178 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7179 { GOT_HISTEDIT_MESG, "mesg",
7180 "single-line log message for commit above (open editor if empty)" },
7183 struct got_histedit_list_entry {
7184 TAILQ_ENTRY(got_histedit_list_entry) entry;
7185 struct got_object_id *commit_id;
7186 const struct got_histedit_cmd *cmd;
7187 char *logmsg;
7189 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7191 static const struct got_error *
7192 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7193 FILE *f, struct got_repository *repo)
7195 const struct got_error *err = NULL;
7196 char *logmsg = NULL, *id_str = NULL;
7197 struct got_commit_object *commit = NULL;
7198 int n;
7200 err = got_object_open_as_commit(&commit, repo, commit_id);
7201 if (err)
7202 goto done;
7204 err = get_short_logmsg(&logmsg, 34, commit);
7205 if (err)
7206 goto done;
7208 err = got_object_id_str(&id_str, commit_id);
7209 if (err)
7210 goto done;
7212 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7213 if (n < 0)
7214 err = got_ferror(f, GOT_ERR_IO);
7215 done:
7216 if (commit)
7217 got_object_commit_close(commit);
7218 free(id_str);
7219 free(logmsg);
7220 return err;
7223 static const struct got_error *
7224 histedit_write_commit_list(struct got_object_id_queue *commits,
7225 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7227 const struct got_error *err = NULL;
7228 struct got_object_qid *qid;
7230 if (SIMPLEQ_EMPTY(commits))
7231 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7233 SIMPLEQ_FOREACH(qid, commits, entry) {
7234 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7235 f, repo);
7236 if (err)
7237 break;
7238 if (edit_logmsg_only) {
7239 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7240 if (n < 0) {
7241 err = got_ferror(f, GOT_ERR_IO);
7242 break;
7247 return err;
7250 static const struct got_error *
7251 write_cmd_list(FILE *f, const char *branch_name,
7252 struct got_object_id_queue *commits)
7254 const struct got_error *err = NULL;
7255 int n, i;
7256 char *id_str;
7257 struct got_object_qid *qid;
7259 qid = SIMPLEQ_FIRST(commits);
7260 err = got_object_id_str(&id_str, qid->id);
7261 if (err)
7262 return err;
7264 n = fprintf(f,
7265 "# Editing the history of branch '%s' starting at\n"
7266 "# commit %s\n"
7267 "# Commits will be processed in order from top to "
7268 "bottom of this file.\n", branch_name, id_str);
7269 if (n < 0) {
7270 err = got_ferror(f, GOT_ERR_IO);
7271 goto done;
7274 n = fprintf(f, "# Available histedit commands:\n");
7275 if (n < 0) {
7276 err = got_ferror(f, GOT_ERR_IO);
7277 goto done;
7280 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7281 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7282 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7283 cmd->desc);
7284 if (n < 0) {
7285 err = got_ferror(f, GOT_ERR_IO);
7286 break;
7289 done:
7290 free(id_str);
7291 return err;
7294 static const struct got_error *
7295 histedit_syntax_error(int lineno)
7297 static char msg[42];
7298 int ret;
7300 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7301 lineno);
7302 if (ret == -1 || ret >= sizeof(msg))
7303 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7305 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7308 static const struct got_error *
7309 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7310 char *logmsg, struct got_repository *repo)
7312 const struct got_error *err;
7313 struct got_commit_object *folded_commit = NULL;
7314 char *id_str, *folded_logmsg = NULL;
7316 err = got_object_id_str(&id_str, hle->commit_id);
7317 if (err)
7318 return err;
7320 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7321 if (err)
7322 goto done;
7324 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7325 if (err)
7326 goto done;
7327 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7328 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7329 folded_logmsg) == -1) {
7330 err = got_error_from_errno("asprintf");
7332 done:
7333 if (folded_commit)
7334 got_object_commit_close(folded_commit);
7335 free(id_str);
7336 free(folded_logmsg);
7337 return err;
7340 static struct got_histedit_list_entry *
7341 get_folded_commits(struct got_histedit_list_entry *hle)
7343 struct got_histedit_list_entry *prev, *folded = NULL;
7345 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7346 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7347 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7348 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7349 folded = prev;
7350 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7353 return folded;
7356 static const struct got_error *
7357 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7358 struct got_repository *repo)
7360 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7361 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7362 const struct got_error *err = NULL;
7363 struct got_commit_object *commit = NULL;
7364 int fd;
7365 struct got_histedit_list_entry *folded = NULL;
7367 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7368 if (err)
7369 return err;
7371 folded = get_folded_commits(hle);
7372 if (folded) {
7373 while (folded != hle) {
7374 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7375 folded = TAILQ_NEXT(folded, entry);
7376 continue;
7378 err = append_folded_commit_msg(&new_msg, folded,
7379 logmsg, repo);
7380 if (err)
7381 goto done;
7382 free(logmsg);
7383 logmsg = new_msg;
7384 folded = TAILQ_NEXT(folded, entry);
7388 err = got_object_id_str(&id_str, hle->commit_id);
7389 if (err)
7390 goto done;
7391 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7392 if (err)
7393 goto done;
7394 if (asprintf(&new_msg,
7395 "%s\n# original log message of commit %s: %s",
7396 logmsg ? logmsg : "", id_str, orig_logmsg) == -1) {
7397 err = got_error_from_errno("asprintf");
7398 goto done;
7400 free(logmsg);
7401 logmsg = new_msg;
7403 err = got_object_id_str(&id_str, hle->commit_id);
7404 if (err)
7405 goto done;
7407 err = got_opentemp_named_fd(&logmsg_path, &fd,
7408 GOT_TMPDIR_STR "/got-logmsg");
7409 if (err)
7410 goto done;
7412 dprintf(fd, logmsg);
7413 close(fd);
7415 err = get_editor(&editor);
7416 if (err)
7417 goto done;
7419 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7420 if (err) {
7421 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7422 goto done;
7423 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7425 done:
7426 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7427 err = got_error_from_errno2("unlink", logmsg_path);
7428 free(logmsg_path);
7429 free(logmsg);
7430 free(orig_logmsg);
7431 free(editor);
7432 if (commit)
7433 got_object_commit_close(commit);
7434 return err;
7437 static const struct got_error *
7438 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7439 FILE *f, struct got_repository *repo)
7441 const struct got_error *err = NULL;
7442 char *line = NULL, *p, *end;
7443 size_t size;
7444 ssize_t len;
7445 int lineno = 0, i;
7446 const struct got_histedit_cmd *cmd;
7447 struct got_object_id *commit_id = NULL;
7448 struct got_histedit_list_entry *hle = NULL;
7450 for (;;) {
7451 len = getline(&line, &size, f);
7452 if (len == -1) {
7453 const struct got_error *getline_err;
7454 if (feof(f))
7455 break;
7456 getline_err = got_error_from_errno("getline");
7457 err = got_ferror(f, getline_err->code);
7458 break;
7460 lineno++;
7461 p = line;
7462 while (isspace((unsigned char)p[0]))
7463 p++;
7464 if (p[0] == '#' || p[0] == '\0') {
7465 free(line);
7466 line = NULL;
7467 continue;
7469 cmd = NULL;
7470 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7471 cmd = &got_histedit_cmds[i];
7472 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7473 isspace((unsigned char)p[strlen(cmd->name)])) {
7474 p += strlen(cmd->name);
7475 break;
7477 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7478 p++;
7479 break;
7482 if (i == nitems(got_histedit_cmds)) {
7483 err = histedit_syntax_error(lineno);
7484 break;
7486 while (isspace((unsigned char)p[0]))
7487 p++;
7488 if (cmd->code == GOT_HISTEDIT_MESG) {
7489 if (hle == NULL || hle->logmsg != NULL) {
7490 err = got_error(GOT_ERR_HISTEDIT_CMD);
7491 break;
7493 if (p[0] == '\0') {
7494 err = histedit_edit_logmsg(hle, repo);
7495 if (err)
7496 break;
7497 } else {
7498 hle->logmsg = strdup(p);
7499 if (hle->logmsg == NULL) {
7500 err = got_error_from_errno("strdup");
7501 break;
7504 free(line);
7505 line = NULL;
7506 continue;
7507 } else {
7508 end = p;
7509 while (end[0] && !isspace((unsigned char)end[0]))
7510 end++;
7511 *end = '\0';
7513 err = got_object_resolve_id_str(&commit_id, repo, p);
7514 if (err) {
7515 /* override error code */
7516 err = histedit_syntax_error(lineno);
7517 break;
7520 hle = malloc(sizeof(*hle));
7521 if (hle == NULL) {
7522 err = got_error_from_errno("malloc");
7523 break;
7525 hle->cmd = cmd;
7526 hle->commit_id = commit_id;
7527 hle->logmsg = NULL;
7528 commit_id = NULL;
7529 free(line);
7530 line = NULL;
7531 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7534 free(line);
7535 free(commit_id);
7536 return err;
7539 static const struct got_error *
7540 histedit_check_script(struct got_histedit_list *histedit_cmds,
7541 struct got_object_id_queue *commits, struct got_repository *repo)
7543 const struct got_error *err = NULL;
7544 struct got_object_qid *qid;
7545 struct got_histedit_list_entry *hle;
7546 static char msg[92];
7547 char *id_str;
7549 if (TAILQ_EMPTY(histedit_cmds))
7550 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7551 "histedit script contains no commands");
7552 if (SIMPLEQ_EMPTY(commits))
7553 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7555 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7556 struct got_histedit_list_entry *hle2;
7557 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7558 if (hle == hle2)
7559 continue;
7560 if (got_object_id_cmp(hle->commit_id,
7561 hle2->commit_id) != 0)
7562 continue;
7563 err = got_object_id_str(&id_str, hle->commit_id);
7564 if (err)
7565 return err;
7566 snprintf(msg, sizeof(msg), "commit %s is listed "
7567 "more than once in histedit script", id_str);
7568 free(id_str);
7569 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7573 SIMPLEQ_FOREACH(qid, commits, entry) {
7574 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7575 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7576 break;
7578 if (hle == NULL) {
7579 err = got_object_id_str(&id_str, qid->id);
7580 if (err)
7581 return err;
7582 snprintf(msg, sizeof(msg),
7583 "commit %s missing from histedit script", id_str);
7584 free(id_str);
7585 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7589 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
7590 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
7591 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
7592 "last commit in histedit script cannot be folded");
7594 return NULL;
7597 static const struct got_error *
7598 histedit_run_editor(struct got_histedit_list *histedit_cmds,
7599 const char *path, struct got_object_id_queue *commits,
7600 struct got_repository *repo)
7602 const struct got_error *err = NULL;
7603 char *editor;
7604 FILE *f = NULL;
7606 err = get_editor(&editor);
7607 if (err)
7608 return err;
7610 if (spawn_editor(editor, path) == -1) {
7611 err = got_error_from_errno("failed spawning editor");
7612 goto done;
7615 f = fopen(path, "r");
7616 if (f == NULL) {
7617 err = got_error_from_errno("fopen");
7618 goto done;
7620 err = histedit_parse_list(histedit_cmds, f, repo);
7621 if (err)
7622 goto done;
7624 err = histedit_check_script(histedit_cmds, commits, repo);
7625 done:
7626 if (f && fclose(f) != 0 && err == NULL)
7627 err = got_error_from_errno("fclose");
7628 free(editor);
7629 return err;
7632 static const struct got_error *
7633 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
7634 struct got_object_id_queue *, const char *, const char *,
7635 struct got_repository *);
7637 static const struct got_error *
7638 histedit_edit_script(struct got_histedit_list *histedit_cmds,
7639 struct got_object_id_queue *commits, const char *branch_name,
7640 int edit_logmsg_only, struct got_repository *repo)
7642 const struct got_error *err;
7643 FILE *f = NULL;
7644 char *path = NULL;
7646 err = got_opentemp_named(&path, &f, "got-histedit");
7647 if (err)
7648 return err;
7650 err = write_cmd_list(f, branch_name, commits);
7651 if (err)
7652 goto done;
7654 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
7655 if (err)
7656 goto done;
7658 if (edit_logmsg_only) {
7659 rewind(f);
7660 err = histedit_parse_list(histedit_cmds, f, repo);
7661 } else {
7662 if (fclose(f) != 0) {
7663 err = got_error_from_errno("fclose");
7664 goto done;
7666 f = NULL;
7667 err = histedit_run_editor(histedit_cmds, path, commits, repo);
7668 if (err) {
7669 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7670 err->code != GOT_ERR_HISTEDIT_CMD)
7671 goto done;
7672 err = histedit_edit_list_retry(histedit_cmds, err,
7673 commits, path, branch_name, repo);
7676 done:
7677 if (f && fclose(f) != 0 && err == NULL)
7678 err = got_error_from_errno("fclose");
7679 if (path && unlink(path) != 0 && err == NULL)
7680 err = got_error_from_errno2("unlink", path);
7681 free(path);
7682 return err;
7685 static const struct got_error *
7686 histedit_save_list(struct got_histedit_list *histedit_cmds,
7687 struct got_worktree *worktree, struct got_repository *repo)
7689 const struct got_error *err = NULL;
7690 char *path = NULL;
7691 FILE *f = NULL;
7692 struct got_histedit_list_entry *hle;
7693 struct got_commit_object *commit = NULL;
7695 err = got_worktree_get_histedit_script_path(&path, worktree);
7696 if (err)
7697 return err;
7699 f = fopen(path, "w");
7700 if (f == NULL) {
7701 err = got_error_from_errno2("fopen", path);
7702 goto done;
7704 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7705 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
7706 repo);
7707 if (err)
7708 break;
7710 if (hle->logmsg) {
7711 int n = fprintf(f, "%c %s\n",
7712 GOT_HISTEDIT_MESG, hle->logmsg);
7713 if (n < 0) {
7714 err = got_ferror(f, GOT_ERR_IO);
7715 break;
7719 done:
7720 if (f && fclose(f) != 0 && err == NULL)
7721 err = got_error_from_errno("fclose");
7722 free(path);
7723 if (commit)
7724 got_object_commit_close(commit);
7725 return err;
7728 void
7729 histedit_free_list(struct got_histedit_list *histedit_cmds)
7731 struct got_histedit_list_entry *hle;
7733 while ((hle = TAILQ_FIRST(histedit_cmds))) {
7734 TAILQ_REMOVE(histedit_cmds, hle, entry);
7735 free(hle);
7739 static const struct got_error *
7740 histedit_load_list(struct got_histedit_list *histedit_cmds,
7741 const char *path, struct got_repository *repo)
7743 const struct got_error *err = NULL;
7744 FILE *f = NULL;
7746 f = fopen(path, "r");
7747 if (f == NULL) {
7748 err = got_error_from_errno2("fopen", path);
7749 goto done;
7752 err = histedit_parse_list(histedit_cmds, f, repo);
7753 done:
7754 if (f && fclose(f) != 0 && err == NULL)
7755 err = got_error_from_errno("fclose");
7756 return err;
7759 static const struct got_error *
7760 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
7761 const struct got_error *edit_err, struct got_object_id_queue *commits,
7762 const char *path, const char *branch_name, struct got_repository *repo)
7764 const struct got_error *err = NULL, *prev_err = edit_err;
7765 int resp = ' ';
7767 while (resp != 'c' && resp != 'r' && resp != 'a') {
7768 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
7769 "or (a)bort: ", getprogname(), prev_err->msg);
7770 resp = getchar();
7771 if (resp == '\n')
7772 resp = getchar();
7773 if (resp == 'c') {
7774 histedit_free_list(histedit_cmds);
7775 err = histedit_run_editor(histedit_cmds, path, commits,
7776 repo);
7777 if (err) {
7778 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7779 err->code != GOT_ERR_HISTEDIT_CMD)
7780 break;
7781 prev_err = err;
7782 resp = ' ';
7783 continue;
7785 break;
7786 } else if (resp == 'r') {
7787 histedit_free_list(histedit_cmds);
7788 err = histedit_edit_script(histedit_cmds,
7789 commits, branch_name, 0, repo);
7790 if (err) {
7791 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
7792 err->code != GOT_ERR_HISTEDIT_CMD)
7793 break;
7794 prev_err = err;
7795 resp = ' ';
7796 continue;
7798 break;
7799 } else if (resp == 'a') {
7800 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
7801 break;
7802 } else
7803 printf("invalid response '%c'\n", resp);
7806 return err;
7809 static const struct got_error *
7810 histedit_complete(struct got_worktree *worktree,
7811 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
7812 struct got_reference *branch, struct got_repository *repo)
7814 printf("Switching work tree to %s\n",
7815 got_ref_get_symref_target(branch));
7816 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
7817 branch, repo);
7820 static const struct got_error *
7821 show_histedit_progress(struct got_commit_object *commit,
7822 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
7824 const struct got_error *err;
7825 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7827 err = got_object_id_str(&old_id_str, hle->commit_id);
7828 if (err)
7829 goto done;
7831 if (new_id) {
7832 err = got_object_id_str(&new_id_str, new_id);
7833 if (err)
7834 goto done;
7837 old_id_str[12] = '\0';
7838 if (new_id_str)
7839 new_id_str[12] = '\0';
7841 if (hle->logmsg) {
7842 logmsg = strdup(hle->logmsg);
7843 if (logmsg == NULL) {
7844 err = got_error_from_errno("strdup");
7845 goto done;
7847 trim_logmsg(logmsg, 42);
7848 } else {
7849 err = get_short_logmsg(&logmsg, 42, commit);
7850 if (err)
7851 goto done;
7854 switch (hle->cmd->code) {
7855 case GOT_HISTEDIT_PICK:
7856 case GOT_HISTEDIT_EDIT:
7857 printf("%s -> %s: %s\n", old_id_str,
7858 new_id_str ? new_id_str : "no-op change", logmsg);
7859 break;
7860 case GOT_HISTEDIT_DROP:
7861 case GOT_HISTEDIT_FOLD:
7862 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
7863 logmsg);
7864 break;
7865 default:
7866 break;
7868 done:
7869 free(old_id_str);
7870 free(new_id_str);
7871 return err;
7874 static const struct got_error *
7875 histedit_commit(struct got_pathlist_head *merged_paths,
7876 struct got_worktree *worktree, struct got_fileindex *fileindex,
7877 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
7878 struct got_repository *repo)
7880 const struct got_error *err;
7881 struct got_commit_object *commit;
7882 struct got_object_id *new_commit_id;
7884 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
7885 && hle->logmsg == NULL) {
7886 err = histedit_edit_logmsg(hle, repo);
7887 if (err)
7888 return err;
7891 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7892 if (err)
7893 return err;
7895 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
7896 worktree, fileindex, tmp_branch, commit, hle->commit_id,
7897 hle->logmsg, repo);
7898 if (err) {
7899 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
7900 goto done;
7901 err = show_histedit_progress(commit, hle, NULL);
7902 } else {
7903 err = show_histedit_progress(commit, hle, new_commit_id);
7904 free(new_commit_id);
7906 done:
7907 got_object_commit_close(commit);
7908 return err;
7911 static const struct got_error *
7912 histedit_skip_commit(struct got_histedit_list_entry *hle,
7913 struct got_worktree *worktree, struct got_repository *repo)
7915 const struct got_error *error;
7916 struct got_commit_object *commit;
7918 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
7919 repo);
7920 if (error)
7921 return error;
7923 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
7924 if (error)
7925 return error;
7927 error = show_histedit_progress(commit, hle, NULL);
7928 got_object_commit_close(commit);
7929 return error;
7932 static const struct got_error *
7933 check_local_changes(void *arg, unsigned char status,
7934 unsigned char staged_status, const char *path,
7935 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7936 struct got_object_id *commit_id, int dirfd, const char *de_name)
7938 int *have_local_changes = arg;
7940 switch (status) {
7941 case GOT_STATUS_ADD:
7942 case GOT_STATUS_DELETE:
7943 case GOT_STATUS_MODIFY:
7944 case GOT_STATUS_CONFLICT:
7945 *have_local_changes = 1;
7946 return got_error(GOT_ERR_CANCELLED);
7947 default:
7948 break;
7951 switch (staged_status) {
7952 case GOT_STATUS_ADD:
7953 case GOT_STATUS_DELETE:
7954 case GOT_STATUS_MODIFY:
7955 *have_local_changes = 1;
7956 return got_error(GOT_ERR_CANCELLED);
7957 default:
7958 break;
7961 return NULL;
7964 static const struct got_error *
7965 cmd_histedit(int argc, char *argv[])
7967 const struct got_error *error = NULL;
7968 struct got_worktree *worktree = NULL;
7969 struct got_fileindex *fileindex = NULL;
7970 struct got_repository *repo = NULL;
7971 char *cwd = NULL;
7972 struct got_reference *branch = NULL;
7973 struct got_reference *tmp_branch = NULL;
7974 struct got_object_id *resume_commit_id = NULL;
7975 struct got_object_id *base_commit_id = NULL;
7976 struct got_object_id *head_commit_id = NULL;
7977 struct got_commit_object *commit = NULL;
7978 int ch, rebase_in_progress = 0;
7979 struct got_update_progress_arg upa;
7980 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
7981 int edit_logmsg_only = 0;
7982 const char *edit_script_path = NULL;
7983 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7984 struct got_object_id_queue commits;
7985 struct got_pathlist_head merged_paths;
7986 const struct got_object_id_queue *parent_ids;
7987 struct got_object_qid *pid;
7988 struct got_histedit_list histedit_cmds;
7989 struct got_histedit_list_entry *hle;
7991 SIMPLEQ_INIT(&commits);
7992 TAILQ_INIT(&histedit_cmds);
7993 TAILQ_INIT(&merged_paths);
7994 memset(&upa, 0, sizeof(upa));
7996 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
7997 switch (ch) {
7998 case 'a':
7999 abort_edit = 1;
8000 break;
8001 case 'c':
8002 continue_edit = 1;
8003 break;
8004 case 'F':
8005 edit_script_path = optarg;
8006 break;
8007 case 'm':
8008 edit_logmsg_only = 1;
8009 break;
8010 default:
8011 usage_histedit();
8012 /* NOTREACHED */
8016 argc -= optind;
8017 argv += optind;
8019 #ifndef PROFILE
8020 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8021 "unveil", NULL) == -1)
8022 err(1, "pledge");
8023 #endif
8024 if (abort_edit && continue_edit)
8025 errx(1, "histedit's -a and -c options are mutually exclusive");
8026 if (edit_script_path && edit_logmsg_only)
8027 errx(1, "histedit's -F and -m options are mutually exclusive");
8028 if (abort_edit && edit_logmsg_only)
8029 errx(1, "histedit's -a and -m options are mutually exclusive");
8030 if (continue_edit && edit_logmsg_only)
8031 errx(1, "histedit's -c and -m options are mutually exclusive");
8032 if (argc != 0)
8033 usage_histedit();
8036 * This command cannot apply unveil(2) in all cases because the
8037 * user may choose to run an editor to edit the histedit script
8038 * and to edit individual commit log messages.
8039 * unveil(2) traverses exec(2); if an editor is used we have to
8040 * apply unveil after edit script and log messages have been written.
8041 * XXX TODO: Make use of unveil(2) where possible.
8044 cwd = getcwd(NULL, 0);
8045 if (cwd == NULL) {
8046 error = got_error_from_errno("getcwd");
8047 goto done;
8049 error = got_worktree_open(&worktree, cwd);
8050 if (error) {
8051 if (error->code == GOT_ERR_NOT_WORKTREE)
8052 error = wrap_not_worktree_error(error, "histedit", cwd);
8053 goto done;
8056 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8057 NULL);
8058 if (error != NULL)
8059 goto done;
8061 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8062 if (error)
8063 goto done;
8064 if (rebase_in_progress) {
8065 error = got_error(GOT_ERR_REBASING);
8066 goto done;
8069 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8070 if (error)
8071 goto done;
8073 if (edit_in_progress && edit_logmsg_only) {
8074 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8075 "histedit operation is in progress in this "
8076 "work tree and must be continued or aborted "
8077 "before the -m option can be used");
8078 goto done;
8081 if (edit_in_progress && abort_edit) {
8082 error = got_worktree_histedit_continue(&resume_commit_id,
8083 &tmp_branch, &branch, &base_commit_id, &fileindex,
8084 worktree, repo);
8085 if (error)
8086 goto done;
8087 printf("Switching work tree to %s\n",
8088 got_ref_get_symref_target(branch));
8089 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8090 branch, base_commit_id, update_progress, &upa);
8091 if (error)
8092 goto done;
8093 printf("Histedit of %s aborted\n",
8094 got_ref_get_symref_target(branch));
8095 print_update_progress_stats(&upa);
8096 goto done; /* nothing else to do */
8097 } else if (abort_edit) {
8098 error = got_error(GOT_ERR_NOT_HISTEDIT);
8099 goto done;
8102 if (continue_edit) {
8103 char *path;
8105 if (!edit_in_progress) {
8106 error = got_error(GOT_ERR_NOT_HISTEDIT);
8107 goto done;
8110 error = got_worktree_get_histedit_script_path(&path, worktree);
8111 if (error)
8112 goto done;
8114 error = histedit_load_list(&histedit_cmds, path, repo);
8115 free(path);
8116 if (error)
8117 goto done;
8119 error = got_worktree_histedit_continue(&resume_commit_id,
8120 &tmp_branch, &branch, &base_commit_id, &fileindex,
8121 worktree, repo);
8122 if (error)
8123 goto done;
8125 error = got_ref_resolve(&head_commit_id, repo, branch);
8126 if (error)
8127 goto done;
8129 error = got_object_open_as_commit(&commit, repo,
8130 head_commit_id);
8131 if (error)
8132 goto done;
8133 parent_ids = got_object_commit_get_parent_ids(commit);
8134 pid = SIMPLEQ_FIRST(parent_ids);
8135 if (pid == NULL) {
8136 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8137 goto done;
8139 error = collect_commits(&commits, head_commit_id, pid->id,
8140 base_commit_id, got_worktree_get_path_prefix(worktree),
8141 GOT_ERR_HISTEDIT_PATH, repo);
8142 got_object_commit_close(commit);
8143 commit = NULL;
8144 if (error)
8145 goto done;
8146 } else {
8147 if (edit_in_progress) {
8148 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8149 goto done;
8152 error = got_ref_open(&branch, repo,
8153 got_worktree_get_head_ref_name(worktree), 0);
8154 if (error != NULL)
8155 goto done;
8157 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8158 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8159 "will not edit commit history of a branch outside "
8160 "the \"refs/heads/\" reference namespace");
8161 goto done;
8164 error = got_ref_resolve(&head_commit_id, repo, branch);
8165 got_ref_close(branch);
8166 branch = NULL;
8167 if (error)
8168 goto done;
8170 error = got_object_open_as_commit(&commit, repo,
8171 head_commit_id);
8172 if (error)
8173 goto done;
8174 parent_ids = got_object_commit_get_parent_ids(commit);
8175 pid = SIMPLEQ_FIRST(parent_ids);
8176 if (pid == NULL) {
8177 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8178 goto done;
8180 error = collect_commits(&commits, head_commit_id, pid->id,
8181 got_worktree_get_base_commit_id(worktree),
8182 got_worktree_get_path_prefix(worktree),
8183 GOT_ERR_HISTEDIT_PATH, repo);
8184 got_object_commit_close(commit);
8185 commit = NULL;
8186 if (error)
8187 goto done;
8189 if (SIMPLEQ_EMPTY(&commits)) {
8190 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8191 goto done;
8194 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8195 &base_commit_id, &fileindex, worktree, repo);
8196 if (error)
8197 goto done;
8199 if (edit_script_path) {
8200 error = histedit_load_list(&histedit_cmds,
8201 edit_script_path, repo);
8202 if (error) {
8203 got_worktree_histedit_abort(worktree, fileindex,
8204 repo, branch, base_commit_id,
8205 update_progress, &upa);
8206 print_update_progress_stats(&upa);
8207 goto done;
8209 } else {
8210 const char *branch_name;
8211 branch_name = got_ref_get_symref_target(branch);
8212 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8213 branch_name += 11;
8214 error = histedit_edit_script(&histedit_cmds, &commits,
8215 branch_name, edit_logmsg_only, repo);
8216 if (error) {
8217 got_worktree_histedit_abort(worktree, fileindex,
8218 repo, branch, base_commit_id,
8219 update_progress, &upa);
8220 print_update_progress_stats(&upa);
8221 goto done;
8226 error = histedit_save_list(&histedit_cmds, worktree,
8227 repo);
8228 if (error) {
8229 got_worktree_histedit_abort(worktree, fileindex,
8230 repo, branch, base_commit_id,
8231 update_progress, &upa);
8232 print_update_progress_stats(&upa);
8233 goto done;
8238 error = histedit_check_script(&histedit_cmds, &commits, repo);
8239 if (error)
8240 goto done;
8242 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8243 if (resume_commit_id) {
8244 if (got_object_id_cmp(hle->commit_id,
8245 resume_commit_id) != 0)
8246 continue;
8248 resume_commit_id = NULL;
8249 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8250 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8251 error = histedit_skip_commit(hle, worktree,
8252 repo);
8253 if (error)
8254 goto done;
8255 } else {
8256 struct got_pathlist_head paths;
8257 int have_changes = 0;
8259 TAILQ_INIT(&paths);
8260 error = got_pathlist_append(&paths, "", NULL);
8261 if (error)
8262 goto done;
8263 error = got_worktree_status(worktree, &paths,
8264 repo, check_local_changes, &have_changes,
8265 check_cancelled, NULL);
8266 got_pathlist_free(&paths);
8267 if (error) {
8268 if (error->code != GOT_ERR_CANCELLED)
8269 goto done;
8270 if (sigint_received || sigpipe_received)
8271 goto done;
8273 if (have_changes) {
8274 error = histedit_commit(NULL, worktree,
8275 fileindex, tmp_branch, hle, repo);
8276 if (error)
8277 goto done;
8278 } else {
8279 error = got_object_open_as_commit(
8280 &commit, repo, hle->commit_id);
8281 if (error)
8282 goto done;
8283 error = show_histedit_progress(commit,
8284 hle, NULL);
8285 got_object_commit_close(commit);
8286 commit = NULL;
8287 if (error)
8288 goto done;
8291 continue;
8294 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8295 error = histedit_skip_commit(hle, worktree, repo);
8296 if (error)
8297 goto done;
8298 continue;
8301 error = got_object_open_as_commit(&commit, repo,
8302 hle->commit_id);
8303 if (error)
8304 goto done;
8305 parent_ids = got_object_commit_get_parent_ids(commit);
8306 pid = SIMPLEQ_FIRST(parent_ids);
8308 error = got_worktree_histedit_merge_files(&merged_paths,
8309 worktree, fileindex, pid->id, hle->commit_id, repo,
8310 update_progress, &upa, check_cancelled, NULL);
8311 if (error)
8312 goto done;
8313 got_object_commit_close(commit);
8314 commit = NULL;
8316 print_update_progress_stats(&upa);
8317 if (upa.conflicts > 0)
8318 rebase_status = GOT_STATUS_CONFLICT;
8320 if (rebase_status == GOT_STATUS_CONFLICT) {
8321 error = show_rebase_merge_conflict(hle->commit_id,
8322 repo);
8323 if (error)
8324 goto done;
8325 got_worktree_rebase_pathlist_free(&merged_paths);
8326 break;
8329 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8330 char *id_str;
8331 error = got_object_id_str(&id_str, hle->commit_id);
8332 if (error)
8333 goto done;
8334 printf("Stopping histedit for amending commit %s\n",
8335 id_str);
8336 free(id_str);
8337 got_worktree_rebase_pathlist_free(&merged_paths);
8338 error = got_worktree_histedit_postpone(worktree,
8339 fileindex);
8340 goto done;
8343 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8344 error = histedit_skip_commit(hle, worktree, repo);
8345 if (error)
8346 goto done;
8347 continue;
8350 error = histedit_commit(&merged_paths, worktree, fileindex,
8351 tmp_branch, hle, repo);
8352 got_worktree_rebase_pathlist_free(&merged_paths);
8353 if (error)
8354 goto done;
8357 if (rebase_status == GOT_STATUS_CONFLICT) {
8358 error = got_worktree_histedit_postpone(worktree, fileindex);
8359 if (error)
8360 goto done;
8361 error = got_error_msg(GOT_ERR_CONFLICTS,
8362 "conflicts must be resolved before histedit can continue");
8363 } else
8364 error = histedit_complete(worktree, fileindex, tmp_branch,
8365 branch, repo);
8366 done:
8367 got_object_id_queue_free(&commits);
8368 histedit_free_list(&histedit_cmds);
8369 free(head_commit_id);
8370 free(base_commit_id);
8371 free(resume_commit_id);
8372 if (commit)
8373 got_object_commit_close(commit);
8374 if (branch)
8375 got_ref_close(branch);
8376 if (tmp_branch)
8377 got_ref_close(tmp_branch);
8378 if (worktree)
8379 got_worktree_close(worktree);
8380 if (repo)
8381 got_repo_close(repo);
8382 return error;
8385 __dead static void
8386 usage_integrate(void)
8388 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8389 exit(1);
8392 static const struct got_error *
8393 cmd_integrate(int argc, char *argv[])
8395 const struct got_error *error = NULL;
8396 struct got_repository *repo = NULL;
8397 struct got_worktree *worktree = NULL;
8398 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8399 const char *branch_arg = NULL;
8400 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8401 struct got_fileindex *fileindex = NULL;
8402 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8403 int ch;
8404 struct got_update_progress_arg upa;
8406 while ((ch = getopt(argc, argv, "")) != -1) {
8407 switch (ch) {
8408 default:
8409 usage_integrate();
8410 /* NOTREACHED */
8414 argc -= optind;
8415 argv += optind;
8417 if (argc != 1)
8418 usage_integrate();
8419 branch_arg = argv[0];
8421 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8422 "unveil", NULL) == -1)
8423 err(1, "pledge");
8425 cwd = getcwd(NULL, 0);
8426 if (cwd == NULL) {
8427 error = got_error_from_errno("getcwd");
8428 goto done;
8431 error = got_worktree_open(&worktree, cwd);
8432 if (error) {
8433 if (error->code == GOT_ERR_NOT_WORKTREE)
8434 error = wrap_not_worktree_error(error, "integrate",
8435 cwd);
8436 goto done;
8439 error = check_rebase_or_histedit_in_progress(worktree);
8440 if (error)
8441 goto done;
8443 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8444 NULL);
8445 if (error != NULL)
8446 goto done;
8448 error = apply_unveil(got_repo_get_path(repo), 0,
8449 got_worktree_get_root_path(worktree));
8450 if (error)
8451 goto done;
8453 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8454 error = got_error_from_errno("asprintf");
8455 goto done;
8458 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8459 &base_branch_ref, worktree, refname, repo);
8460 if (error)
8461 goto done;
8463 refname = strdup(got_ref_get_name(branch_ref));
8464 if (refname == NULL) {
8465 error = got_error_from_errno("strdup");
8466 got_worktree_integrate_abort(worktree, fileindex, repo,
8467 branch_ref, base_branch_ref);
8468 goto done;
8470 base_refname = strdup(got_ref_get_name(base_branch_ref));
8471 if (base_refname == NULL) {
8472 error = got_error_from_errno("strdup");
8473 got_worktree_integrate_abort(worktree, fileindex, repo,
8474 branch_ref, base_branch_ref);
8475 goto done;
8478 error = got_ref_resolve(&commit_id, repo, branch_ref);
8479 if (error)
8480 goto done;
8482 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8483 if (error)
8484 goto done;
8486 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8487 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8488 "specified branch has already been integrated");
8489 got_worktree_integrate_abort(worktree, fileindex, repo,
8490 branch_ref, base_branch_ref);
8491 goto done;
8494 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8495 if (error) {
8496 if (error->code == GOT_ERR_ANCESTRY)
8497 error = got_error(GOT_ERR_REBASE_REQUIRED);
8498 got_worktree_integrate_abort(worktree, fileindex, repo,
8499 branch_ref, base_branch_ref);
8500 goto done;
8503 memset(&upa, 0, sizeof(upa));
8504 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8505 branch_ref, base_branch_ref, update_progress, &upa,
8506 check_cancelled, NULL);
8507 if (error)
8508 goto done;
8510 printf("Integrated %s into %s\n", refname, base_refname);
8511 print_update_progress_stats(&upa);
8512 done:
8513 if (repo)
8514 got_repo_close(repo);
8515 if (worktree)
8516 got_worktree_close(worktree);
8517 free(cwd);
8518 free(base_commit_id);
8519 free(commit_id);
8520 free(refname);
8521 free(base_refname);
8522 return error;
8525 __dead static void
8526 usage_stage(void)
8528 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8529 "[file-path ...]\n",
8530 getprogname());
8531 exit(1);
8534 static const struct got_error *
8535 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8536 const char *path, struct got_object_id *blob_id,
8537 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8538 int dirfd, const char *de_name)
8540 const struct got_error *err = NULL;
8541 char *id_str = NULL;
8543 if (staged_status != GOT_STATUS_ADD &&
8544 staged_status != GOT_STATUS_MODIFY &&
8545 staged_status != GOT_STATUS_DELETE)
8546 return NULL;
8548 if (staged_status == GOT_STATUS_ADD ||
8549 staged_status == GOT_STATUS_MODIFY)
8550 err = got_object_id_str(&id_str, staged_blob_id);
8551 else
8552 err = got_object_id_str(&id_str, blob_id);
8553 if (err)
8554 return err;
8556 printf("%s %c %s\n", id_str, staged_status, path);
8557 free(id_str);
8558 return NULL;
8561 static const struct got_error *
8562 cmd_stage(int argc, char *argv[])
8564 const struct got_error *error = NULL;
8565 struct got_repository *repo = NULL;
8566 struct got_worktree *worktree = NULL;
8567 char *cwd = NULL;
8568 struct got_pathlist_head paths;
8569 struct got_pathlist_entry *pe;
8570 int ch, list_stage = 0, pflag = 0;
8571 FILE *patch_script_file = NULL;
8572 const char *patch_script_path = NULL;
8573 struct choose_patch_arg cpa;
8575 TAILQ_INIT(&paths);
8577 while ((ch = getopt(argc, argv, "lpF:")) != -1) {
8578 switch (ch) {
8579 case 'l':
8580 list_stage = 1;
8581 break;
8582 case 'p':
8583 pflag = 1;
8584 break;
8585 case 'F':
8586 patch_script_path = optarg;
8587 break;
8588 default:
8589 usage_stage();
8590 /* NOTREACHED */
8594 argc -= optind;
8595 argv += optind;
8597 #ifndef PROFILE
8598 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8599 "unveil", NULL) == -1)
8600 err(1, "pledge");
8601 #endif
8602 if (list_stage && (pflag || patch_script_path))
8603 errx(1, "-l option cannot be used with other options");
8604 if (patch_script_path && !pflag)
8605 errx(1, "-F option can only be used together with -p option");
8607 cwd = getcwd(NULL, 0);
8608 if (cwd == NULL) {
8609 error = got_error_from_errno("getcwd");
8610 goto done;
8613 error = got_worktree_open(&worktree, cwd);
8614 if (error) {
8615 if (error->code == GOT_ERR_NOT_WORKTREE)
8616 error = wrap_not_worktree_error(error, "stage", cwd);
8617 goto done;
8620 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8621 NULL);
8622 if (error != NULL)
8623 goto done;
8625 if (patch_script_path) {
8626 patch_script_file = fopen(patch_script_path, "r");
8627 if (patch_script_file == NULL) {
8628 error = got_error_from_errno2("fopen",
8629 patch_script_path);
8630 goto done;
8633 error = apply_unveil(got_repo_get_path(repo), 0,
8634 got_worktree_get_root_path(worktree));
8635 if (error)
8636 goto done;
8638 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8639 if (error)
8640 goto done;
8642 if (list_stage)
8643 error = got_worktree_status(worktree, &paths, repo,
8644 print_stage, NULL, check_cancelled, NULL);
8645 else {
8646 cpa.patch_script_file = patch_script_file;
8647 cpa.action = "stage";
8648 error = got_worktree_stage(worktree, &paths,
8649 pflag ? NULL : print_status, NULL,
8650 pflag ? choose_patch : NULL, &cpa, repo);
8652 done:
8653 if (patch_script_file && fclose(patch_script_file) == EOF &&
8654 error == NULL)
8655 error = got_error_from_errno2("fclose", patch_script_path);
8656 if (repo)
8657 got_repo_close(repo);
8658 if (worktree)
8659 got_worktree_close(worktree);
8660 TAILQ_FOREACH(pe, &paths, entry)
8661 free((char *)pe->path);
8662 got_pathlist_free(&paths);
8663 free(cwd);
8664 return error;
8667 __dead static void
8668 usage_unstage(void)
8670 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
8671 "[file-path ...]\n",
8672 getprogname());
8673 exit(1);
8677 static const struct got_error *
8678 cmd_unstage(int argc, char *argv[])
8680 const struct got_error *error = NULL;
8681 struct got_repository *repo = NULL;
8682 struct got_worktree *worktree = NULL;
8683 char *cwd = NULL;
8684 struct got_pathlist_head paths;
8685 struct got_pathlist_entry *pe;
8686 int ch, pflag = 0;
8687 struct got_update_progress_arg upa;
8688 FILE *patch_script_file = NULL;
8689 const char *patch_script_path = NULL;
8690 struct choose_patch_arg cpa;
8692 TAILQ_INIT(&paths);
8694 while ((ch = getopt(argc, argv, "pF:")) != -1) {
8695 switch (ch) {
8696 case 'p':
8697 pflag = 1;
8698 break;
8699 case 'F':
8700 patch_script_path = optarg;
8701 break;
8702 default:
8703 usage_unstage();
8704 /* NOTREACHED */
8708 argc -= optind;
8709 argv += optind;
8711 #ifndef PROFILE
8712 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8713 "unveil", NULL) == -1)
8714 err(1, "pledge");
8715 #endif
8716 if (patch_script_path && !pflag)
8717 errx(1, "-F option can only be used together with -p option");
8719 cwd = getcwd(NULL, 0);
8720 if (cwd == NULL) {
8721 error = got_error_from_errno("getcwd");
8722 goto done;
8725 error = got_worktree_open(&worktree, cwd);
8726 if (error) {
8727 if (error->code == GOT_ERR_NOT_WORKTREE)
8728 error = wrap_not_worktree_error(error, "unstage", cwd);
8729 goto done;
8732 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8733 NULL);
8734 if (error != NULL)
8735 goto done;
8737 if (patch_script_path) {
8738 patch_script_file = fopen(patch_script_path, "r");
8739 if (patch_script_file == NULL) {
8740 error = got_error_from_errno2("fopen",
8741 patch_script_path);
8742 goto done;
8746 error = apply_unveil(got_repo_get_path(repo), 0,
8747 got_worktree_get_root_path(worktree));
8748 if (error)
8749 goto done;
8751 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8752 if (error)
8753 goto done;
8755 cpa.patch_script_file = patch_script_file;
8756 cpa.action = "unstage";
8757 memset(&upa, 0, sizeof(upa));
8758 error = got_worktree_unstage(worktree, &paths, update_progress,
8759 &upa, pflag ? choose_patch : NULL, &cpa, repo);
8760 if (!error)
8761 print_update_progress_stats(&upa);
8762 done:
8763 if (patch_script_file && fclose(patch_script_file) == EOF &&
8764 error == NULL)
8765 error = got_error_from_errno2("fclose", patch_script_path);
8766 if (repo)
8767 got_repo_close(repo);
8768 if (worktree)
8769 got_worktree_close(worktree);
8770 TAILQ_FOREACH(pe, &paths, entry)
8771 free((char *)pe->path);
8772 got_pathlist_free(&paths);
8773 free(cwd);
8774 return error;
8777 __dead static void
8778 usage_cat(void)
8780 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
8781 "arg1 [arg2 ...]\n", getprogname());
8782 exit(1);
8785 static const struct got_error *
8786 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8788 const struct got_error *err;
8789 struct got_blob_object *blob;
8791 err = got_object_open_as_blob(&blob, repo, id, 8192);
8792 if (err)
8793 return err;
8795 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8796 got_object_blob_close(blob);
8797 return err;
8800 static const struct got_error *
8801 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8803 const struct got_error *err;
8804 struct got_tree_object *tree;
8805 int nentries, i;
8807 err = got_object_open_as_tree(&tree, repo, id);
8808 if (err)
8809 return err;
8811 nentries = got_object_tree_get_nentries(tree);
8812 for (i = 0; i < nentries; i++) {
8813 struct got_tree_entry *te;
8814 char *id_str;
8815 if (sigint_received || sigpipe_received)
8816 break;
8817 te = got_object_tree_get_entry(tree, i);
8818 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8819 if (err)
8820 break;
8821 fprintf(outfile, "%s %.7o %s\n", id_str,
8822 got_tree_entry_get_mode(te),
8823 got_tree_entry_get_name(te));
8824 free(id_str);
8827 got_object_tree_close(tree);
8828 return err;
8831 static const struct got_error *
8832 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8834 const struct got_error *err;
8835 struct got_commit_object *commit;
8836 const struct got_object_id_queue *parent_ids;
8837 struct got_object_qid *pid;
8838 char *id_str = NULL;
8839 const char *logmsg = NULL;
8841 err = got_object_open_as_commit(&commit, repo, id);
8842 if (err)
8843 return err;
8845 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8846 if (err)
8847 goto done;
8849 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8850 parent_ids = got_object_commit_get_parent_ids(commit);
8851 fprintf(outfile, "numparents %d\n",
8852 got_object_commit_get_nparents(commit));
8853 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
8854 char *pid_str;
8855 err = got_object_id_str(&pid_str, pid->id);
8856 if (err)
8857 goto done;
8858 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8859 free(pid_str);
8861 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
8862 got_object_commit_get_author(commit),
8863 got_object_commit_get_author_time(commit));
8865 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
8866 got_object_commit_get_author(commit),
8867 got_object_commit_get_committer_time(commit));
8869 logmsg = got_object_commit_get_logmsg_raw(commit);
8870 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8871 fprintf(outfile, "%s", logmsg);
8872 done:
8873 free(id_str);
8874 got_object_commit_close(commit);
8875 return err;
8878 static const struct got_error *
8879 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8881 const struct got_error *err;
8882 struct got_tag_object *tag;
8883 char *id_str = NULL;
8884 const char *tagmsg = NULL;
8886 err = got_object_open_as_tag(&tag, repo, id);
8887 if (err)
8888 return err;
8890 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8891 if (err)
8892 goto done;
8894 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8896 switch (got_object_tag_get_object_type(tag)) {
8897 case GOT_OBJ_TYPE_BLOB:
8898 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8899 GOT_OBJ_LABEL_BLOB);
8900 break;
8901 case GOT_OBJ_TYPE_TREE:
8902 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8903 GOT_OBJ_LABEL_TREE);
8904 break;
8905 case GOT_OBJ_TYPE_COMMIT:
8906 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8907 GOT_OBJ_LABEL_COMMIT);
8908 break;
8909 case GOT_OBJ_TYPE_TAG:
8910 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8911 GOT_OBJ_LABEL_TAG);
8912 break;
8913 default:
8914 break;
8917 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8918 got_object_tag_get_name(tag));
8920 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
8921 got_object_tag_get_tagger(tag),
8922 got_object_tag_get_tagger_time(tag));
8924 tagmsg = got_object_tag_get_message(tag);
8925 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8926 fprintf(outfile, "%s", tagmsg);
8927 done:
8928 free(id_str);
8929 got_object_tag_close(tag);
8930 return err;
8933 static const struct got_error *
8934 cmd_cat(int argc, char *argv[])
8936 const struct got_error *error;
8937 struct got_repository *repo = NULL;
8938 struct got_worktree *worktree = NULL;
8939 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8940 const char *commit_id_str = NULL;
8941 struct got_object_id *id = NULL, *commit_id = NULL;
8942 int ch, obj_type, i, force_path = 0;
8944 #ifndef PROFILE
8945 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8946 NULL) == -1)
8947 err(1, "pledge");
8948 #endif
8950 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
8951 switch (ch) {
8952 case 'c':
8953 commit_id_str = optarg;
8954 break;
8955 case 'r':
8956 repo_path = realpath(optarg, NULL);
8957 if (repo_path == NULL)
8958 return got_error_from_errno2("realpath",
8959 optarg);
8960 got_path_strip_trailing_slashes(repo_path);
8961 break;
8962 case 'P':
8963 force_path = 1;
8964 break;
8965 default:
8966 usage_cat();
8967 /* NOTREACHED */
8971 argc -= optind;
8972 argv += optind;
8974 cwd = getcwd(NULL, 0);
8975 if (cwd == NULL) {
8976 error = got_error_from_errno("getcwd");
8977 goto done;
8979 error = got_worktree_open(&worktree, cwd);
8980 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8981 goto done;
8982 if (worktree) {
8983 if (repo_path == NULL) {
8984 repo_path = strdup(
8985 got_worktree_get_repo_path(worktree));
8986 if (repo_path == NULL) {
8987 error = got_error_from_errno("strdup");
8988 goto done;
8993 if (repo_path == NULL) {
8994 repo_path = getcwd(NULL, 0);
8995 if (repo_path == NULL)
8996 return got_error_from_errno("getcwd");
8999 error = got_repo_open(&repo, repo_path, NULL);
9000 free(repo_path);
9001 if (error != NULL)
9002 goto done;
9004 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9005 if (error)
9006 goto done;
9008 if (commit_id_str == NULL)
9009 commit_id_str = GOT_REF_HEAD;
9010 error = got_repo_match_object_id(&commit_id, NULL,
9011 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9012 if (error)
9013 goto done;
9015 for (i = 0; i < argc; i++) {
9016 if (force_path) {
9017 error = got_object_id_by_path(&id, repo, commit_id,
9018 argv[i]);
9019 if (error)
9020 break;
9021 } else {
9022 error = got_repo_match_object_id(&id, &label, argv[i],
9023 GOT_OBJ_TYPE_ANY, 0, repo);
9024 if (error) {
9025 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9026 error->code != GOT_ERR_NOT_REF)
9027 break;
9028 error = got_object_id_by_path(&id, repo,
9029 commit_id, argv[i]);
9030 if (error)
9031 break;
9035 error = got_object_get_type(&obj_type, repo, id);
9036 if (error)
9037 break;
9039 switch (obj_type) {
9040 case GOT_OBJ_TYPE_BLOB:
9041 error = cat_blob(id, repo, stdout);
9042 break;
9043 case GOT_OBJ_TYPE_TREE:
9044 error = cat_tree(id, repo, stdout);
9045 break;
9046 case GOT_OBJ_TYPE_COMMIT:
9047 error = cat_commit(id, repo, stdout);
9048 break;
9049 case GOT_OBJ_TYPE_TAG:
9050 error = cat_tag(id, repo, stdout);
9051 break;
9052 default:
9053 error = got_error(GOT_ERR_OBJ_TYPE);
9054 break;
9056 if (error)
9057 break;
9058 free(label);
9059 label = NULL;
9060 free(id);
9061 id = NULL;
9063 done:
9064 free(label);
9065 free(id);
9066 free(commit_id);
9067 if (worktree)
9068 got_worktree_close(worktree);
9069 if (repo) {
9070 const struct got_error *repo_error;
9071 repo_error = got_repo_close(repo);
9072 if (error == NULL)
9073 error = repo_error;
9075 return error;