Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/param.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
59 #ifndef nitems
60 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
61 #endif
63 static volatile sig_atomic_t sigint_received;
64 static volatile sig_atomic_t sigpipe_received;
66 static void
67 catch_sigint(int signo)
68 {
69 sigint_received = 1;
70 }
72 static void
73 catch_sigpipe(int signo)
74 {
75 sigpipe_received = 1;
76 }
79 struct got_cmd {
80 const char *cmd_name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 const char *cmd_alias;
84 };
86 __dead static void usage(int);
87 __dead static void usage_init(void);
88 __dead static void usage_import(void);
89 __dead static void usage_clone(void);
90 __dead static void usage_fetch(void);
91 __dead static void usage_checkout(void);
92 __dead static void usage_update(void);
93 __dead static void usage_log(void);
94 __dead static void usage_diff(void);
95 __dead static void usage_blame(void);
96 __dead static void usage_tree(void);
97 __dead static void usage_status(void);
98 __dead static void usage_ref(void);
99 __dead static void usage_branch(void);
100 __dead static void usage_tag(void);
101 __dead static void usage_add(void);
102 __dead static void usage_remove(void);
103 __dead static void usage_revert(void);
104 __dead static void usage_commit(void);
105 __dead static void usage_cherrypick(void);
106 __dead static void usage_backout(void);
107 __dead static void usage_rebase(void);
108 __dead static void usage_histedit(void);
109 __dead static void usage_integrate(void);
110 __dead static void usage_stage(void);
111 __dead static void usage_unstage(void);
112 __dead static void usage_cat(void);
113 __dead static void usage_info(void);
115 static const struct got_error* cmd_init(int, char *[]);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_fetch(int, char *[]);
119 static const struct got_error* cmd_checkout(int, char *[]);
120 static const struct got_error* cmd_update(int, char *[]);
121 static const struct got_error* cmd_log(int, char *[]);
122 static const struct got_error* cmd_diff(int, char *[]);
123 static const struct got_error* cmd_blame(int, char *[]);
124 static const struct got_error* cmd_tree(int, char *[]);
125 static const struct got_error* cmd_status(int, char *[]);
126 static const struct got_error* cmd_ref(int, char *[]);
127 static const struct got_error* cmd_branch(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_rebase(int, char *[]);
136 static const struct got_error* cmd_histedit(int, char *[]);
137 static const struct got_error* cmd_integrate(int, char *[]);
138 static const struct got_error* cmd_stage(int, char *[]);
139 static const struct got_error* cmd_unstage(int, char *[]);
140 static const struct got_error* cmd_cat(int, char *[]);
141 static const struct got_error* cmd_info(int, char *[]);
143 static struct got_cmd got_commands[] = {
144 { "init", cmd_init, usage_init, "" },
145 { "import", cmd_import, usage_import, "im" },
146 { "clone", cmd_clone, usage_clone, "cl" },
147 { "fetch", cmd_fetch, usage_fetch, "fe" },
148 { "checkout", cmd_checkout, usage_checkout, "co" },
149 { "update", cmd_update, usage_update, "up" },
150 { "log", cmd_log, usage_log, "" },
151 { "diff", cmd_diff, usage_diff, "di" },
152 { "blame", cmd_blame, usage_blame, "bl" },
153 { "tree", cmd_tree, usage_tree, "tr" },
154 { "status", cmd_status, usage_status, "st" },
155 { "ref", cmd_ref, usage_ref, "" },
156 { "branch", cmd_branch, usage_branch, "br" },
157 { "tag", cmd_tag, usage_tag, "" },
158 { "add", cmd_add, usage_add, "" },
159 { "remove", cmd_remove, usage_remove, "rm" },
160 { "revert", cmd_revert, usage_revert, "rv" },
161 { "commit", cmd_commit, usage_commit, "ci" },
162 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
163 { "backout", cmd_backout, usage_backout, "bo" },
164 { "rebase", cmd_rebase, usage_rebase, "rb" },
165 { "histedit", cmd_histedit, usage_histedit, "he" },
166 { "integrate", cmd_integrate, usage_integrate,"ig" },
167 { "stage", cmd_stage, usage_stage, "sg" },
168 { "unstage", cmd_unstage, usage_unstage, "ug" },
169 { "cat", cmd_cat, usage_cat, "" },
170 { "info", cmd_info, usage_info, "" },
171 };
173 static void
174 list_commands(void)
176 int i;
178 fprintf(stderr, "commands:");
179 for (i = 0; i < nitems(got_commands); i++) {
180 struct got_cmd *cmd = &got_commands[i];
181 fprintf(stderr, " %s", cmd->cmd_name);
183 fputc('\n', stderr);
186 int
187 main(int argc, char *argv[])
189 struct got_cmd *cmd;
190 unsigned int i;
191 int ch;
192 int hflag = 0, Vflag = 0;
193 static struct option longopts[] = {
194 { "version", no_argument, NULL, 'V' },
195 { NULL, 0, NULL, 0}
196 };
198 setlocale(LC_CTYPE, "");
200 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
201 switch (ch) {
202 case 'h':
203 hflag = 1;
204 break;
205 case 'V':
206 Vflag = 1;
207 break;
208 default:
209 usage(hflag);
210 /* NOTREACHED */
214 argc -= optind;
215 argv += optind;
216 optind = 0;
218 if (Vflag) {
219 got_version_print_str();
220 return 1;
223 if (argc <= 0)
224 usage(hflag);
226 signal(SIGINT, catch_sigint);
227 signal(SIGPIPE, catch_sigpipe);
229 for (i = 0; i < nitems(got_commands); i++) {
230 const struct got_error *error;
232 cmd = &got_commands[i];
234 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
235 strcmp(cmd->cmd_alias, argv[0]) != 0)
236 continue;
238 if (hflag)
239 got_commands[i].cmd_usage();
241 error = got_commands[i].cmd_main(argc, argv);
242 if (error && error->code != GOT_ERR_CANCELLED &&
243 error->code != GOT_ERR_PRIVSEP_EXIT &&
244 !(sigpipe_received &&
245 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
246 !(sigint_received &&
247 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
248 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
249 return 1;
252 return 0;
255 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
256 list_commands();
257 return 1;
260 __dead static void
261 usage(int hflag)
263 fprintf(stderr, "usage: %s [-h] [-V | --version] command [arg ...]\n",
264 getprogname());
265 if (hflag)
266 list_commands();
267 exit(1);
270 static const struct got_error *
271 get_editor(char **abspath)
273 const struct got_error *err = NULL;
274 const char *editor;
276 *abspath = NULL;
278 editor = getenv("VISUAL");
279 if (editor == NULL)
280 editor = getenv("EDITOR");
282 if (editor) {
283 err = got_path_find_prog(abspath, editor);
284 if (err)
285 return err;
288 if (*abspath == NULL) {
289 *abspath = strdup("/bin/ed");
290 if (*abspath == NULL)
291 return got_error_from_errno("strdup");
294 return NULL;
297 static const struct got_error *
298 apply_unveil(const char *repo_path, int repo_read_only,
299 const char *worktree_path)
301 const struct got_error *err;
303 #ifdef PROFILE
304 if (unveil("gmon.out", "rwc") != 0)
305 return got_error_from_errno2("unveil", "gmon.out");
306 #endif
307 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
308 return got_error_from_errno2("unveil", repo_path);
310 if (worktree_path && unveil(worktree_path, "rwc") != 0)
311 return got_error_from_errno2("unveil", worktree_path);
313 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
314 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
316 err = got_privsep_unveil_exec_helpers();
317 if (err != NULL)
318 return err;
320 if (unveil(NULL, NULL) != 0)
321 return got_error_from_errno("unveil");
323 return NULL;
326 __dead static void
327 usage_init(void)
329 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
330 exit(1);
333 static const struct got_error *
334 cmd_init(int argc, char *argv[])
336 const struct got_error *error = NULL;
337 char *repo_path = NULL;
338 int ch;
340 while ((ch = getopt(argc, argv, "")) != -1) {
341 switch (ch) {
342 default:
343 usage_init();
344 /* NOTREACHED */
348 argc -= optind;
349 argv += optind;
351 #ifndef PROFILE
352 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
353 err(1, "pledge");
354 #endif
355 if (argc != 1)
356 usage_init();
358 repo_path = strdup(argv[0]);
359 if (repo_path == NULL)
360 return got_error_from_errno("strdup");
362 got_path_strip_trailing_slashes(repo_path);
364 error = got_path_mkdir(repo_path);
365 if (error &&
366 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
367 goto done;
369 error = apply_unveil(repo_path, 0, NULL);
370 if (error)
371 goto done;
373 error = got_repo_init(repo_path);
374 done:
375 free(repo_path);
376 return error;
379 __dead static void
380 usage_import(void)
382 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
383 "[-r repository-path] [-I pattern] path\n", getprogname());
384 exit(1);
387 int
388 spawn_editor(const char *editor, const char *file)
390 pid_t pid;
391 sig_t sighup, sigint, sigquit;
392 int st = -1;
394 sighup = signal(SIGHUP, SIG_IGN);
395 sigint = signal(SIGINT, SIG_IGN);
396 sigquit = signal(SIGQUIT, SIG_IGN);
398 switch (pid = fork()) {
399 case -1:
400 goto doneediting;
401 case 0:
402 execl(editor, editor, file, (char *)NULL);
403 _exit(127);
406 while (waitpid(pid, &st, 0) == -1)
407 if (errno != EINTR)
408 break;
410 doneediting:
411 (void)signal(SIGHUP, sighup);
412 (void)signal(SIGINT, sigint);
413 (void)signal(SIGQUIT, sigquit);
415 if (!WIFEXITED(st)) {
416 errno = EINTR;
417 return -1;
420 return WEXITSTATUS(st);
423 static const struct got_error *
424 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
425 const char *initial_content)
427 const struct got_error *err = NULL;
428 char buf[1024];
429 struct stat st, st2;
430 FILE *fp;
431 int content_changed = 0;
432 size_t len;
434 *logmsg = NULL;
436 if (stat(logmsg_path, &st) == -1)
437 return got_error_from_errno2("stat", logmsg_path);
439 if (spawn_editor(editor, logmsg_path) == -1)
440 return got_error_from_errno("failed spawning editor");
442 if (stat(logmsg_path, &st2) == -1)
443 return got_error_from_errno("stat");
445 if (st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 *logmsg = malloc(st2.st_size + 1);
450 if (*logmsg == NULL)
451 return got_error_from_errno("malloc");
452 (*logmsg)[0] = '\0';
453 len = 0;
455 fp = fopen(logmsg_path, "r");
456 if (fp == NULL) {
457 err = got_error_from_errno("fopen");
458 goto done;
460 while (fgets(buf, sizeof(buf), fp) != NULL) {
461 if (!content_changed && strcmp(buf, initial_content) != 0)
462 content_changed = 1;
463 if (buf[0] == '#' || (len == 0 && buf[0] == '\n'))
464 continue; /* remove comments and leading empty lines */
465 len = strlcat(*logmsg, buf, st2.st_size);
467 fclose(fp);
469 while (len > 0 && (*logmsg)[len - 1] == '\n') {
470 (*logmsg)[len - 1] = '\0';
471 len--;
474 if (len == 0 || !content_changed)
475 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
476 "commit message cannot be empty, aborting");
477 done:
478 if (err) {
479 free(*logmsg);
480 *logmsg = NULL;
482 return err;
485 static const struct got_error *
486 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
487 const char *path_dir, const char *branch_name)
489 char *initial_content = NULL;
490 const struct got_error *err = NULL;
491 int initial_content_len;
492 int fd = -1;
494 initial_content_len = asprintf(&initial_content,
495 "\n# %s to be imported to branch %s\n", path_dir,
496 branch_name);
497 if (initial_content_len == -1)
498 return got_error_from_errno("asprintf");
500 err = got_opentemp_named_fd(logmsg_path, &fd,
501 GOT_TMPDIR_STR "/got-importmsg");
502 if (err)
503 goto done;
505 if (write(fd, initial_content, initial_content_len) == -1) {
506 err = got_error_from_errno2("write", *logmsg_path);
507 goto done;
510 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content);
511 done:
512 if (fd != -1 && close(fd) == -1 && err == NULL)
513 err = got_error_from_errno2("close", *logmsg_path);
514 free(initial_content);
515 return err;
518 static const struct got_error *
519 import_progress(void *arg, const char *path)
521 printf("A %s\n", path);
522 return NULL;
525 static const struct got_error *
526 get_author(char **author, struct got_repository *repo,
527 struct got_worktree *worktree)
529 const struct got_error *err = NULL;
530 const char *got_author = NULL, *name, *email;
531 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
533 *author = NULL;
535 if (worktree)
536 worktree_conf = got_worktree_get_gotconfig(worktree);
537 repo_conf = got_repo_get_gotconfig(repo);
539 /*
540 * Priority of potential author information sources, from most
541 * significant to least significant:
542 * 1) work tree's .got/got.conf file
543 * 2) repository's got.conf file
544 * 3) repository's git config file
545 * 4) environment variables
546 * 5) global git config files (in user's home directory or /etc)
547 */
549 if (worktree_conf)
550 got_author = got_gotconfig_get_author(worktree_conf);
551 if (got_author == NULL)
552 got_author = got_gotconfig_get_author(repo_conf);
553 if (got_author == NULL) {
554 name = got_repo_get_gitconfig_author_name(repo);
555 email = got_repo_get_gitconfig_author_email(repo);
556 if (name && email) {
557 if (asprintf(author, "%s <%s>", name, email) == -1)
558 return got_error_from_errno("asprintf");
559 return NULL;
562 got_author = getenv("GOT_AUTHOR");
563 if (got_author == NULL) {
564 name = got_repo_get_global_gitconfig_author_name(repo);
565 email = got_repo_get_global_gitconfig_author_email(
566 repo);
567 if (name && email) {
568 if (asprintf(author, "%s <%s>", name, email)
569 == -1)
570 return got_error_from_errno("asprintf");
571 return NULL;
573 /* TODO: Look up user in password database? */
574 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
578 *author = strdup(got_author);
579 if (*author == NULL)
580 return got_error_from_errno("strdup");
582 /*
583 * Really dumb email address check; we're only doing this to
584 * avoid git's object parser breaking on commits we create.
585 */
586 while (*got_author && *got_author != '<')
587 got_author++;
588 if (*got_author != '<') {
589 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
590 goto done;
592 while (*got_author && *got_author != '@')
593 got_author++;
594 if (*got_author != '@') {
595 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
596 goto done;
598 while (*got_author && *got_author != '>')
599 got_author++;
600 if (*got_author != '>')
601 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
602 done:
603 if (err) {
604 free(*author);
605 *author = NULL;
607 return err;
610 static const struct got_error *
611 get_gitconfig_path(char **gitconfig_path)
613 const char *homedir = getenv("HOME");
615 *gitconfig_path = NULL;
616 if (homedir) {
617 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
618 return got_error_from_errno("asprintf");
621 return NULL;
624 static const struct got_error *
625 cmd_import(int argc, char *argv[])
627 const struct got_error *error = NULL;
628 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
629 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
630 const char *branch_name = "main";
631 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
632 struct got_repository *repo = NULL;
633 struct got_reference *branch_ref = NULL, *head_ref = NULL;
634 struct got_object_id *new_commit_id = NULL;
635 int ch;
636 struct got_pathlist_head ignores;
637 struct got_pathlist_entry *pe;
638 int preserve_logmsg = 0;
640 TAILQ_INIT(&ignores);
642 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
643 switch (ch) {
644 case 'b':
645 branch_name = optarg;
646 break;
647 case 'm':
648 logmsg = strdup(optarg);
649 if (logmsg == NULL) {
650 error = got_error_from_errno("strdup");
651 goto done;
653 break;
654 case 'r':
655 repo_path = realpath(optarg, NULL);
656 if (repo_path == NULL) {
657 error = got_error_from_errno2("realpath",
658 optarg);
659 goto done;
661 break;
662 case 'I':
663 if (optarg[0] == '\0')
664 break;
665 error = got_pathlist_insert(&pe, &ignores, optarg,
666 NULL);
667 if (error)
668 goto done;
669 break;
670 default:
671 usage_import();
672 /* NOTREACHED */
676 argc -= optind;
677 argv += optind;
679 #ifndef PROFILE
680 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
681 "unveil",
682 NULL) == -1)
683 err(1, "pledge");
684 #endif
685 if (argc != 1)
686 usage_import();
688 if (repo_path == NULL) {
689 repo_path = getcwd(NULL, 0);
690 if (repo_path == NULL)
691 return got_error_from_errno("getcwd");
693 got_path_strip_trailing_slashes(repo_path);
694 error = get_gitconfig_path(&gitconfig_path);
695 if (error)
696 goto done;
697 error = got_repo_open(&repo, repo_path, gitconfig_path);
698 if (error)
699 goto done;
701 error = get_author(&author, repo, NULL);
702 if (error)
703 return error;
705 /*
706 * Don't let the user create a branch name with a leading '-'.
707 * While technically a valid reference name, this case is usually
708 * an unintended typo.
709 */
710 if (branch_name[0] == '-')
711 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
713 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
714 error = got_error_from_errno("asprintf");
715 goto done;
718 error = got_ref_open(&branch_ref, repo, refname, 0);
719 if (error) {
720 if (error->code != GOT_ERR_NOT_REF)
721 goto done;
722 } else {
723 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
724 "import target branch already exists");
725 goto done;
728 path_dir = realpath(argv[0], NULL);
729 if (path_dir == NULL) {
730 error = got_error_from_errno2("realpath", argv[0]);
731 goto done;
733 got_path_strip_trailing_slashes(path_dir);
735 /*
736 * unveil(2) traverses exec(2); if an editor is used we have
737 * to apply unveil after the log message has been written.
738 */
739 if (logmsg == NULL || strlen(logmsg) == 0) {
740 error = get_editor(&editor);
741 if (error)
742 goto done;
743 free(logmsg);
744 error = collect_import_msg(&logmsg, &logmsg_path, editor,
745 path_dir, refname);
746 if (error) {
747 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
748 logmsg_path != NULL)
749 preserve_logmsg = 1;
750 goto done;
754 if (unveil(path_dir, "r") != 0) {
755 error = got_error_from_errno2("unveil", path_dir);
756 if (logmsg_path)
757 preserve_logmsg = 1;
758 goto done;
761 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
762 if (error) {
763 if (logmsg_path)
764 preserve_logmsg = 1;
765 goto done;
768 error = got_repo_import(&new_commit_id, path_dir, logmsg,
769 author, &ignores, repo, import_progress, NULL);
770 if (error) {
771 if (logmsg_path)
772 preserve_logmsg = 1;
773 goto done;
776 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
777 if (error) {
778 if (logmsg_path)
779 preserve_logmsg = 1;
780 goto done;
783 error = got_ref_write(branch_ref, repo);
784 if (error) {
785 if (logmsg_path)
786 preserve_logmsg = 1;
787 goto done;
790 error = got_object_id_str(&id_str, new_commit_id);
791 if (error) {
792 if (logmsg_path)
793 preserve_logmsg = 1;
794 goto done;
797 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
798 if (error) {
799 if (error->code != GOT_ERR_NOT_REF) {
800 if (logmsg_path)
801 preserve_logmsg = 1;
802 goto done;
805 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
806 branch_ref);
807 if (error) {
808 if (logmsg_path)
809 preserve_logmsg = 1;
810 goto done;
813 error = got_ref_write(head_ref, repo);
814 if (error) {
815 if (logmsg_path)
816 preserve_logmsg = 1;
817 goto done;
821 printf("Created branch %s with commit %s\n",
822 got_ref_get_name(branch_ref), id_str);
823 done:
824 if (preserve_logmsg) {
825 fprintf(stderr, "%s: log message preserved in %s\n",
826 getprogname(), logmsg_path);
827 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
828 error = got_error_from_errno2("unlink", logmsg_path);
829 free(logmsg);
830 free(logmsg_path);
831 free(repo_path);
832 free(editor);
833 free(refname);
834 free(new_commit_id);
835 free(id_str);
836 free(author);
837 free(gitconfig_path);
838 if (branch_ref)
839 got_ref_close(branch_ref);
840 if (head_ref)
841 got_ref_close(head_ref);
842 return error;
845 __dead static void
846 usage_clone(void)
848 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
849 "[-R reference] repository-url [directory]\n", getprogname());
850 exit(1);
853 struct got_fetch_progress_arg {
854 char last_scaled_size[FMT_SCALED_STRSIZE];
855 int last_p_indexed;
856 int last_p_resolved;
857 int verbosity;
858 };
860 static const struct got_error *
861 fetch_progress(void *arg, const char *message, off_t packfile_size,
862 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
864 struct got_fetch_progress_arg *a = arg;
865 char scaled_size[FMT_SCALED_STRSIZE];
866 int p_indexed, p_resolved;
867 int print_size = 0, print_indexed = 0, print_resolved = 0;
869 if (a->verbosity < 0)
870 return NULL;
872 if (message && message[0] != '\0') {
873 printf("\rserver: %s", message);
874 fflush(stdout);
875 return NULL;
878 if (packfile_size > 0 || nobj_indexed > 0) {
879 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
880 (a->last_scaled_size[0] == '\0' ||
881 strcmp(scaled_size, a->last_scaled_size)) != 0) {
882 print_size = 1;
883 if (strlcpy(a->last_scaled_size, scaled_size,
884 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
885 return got_error(GOT_ERR_NO_SPACE);
887 if (nobj_indexed > 0) {
888 p_indexed = (nobj_indexed * 100) / nobj_total;
889 if (p_indexed != a->last_p_indexed) {
890 a->last_p_indexed = p_indexed;
891 print_indexed = 1;
892 print_size = 1;
895 if (nobj_resolved > 0) {
896 p_resolved = (nobj_resolved * 100) /
897 (nobj_total - nobj_loose);
898 if (p_resolved != a->last_p_resolved) {
899 a->last_p_resolved = p_resolved;
900 print_resolved = 1;
901 print_indexed = 1;
902 print_size = 1;
907 if (print_size || print_indexed || print_resolved)
908 printf("\r");
909 if (print_size)
910 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
911 if (print_indexed)
912 printf("; indexing %d%%", p_indexed);
913 if (print_resolved)
914 printf("; resolving deltas %d%%", p_resolved);
915 if (print_size || print_indexed || print_resolved)
916 fflush(stdout);
918 return NULL;
921 static const struct got_error *
922 create_symref(const char *refname, struct got_reference *target_ref,
923 int verbosity, struct got_repository *repo)
925 const struct got_error *err;
926 struct got_reference *head_symref;
928 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
929 if (err)
930 return err;
932 err = got_ref_write(head_symref, repo);
933 got_ref_close(head_symref);
934 if (err == NULL && verbosity > 0) {
935 printf("Created reference %s: %s\n", GOT_REF_HEAD,
936 got_ref_get_name(target_ref));
938 return err;
941 static const struct got_error *
942 list_remote_refs(struct got_pathlist_head *symrefs,
943 struct got_pathlist_head *refs)
945 const struct got_error *err;
946 struct got_pathlist_entry *pe;
948 TAILQ_FOREACH(pe, symrefs, entry) {
949 const char *refname = pe->path;
950 const char *targetref = pe->data;
952 printf("%s: %s\n", refname, targetref);
955 TAILQ_FOREACH(pe, refs, entry) {
956 const char *refname = pe->path;
957 struct got_object_id *id = pe->data;
958 char *id_str;
960 err = got_object_id_str(&id_str, id);
961 if (err)
962 return err;
963 printf("%s: %s\n", refname, id_str);
964 free(id_str);
967 return NULL;
970 static const struct got_error *
971 create_ref(const char *refname, struct got_object_id *id,
972 int verbosity, struct got_repository *repo)
974 const struct got_error *err = NULL;
975 struct got_reference *ref;
976 char *id_str;
978 err = got_object_id_str(&id_str, id);
979 if (err)
980 return err;
982 err = got_ref_alloc(&ref, refname, id);
983 if (err)
984 goto done;
986 err = got_ref_write(ref, repo);
987 got_ref_close(ref);
989 if (err == NULL && verbosity >= 0)
990 printf("Created reference %s: %s\n", refname, id_str);
991 done:
992 free(id_str);
993 return err;
996 static int
997 match_wanted_ref(const char *refname, const char *wanted_ref)
999 if (strncmp(refname, "refs/", 5) != 0)
1000 return 0;
1001 refname += 5;
1004 * Prevent fetching of references that won't make any
1005 * sense outside of the remote repository's context.
1007 if (strncmp(refname, "got/", 4) == 0)
1008 return 0;
1009 if (strncmp(refname, "remotes/", 8) == 0)
1010 return 0;
1012 if (strncmp(wanted_ref, "refs/", 5) == 0)
1013 wanted_ref += 5;
1015 /* Allow prefix match. */
1016 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1017 return 1;
1019 /* Allow exact match. */
1020 return (strcmp(refname, wanted_ref) == 0);
1023 static int
1024 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1026 struct got_pathlist_entry *pe;
1028 TAILQ_FOREACH(pe, wanted_refs, entry) {
1029 if (match_wanted_ref(refname, pe->path))
1030 return 1;
1033 return 0;
1036 static const struct got_error *
1037 create_wanted_ref(const char *refname, struct got_object_id *id,
1038 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1040 const struct got_error *err;
1041 char *remote_refname;
1043 if (strncmp("refs/", refname, 5) == 0)
1044 refname += 5;
1046 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1047 remote_repo_name, refname) == -1)
1048 return got_error_from_errno("asprintf");
1050 err = create_ref(remote_refname, id, verbosity, repo);
1051 free(remote_refname);
1052 return err;
1055 static const struct got_error *
1056 cmd_clone(int argc, char *argv[])
1058 const struct got_error *error = NULL;
1059 const char *uri, *dirname;
1060 char *proto, *host, *port, *repo_name, *server_path;
1061 char *default_destdir = NULL, *id_str = NULL;
1062 const char *repo_path;
1063 struct got_repository *repo = NULL;
1064 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1065 struct got_pathlist_entry *pe;
1066 struct got_object_id *pack_hash = NULL;
1067 int ch, fetchfd = -1, fetchstatus;
1068 pid_t fetchpid = -1;
1069 struct got_fetch_progress_arg fpa;
1070 char *git_url = NULL;
1071 char *gitconfig_path = NULL, *gotconfig_path = NULL;
1072 char *gitconfig = NULL, *gotconfig = NULL;
1073 FILE *gitconfig_file = NULL, *gotconfig_file = NULL;
1074 ssize_t n;
1075 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1076 int list_refs_only = 0;
1077 struct got_reference *head_symref = NULL;
1079 TAILQ_INIT(&refs);
1080 TAILQ_INIT(&symrefs);
1081 TAILQ_INIT(&wanted_branches);
1082 TAILQ_INIT(&wanted_refs);
1084 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1085 switch (ch) {
1086 case 'a':
1087 fetch_all_branches = 1;
1088 break;
1089 case 'b':
1090 error = got_pathlist_append(&wanted_branches,
1091 optarg, NULL);
1092 if (error)
1093 return error;
1094 break;
1095 case 'l':
1096 list_refs_only = 1;
1097 break;
1098 case 'm':
1099 mirror_references = 1;
1100 break;
1101 case 'v':
1102 if (verbosity < 0)
1103 verbosity = 0;
1104 else if (verbosity < 3)
1105 verbosity++;
1106 break;
1107 case 'q':
1108 verbosity = -1;
1109 break;
1110 case 'R':
1111 error = got_pathlist_append(&wanted_refs,
1112 optarg, NULL);
1113 if (error)
1114 return error;
1115 break;
1116 default:
1117 usage_clone();
1118 break;
1121 argc -= optind;
1122 argv += optind;
1124 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1125 errx(1, "-a and -b options are mutually exclusive");
1126 if (list_refs_only) {
1127 if (!TAILQ_EMPTY(&wanted_branches))
1128 errx(1, "-l and -b options are mutually exclusive");
1129 if (fetch_all_branches)
1130 errx(1, "-l and -a options are mutually exclusive");
1131 if (mirror_references)
1132 errx(1, "-l and -m options are mutually exclusive");
1133 if (verbosity == -1)
1134 errx(1, "-l and -q options are mutually exclusive");
1135 if (!TAILQ_EMPTY(&wanted_refs))
1136 errx(1, "-l and -R options are mutually exclusive");
1139 uri = argv[0];
1141 if (argc == 1)
1142 dirname = NULL;
1143 else if (argc == 2)
1144 dirname = argv[1];
1145 else
1146 usage_clone();
1148 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1149 &repo_name, uri);
1150 if (error)
1151 goto done;
1153 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1154 host, port ? ":" : "", port ? port : "",
1155 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1156 error = got_error_from_errno("asprintf");
1157 goto done;
1160 if (strcmp(proto, "git") == 0) {
1161 #ifndef PROFILE
1162 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1163 "sendfd dns inet unveil", NULL) == -1)
1164 err(1, "pledge");
1165 #endif
1166 } else if (strcmp(proto, "git+ssh") == 0 ||
1167 strcmp(proto, "ssh") == 0) {
1168 #ifndef PROFILE
1169 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1170 "sendfd unveil", NULL) == -1)
1171 err(1, "pledge");
1172 #endif
1173 } else if (strcmp(proto, "http") == 0 ||
1174 strcmp(proto, "git+http") == 0) {
1175 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1176 goto done;
1177 } else {
1178 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1179 goto done;
1181 if (dirname == NULL) {
1182 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1183 error = got_error_from_errno("asprintf");
1184 goto done;
1186 repo_path = default_destdir;
1187 } else
1188 repo_path = dirname;
1190 if (!list_refs_only) {
1191 error = got_path_mkdir(repo_path);
1192 if (error)
1193 goto done;
1195 error = got_repo_init(repo_path);
1196 if (error)
1197 goto done;
1198 error = got_repo_open(&repo, repo_path, NULL);
1199 if (error)
1200 goto done;
1203 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1204 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1205 error = got_error_from_errno2("unveil",
1206 GOT_FETCH_PATH_SSH);
1207 goto done;
1210 error = apply_unveil(repo ? got_repo_get_path(repo) : NULL, 0, NULL);
1211 if (error)
1212 goto done;
1214 if (verbosity >= 0)
1215 printf("Connecting to %s%s%s\n", host,
1216 port ? ":" : "", port ? port : "");
1218 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1219 server_path, verbosity);
1220 if (error)
1221 goto done;
1223 fpa.last_scaled_size[0] = '\0';
1224 fpa.last_p_indexed = -1;
1225 fpa.last_p_resolved = -1;
1226 fpa.verbosity = verbosity;
1227 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1228 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1229 fetch_all_branches, &wanted_branches, &wanted_refs,
1230 list_refs_only, verbosity, fetchfd, repo,
1231 fetch_progress, &fpa);
1232 if (error)
1233 goto done;
1235 if (list_refs_only) {
1236 error = list_remote_refs(&symrefs, &refs);
1237 goto done;
1240 error = got_object_id_str(&id_str, pack_hash);
1241 if (error)
1242 goto done;
1243 if (verbosity >= 0)
1244 printf("\nFetched %s.pack\n", id_str);
1245 free(id_str);
1247 /* Set up references provided with the pack file. */
1248 TAILQ_FOREACH(pe, &refs, entry) {
1249 const char *refname = pe->path;
1250 struct got_object_id *id = pe->data;
1251 char *remote_refname;
1253 if (is_wanted_ref(&wanted_refs, refname) &&
1254 !mirror_references) {
1255 error = create_wanted_ref(refname, id,
1256 GOT_FETCH_DEFAULT_REMOTE_NAME,
1257 verbosity - 1, repo);
1258 if (error)
1259 goto done;
1260 continue;
1263 error = create_ref(refname, id, verbosity - 1, repo);
1264 if (error)
1265 goto done;
1267 if (mirror_references)
1268 continue;
1270 if (strncmp("refs/heads/", refname, 11) != 0)
1271 continue;
1273 if (asprintf(&remote_refname,
1274 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1275 refname + 11) == -1) {
1276 error = got_error_from_errno("asprintf");
1277 goto done;
1279 error = create_ref(remote_refname, id, verbosity - 1, repo);
1280 free(remote_refname);
1281 if (error)
1282 goto done;
1285 /* Set the HEAD reference if the server provided one. */
1286 TAILQ_FOREACH(pe, &symrefs, entry) {
1287 struct got_reference *target_ref;
1288 const char *refname = pe->path;
1289 const char *target = pe->data;
1290 char *remote_refname = NULL, *remote_target = NULL;
1292 if (strcmp(refname, GOT_REF_HEAD) != 0)
1293 continue;
1295 error = got_ref_open(&target_ref, repo, target, 0);
1296 if (error) {
1297 if (error->code == GOT_ERR_NOT_REF) {
1298 error = NULL;
1299 continue;
1301 goto done;
1304 error = create_symref(refname, target_ref, verbosity, repo);
1305 got_ref_close(target_ref);
1306 if (error)
1307 goto done;
1309 if (mirror_references)
1310 continue;
1312 if (strncmp("refs/heads/", target, 11) != 0)
1313 continue;
1315 if (asprintf(&remote_refname,
1316 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1317 refname) == -1) {
1318 error = got_error_from_errno("asprintf");
1319 goto done;
1321 if (asprintf(&remote_target,
1322 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1323 target + 11) == -1) {
1324 error = got_error_from_errno("asprintf");
1325 free(remote_refname);
1326 goto done;
1328 error = got_ref_open(&target_ref, repo, remote_target, 0);
1329 if (error) {
1330 free(remote_refname);
1331 free(remote_target);
1332 if (error->code == GOT_ERR_NOT_REF) {
1333 error = NULL;
1334 continue;
1336 goto done;
1338 error = create_symref(remote_refname, target_ref,
1339 verbosity - 1, repo);
1340 free(remote_refname);
1341 free(remote_target);
1342 got_ref_close(target_ref);
1343 if (error)
1344 goto done;
1346 if (pe == NULL) {
1348 * We failed to set the HEAD reference. If we asked for
1349 * a set of wanted branches use the first of one of those
1350 * which could be fetched instead.
1352 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1353 const char *target = pe->path;
1354 struct got_reference *target_ref;
1356 error = got_ref_open(&target_ref, repo, target, 0);
1357 if (error) {
1358 if (error->code == GOT_ERR_NOT_REF) {
1359 error = NULL;
1360 continue;
1362 goto done;
1365 error = create_symref(GOT_REF_HEAD, target_ref,
1366 verbosity, repo);
1367 got_ref_close(target_ref);
1368 if (error)
1369 goto done;
1370 break;
1374 /* Create got.conf(5). */
1375 gotconfig_path = got_repo_get_path_gotconfig(repo);
1376 if (gotconfig_path == NULL) {
1377 error = got_error_from_errno("got_repo_get_path_gotconfig");
1378 goto done;
1380 gotconfig_file = fopen(gotconfig_path, "a");
1381 if (gotconfig_file == NULL) {
1382 error = got_error_from_errno2("fopen", gotconfig_path);
1383 goto done;
1385 got_path_strip_trailing_slashes(server_path);
1386 if (asprintf(&gotconfig,
1387 "remote \"%s\" {\n"
1388 "\tserver %s\n"
1389 "\tprotocol %s\n"
1390 "%s%s%s"
1391 "\trepository \"%s\"\n"
1392 "%s"
1393 "}\n",
1394 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1395 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1396 server_path,
1397 mirror_references ? "\tmirror-references yes\n" : "") == -1) {
1398 error = got_error_from_errno("asprintf");
1399 goto done;
1401 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1402 if (n != strlen(gotconfig)) {
1403 error = got_ferror(gotconfig_file, GOT_ERR_IO);
1404 goto done;
1407 /* Create a config file Git can understand. */
1408 gitconfig_path = got_repo_get_path_gitconfig(repo);
1409 if (gitconfig_path == NULL) {
1410 error = got_error_from_errno("got_repo_get_path_gitconfig");
1411 goto done;
1413 gitconfig_file = fopen(gitconfig_path, "a");
1414 if (gitconfig_file == NULL) {
1415 error = got_error_from_errno2("fopen", gitconfig_path);
1416 goto done;
1418 if (mirror_references) {
1419 if (asprintf(&gitconfig,
1420 "[remote \"%s\"]\n"
1421 "\turl = %s\n"
1422 "\tfetch = +refs/*:refs/*\n"
1423 "\tmirror = true\n",
1424 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url) == -1) {
1425 error = got_error_from_errno("asprintf");
1426 goto done;
1428 } else if (fetch_all_branches) {
1429 if (asprintf(&gitconfig,
1430 "[remote \"%s\"]\n"
1431 "\turl = %s\n"
1432 "\tfetch = +refs/heads/*:refs/remotes/%s/*\n",
1433 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1434 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1435 error = got_error_from_errno("asprintf");
1436 goto done;
1438 } else {
1439 const char *branchname;
1442 * If the server specified a default branch, use just that one.
1443 * Otherwise fall back to fetching all branches on next fetch.
1445 if (head_symref) {
1446 branchname = got_ref_get_symref_target(head_symref);
1447 if (strncmp(branchname, "refs/heads/", 11) == 0)
1448 branchname += 11;
1449 } else
1450 branchname = "*"; /* fall back to all branches */
1451 if (asprintf(&gitconfig,
1452 "[remote \"%s\"]\n"
1453 "\turl = %s\n"
1454 "\tfetch = +refs/heads/%s:refs/remotes/%s/%s\n",
1455 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url,
1456 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1457 branchname) == -1) {
1458 error = got_error_from_errno("asprintf");
1459 goto done;
1462 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1463 if (n != strlen(gitconfig)) {
1464 error = got_ferror(gitconfig_file, GOT_ERR_IO);
1465 goto done;
1468 if (verbosity >= 0)
1469 printf("Created %s repository '%s'\n",
1470 mirror_references ? "mirrored" : "cloned", repo_path);
1471 done:
1472 if (fetchpid > 0) {
1473 if (kill(fetchpid, SIGTERM) == -1)
1474 error = got_error_from_errno("kill");
1475 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1476 error = got_error_from_errno("waitpid");
1478 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1479 error = got_error_from_errno("close");
1480 if (gotconfig_file && fclose(gotconfig_file) == EOF && error == NULL)
1481 error = got_error_from_errno("fclose");
1482 if (gitconfig_file && fclose(gitconfig_file) == EOF && error == NULL)
1483 error = got_error_from_errno("fclose");
1484 if (repo)
1485 got_repo_close(repo);
1486 if (head_symref)
1487 got_ref_close(head_symref);
1488 TAILQ_FOREACH(pe, &refs, entry) {
1489 free((void *)pe->path);
1490 free(pe->data);
1492 got_pathlist_free(&refs);
1493 TAILQ_FOREACH(pe, &symrefs, entry) {
1494 free((void *)pe->path);
1495 free(pe->data);
1497 got_pathlist_free(&symrefs);
1498 got_pathlist_free(&wanted_branches);
1499 got_pathlist_free(&wanted_refs);
1500 free(pack_hash);
1501 free(proto);
1502 free(host);
1503 free(port);
1504 free(server_path);
1505 free(repo_name);
1506 free(default_destdir);
1507 free(gotconfig);
1508 free(gitconfig);
1509 free(gotconfig_path);
1510 free(gitconfig_path);
1511 free(git_url);
1512 return error;
1515 static const struct got_error *
1516 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1517 int replace_tags, int verbosity, struct got_repository *repo)
1519 const struct got_error *err = NULL;
1520 char *new_id_str = NULL;
1521 struct got_object_id *old_id = NULL;
1523 err = got_object_id_str(&new_id_str, new_id);
1524 if (err)
1525 goto done;
1527 if (!replace_tags &&
1528 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1529 err = got_ref_resolve(&old_id, repo, ref);
1530 if (err)
1531 goto done;
1532 if (got_object_id_cmp(old_id, new_id) == 0)
1533 goto done;
1534 if (verbosity >= 0) {
1535 printf("Rejecting update of existing tag %s: %s\n",
1536 got_ref_get_name(ref), new_id_str);
1538 goto done;
1541 if (got_ref_is_symbolic(ref)) {
1542 if (verbosity >= 0) {
1543 printf("Replacing reference %s: %s\n",
1544 got_ref_get_name(ref),
1545 got_ref_get_symref_target(ref));
1547 err = got_ref_change_symref_to_ref(ref, new_id);
1548 if (err)
1549 goto done;
1550 err = got_ref_write(ref, repo);
1551 if (err)
1552 goto done;
1553 } else {
1554 err = got_ref_resolve(&old_id, repo, ref);
1555 if (err)
1556 goto done;
1557 if (got_object_id_cmp(old_id, new_id) == 0)
1558 goto done;
1560 err = got_ref_change_ref(ref, new_id);
1561 if (err)
1562 goto done;
1563 err = got_ref_write(ref, repo);
1564 if (err)
1565 goto done;
1568 if (verbosity >= 0)
1569 printf("Updated %s: %s\n", got_ref_get_name(ref),
1570 new_id_str);
1571 done:
1572 free(old_id);
1573 free(new_id_str);
1574 return err;
1577 static const struct got_error *
1578 update_symref(const char *refname, struct got_reference *target_ref,
1579 int verbosity, struct got_repository *repo)
1581 const struct got_error *err = NULL, *unlock_err;
1582 struct got_reference *symref;
1583 int symref_is_locked = 0;
1585 err = got_ref_open(&symref, repo, refname, 1);
1586 if (err) {
1587 if (err->code != GOT_ERR_NOT_REF)
1588 return err;
1589 err = got_ref_alloc_symref(&symref, refname, target_ref);
1590 if (err)
1591 goto done;
1593 err = got_ref_write(symref, repo);
1594 if (err)
1595 goto done;
1597 if (verbosity >= 0)
1598 printf("Created reference %s: %s\n",
1599 got_ref_get_name(symref),
1600 got_ref_get_symref_target(symref));
1601 } else {
1602 symref_is_locked = 1;
1604 if (strcmp(got_ref_get_symref_target(symref),
1605 got_ref_get_name(target_ref)) == 0)
1606 goto done;
1608 err = got_ref_change_symref(symref,
1609 got_ref_get_name(target_ref));
1610 if (err)
1611 goto done;
1613 err = got_ref_write(symref, repo);
1614 if (err)
1615 goto done;
1617 if (verbosity >= 0)
1618 printf("Updated %s: %s\n", got_ref_get_name(symref),
1619 got_ref_get_symref_target(symref));
1622 done:
1623 if (symref_is_locked) {
1624 unlock_err = got_ref_unlock(symref);
1625 if (unlock_err && err == NULL)
1626 err = unlock_err;
1628 got_ref_close(symref);
1629 return err;
1632 __dead static void
1633 usage_fetch(void)
1635 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1636 "[-r repository-path] [-t] [-q] [-v] [-R reference] "
1637 "[remote-repository-name]\n",
1638 getprogname());
1639 exit(1);
1642 static const struct got_error *
1643 delete_missing_ref(struct got_reference *ref,
1644 int verbosity, struct got_repository *repo)
1646 const struct got_error *err = NULL;
1647 struct got_object_id *id = NULL;
1648 char *id_str = NULL;
1650 if (got_ref_is_symbolic(ref)) {
1651 err = got_ref_delete(ref, repo);
1652 if (err)
1653 return err;
1654 if (verbosity >= 0) {
1655 printf("Deleted reference %s: %s\n",
1656 got_ref_get_name(ref),
1657 got_ref_get_symref_target(ref));
1659 } else {
1660 err = got_ref_resolve(&id, repo, ref);
1661 if (err)
1662 return err;
1663 err = got_object_id_str(&id_str, id);
1664 if (err)
1665 goto done;
1667 err = got_ref_delete(ref, repo);
1668 if (err)
1669 goto done;
1670 if (verbosity >= 0) {
1671 printf("Deleted reference %s: %s\n",
1672 got_ref_get_name(ref), id_str);
1675 done:
1676 free(id);
1677 free(id_str);
1678 return NULL;
1681 static const struct got_error *
1682 delete_missing_refs(struct got_pathlist_head *their_refs,
1683 struct got_pathlist_head *their_symrefs,
1684 const struct got_remote_repo *remote,
1685 int verbosity, struct got_repository *repo)
1687 const struct got_error *err = NULL, *unlock_err;
1688 struct got_reflist_head my_refs;
1689 struct got_reflist_entry *re;
1690 struct got_pathlist_entry *pe;
1691 char *remote_namespace = NULL;
1692 char *local_refname = NULL;
1694 SIMPLEQ_INIT(&my_refs);
1696 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
1697 == -1)
1698 return got_error_from_errno("asprintf");
1700 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
1701 if (err)
1702 goto done;
1704 SIMPLEQ_FOREACH(re, &my_refs, entry) {
1705 const char *refname = got_ref_get_name(re->ref);
1707 if (!remote->mirror_references) {
1708 if (strncmp(refname, remote_namespace,
1709 strlen(remote_namespace)) == 0) {
1710 if (strcmp(refname + strlen(remote_namespace),
1711 GOT_REF_HEAD) == 0)
1712 continue;
1713 if (asprintf(&local_refname, "refs/heads/%s",
1714 refname + strlen(remote_namespace)) == -1) {
1715 err = got_error_from_errno("asprintf");
1716 goto done;
1718 } else if (strncmp(refname, "refs/tags/", 10) != 0)
1719 continue;
1722 TAILQ_FOREACH(pe, their_refs, entry) {
1723 if (strcmp(local_refname, pe->path) == 0)
1724 break;
1726 if (pe != NULL)
1727 continue;
1729 TAILQ_FOREACH(pe, their_symrefs, entry) {
1730 if (strcmp(local_refname, pe->path) == 0)
1731 break;
1733 if (pe != NULL)
1734 continue;
1736 err = delete_missing_ref(re->ref, verbosity, repo);
1737 if (err)
1738 break;
1740 if (local_refname) {
1741 struct got_reference *ref;
1742 err = got_ref_open(&ref, repo, local_refname, 1);
1743 if (err) {
1744 if (err->code != GOT_ERR_NOT_REF)
1745 break;
1746 free(local_refname);
1747 local_refname = NULL;
1748 continue;
1750 err = delete_missing_ref(ref, verbosity, repo);
1751 if (err)
1752 break;
1753 unlock_err = got_ref_unlock(ref);
1754 got_ref_close(ref);
1755 if (unlock_err && err == NULL) {
1756 err = unlock_err;
1757 break;
1760 free(local_refname);
1761 local_refname = NULL;
1764 done:
1765 free(remote_namespace);
1766 free(local_refname);
1767 return err;
1770 static const struct got_error *
1771 update_wanted_ref(const char *refname, struct got_object_id *id,
1772 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1774 const struct got_error *err, *unlock_err;
1775 char *remote_refname;
1776 struct got_reference *ref;
1778 if (strncmp("refs/", refname, 5) == 0)
1779 refname += 5;
1781 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1782 remote_repo_name, refname) == -1)
1783 return got_error_from_errno("asprintf");
1785 err = got_ref_open(&ref, repo, remote_refname, 1);
1786 if (err) {
1787 if (err->code != GOT_ERR_NOT_REF)
1788 goto done;
1789 err = create_ref(remote_refname, id, verbosity, repo);
1790 } else {
1791 err = update_ref(ref, id, 0, verbosity, repo);
1792 unlock_err = got_ref_unlock(ref);
1793 if (unlock_err && err == NULL)
1794 err = unlock_err;
1795 got_ref_close(ref);
1797 done:
1798 free(remote_refname);
1799 return err;
1802 static const struct got_error *
1803 cmd_fetch(int argc, char *argv[])
1805 const struct got_error *error = NULL, *unlock_err;
1806 char *cwd = NULL, *repo_path = NULL;
1807 const char *remote_name;
1808 char *proto = NULL, *host = NULL, *port = NULL;
1809 char *repo_name = NULL, *server_path = NULL;
1810 const struct got_remote_repo *remotes, *remote = NULL;
1811 int nremotes;
1812 char *id_str = NULL;
1813 struct got_repository *repo = NULL;
1814 struct got_worktree *worktree = NULL;
1815 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
1816 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1817 struct got_pathlist_entry *pe;
1818 struct got_object_id *pack_hash = NULL;
1819 int i, ch, fetchfd = -1, fetchstatus;
1820 pid_t fetchpid = -1;
1821 struct got_fetch_progress_arg fpa;
1822 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
1823 int delete_refs = 0, replace_tags = 0;
1825 TAILQ_INIT(&refs);
1826 TAILQ_INIT(&symrefs);
1827 TAILQ_INIT(&wanted_branches);
1828 TAILQ_INIT(&wanted_refs);
1830 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:")) != -1) {
1831 switch (ch) {
1832 case 'a':
1833 fetch_all_branches = 1;
1834 break;
1835 case 'b':
1836 error = got_pathlist_append(&wanted_branches,
1837 optarg, NULL);
1838 if (error)
1839 return error;
1840 break;
1841 case 'd':
1842 delete_refs = 1;
1843 break;
1844 case 'l':
1845 list_refs_only = 1;
1846 break;
1847 case 'r':
1848 repo_path = realpath(optarg, NULL);
1849 if (repo_path == NULL)
1850 return got_error_from_errno2("realpath",
1851 optarg);
1852 got_path_strip_trailing_slashes(repo_path);
1853 break;
1854 case 't':
1855 replace_tags = 1;
1856 break;
1857 case 'v':
1858 if (verbosity < 0)
1859 verbosity = 0;
1860 else if (verbosity < 3)
1861 verbosity++;
1862 break;
1863 case 'q':
1864 verbosity = -1;
1865 break;
1866 case 'R':
1867 error = got_pathlist_append(&wanted_refs,
1868 optarg, NULL);
1869 if (error)
1870 return error;
1871 break;
1872 default:
1873 usage_fetch();
1874 break;
1877 argc -= optind;
1878 argv += optind;
1880 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1881 errx(1, "-a and -b options are mutually exclusive");
1882 if (list_refs_only) {
1883 if (!TAILQ_EMPTY(&wanted_branches))
1884 errx(1, "-l and -b options are mutually exclusive");
1885 if (fetch_all_branches)
1886 errx(1, "-l and -a options are mutually exclusive");
1887 if (delete_refs)
1888 errx(1, "-l and -d options are mutually exclusive");
1889 if (verbosity == -1)
1890 errx(1, "-l and -q options are mutually exclusive");
1893 if (argc == 0)
1894 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
1895 else if (argc == 1)
1896 remote_name = argv[0];
1897 else
1898 usage_fetch();
1900 cwd = getcwd(NULL, 0);
1901 if (cwd == NULL) {
1902 error = got_error_from_errno("getcwd");
1903 goto done;
1906 if (repo_path == NULL) {
1907 error = got_worktree_open(&worktree, cwd);
1908 if (error && error->code != GOT_ERR_NOT_WORKTREE)
1909 goto done;
1910 else
1911 error = NULL;
1912 if (worktree) {
1913 repo_path =
1914 strdup(got_worktree_get_repo_path(worktree));
1915 if (repo_path == NULL)
1916 error = got_error_from_errno("strdup");
1917 if (error)
1918 goto done;
1919 } else {
1920 repo_path = strdup(cwd);
1921 if (repo_path == NULL) {
1922 error = got_error_from_errno("strdup");
1923 goto done;
1928 error = got_repo_open(&repo, repo_path, NULL);
1929 if (error)
1930 goto done;
1932 if (worktree) {
1933 worktree_conf = got_worktree_get_gotconfig(worktree);
1934 if (worktree_conf) {
1935 got_gotconfig_get_remotes(&nremotes, &remotes,
1936 worktree_conf);
1937 for (i = 0; i < nremotes; i++) {
1938 remote = &remotes[i];
1939 if (strcmp(remote->name, remote_name) == 0)
1940 break;
1944 if (remote == NULL) {
1945 repo_conf = got_repo_get_gotconfig(repo);
1946 if (repo_conf) {
1947 got_gotconfig_get_remotes(&nremotes, &remotes,
1948 repo_conf);
1949 for (i = 0; i < nremotes; i++) {
1950 remote = &remotes[i];
1951 if (strcmp(remote->name, remote_name) == 0)
1952 break;
1956 if (remote == NULL) {
1957 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
1958 for (i = 0; i < nremotes; i++) {
1959 remote = &remotes[i];
1960 if (strcmp(remote->name, remote_name) == 0)
1961 break;
1964 if (remote == NULL) {
1965 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
1966 goto done;
1969 error = got_fetch_parse_uri(&proto, &host, &port, &server_path,
1970 &repo_name, remote->url);
1971 if (error)
1972 goto done;
1974 if (strcmp(proto, "git") == 0) {
1975 #ifndef PROFILE
1976 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1977 "sendfd dns inet unveil", NULL) == -1)
1978 err(1, "pledge");
1979 #endif
1980 } else if (strcmp(proto, "git+ssh") == 0 ||
1981 strcmp(proto, "ssh") == 0) {
1982 #ifndef PROFILE
1983 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1984 "sendfd unveil", NULL) == -1)
1985 err(1, "pledge");
1986 #endif
1987 } else if (strcmp(proto, "http") == 0 ||
1988 strcmp(proto, "git+http") == 0) {
1989 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1990 goto done;
1991 } else {
1992 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1993 goto done;
1996 if (strcmp(proto, "git+ssh") == 0 || strcmp(proto, "ssh") == 0) {
1997 if (unveil(GOT_FETCH_PATH_SSH, "x") != 0) {
1998 error = got_error_from_errno2("unveil",
1999 GOT_FETCH_PATH_SSH);
2000 goto done;
2003 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2004 if (error)
2005 goto done;
2007 if (verbosity >= 0)
2008 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2009 port ? ":" : "", port ? port : "");
2011 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2012 server_path, verbosity);
2013 if (error)
2014 goto done;
2016 fpa.last_scaled_size[0] = '\0';
2017 fpa.last_p_indexed = -1;
2018 fpa.last_p_resolved = -1;
2019 fpa.verbosity = verbosity;
2020 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2021 remote->mirror_references, fetch_all_branches, &wanted_branches,
2022 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2023 fetch_progress, &fpa);
2024 if (error)
2025 goto done;
2027 if (list_refs_only) {
2028 error = list_remote_refs(&symrefs, &refs);
2029 goto done;
2032 if (pack_hash == NULL) {
2033 if (verbosity >= 0)
2034 printf("Already up-to-date\n");
2035 } else if (verbosity >= 0) {
2036 error = got_object_id_str(&id_str, pack_hash);
2037 if (error)
2038 goto done;
2039 printf("\nFetched %s.pack\n", id_str);
2040 free(id_str);
2041 id_str = NULL;
2044 /* Update references provided with the pack file. */
2045 TAILQ_FOREACH(pe, &refs, entry) {
2046 const char *refname = pe->path;
2047 struct got_object_id *id = pe->data;
2048 struct got_reference *ref;
2049 char *remote_refname;
2051 if (is_wanted_ref(&wanted_refs, refname) &&
2052 !remote->mirror_references) {
2053 error = update_wanted_ref(refname, id,
2054 remote->name, verbosity, repo);
2055 if (error)
2056 goto done;
2057 continue;
2060 if (remote->mirror_references ||
2061 strncmp("refs/tags/", refname, 10) == 0) {
2062 error = got_ref_open(&ref, repo, refname, 1);
2063 if (error) {
2064 if (error->code != GOT_ERR_NOT_REF)
2065 goto done;
2066 error = create_ref(refname, id, verbosity,
2067 repo);
2068 if (error)
2069 goto done;
2070 } else {
2071 error = update_ref(ref, id, replace_tags,
2072 verbosity, repo);
2073 unlock_err = got_ref_unlock(ref);
2074 if (unlock_err && error == NULL)
2075 error = unlock_err;
2076 got_ref_close(ref);
2077 if (error)
2078 goto done;
2080 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2081 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2082 remote_name, refname + 11) == -1) {
2083 error = got_error_from_errno("asprintf");
2084 goto done;
2087 error = got_ref_open(&ref, repo, remote_refname, 1);
2088 if (error) {
2089 if (error->code != GOT_ERR_NOT_REF)
2090 goto done;
2091 error = create_ref(remote_refname, id,
2092 verbosity, repo);
2093 if (error)
2094 goto done;
2095 } else {
2096 error = update_ref(ref, id, replace_tags,
2097 verbosity, repo);
2098 unlock_err = got_ref_unlock(ref);
2099 if (unlock_err && error == NULL)
2100 error = unlock_err;
2101 got_ref_close(ref);
2102 if (error)
2103 goto done;
2106 /* Also create a local branch if none exists yet. */
2107 error = got_ref_open(&ref, repo, refname, 1);
2108 if (error) {
2109 if (error->code != GOT_ERR_NOT_REF)
2110 goto done;
2111 error = create_ref(refname, id, verbosity,
2112 repo);
2113 if (error)
2114 goto done;
2115 } else {
2116 unlock_err = got_ref_unlock(ref);
2117 if (unlock_err && error == NULL)
2118 error = unlock_err;
2119 got_ref_close(ref);
2123 if (delete_refs) {
2124 error = delete_missing_refs(&refs, &symrefs, remote,
2125 verbosity, repo);
2126 if (error)
2127 goto done;
2130 if (!remote->mirror_references) {
2131 /* Update remote HEAD reference if the server provided one. */
2132 TAILQ_FOREACH(pe, &symrefs, entry) {
2133 struct got_reference *target_ref;
2134 const char *refname = pe->path;
2135 const char *target = pe->data;
2136 char *remote_refname = NULL, *remote_target = NULL;
2138 if (strcmp(refname, GOT_REF_HEAD) != 0)
2139 continue;
2141 if (strncmp("refs/heads/", target, 11) != 0)
2142 continue;
2144 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2145 remote->name, refname) == -1) {
2146 error = got_error_from_errno("asprintf");
2147 goto done;
2149 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2150 remote->name, target + 11) == -1) {
2151 error = got_error_from_errno("asprintf");
2152 free(remote_refname);
2153 goto done;
2156 error = got_ref_open(&target_ref, repo, remote_target,
2157 0);
2158 if (error) {
2159 free(remote_refname);
2160 free(remote_target);
2161 if (error->code == GOT_ERR_NOT_REF) {
2162 error = NULL;
2163 continue;
2165 goto done;
2167 error = update_symref(remote_refname, target_ref,
2168 verbosity, repo);
2169 free(remote_refname);
2170 free(remote_target);
2171 got_ref_close(target_ref);
2172 if (error)
2173 goto done;
2176 done:
2177 if (fetchpid > 0) {
2178 if (kill(fetchpid, SIGTERM) == -1)
2179 error = got_error_from_errno("kill");
2180 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2181 error = got_error_from_errno("waitpid");
2183 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2184 error = got_error_from_errno("close");
2185 if (repo)
2186 got_repo_close(repo);
2187 if (worktree)
2188 got_worktree_close(worktree);
2189 TAILQ_FOREACH(pe, &refs, entry) {
2190 free((void *)pe->path);
2191 free(pe->data);
2193 got_pathlist_free(&refs);
2194 TAILQ_FOREACH(pe, &symrefs, entry) {
2195 free((void *)pe->path);
2196 free(pe->data);
2198 got_pathlist_free(&symrefs);
2199 got_pathlist_free(&wanted_branches);
2200 got_pathlist_free(&wanted_refs);
2201 free(id_str);
2202 free(cwd);
2203 free(repo_path);
2204 free(pack_hash);
2205 free(proto);
2206 free(host);
2207 free(port);
2208 free(server_path);
2209 free(repo_name);
2210 return error;
2214 __dead static void
2215 usage_checkout(void)
2217 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2218 "[-p prefix] repository-path [worktree-path]\n", getprogname());
2219 exit(1);
2222 static void
2223 show_worktree_base_ref_warning(void)
2225 fprintf(stderr, "%s: warning: could not create a reference "
2226 "to the work tree's base commit; the commit could be "
2227 "garbage-collected by Git; making the repository "
2228 "writable and running 'got update' will prevent this\n",
2229 getprogname());
2232 struct got_checkout_progress_arg {
2233 const char *worktree_path;
2234 int had_base_commit_ref_error;
2237 static const struct got_error *
2238 checkout_progress(void *arg, unsigned char status, const char *path)
2240 struct got_checkout_progress_arg *a = arg;
2242 /* Base commit bump happens silently. */
2243 if (status == GOT_STATUS_BUMP_BASE)
2244 return NULL;
2246 if (status == GOT_STATUS_BASE_REF_ERR) {
2247 a->had_base_commit_ref_error = 1;
2248 return NULL;
2251 while (path[0] == '/')
2252 path++;
2254 printf("%c %s/%s\n", status, a->worktree_path, path);
2255 return NULL;
2258 static const struct got_error *
2259 check_cancelled(void *arg)
2261 if (sigint_received || sigpipe_received)
2262 return got_error(GOT_ERR_CANCELLED);
2263 return NULL;
2266 static const struct got_error *
2267 check_linear_ancestry(struct got_object_id *commit_id,
2268 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2269 struct got_repository *repo)
2271 const struct got_error *err = NULL;
2272 struct got_object_id *yca_id;
2274 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2275 commit_id, base_commit_id, repo, check_cancelled, NULL);
2276 if (err)
2277 return err;
2279 if (yca_id == NULL)
2280 return got_error(GOT_ERR_ANCESTRY);
2283 * Require a straight line of history between the target commit
2284 * and the work tree's base commit.
2286 * Non-linear situations such as this require a rebase:
2288 * (commit) D F (base_commit)
2289 * \ /
2290 * C E
2291 * \ /
2292 * B (yca)
2293 * |
2294 * A
2296 * 'got update' only handles linear cases:
2297 * Update forwards in time: A (base/yca) - B - C - D (commit)
2298 * Update backwards in time: D (base) - C - B - A (commit/yca)
2300 if (allow_forwards_in_time_only) {
2301 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2302 return got_error(GOT_ERR_ANCESTRY);
2303 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2304 got_object_id_cmp(base_commit_id, yca_id) != 0)
2305 return got_error(GOT_ERR_ANCESTRY);
2307 free(yca_id);
2308 return NULL;
2311 static const struct got_error *
2312 check_same_branch(struct got_object_id *commit_id,
2313 struct got_reference *head_ref, struct got_object_id *yca_id,
2314 struct got_repository *repo)
2316 const struct got_error *err = NULL;
2317 struct got_commit_graph *graph = NULL;
2318 struct got_object_id *head_commit_id = NULL;
2319 int is_same_branch = 0;
2321 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2322 if (err)
2323 goto done;
2325 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2326 is_same_branch = 1;
2327 goto done;
2329 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2330 is_same_branch = 1;
2331 goto done;
2334 err = got_commit_graph_open(&graph, "/", 1);
2335 if (err)
2336 goto done;
2338 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2339 check_cancelled, NULL);
2340 if (err)
2341 goto done;
2343 for (;;) {
2344 struct got_object_id *id;
2345 err = got_commit_graph_iter_next(&id, graph, repo,
2346 check_cancelled, NULL);
2347 if (err) {
2348 if (err->code == GOT_ERR_ITER_COMPLETED)
2349 err = NULL;
2350 break;
2353 if (id) {
2354 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2355 break;
2356 if (got_object_id_cmp(id, commit_id) == 0) {
2357 is_same_branch = 1;
2358 break;
2362 done:
2363 if (graph)
2364 got_commit_graph_close(graph);
2365 free(head_commit_id);
2366 if (!err && !is_same_branch)
2367 err = got_error(GOT_ERR_ANCESTRY);
2368 return err;
2371 static const struct got_error *
2372 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2374 static char msg[512];
2375 const char *branch_name;
2377 if (got_ref_is_symbolic(ref))
2378 branch_name = got_ref_get_symref_target(ref);
2379 else
2380 branch_name = got_ref_get_name(ref);
2382 if (strncmp("refs/heads/", branch_name, 11) == 0)
2383 branch_name += 11;
2385 snprintf(msg, sizeof(msg),
2386 "target commit is not contained in branch '%s'; "
2387 "the branch to use must be specified with -b; "
2388 "if necessary a new branch can be created for "
2389 "this commit with 'got branch -c %s BRANCH_NAME'",
2390 branch_name, commit_id_str);
2392 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2395 static const struct got_error *
2396 cmd_checkout(int argc, char *argv[])
2398 const struct got_error *error = NULL;
2399 struct got_repository *repo = NULL;
2400 struct got_reference *head_ref = NULL;
2401 struct got_worktree *worktree = NULL;
2402 char *repo_path = NULL;
2403 char *worktree_path = NULL;
2404 const char *path_prefix = "";
2405 const char *branch_name = GOT_REF_HEAD;
2406 char *commit_id_str = NULL;
2407 int ch, same_path_prefix, allow_nonempty = 0;
2408 struct got_pathlist_head paths;
2409 struct got_checkout_progress_arg cpa;
2411 TAILQ_INIT(&paths);
2413 while ((ch = getopt(argc, argv, "b:c:Ep:")) != -1) {
2414 switch (ch) {
2415 case 'b':
2416 branch_name = optarg;
2417 break;
2418 case 'c':
2419 commit_id_str = strdup(optarg);
2420 if (commit_id_str == NULL)
2421 return got_error_from_errno("strdup");
2422 break;
2423 case 'E':
2424 allow_nonempty = 1;
2425 break;
2426 case 'p':
2427 path_prefix = optarg;
2428 break;
2429 default:
2430 usage_checkout();
2431 /* NOTREACHED */
2435 argc -= optind;
2436 argv += optind;
2438 #ifndef PROFILE
2439 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2440 "unveil", NULL) == -1)
2441 err(1, "pledge");
2442 #endif
2443 if (argc == 1) {
2444 char *cwd, *base, *dotgit;
2445 repo_path = realpath(argv[0], NULL);
2446 if (repo_path == NULL)
2447 return got_error_from_errno2("realpath", argv[0]);
2448 cwd = getcwd(NULL, 0);
2449 if (cwd == NULL) {
2450 error = got_error_from_errno("getcwd");
2451 goto done;
2453 if (path_prefix[0]) {
2454 base = basename(path_prefix);
2455 if (base == NULL) {
2456 error = got_error_from_errno2("basename",
2457 path_prefix);
2458 goto done;
2460 } else {
2461 base = basename(repo_path);
2462 if (base == NULL) {
2463 error = got_error_from_errno2("basename",
2464 repo_path);
2465 goto done;
2468 dotgit = strstr(base, ".git");
2469 if (dotgit)
2470 *dotgit = '\0';
2471 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2472 error = got_error_from_errno("asprintf");
2473 free(cwd);
2474 goto done;
2476 free(cwd);
2477 } else if (argc == 2) {
2478 repo_path = realpath(argv[0], NULL);
2479 if (repo_path == NULL) {
2480 error = got_error_from_errno2("realpath", argv[0]);
2481 goto done;
2483 worktree_path = realpath(argv[1], NULL);
2484 if (worktree_path == NULL) {
2485 if (errno != ENOENT) {
2486 error = got_error_from_errno2("realpath",
2487 argv[1]);
2488 goto done;
2490 worktree_path = strdup(argv[1]);
2491 if (worktree_path == NULL) {
2492 error = got_error_from_errno("strdup");
2493 goto done;
2496 } else
2497 usage_checkout();
2499 got_path_strip_trailing_slashes(repo_path);
2500 got_path_strip_trailing_slashes(worktree_path);
2502 error = got_repo_open(&repo, repo_path, NULL);
2503 if (error != NULL)
2504 goto done;
2506 /* Pre-create work tree path for unveil(2) */
2507 error = got_path_mkdir(worktree_path);
2508 if (error) {
2509 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2510 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2511 goto done;
2512 if (!allow_nonempty &&
2513 !got_path_dir_is_empty(worktree_path)) {
2514 error = got_error_path(worktree_path,
2515 GOT_ERR_DIR_NOT_EMPTY);
2516 goto done;
2520 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2521 if (error)
2522 goto done;
2524 error = got_ref_open(&head_ref, repo, branch_name, 0);
2525 if (error != NULL)
2526 goto done;
2528 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2529 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2530 goto done;
2532 error = got_worktree_open(&worktree, worktree_path);
2533 if (error != NULL)
2534 goto done;
2536 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2537 path_prefix);
2538 if (error != NULL)
2539 goto done;
2540 if (!same_path_prefix) {
2541 error = got_error(GOT_ERR_PATH_PREFIX);
2542 goto done;
2545 if (commit_id_str) {
2546 struct got_object_id *commit_id;
2547 error = got_repo_match_object_id(&commit_id, NULL,
2548 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2549 if (error)
2550 goto done;
2551 error = check_linear_ancestry(commit_id,
2552 got_worktree_get_base_commit_id(worktree), 0, repo);
2553 if (error != NULL) {
2554 free(commit_id);
2555 if (error->code == GOT_ERR_ANCESTRY) {
2556 error = checkout_ancestry_error(
2557 head_ref, commit_id_str);
2559 goto done;
2561 error = check_same_branch(commit_id, head_ref, NULL, repo);
2562 if (error) {
2563 if (error->code == GOT_ERR_ANCESTRY) {
2564 error = checkout_ancestry_error(
2565 head_ref, commit_id_str);
2567 goto done;
2569 error = got_worktree_set_base_commit_id(worktree, repo,
2570 commit_id);
2571 free(commit_id);
2572 if (error)
2573 goto done;
2576 error = got_pathlist_append(&paths, "", NULL);
2577 if (error)
2578 goto done;
2579 cpa.worktree_path = worktree_path;
2580 cpa.had_base_commit_ref_error = 0;
2581 error = got_worktree_checkout_files(worktree, &paths, repo,
2582 checkout_progress, &cpa, check_cancelled, NULL);
2583 if (error != NULL)
2584 goto done;
2586 printf("Now shut up and hack\n");
2587 if (cpa.had_base_commit_ref_error)
2588 show_worktree_base_ref_warning();
2589 done:
2590 got_pathlist_free(&paths);
2591 free(commit_id_str);
2592 free(repo_path);
2593 free(worktree_path);
2594 return error;
2597 struct got_update_progress_arg {
2598 int did_something;
2599 int conflicts;
2600 int obstructed;
2601 int not_updated;
2604 void
2605 print_update_progress_stats(struct got_update_progress_arg *upa)
2607 if (!upa->did_something)
2608 return;
2610 if (upa->conflicts > 0)
2611 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2612 if (upa->obstructed > 0)
2613 printf("File paths obstructed by a non-regular file: %d\n",
2614 upa->obstructed);
2615 if (upa->not_updated > 0)
2616 printf("Files not updated because of existing merge "
2617 "conflicts: %d\n", upa->not_updated);
2620 __dead static void
2621 usage_update(void)
2623 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [path ...]\n",
2624 getprogname());
2625 exit(1);
2628 static const struct got_error *
2629 update_progress(void *arg, unsigned char status, const char *path)
2631 struct got_update_progress_arg *upa = arg;
2633 if (status == GOT_STATUS_EXISTS ||
2634 status == GOT_STATUS_BASE_REF_ERR)
2635 return NULL;
2637 upa->did_something = 1;
2639 /* Base commit bump happens silently. */
2640 if (status == GOT_STATUS_BUMP_BASE)
2641 return NULL;
2643 if (status == GOT_STATUS_CONFLICT)
2644 upa->conflicts++;
2645 if (status == GOT_STATUS_OBSTRUCTED)
2646 upa->obstructed++;
2647 if (status == GOT_STATUS_CANNOT_UPDATE)
2648 upa->not_updated++;
2650 while (path[0] == '/')
2651 path++;
2652 printf("%c %s\n", status, path);
2653 return NULL;
2656 static const struct got_error *
2657 switch_head_ref(struct got_reference *head_ref,
2658 struct got_object_id *commit_id, struct got_worktree *worktree,
2659 struct got_repository *repo)
2661 const struct got_error *err = NULL;
2662 char *base_id_str;
2663 int ref_has_moved = 0;
2665 /* Trivial case: switching between two different references. */
2666 if (strcmp(got_ref_get_name(head_ref),
2667 got_worktree_get_head_ref_name(worktree)) != 0) {
2668 printf("Switching work tree from %s to %s\n",
2669 got_worktree_get_head_ref_name(worktree),
2670 got_ref_get_name(head_ref));
2671 return got_worktree_set_head_ref(worktree, head_ref);
2674 err = check_linear_ancestry(commit_id,
2675 got_worktree_get_base_commit_id(worktree), 0, repo);
2676 if (err) {
2677 if (err->code != GOT_ERR_ANCESTRY)
2678 return err;
2679 ref_has_moved = 1;
2681 if (!ref_has_moved)
2682 return NULL;
2684 /* Switching to a rebased branch with the same reference name. */
2685 err = got_object_id_str(&base_id_str,
2686 got_worktree_get_base_commit_id(worktree));
2687 if (err)
2688 return err;
2689 printf("Reference %s now points at a different branch\n",
2690 got_worktree_get_head_ref_name(worktree));
2691 printf("Switching work tree from %s to %s\n", base_id_str,
2692 got_worktree_get_head_ref_name(worktree));
2693 return NULL;
2696 static const struct got_error *
2697 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2699 const struct got_error *err;
2700 int in_progress;
2702 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2703 if (err)
2704 return err;
2705 if (in_progress)
2706 return got_error(GOT_ERR_REBASING);
2708 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2709 if (err)
2710 return err;
2711 if (in_progress)
2712 return got_error(GOT_ERR_HISTEDIT_BUSY);
2714 return NULL;
2717 static const struct got_error *
2718 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2719 char *argv[], struct got_worktree *worktree)
2721 const struct got_error *err = NULL;
2722 char *path;
2723 int i;
2725 if (argc == 0) {
2726 path = strdup("");
2727 if (path == NULL)
2728 return got_error_from_errno("strdup");
2729 return got_pathlist_append(paths, path, NULL);
2732 for (i = 0; i < argc; i++) {
2733 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2734 if (err)
2735 break;
2736 err = got_pathlist_append(paths, path, NULL);
2737 if (err) {
2738 free(path);
2739 break;
2743 return err;
2746 static const struct got_error *
2747 wrap_not_worktree_error(const struct got_error *orig_err,
2748 const char *cmdname, const char *path)
2750 const struct got_error *err;
2751 struct got_repository *repo;
2752 static char msg[512];
2754 err = got_repo_open(&repo, path, NULL);
2755 if (err)
2756 return orig_err;
2758 snprintf(msg, sizeof(msg),
2759 "'got %s' needs a work tree in addition to a git repository\n"
2760 "Work trees can be checked out from this Git repository with "
2761 "'got checkout'.\n"
2762 "The got(1) manual page contains more information.", cmdname);
2763 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2764 got_repo_close(repo);
2765 return err;
2768 static const struct got_error *
2769 cmd_update(int argc, char *argv[])
2771 const struct got_error *error = NULL;
2772 struct got_repository *repo = NULL;
2773 struct got_worktree *worktree = NULL;
2774 char *worktree_path = NULL;
2775 struct got_object_id *commit_id = NULL;
2776 char *commit_id_str = NULL;
2777 const char *branch_name = NULL;
2778 struct got_reference *head_ref = NULL;
2779 struct got_pathlist_head paths;
2780 struct got_pathlist_entry *pe;
2781 int ch;
2782 struct got_update_progress_arg upa;
2784 TAILQ_INIT(&paths);
2786 while ((ch = getopt(argc, argv, "b:c:")) != -1) {
2787 switch (ch) {
2788 case 'b':
2789 branch_name = optarg;
2790 break;
2791 case 'c':
2792 commit_id_str = strdup(optarg);
2793 if (commit_id_str == NULL)
2794 return got_error_from_errno("strdup");
2795 break;
2796 default:
2797 usage_update();
2798 /* NOTREACHED */
2802 argc -= optind;
2803 argv += optind;
2805 #ifndef PROFILE
2806 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2807 "unveil", NULL) == -1)
2808 err(1, "pledge");
2809 #endif
2810 worktree_path = getcwd(NULL, 0);
2811 if (worktree_path == NULL) {
2812 error = got_error_from_errno("getcwd");
2813 goto done;
2815 error = got_worktree_open(&worktree, worktree_path);
2816 if (error) {
2817 if (error->code == GOT_ERR_NOT_WORKTREE)
2818 error = wrap_not_worktree_error(error, "update",
2819 worktree_path);
2820 goto done;
2823 error = check_rebase_or_histedit_in_progress(worktree);
2824 if (error)
2825 goto done;
2827 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
2828 NULL);
2829 if (error != NULL)
2830 goto done;
2832 error = apply_unveil(got_repo_get_path(repo), 0,
2833 got_worktree_get_root_path(worktree));
2834 if (error)
2835 goto done;
2837 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2838 if (error)
2839 goto done;
2841 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
2842 got_worktree_get_head_ref_name(worktree), 0);
2843 if (error != NULL)
2844 goto done;
2845 if (commit_id_str == NULL) {
2846 error = got_ref_resolve(&commit_id, repo, head_ref);
2847 if (error != NULL)
2848 goto done;
2849 error = got_object_id_str(&commit_id_str, commit_id);
2850 if (error != NULL)
2851 goto done;
2852 } else {
2853 error = got_repo_match_object_id(&commit_id, NULL,
2854 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
2855 free(commit_id_str);
2856 commit_id_str = NULL;
2857 if (error)
2858 goto done;
2859 error = got_object_id_str(&commit_id_str, commit_id);
2860 if (error)
2861 goto done;
2864 if (branch_name) {
2865 struct got_object_id *head_commit_id;
2866 TAILQ_FOREACH(pe, &paths, entry) {
2867 if (pe->path_len == 0)
2868 continue;
2869 error = got_error_msg(GOT_ERR_BAD_PATH,
2870 "switching between branches requires that "
2871 "the entire work tree gets updated");
2872 goto done;
2874 error = got_ref_resolve(&head_commit_id, repo, head_ref);
2875 if (error)
2876 goto done;
2877 error = check_linear_ancestry(commit_id, head_commit_id, 0,
2878 repo);
2879 free(head_commit_id);
2880 if (error != NULL)
2881 goto done;
2882 error = check_same_branch(commit_id, head_ref, NULL, repo);
2883 if (error)
2884 goto done;
2885 error = switch_head_ref(head_ref, commit_id, worktree, repo);
2886 if (error)
2887 goto done;
2888 } else {
2889 error = check_linear_ancestry(commit_id,
2890 got_worktree_get_base_commit_id(worktree), 0, repo);
2891 if (error != NULL) {
2892 if (error->code == GOT_ERR_ANCESTRY)
2893 error = got_error(GOT_ERR_BRANCH_MOVED);
2894 goto done;
2896 error = check_same_branch(commit_id, head_ref, NULL, repo);
2897 if (error)
2898 goto done;
2901 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2902 commit_id) != 0) {
2903 error = got_worktree_set_base_commit_id(worktree, repo,
2904 commit_id);
2905 if (error)
2906 goto done;
2909 memset(&upa, 0, sizeof(upa));
2910 error = got_worktree_checkout_files(worktree, &paths, repo,
2911 update_progress, &upa, check_cancelled, NULL);
2912 if (error != NULL)
2913 goto done;
2915 if (upa.did_something)
2916 printf("Updated to commit %s\n", commit_id_str);
2917 else
2918 printf("Already up-to-date\n");
2919 print_update_progress_stats(&upa);
2920 done:
2921 free(worktree_path);
2922 TAILQ_FOREACH(pe, &paths, entry)
2923 free((char *)pe->path);
2924 got_pathlist_free(&paths);
2925 free(commit_id);
2926 free(commit_id_str);
2927 return error;
2930 static const struct got_error *
2931 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
2932 const char *path, int diff_context, int ignore_whitespace,
2933 struct got_repository *repo)
2935 const struct got_error *err = NULL;
2936 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
2938 if (blob_id1) {
2939 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
2940 if (err)
2941 goto done;
2944 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
2945 if (err)
2946 goto done;
2948 while (path[0] == '/')
2949 path++;
2950 err = got_diff_blob(blob1, blob2, path, path, diff_context,
2951 ignore_whitespace, stdout);
2952 done:
2953 if (blob1)
2954 got_object_blob_close(blob1);
2955 got_object_blob_close(blob2);
2956 return err;
2959 static const struct got_error *
2960 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
2961 const char *path, int diff_context, int ignore_whitespace,
2962 struct got_repository *repo)
2964 const struct got_error *err = NULL;
2965 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
2966 struct got_diff_blob_output_unidiff_arg arg;
2968 if (tree_id1) {
2969 err = got_object_open_as_tree(&tree1, repo, tree_id1);
2970 if (err)
2971 goto done;
2974 err = got_object_open_as_tree(&tree2, repo, tree_id2);
2975 if (err)
2976 goto done;
2978 arg.diff_context = diff_context;
2979 arg.ignore_whitespace = ignore_whitespace;
2980 arg.outfile = stdout;
2981 while (path[0] == '/')
2982 path++;
2983 err = got_diff_tree(tree1, tree2, path, path, repo,
2984 got_diff_blob_output_unidiff, &arg, 1);
2985 done:
2986 if (tree1)
2987 got_object_tree_close(tree1);
2988 if (tree2)
2989 got_object_tree_close(tree2);
2990 return err;
2993 static const struct got_error *
2994 get_changed_paths(struct got_pathlist_head *paths,
2995 struct got_commit_object *commit, struct got_repository *repo)
2997 const struct got_error *err = NULL;
2998 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
2999 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3000 struct got_object_qid *qid;
3002 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3003 if (qid != NULL) {
3004 struct got_commit_object *pcommit;
3005 err = got_object_open_as_commit(&pcommit, repo,
3006 qid->id);
3007 if (err)
3008 return err;
3010 tree_id1 = got_object_commit_get_tree_id(pcommit);
3011 got_object_commit_close(pcommit);
3015 if (tree_id1) {
3016 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3017 if (err)
3018 goto done;
3021 tree_id2 = got_object_commit_get_tree_id(commit);
3022 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3023 if (err)
3024 goto done;
3026 err = got_diff_tree(tree1, tree2, "", "", repo,
3027 got_diff_tree_collect_changed_paths, paths, 0);
3028 done:
3029 if (tree1)
3030 got_object_tree_close(tree1);
3031 if (tree2)
3032 got_object_tree_close(tree2);
3033 return err;
3036 static const struct got_error *
3037 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3038 const char *path, int diff_context, struct got_repository *repo)
3040 const struct got_error *err = NULL;
3041 struct got_commit_object *pcommit = NULL;
3042 char *id_str1 = NULL, *id_str2 = NULL;
3043 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3044 struct got_object_qid *qid;
3046 qid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
3047 if (qid != NULL) {
3048 err = got_object_open_as_commit(&pcommit, repo,
3049 qid->id);
3050 if (err)
3051 return err;
3054 if (path && path[0] != '\0') {
3055 int obj_type;
3056 err = got_object_id_by_path(&obj_id2, repo, id, path);
3057 if (err)
3058 goto done;
3059 err = got_object_id_str(&id_str2, obj_id2);
3060 if (err) {
3061 free(obj_id2);
3062 goto done;
3064 if (pcommit) {
3065 err = got_object_id_by_path(&obj_id1, repo,
3066 qid->id, path);
3067 if (err) {
3068 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3069 free(obj_id2);
3070 goto done;
3072 } else {
3073 err = got_object_id_str(&id_str1, obj_id1);
3074 if (err) {
3075 free(obj_id2);
3076 goto done;
3080 err = got_object_get_type(&obj_type, repo, obj_id2);
3081 if (err) {
3082 free(obj_id2);
3083 goto done;
3085 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3086 switch (obj_type) {
3087 case GOT_OBJ_TYPE_BLOB:
3088 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3089 0, repo);
3090 break;
3091 case GOT_OBJ_TYPE_TREE:
3092 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3093 0, repo);
3094 break;
3095 default:
3096 err = got_error(GOT_ERR_OBJ_TYPE);
3097 break;
3099 free(obj_id1);
3100 free(obj_id2);
3101 } else {
3102 obj_id2 = got_object_commit_get_tree_id(commit);
3103 err = got_object_id_str(&id_str2, obj_id2);
3104 if (err)
3105 goto done;
3106 obj_id1 = got_object_commit_get_tree_id(pcommit);
3107 err = got_object_id_str(&id_str1, obj_id1);
3108 if (err)
3109 goto done;
3110 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3111 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, repo);
3113 done:
3114 free(id_str1);
3115 free(id_str2);
3116 if (pcommit)
3117 got_object_commit_close(pcommit);
3118 return err;
3121 static char *
3122 get_datestr(time_t *time, char *datebuf)
3124 struct tm mytm, *tm;
3125 char *p, *s;
3127 tm = gmtime_r(time, &mytm);
3128 if (tm == NULL)
3129 return NULL;
3130 s = asctime_r(tm, datebuf);
3131 if (s == NULL)
3132 return NULL;
3133 p = strchr(s, '\n');
3134 if (p)
3135 *p = '\0';
3136 return s;
3139 static const struct got_error *
3140 match_logmsg(int *have_match, struct got_object_id *id,
3141 struct got_commit_object *commit, regex_t *regex)
3143 const struct got_error *err = NULL;
3144 regmatch_t regmatch;
3145 char *id_str = NULL, *logmsg = NULL;
3147 *have_match = 0;
3149 err = got_object_id_str(&id_str, id);
3150 if (err)
3151 return err;
3153 err = got_object_commit_get_logmsg(&logmsg, commit);
3154 if (err)
3155 goto done;
3157 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3158 *have_match = 1;
3159 done:
3160 free(id_str);
3161 free(logmsg);
3162 return err;
3165 static void
3166 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3167 regex_t *regex)
3169 regmatch_t regmatch;
3170 struct got_pathlist_entry *pe;
3172 *have_match = 0;
3174 TAILQ_FOREACH(pe, changed_paths, entry) {
3175 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3176 *have_match = 1;
3177 break;
3182 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3184 static const struct got_error *
3185 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3186 struct got_repository *repo, const char *path,
3187 struct got_pathlist_head *changed_paths, int show_patch,
3188 int diff_context, struct got_reflist_head *refs)
3190 const struct got_error *err = NULL;
3191 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3192 char datebuf[26];
3193 time_t committer_time;
3194 const char *author, *committer;
3195 char *refs_str = NULL;
3196 struct got_reflist_entry *re;
3198 SIMPLEQ_FOREACH(re, refs, entry) {
3199 char *s;
3200 const char *name;
3201 struct got_tag_object *tag = NULL;
3202 int cmp;
3204 name = got_ref_get_name(re->ref);
3205 if (strcmp(name, GOT_REF_HEAD) == 0)
3206 continue;
3207 if (strncmp(name, "refs/", 5) == 0)
3208 name += 5;
3209 if (strncmp(name, "got/", 4) == 0)
3210 continue;
3211 if (strncmp(name, "heads/", 6) == 0)
3212 name += 6;
3213 if (strncmp(name, "remotes/", 8) == 0) {
3214 name += 8;
3215 s = strstr(name, "/" GOT_REF_HEAD);
3216 if (s != NULL && s[strlen(s)] == '\0')
3217 continue;
3219 if (strncmp(name, "tags/", 5) == 0) {
3220 err = got_object_open_as_tag(&tag, repo, re->id);
3221 if (err) {
3222 if (err->code != GOT_ERR_OBJ_TYPE)
3223 return err;
3224 /* Ref points at something other than a tag. */
3225 err = NULL;
3226 tag = NULL;
3229 cmp = got_object_id_cmp(tag ?
3230 got_object_tag_get_object_id(tag) : re->id, id);
3231 if (tag)
3232 got_object_tag_close(tag);
3233 if (cmp != 0)
3234 continue;
3235 s = refs_str;
3236 if (asprintf(&refs_str, "%s%s%s", s ? s : "", s ? ", " : "",
3237 name) == -1) {
3238 err = got_error_from_errno("asprintf");
3239 free(s);
3240 return err;
3242 free(s);
3244 err = got_object_id_str(&id_str, id);
3245 if (err)
3246 return err;
3248 printf(GOT_COMMIT_SEP_STR);
3249 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3250 refs_str ? refs_str : "", refs_str ? ")" : "");
3251 free(id_str);
3252 id_str = NULL;
3253 free(refs_str);
3254 refs_str = NULL;
3255 printf("from: %s\n", got_object_commit_get_author(commit));
3256 committer_time = got_object_commit_get_committer_time(commit);
3257 datestr = get_datestr(&committer_time, datebuf);
3258 if (datestr)
3259 printf("date: %s UTC\n", datestr);
3260 author = got_object_commit_get_author(commit);
3261 committer = got_object_commit_get_committer(commit);
3262 if (strcmp(author, committer) != 0)
3263 printf("via: %s\n", committer);
3264 if (got_object_commit_get_nparents(commit) > 1) {
3265 const struct got_object_id_queue *parent_ids;
3266 struct got_object_qid *qid;
3267 int n = 1;
3268 parent_ids = got_object_commit_get_parent_ids(commit);
3269 SIMPLEQ_FOREACH(qid, parent_ids, entry) {
3270 err = got_object_id_str(&id_str, qid->id);
3271 if (err)
3272 return err;
3273 printf("parent %d: %s\n", n++, id_str);
3274 free(id_str);
3278 err = got_object_commit_get_logmsg(&logmsg0, commit);
3279 if (err)
3280 return err;
3282 logmsg = logmsg0;
3283 do {
3284 line = strsep(&logmsg, "\n");
3285 if (line)
3286 printf(" %s\n", line);
3287 } while (line);
3288 free(logmsg0);
3290 if (changed_paths) {
3291 struct got_pathlist_entry *pe;
3292 TAILQ_FOREACH(pe, changed_paths, entry) {
3293 struct got_diff_changed_path *cp = pe->data;
3294 printf(" %c %s\n", cp->status, pe->path);
3296 printf("\n");
3298 if (show_patch) {
3299 err = print_patch(commit, id, path, diff_context, repo);
3300 if (err == 0)
3301 printf("\n");
3304 if (fflush(stdout) != 0 && err == NULL)
3305 err = got_error_from_errno("fflush");
3306 return err;
3309 static const struct got_error *
3310 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3311 struct got_repository *repo, const char *path, int show_changed_paths,
3312 int show_patch, const char *search_pattern, int diff_context, int limit,
3313 int log_branches, int reverse_display_order, struct got_reflist_head *refs)
3315 const struct got_error *err;
3316 struct got_commit_graph *graph;
3317 regex_t regex;
3318 int have_match;
3319 struct got_object_id_queue reversed_commits;
3320 struct got_object_qid *qid;
3321 struct got_commit_object *commit;
3322 struct got_pathlist_head changed_paths;
3323 struct got_pathlist_entry *pe;
3325 SIMPLEQ_INIT(&reversed_commits);
3326 TAILQ_INIT(&changed_paths);
3328 if (search_pattern && regcomp(&regex, search_pattern,
3329 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3330 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3332 err = got_commit_graph_open(&graph, path, !log_branches);
3333 if (err)
3334 return err;
3335 err = got_commit_graph_iter_start(graph, root_id, repo,
3336 check_cancelled, NULL);
3337 if (err)
3338 goto done;
3339 for (;;) {
3340 struct got_object_id *id;
3342 if (sigint_received || sigpipe_received)
3343 break;
3345 err = got_commit_graph_iter_next(&id, graph, repo,
3346 check_cancelled, NULL);
3347 if (err) {
3348 if (err->code == GOT_ERR_ITER_COMPLETED)
3349 err = NULL;
3350 break;
3352 if (id == NULL)
3353 break;
3355 err = got_object_open_as_commit(&commit, repo, id);
3356 if (err)
3357 break;
3359 if (show_changed_paths && !reverse_display_order) {
3360 err = get_changed_paths(&changed_paths, commit, repo);
3361 if (err)
3362 break;
3365 if (search_pattern) {
3366 err = match_logmsg(&have_match, id, commit, &regex);
3367 if (err) {
3368 got_object_commit_close(commit);
3369 break;
3371 if (have_match == 0 && show_changed_paths)
3372 match_changed_paths(&have_match,
3373 &changed_paths, &regex);
3374 if (have_match == 0) {
3375 got_object_commit_close(commit);
3376 TAILQ_FOREACH(pe, &changed_paths, entry) {
3377 free((char *)pe->path);
3378 free(pe->data);
3380 got_pathlist_free(&changed_paths);
3381 continue;
3385 if (reverse_display_order) {
3386 err = got_object_qid_alloc(&qid, id);
3387 if (err)
3388 break;
3389 SIMPLEQ_INSERT_HEAD(&reversed_commits, qid, entry);
3390 got_object_commit_close(commit);
3391 } else {
3392 err = print_commit(commit, id, repo, path,
3393 show_changed_paths ? &changed_paths : NULL,
3394 show_patch, diff_context, refs);
3395 got_object_commit_close(commit);
3396 if (err)
3397 break;
3399 if ((limit && --limit == 0) ||
3400 (end_id && got_object_id_cmp(id, end_id) == 0))
3401 break;
3403 TAILQ_FOREACH(pe, &changed_paths, entry) {
3404 free((char *)pe->path);
3405 free(pe->data);
3407 got_pathlist_free(&changed_paths);
3409 if (reverse_display_order) {
3410 SIMPLEQ_FOREACH(qid, &reversed_commits, entry) {
3411 err = got_object_open_as_commit(&commit, repo, qid->id);
3412 if (err)
3413 break;
3414 if (show_changed_paths) {
3415 err = get_changed_paths(&changed_paths,
3416 commit, repo);
3417 if (err)
3418 break;
3420 err = print_commit(commit, qid->id, repo, path,
3421 show_changed_paths ? &changed_paths : NULL,
3422 show_patch, diff_context, refs);
3423 got_object_commit_close(commit);
3424 if (err)
3425 break;
3426 TAILQ_FOREACH(pe, &changed_paths, entry) {
3427 free((char *)pe->path);
3428 free(pe->data);
3430 got_pathlist_free(&changed_paths);
3433 done:
3434 while (!SIMPLEQ_EMPTY(&reversed_commits)) {
3435 qid = SIMPLEQ_FIRST(&reversed_commits);
3436 SIMPLEQ_REMOVE_HEAD(&reversed_commits, entry);
3437 got_object_qid_free(qid);
3439 TAILQ_FOREACH(pe, &changed_paths, entry) {
3440 free((char *)pe->path);
3441 free(pe->data);
3443 got_pathlist_free(&changed_paths);
3444 if (search_pattern)
3445 regfree(&regex);
3446 got_commit_graph_close(graph);
3447 return err;
3450 __dead static void
3451 usage_log(void)
3453 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3454 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3455 "[-R] [path]\n", getprogname());
3456 exit(1);
3459 static int
3460 get_default_log_limit(void)
3462 const char *got_default_log_limit;
3463 long long n;
3464 const char *errstr;
3466 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3467 if (got_default_log_limit == NULL)
3468 return 0;
3469 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3470 if (errstr != NULL)
3471 return 0;
3472 return n;
3475 static const struct got_error *
3476 resolve_commit_arg(struct got_object_id **id, const char *commit_arg,
3477 struct got_repository *repo)
3479 const struct got_error *err = NULL;
3480 struct got_reference *ref;
3482 *id = NULL;
3484 err = got_ref_open(&ref, repo, commit_arg, 0);
3485 if (err == NULL) {
3486 int obj_type;
3487 err = got_ref_resolve(id, repo, ref);
3488 got_ref_close(ref);
3489 if (err)
3490 return err;
3491 err = got_object_get_type(&obj_type, repo, *id);
3492 if (err)
3493 return err;
3494 if (obj_type == GOT_OBJ_TYPE_TAG) {
3495 struct got_tag_object *tag;
3496 err = got_object_open_as_tag(&tag, repo, *id);
3497 if (err)
3498 return err;
3499 if (got_object_tag_get_object_type(tag) !=
3500 GOT_OBJ_TYPE_COMMIT) {
3501 got_object_tag_close(tag);
3502 return got_error(GOT_ERR_OBJ_TYPE);
3504 free(*id);
3505 *id = got_object_id_dup(
3506 got_object_tag_get_object_id(tag));
3507 if (*id == NULL)
3508 err = got_error_from_errno(
3509 "got_object_id_dup");
3510 got_object_tag_close(tag);
3511 if (err)
3512 return err;
3513 } else if (obj_type != GOT_OBJ_TYPE_COMMIT)
3514 return got_error(GOT_ERR_OBJ_TYPE);
3515 } else {
3516 err = got_repo_match_object_id_prefix(id, commit_arg,
3517 GOT_OBJ_TYPE_COMMIT, repo);
3520 return err;
3523 static const struct got_error *
3524 cmd_log(int argc, char *argv[])
3526 const struct got_error *error;
3527 struct got_repository *repo = NULL;
3528 struct got_worktree *worktree = NULL;
3529 struct got_object_id *start_id = NULL, *end_id = NULL;
3530 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3531 const char *start_commit = NULL, *end_commit = NULL;
3532 const char *search_pattern = NULL;
3533 int diff_context = -1, ch;
3534 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3535 int reverse_display_order = 0;
3536 const char *errstr;
3537 struct got_reflist_head refs;
3539 SIMPLEQ_INIT(&refs);
3541 #ifndef PROFILE
3542 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3543 NULL)
3544 == -1)
3545 err(1, "pledge");
3546 #endif
3548 limit = get_default_log_limit();
3550 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
3551 switch (ch) {
3552 case 'p':
3553 show_patch = 1;
3554 break;
3555 case 'P':
3556 show_changed_paths = 1;
3557 break;
3558 case 'c':
3559 start_commit = optarg;
3560 break;
3561 case 'C':
3562 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3563 &errstr);
3564 if (errstr != NULL)
3565 err(1, "-C option %s", errstr);
3566 break;
3567 case 'l':
3568 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3569 if (errstr != NULL)
3570 err(1, "-l option %s", errstr);
3571 break;
3572 case 'b':
3573 log_branches = 1;
3574 break;
3575 case 'r':
3576 repo_path = realpath(optarg, NULL);
3577 if (repo_path == NULL)
3578 return got_error_from_errno2("realpath",
3579 optarg);
3580 got_path_strip_trailing_slashes(repo_path);
3581 break;
3582 case 'R':
3583 reverse_display_order = 1;
3584 break;
3585 case 's':
3586 search_pattern = optarg;
3587 break;
3588 case 'x':
3589 end_commit = optarg;
3590 break;
3591 default:
3592 usage_log();
3593 /* NOTREACHED */
3597 argc -= optind;
3598 argv += optind;
3600 if (diff_context == -1)
3601 diff_context = 3;
3602 else if (!show_patch)
3603 errx(1, "-C reguires -p");
3605 cwd = getcwd(NULL, 0);
3606 if (cwd == NULL) {
3607 error = got_error_from_errno("getcwd");
3608 goto done;
3611 if (repo_path == NULL) {
3612 error = got_worktree_open(&worktree, cwd);
3613 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3614 goto done;
3615 error = NULL;
3618 if (argc == 0) {
3619 path = strdup("");
3620 if (path == NULL) {
3621 error = got_error_from_errno("strdup");
3622 goto done;
3624 } else if (argc == 1) {
3625 if (worktree) {
3626 error = got_worktree_resolve_path(&path, worktree,
3627 argv[0]);
3628 if (error)
3629 goto done;
3630 } else {
3631 path = strdup(argv[0]);
3632 if (path == NULL) {
3633 error = got_error_from_errno("strdup");
3634 goto done;
3637 } else
3638 usage_log();
3640 if (repo_path == NULL) {
3641 repo_path = worktree ?
3642 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
3644 if (repo_path == NULL) {
3645 error = got_error_from_errno("strdup");
3646 goto done;
3649 error = got_repo_open(&repo, repo_path, NULL);
3650 if (error != NULL)
3651 goto done;
3653 error = apply_unveil(got_repo_get_path(repo), 1,
3654 worktree ? got_worktree_get_root_path(worktree) : NULL);
3655 if (error)
3656 goto done;
3658 if (start_commit == NULL) {
3659 struct got_reference *head_ref;
3660 struct got_commit_object *commit = NULL;
3661 error = got_ref_open(&head_ref, repo,
3662 worktree ? got_worktree_get_head_ref_name(worktree)
3663 : GOT_REF_HEAD, 0);
3664 if (error != NULL)
3665 goto done;
3666 error = got_ref_resolve(&start_id, repo, head_ref);
3667 got_ref_close(head_ref);
3668 if (error != NULL)
3669 goto done;
3670 error = got_object_open_as_commit(&commit, repo,
3671 start_id);
3672 if (error != NULL)
3673 goto done;
3674 got_object_commit_close(commit);
3675 } else {
3676 error = resolve_commit_arg(&start_id, start_commit, repo);
3677 if (error != NULL)
3678 goto done;
3680 if (end_commit != NULL) {
3681 error = resolve_commit_arg(&end_id, end_commit, repo);
3682 if (error != NULL)
3683 goto done;
3686 if (worktree) {
3687 const char *prefix = got_worktree_get_path_prefix(worktree);
3688 char *p;
3689 if (asprintf(&p, "%s%s%s", prefix,
3690 (strcmp(prefix, "/") != 0) ? "/" : "", path) == -1) {
3691 error = got_error_from_errno("asprintf");
3692 goto done;
3694 error = got_repo_map_path(&in_repo_path, repo, p, 0);
3695 free(p);
3696 } else
3697 error = got_repo_map_path(&in_repo_path, repo, path, 1);
3698 if (error != NULL)
3699 goto done;
3700 if (in_repo_path) {
3701 free(path);
3702 path = in_repo_path;
3705 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
3706 if (error)
3707 goto done;
3709 error = print_commits(start_id, end_id, repo, path, show_changed_paths,
3710 show_patch, search_pattern, diff_context, limit, log_branches,
3711 reverse_display_order, &refs);
3712 done:
3713 free(path);
3714 free(repo_path);
3715 free(cwd);
3716 if (worktree)
3717 got_worktree_close(worktree);
3718 if (repo) {
3719 const struct got_error *repo_error;
3720 repo_error = got_repo_close(repo);
3721 if (error == NULL)
3722 error = repo_error;
3724 got_ref_list_free(&refs);
3725 return error;
3728 __dead static void
3729 usage_diff(void)
3731 fprintf(stderr, "usage: %s diff [-C number] [-r repository-path] [-s] "
3732 "[-w] [object1 object2 | path]\n", getprogname());
3733 exit(1);
3736 struct print_diff_arg {
3737 struct got_repository *repo;
3738 struct got_worktree *worktree;
3739 int diff_context;
3740 const char *id_str;
3741 int header_shown;
3742 int diff_staged;
3743 int ignore_whitespace;
3747 * Create a file which contains the target path of a symlink so we can feed
3748 * it as content to the diff engine.
3750 static const struct got_error *
3751 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
3752 const char *abspath)
3754 const struct got_error *err = NULL;
3755 char target_path[PATH_MAX];
3756 ssize_t target_len, outlen;
3758 *fd = -1;
3760 if (dirfd != -1) {
3761 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
3762 if (target_len == -1)
3763 return got_error_from_errno2("readlinkat", abspath);
3764 } else {
3765 target_len = readlink(abspath, target_path, PATH_MAX);
3766 if (target_len == -1)
3767 return got_error_from_errno2("readlink", abspath);
3770 *fd = got_opentempfd();
3771 if (*fd == -1)
3772 return got_error_from_errno("got_opentempfd");
3774 outlen = write(*fd, target_path, target_len);
3775 if (outlen == -1) {
3776 err = got_error_from_errno("got_opentempfd");
3777 goto done;
3780 if (lseek(*fd, 0, SEEK_SET) == -1) {
3781 err = got_error_from_errno2("lseek", abspath);
3782 goto done;
3784 done:
3785 if (err) {
3786 close(*fd);
3787 *fd = -1;
3789 return err;
3792 static const struct got_error *
3793 print_diff(void *arg, unsigned char status, unsigned char staged_status,
3794 const char *path, struct got_object_id *blob_id,
3795 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
3796 int dirfd, const char *de_name)
3798 struct print_diff_arg *a = arg;
3799 const struct got_error *err = NULL;
3800 struct got_blob_object *blob1 = NULL;
3801 int fd = -1;
3802 FILE *f2 = NULL;
3803 char *abspath = NULL, *label1 = NULL;
3804 struct stat sb;
3806 if (a->diff_staged) {
3807 if (staged_status != GOT_STATUS_MODIFY &&
3808 staged_status != GOT_STATUS_ADD &&
3809 staged_status != GOT_STATUS_DELETE)
3810 return NULL;
3811 } else {
3812 if (staged_status == GOT_STATUS_DELETE)
3813 return NULL;
3814 if (status == GOT_STATUS_NONEXISTENT)
3815 return got_error_set_errno(ENOENT, path);
3816 if (status != GOT_STATUS_MODIFY &&
3817 status != GOT_STATUS_ADD &&
3818 status != GOT_STATUS_DELETE &&
3819 status != GOT_STATUS_CONFLICT)
3820 return NULL;
3823 if (!a->header_shown) {
3824 printf("diff %s %s%s\n", a->id_str,
3825 got_worktree_get_root_path(a->worktree),
3826 a->diff_staged ? " (staged changes)" : "");
3827 a->header_shown = 1;
3830 if (a->diff_staged) {
3831 const char *label1 = NULL, *label2 = NULL;
3832 switch (staged_status) {
3833 case GOT_STATUS_MODIFY:
3834 label1 = path;
3835 label2 = path;
3836 break;
3837 case GOT_STATUS_ADD:
3838 label2 = path;
3839 break;
3840 case GOT_STATUS_DELETE:
3841 label1 = path;
3842 break;
3843 default:
3844 return got_error(GOT_ERR_FILE_STATUS);
3846 return got_diff_objects_as_blobs(blob_id, staged_blob_id,
3847 label1, label2, a->diff_context, a->ignore_whitespace,
3848 a->repo, stdout);
3851 if (staged_status == GOT_STATUS_ADD ||
3852 staged_status == GOT_STATUS_MODIFY) {
3853 char *id_str;
3854 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
3855 8192);
3856 if (err)
3857 goto done;
3858 err = got_object_id_str(&id_str, staged_blob_id);
3859 if (err)
3860 goto done;
3861 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
3862 err = got_error_from_errno("asprintf");
3863 free(id_str);
3864 goto done;
3866 free(id_str);
3867 } else if (status != GOT_STATUS_ADD) {
3868 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
3869 if (err)
3870 goto done;
3873 if (status != GOT_STATUS_DELETE) {
3874 if (asprintf(&abspath, "%s/%s",
3875 got_worktree_get_root_path(a->worktree), path) == -1) {
3876 err = got_error_from_errno("asprintf");
3877 goto done;
3880 if (dirfd != -1) {
3881 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
3882 if (fd == -1) {
3883 if (errno != ELOOP) {
3884 err = got_error_from_errno2("openat",
3885 abspath);
3886 goto done;
3888 err = get_symlink_target_file(&fd, dirfd,
3889 de_name, abspath);
3890 if (err)
3891 goto done;
3893 } else {
3894 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
3895 if (fd == -1) {
3896 if (errno != ELOOP) {
3897 err = got_error_from_errno2("open",
3898 abspath);
3899 goto done;
3901 err = get_symlink_target_file(&fd, dirfd,
3902 de_name, abspath);
3903 if (err)
3904 goto done;
3907 if (fstat(fd, &sb) == -1) {
3908 err = got_error_from_errno2("fstat", abspath);
3909 goto done;
3911 f2 = fdopen(fd, "r");
3912 if (f2 == NULL) {
3913 err = got_error_from_errno2("fdopen", abspath);
3914 goto done;
3916 fd = -1;
3917 } else
3918 sb.st_size = 0;
3920 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
3921 a->diff_context, a->ignore_whitespace, stdout);
3922 done:
3923 if (blob1)
3924 got_object_blob_close(blob1);
3925 if (f2 && fclose(f2) == EOF && err == NULL)
3926 err = got_error_from_errno("fclose");
3927 if (fd != -1 && close(fd) == -1 && err == NULL)
3928 err = got_error_from_errno("close");
3929 free(abspath);
3930 return err;
3933 static const struct got_error *
3934 cmd_diff(int argc, char *argv[])
3936 const struct got_error *error;
3937 struct got_repository *repo = NULL;
3938 struct got_worktree *worktree = NULL;
3939 char *cwd = NULL, *repo_path = NULL;
3940 struct got_object_id *id1 = NULL, *id2 = NULL;
3941 const char *id_str1 = NULL, *id_str2 = NULL;
3942 char *label1 = NULL, *label2 = NULL;
3943 int type1, type2;
3944 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
3945 const char *errstr;
3946 char *path = NULL;
3948 #ifndef PROFILE
3949 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3950 NULL) == -1)
3951 err(1, "pledge");
3952 #endif
3954 while ((ch = getopt(argc, argv, "C:r:sw")) != -1) {
3955 switch (ch) {
3956 case 'C':
3957 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3958 &errstr);
3959 if (errstr != NULL)
3960 err(1, "-C option %s", errstr);
3961 break;
3962 case 'r':
3963 repo_path = realpath(optarg, NULL);
3964 if (repo_path == NULL)
3965 return got_error_from_errno2("realpath",
3966 optarg);
3967 got_path_strip_trailing_slashes(repo_path);
3968 break;
3969 case 's':
3970 diff_staged = 1;
3971 break;
3972 case 'w':
3973 ignore_whitespace = 1;
3974 break;
3975 default:
3976 usage_diff();
3977 /* NOTREACHED */
3981 argc -= optind;
3982 argv += optind;
3984 cwd = getcwd(NULL, 0);
3985 if (cwd == NULL) {
3986 error = got_error_from_errno("getcwd");
3987 goto done;
3989 if (argc <= 1) {
3990 if (repo_path)
3991 errx(1,
3992 "-r option can't be used when diffing a work tree");
3993 error = got_worktree_open(&worktree, cwd);
3994 if (error) {
3995 if (error->code == GOT_ERR_NOT_WORKTREE)
3996 error = wrap_not_worktree_error(error, "diff",
3997 cwd);
3998 goto done;
4000 repo_path = strdup(got_worktree_get_repo_path(worktree));
4001 if (repo_path == NULL) {
4002 error = got_error_from_errno("strdup");
4003 goto done;
4005 if (argc == 1) {
4006 error = got_worktree_resolve_path(&path, worktree,
4007 argv[0]);
4008 if (error)
4009 goto done;
4010 } else {
4011 path = strdup("");
4012 if (path == NULL) {
4013 error = got_error_from_errno("strdup");
4014 goto done;
4017 } else if (argc == 2) {
4018 if (diff_staged)
4019 errx(1, "-s option can't be used when diffing "
4020 "objects in repository");
4021 id_str1 = argv[0];
4022 id_str2 = argv[1];
4023 if (repo_path == NULL) {
4024 error = got_worktree_open(&worktree, cwd);
4025 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4026 goto done;
4027 if (worktree) {
4028 repo_path = strdup(
4029 got_worktree_get_repo_path(worktree));
4030 if (repo_path == NULL) {
4031 error = got_error_from_errno("strdup");
4032 goto done;
4034 } else {
4035 repo_path = strdup(cwd);
4036 if (repo_path == NULL) {
4037 error = got_error_from_errno("strdup");
4038 goto done;
4042 } else
4043 usage_diff();
4045 error = got_repo_open(&repo, repo_path, NULL);
4046 free(repo_path);
4047 if (error != NULL)
4048 goto done;
4050 error = apply_unveil(got_repo_get_path(repo), 1,
4051 worktree ? got_worktree_get_root_path(worktree) : NULL);
4052 if (error)
4053 goto done;
4055 if (argc <= 1) {
4056 struct print_diff_arg arg;
4057 struct got_pathlist_head paths;
4058 char *id_str;
4060 TAILQ_INIT(&paths);
4062 error = got_object_id_str(&id_str,
4063 got_worktree_get_base_commit_id(worktree));
4064 if (error)
4065 goto done;
4066 arg.repo = repo;
4067 arg.worktree = worktree;
4068 arg.diff_context = diff_context;
4069 arg.id_str = id_str;
4070 arg.header_shown = 0;
4071 arg.diff_staged = diff_staged;
4072 arg.ignore_whitespace = ignore_whitespace;
4074 error = got_pathlist_append(&paths, path, NULL);
4075 if (error)
4076 goto done;
4078 error = got_worktree_status(worktree, &paths, repo, print_diff,
4079 &arg, check_cancelled, NULL);
4080 free(id_str);
4081 got_pathlist_free(&paths);
4082 goto done;
4085 error = got_repo_match_object_id(&id1, &label1, id_str1,
4086 GOT_OBJ_TYPE_ANY, 1, repo);
4087 if (error)
4088 goto done;
4090 error = got_repo_match_object_id(&id2, &label2, id_str2,
4091 GOT_OBJ_TYPE_ANY, 1, repo);
4092 if (error)
4093 goto done;
4095 error = got_object_get_type(&type1, repo, id1);
4096 if (error)
4097 goto done;
4099 error = got_object_get_type(&type2, repo, id2);
4100 if (error)
4101 goto done;
4103 if (type1 != type2) {
4104 error = got_error(GOT_ERR_OBJ_TYPE);
4105 goto done;
4108 switch (type1) {
4109 case GOT_OBJ_TYPE_BLOB:
4110 error = got_diff_objects_as_blobs(id1, id2, NULL, NULL,
4111 diff_context, ignore_whitespace, repo, stdout);
4112 break;
4113 case GOT_OBJ_TYPE_TREE:
4114 error = got_diff_objects_as_trees(id1, id2, "", "",
4115 diff_context, ignore_whitespace, repo, stdout);
4116 break;
4117 case GOT_OBJ_TYPE_COMMIT:
4118 printf("diff %s %s\n", label1, label2);
4119 error = got_diff_objects_as_commits(id1, id2, diff_context,
4120 ignore_whitespace, repo, stdout);
4121 break;
4122 default:
4123 error = got_error(GOT_ERR_OBJ_TYPE);
4125 done:
4126 free(label1);
4127 free(label2);
4128 free(id1);
4129 free(id2);
4130 free(path);
4131 if (worktree)
4132 got_worktree_close(worktree);
4133 if (repo) {
4134 const struct got_error *repo_error;
4135 repo_error = got_repo_close(repo);
4136 if (error == NULL)
4137 error = repo_error;
4139 return error;
4142 __dead static void
4143 usage_blame(void)
4145 fprintf(stderr,
4146 "usage: %s blame [-c commit] [-r repository-path] path\n",
4147 getprogname());
4148 exit(1);
4151 struct blame_line {
4152 int annotated;
4153 char *id_str;
4154 char *committer;
4155 char datebuf[11]; /* YYYY-MM-DD + NUL */
4158 struct blame_cb_args {
4159 struct blame_line *lines;
4160 int nlines;
4161 int nlines_prec;
4162 int lineno_cur;
4163 off_t *line_offsets;
4164 FILE *f;
4165 struct got_repository *repo;
4168 static const struct got_error *
4169 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4171 const struct got_error *err = NULL;
4172 struct blame_cb_args *a = arg;
4173 struct blame_line *bline;
4174 char *line = NULL;
4175 size_t linesize = 0;
4176 struct got_commit_object *commit = NULL;
4177 off_t offset;
4178 struct tm tm;
4179 time_t committer_time;
4181 if (nlines != a->nlines ||
4182 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4183 return got_error(GOT_ERR_RANGE);
4185 if (sigint_received)
4186 return got_error(GOT_ERR_ITER_COMPLETED);
4188 if (lineno == -1)
4189 return NULL; /* no change in this commit */
4191 /* Annotate this line. */
4192 bline = &a->lines[lineno - 1];
4193 if (bline->annotated)
4194 return NULL;
4195 err = got_object_id_str(&bline->id_str, id);
4196 if (err)
4197 return err;
4199 err = got_object_open_as_commit(&commit, a->repo, id);
4200 if (err)
4201 goto done;
4203 bline->committer = strdup(got_object_commit_get_committer(commit));
4204 if (bline->committer == NULL) {
4205 err = got_error_from_errno("strdup");
4206 goto done;
4209 committer_time = got_object_commit_get_committer_time(commit);
4210 if (localtime_r(&committer_time, &tm) == NULL)
4211 return got_error_from_errno("localtime_r");
4212 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4213 &tm) >= sizeof(bline->datebuf)) {
4214 err = got_error(GOT_ERR_NO_SPACE);
4215 goto done;
4217 bline->annotated = 1;
4219 /* Print lines annotated so far. */
4220 bline = &a->lines[a->lineno_cur - 1];
4221 if (!bline->annotated)
4222 goto done;
4224 offset = a->line_offsets[a->lineno_cur - 1];
4225 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4226 err = got_error_from_errno("fseeko");
4227 goto done;
4230 while (bline->annotated) {
4231 char *smallerthan, *at, *nl, *committer;
4232 size_t len;
4234 if (getline(&line, &linesize, a->f) == -1) {
4235 if (ferror(a->f))
4236 err = got_error_from_errno("getline");
4237 break;
4240 committer = bline->committer;
4241 smallerthan = strchr(committer, '<');
4242 if (smallerthan && smallerthan[1] != '\0')
4243 committer = smallerthan + 1;
4244 at = strchr(committer, '@');
4245 if (at)
4246 *at = '\0';
4247 len = strlen(committer);
4248 if (len >= 9)
4249 committer[8] = '\0';
4251 nl = strchr(line, '\n');
4252 if (nl)
4253 *nl = '\0';
4254 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4255 bline->id_str, bline->datebuf, committer, line);
4257 a->lineno_cur++;
4258 bline = &a->lines[a->lineno_cur - 1];
4260 done:
4261 if (commit)
4262 got_object_commit_close(commit);
4263 free(line);
4264 return err;
4267 static const struct got_error *
4268 cmd_blame(int argc, char *argv[])
4270 const struct got_error *error;
4271 struct got_repository *repo = NULL;
4272 struct got_worktree *worktree = NULL;
4273 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4274 char *link_target = NULL;
4275 struct got_object_id *obj_id = NULL;
4276 struct got_object_id *commit_id = NULL;
4277 struct got_blob_object *blob = NULL;
4278 char *commit_id_str = NULL;
4279 struct blame_cb_args bca;
4280 int ch, obj_type, i;
4281 size_t filesize;
4283 memset(&bca, 0, sizeof(bca));
4285 #ifndef PROFILE
4286 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4287 NULL) == -1)
4288 err(1, "pledge");
4289 #endif
4291 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4292 switch (ch) {
4293 case 'c':
4294 commit_id_str = optarg;
4295 break;
4296 case 'r':
4297 repo_path = realpath(optarg, NULL);
4298 if (repo_path == NULL)
4299 return got_error_from_errno2("realpath",
4300 optarg);
4301 got_path_strip_trailing_slashes(repo_path);
4302 break;
4303 default:
4304 usage_blame();
4305 /* NOTREACHED */
4309 argc -= optind;
4310 argv += optind;
4312 if (argc == 1)
4313 path = argv[0];
4314 else
4315 usage_blame();
4317 cwd = getcwd(NULL, 0);
4318 if (cwd == NULL) {
4319 error = got_error_from_errno("getcwd");
4320 goto done;
4322 if (repo_path == NULL) {
4323 error = got_worktree_open(&worktree, cwd);
4324 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4325 goto done;
4326 else
4327 error = NULL;
4328 if (worktree) {
4329 repo_path =
4330 strdup(got_worktree_get_repo_path(worktree));
4331 if (repo_path == NULL) {
4332 error = got_error_from_errno("strdup");
4333 if (error)
4334 goto done;
4336 } else {
4337 repo_path = strdup(cwd);
4338 if (repo_path == NULL) {
4339 error = got_error_from_errno("strdup");
4340 goto done;
4345 error = got_repo_open(&repo, repo_path, NULL);
4346 if (error != NULL)
4347 goto done;
4349 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4350 if (error)
4351 goto done;
4353 if (worktree) {
4354 const char *prefix = got_worktree_get_path_prefix(worktree);
4355 char *p, *worktree_subdir = cwd +
4356 strlen(got_worktree_get_root_path(worktree));
4357 if (asprintf(&p, "%s%s%s%s%s",
4358 prefix, (strcmp(prefix, "/") != 0) ? "/" : "",
4359 worktree_subdir, worktree_subdir[0] ? "/" : "",
4360 path) == -1) {
4361 error = got_error_from_errno("asprintf");
4362 goto done;
4364 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4365 free(p);
4366 } else {
4367 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4369 if (error)
4370 goto done;
4372 if (commit_id_str == NULL) {
4373 struct got_reference *head_ref;
4374 error = got_ref_open(&head_ref, repo, worktree ?
4375 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4376 if (error != NULL)
4377 goto done;
4378 error = got_ref_resolve(&commit_id, repo, head_ref);
4379 got_ref_close(head_ref);
4380 if (error != NULL)
4381 goto done;
4382 } else {
4383 error = got_repo_match_object_id(&commit_id, NULL,
4384 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4385 if (error)
4386 goto done;
4389 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4390 commit_id, repo);
4391 if (error)
4392 goto done;
4394 error = got_object_id_by_path(&obj_id, repo, commit_id,
4395 link_target ? link_target : in_repo_path);
4396 if (error)
4397 goto done;
4399 error = got_object_get_type(&obj_type, repo, obj_id);
4400 if (error)
4401 goto done;
4403 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4404 error = got_error_path(link_target ? link_target : in_repo_path,
4405 GOT_ERR_OBJ_TYPE);
4406 goto done;
4409 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4410 if (error)
4411 goto done;
4412 bca.f = got_opentemp();
4413 if (bca.f == NULL) {
4414 error = got_error_from_errno("got_opentemp");
4415 goto done;
4417 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4418 &bca.line_offsets, bca.f, blob);
4419 if (error || bca.nlines == 0)
4420 goto done;
4422 /* Don't include \n at EOF in the blame line count. */
4423 if (bca.line_offsets[bca.nlines - 1] == filesize)
4424 bca.nlines--;
4426 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4427 if (bca.lines == NULL) {
4428 error = got_error_from_errno("calloc");
4429 goto done;
4431 bca.lineno_cur = 1;
4432 bca.nlines_prec = 0;
4433 i = bca.nlines;
4434 while (i > 0) {
4435 i /= 10;
4436 bca.nlines_prec++;
4438 bca.repo = repo;
4440 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4441 repo, blame_cb, &bca, check_cancelled, NULL);
4442 done:
4443 free(in_repo_path);
4444 free(link_target);
4445 free(repo_path);
4446 free(cwd);
4447 free(commit_id);
4448 free(obj_id);
4449 if (blob)
4450 got_object_blob_close(blob);
4451 if (worktree)
4452 got_worktree_close(worktree);
4453 if (repo) {
4454 const struct got_error *repo_error;
4455 repo_error = got_repo_close(repo);
4456 if (error == NULL)
4457 error = repo_error;
4459 if (bca.lines) {
4460 for (i = 0; i < bca.nlines; i++) {
4461 struct blame_line *bline = &bca.lines[i];
4462 free(bline->id_str);
4463 free(bline->committer);
4465 free(bca.lines);
4467 free(bca.line_offsets);
4468 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4469 error = got_error_from_errno("fclose");
4470 return error;
4473 __dead static void
4474 usage_tree(void)
4476 fprintf(stderr,
4477 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4478 getprogname());
4479 exit(1);
4482 static const struct got_error *
4483 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4484 const char *root_path, struct got_repository *repo)
4486 const struct got_error *err = NULL;
4487 int is_root_path = (strcmp(path, root_path) == 0);
4488 const char *modestr = "";
4489 mode_t mode = got_tree_entry_get_mode(te);
4490 char *link_target = NULL;
4492 path += strlen(root_path);
4493 while (path[0] == '/')
4494 path++;
4496 if (got_object_tree_entry_is_submodule(te))
4497 modestr = "$";
4498 else if (S_ISLNK(mode)) {
4499 int i;
4501 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4502 if (err)
4503 return err;
4504 for (i = 0; i < strlen(link_target); i++) {
4505 if (!isprint((unsigned char)link_target[i]))
4506 link_target[i] = '?';
4509 modestr = "@";
4511 else if (S_ISDIR(mode))
4512 modestr = "/";
4513 else if (mode & S_IXUSR)
4514 modestr = "*";
4516 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4517 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4518 link_target ? " -> ": "", link_target ? link_target : "");
4520 free(link_target);
4521 return NULL;
4524 static const struct got_error *
4525 print_tree(const char *path, struct got_object_id *commit_id,
4526 int show_ids, int recurse, const char *root_path,
4527 struct got_repository *repo)
4529 const struct got_error *err = NULL;
4530 struct got_object_id *tree_id = NULL;
4531 struct got_tree_object *tree = NULL;
4532 int nentries, i;
4534 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
4535 if (err)
4536 goto done;
4538 err = got_object_open_as_tree(&tree, repo, tree_id);
4539 if (err)
4540 goto done;
4541 nentries = got_object_tree_get_nentries(tree);
4542 for (i = 0; i < nentries; i++) {
4543 struct got_tree_entry *te;
4544 char *id = NULL;
4546 if (sigint_received || sigpipe_received)
4547 break;
4549 te = got_object_tree_get_entry(tree, i);
4550 if (show_ids) {
4551 char *id_str;
4552 err = got_object_id_str(&id_str,
4553 got_tree_entry_get_id(te));
4554 if (err)
4555 goto done;
4556 if (asprintf(&id, "%s ", id_str) == -1) {
4557 err = got_error_from_errno("asprintf");
4558 free(id_str);
4559 goto done;
4561 free(id_str);
4563 err = print_entry(te, id, path, root_path, repo);
4564 free(id);
4565 if (err)
4566 goto done;
4568 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
4569 char *child_path;
4570 if (asprintf(&child_path, "%s%s%s", path,
4571 path[0] == '/' && path[1] == '\0' ? "" : "/",
4572 got_tree_entry_get_name(te)) == -1) {
4573 err = got_error_from_errno("asprintf");
4574 goto done;
4576 err = print_tree(child_path, commit_id, show_ids, 1,
4577 root_path, repo);
4578 free(child_path);
4579 if (err)
4580 goto done;
4583 done:
4584 if (tree)
4585 got_object_tree_close(tree);
4586 free(tree_id);
4587 return err;
4590 static const struct got_error *
4591 cmd_tree(int argc, char *argv[])
4593 const struct got_error *error;
4594 struct got_repository *repo = NULL;
4595 struct got_worktree *worktree = NULL;
4596 const char *path, *refname = NULL;
4597 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4598 struct got_object_id *commit_id = NULL;
4599 char *commit_id_str = NULL;
4600 int show_ids = 0, recurse = 0;
4601 int ch;
4603 #ifndef PROFILE
4604 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4605 NULL) == -1)
4606 err(1, "pledge");
4607 #endif
4609 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
4610 switch (ch) {
4611 case 'c':
4612 commit_id_str = optarg;
4613 break;
4614 case 'r':
4615 repo_path = realpath(optarg, NULL);
4616 if (repo_path == NULL)
4617 return got_error_from_errno2("realpath",
4618 optarg);
4619 got_path_strip_trailing_slashes(repo_path);
4620 break;
4621 case 'i':
4622 show_ids = 1;
4623 break;
4624 case 'R':
4625 recurse = 1;
4626 break;
4627 default:
4628 usage_tree();
4629 /* NOTREACHED */
4633 argc -= optind;
4634 argv += optind;
4636 if (argc == 1)
4637 path = argv[0];
4638 else if (argc > 1)
4639 usage_tree();
4640 else
4641 path = NULL;
4643 cwd = getcwd(NULL, 0);
4644 if (cwd == NULL) {
4645 error = got_error_from_errno("getcwd");
4646 goto done;
4648 if (repo_path == NULL) {
4649 error = got_worktree_open(&worktree, cwd);
4650 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4651 goto done;
4652 else
4653 error = NULL;
4654 if (worktree) {
4655 repo_path =
4656 strdup(got_worktree_get_repo_path(worktree));
4657 if (repo_path == NULL)
4658 error = got_error_from_errno("strdup");
4659 if (error)
4660 goto done;
4661 } else {
4662 repo_path = strdup(cwd);
4663 if (repo_path == NULL) {
4664 error = got_error_from_errno("strdup");
4665 goto done;
4670 error = got_repo_open(&repo, repo_path, NULL);
4671 if (error != NULL)
4672 goto done;
4674 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4675 if (error)
4676 goto done;
4678 if (path == NULL) {
4679 if (worktree) {
4680 char *p, *worktree_subdir = cwd +
4681 strlen(got_worktree_get_root_path(worktree));
4682 if (asprintf(&p, "%s/%s",
4683 got_worktree_get_path_prefix(worktree),
4684 worktree_subdir) == -1) {
4685 error = got_error_from_errno("asprintf");
4686 goto done;
4688 error = got_repo_map_path(&in_repo_path, repo, p, 0);
4689 free(p);
4690 if (error)
4691 goto done;
4692 } else
4693 path = "/";
4695 if (in_repo_path == NULL) {
4696 error = got_repo_map_path(&in_repo_path, repo, path, 1);
4697 if (error != NULL)
4698 goto done;
4701 if (commit_id_str == NULL) {
4702 struct got_reference *head_ref;
4703 if (worktree)
4704 refname = got_worktree_get_head_ref_name(worktree);
4705 else
4706 refname = GOT_REF_HEAD;
4707 error = got_ref_open(&head_ref, repo, refname, 0);
4708 if (error != NULL)
4709 goto done;
4710 error = got_ref_resolve(&commit_id, repo, head_ref);
4711 got_ref_close(head_ref);
4712 if (error != NULL)
4713 goto done;
4714 } else {
4715 error = got_repo_match_object_id(&commit_id, NULL,
4716 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
4717 if (error)
4718 goto done;
4721 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
4722 in_repo_path, repo);
4723 done:
4724 free(in_repo_path);
4725 free(repo_path);
4726 free(cwd);
4727 free(commit_id);
4728 if (worktree)
4729 got_worktree_close(worktree);
4730 if (repo) {
4731 const struct got_error *repo_error;
4732 repo_error = got_repo_close(repo);
4733 if (error == NULL)
4734 error = repo_error;
4736 return error;
4739 __dead static void
4740 usage_status(void)
4742 fprintf(stderr, "usage: %s status [-s status-codes ] [path ...]\n",
4743 getprogname());
4744 exit(1);
4747 static const struct got_error *
4748 print_status(void *arg, unsigned char status, unsigned char staged_status,
4749 const char *path, struct got_object_id *blob_id,
4750 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4751 int dirfd, const char *de_name)
4753 if (status == staged_status && (status == GOT_STATUS_DELETE))
4754 status = GOT_STATUS_NO_CHANGE;
4755 if (arg) {
4756 char *status_codes = arg;
4757 size_t ncodes = strlen(status_codes);
4758 int i;
4759 for (i = 0; i < ncodes ; i++) {
4760 if (status == status_codes[i] ||
4761 staged_status == status_codes[i])
4762 break;
4764 if (i == ncodes)
4765 return NULL;
4767 printf("%c%c %s\n", status, staged_status, path);
4768 return NULL;
4771 static const struct got_error *
4772 cmd_status(int argc, char *argv[])
4774 const struct got_error *error = NULL;
4775 struct got_repository *repo = NULL;
4776 struct got_worktree *worktree = NULL;
4777 char *cwd = NULL, *status_codes = NULL;;
4778 struct got_pathlist_head paths;
4779 struct got_pathlist_entry *pe;
4780 int ch, i;
4782 TAILQ_INIT(&paths);
4784 while ((ch = getopt(argc, argv, "s:")) != -1) {
4785 switch (ch) {
4786 case 's':
4787 for (i = 0; i < strlen(optarg); i++) {
4788 switch (optarg[i]) {
4789 case GOT_STATUS_MODIFY:
4790 case GOT_STATUS_ADD:
4791 case GOT_STATUS_DELETE:
4792 case GOT_STATUS_CONFLICT:
4793 case GOT_STATUS_MISSING:
4794 case GOT_STATUS_OBSTRUCTED:
4795 case GOT_STATUS_UNVERSIONED:
4796 case GOT_STATUS_MODE_CHANGE:
4797 case GOT_STATUS_NONEXISTENT:
4798 break;
4799 default:
4800 errx(1, "invalid status code '%c'",
4801 optarg[i]);
4804 status_codes = optarg;
4805 break;
4806 default:
4807 usage_status();
4808 /* NOTREACHED */
4812 argc -= optind;
4813 argv += optind;
4815 #ifndef PROFILE
4816 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4817 NULL) == -1)
4818 err(1, "pledge");
4819 #endif
4820 cwd = getcwd(NULL, 0);
4821 if (cwd == NULL) {
4822 error = got_error_from_errno("getcwd");
4823 goto done;
4826 error = got_worktree_open(&worktree, cwd);
4827 if (error) {
4828 if (error->code == GOT_ERR_NOT_WORKTREE)
4829 error = wrap_not_worktree_error(error, "status", cwd);
4830 goto done;
4833 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
4834 NULL);
4835 if (error != NULL)
4836 goto done;
4838 error = apply_unveil(got_repo_get_path(repo), 1,
4839 got_worktree_get_root_path(worktree));
4840 if (error)
4841 goto done;
4843 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
4844 if (error)
4845 goto done;
4847 error = got_worktree_status(worktree, &paths, repo, print_status,
4848 status_codes, check_cancelled, NULL);
4849 done:
4850 TAILQ_FOREACH(pe, &paths, entry)
4851 free((char *)pe->path);
4852 got_pathlist_free(&paths);
4853 free(cwd);
4854 return error;
4857 __dead static void
4858 usage_ref(void)
4860 fprintf(stderr,
4861 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
4862 "[-d] [name]\n",
4863 getprogname());
4864 exit(1);
4867 static const struct got_error *
4868 list_refs(struct got_repository *repo, const char *refname)
4870 static const struct got_error *err = NULL;
4871 struct got_reflist_head refs;
4872 struct got_reflist_entry *re;
4874 SIMPLEQ_INIT(&refs);
4875 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
4876 if (err)
4877 return err;
4879 SIMPLEQ_FOREACH(re, &refs, entry) {
4880 char *refstr;
4881 refstr = got_ref_to_str(re->ref);
4882 if (refstr == NULL)
4883 return got_error_from_errno("got_ref_to_str");
4884 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
4885 free(refstr);
4888 got_ref_list_free(&refs);
4889 return NULL;
4892 static const struct got_error *
4893 delete_ref(struct got_repository *repo, const char *refname)
4895 const struct got_error *err = NULL;
4896 struct got_reference *ref;
4898 err = got_ref_open(&ref, repo, refname, 0);
4899 if (err)
4900 return err;
4902 err = got_ref_delete(ref, repo);
4903 got_ref_close(ref);
4904 return err;
4907 static const struct got_error *
4908 add_ref(struct got_repository *repo, const char *refname, const char *target)
4910 const struct got_error *err = NULL;
4911 struct got_object_id *id;
4912 struct got_reference *ref = NULL;
4915 * Don't let the user create a reference name with a leading '-'.
4916 * While technically a valid reference name, this case is usually
4917 * an unintended typo.
4919 if (refname[0] == '-')
4920 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4922 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
4923 repo);
4924 if (err) {
4925 struct got_reference *target_ref;
4927 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
4928 return err;
4929 err = got_ref_open(&target_ref, repo, target, 0);
4930 if (err)
4931 return err;
4932 err = got_ref_resolve(&id, repo, target_ref);
4933 got_ref_close(target_ref);
4934 if (err)
4935 return err;
4938 err = got_ref_alloc(&ref, refname, id);
4939 if (err)
4940 goto done;
4942 err = got_ref_write(ref, repo);
4943 done:
4944 if (ref)
4945 got_ref_close(ref);
4946 free(id);
4947 return err;
4950 static const struct got_error *
4951 add_symref(struct got_repository *repo, const char *refname, const char *target)
4953 const struct got_error *err = NULL;
4954 struct got_reference *ref = NULL;
4955 struct got_reference *target_ref = NULL;
4958 * Don't let the user create a reference name with a leading '-'.
4959 * While technically a valid reference name, this case is usually
4960 * an unintended typo.
4962 if (refname[0] == '-')
4963 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
4965 err = got_ref_open(&target_ref, repo, target, 0);
4966 if (err)
4967 return err;
4969 err = got_ref_alloc_symref(&ref, refname, target_ref);
4970 if (err)
4971 goto done;
4973 err = got_ref_write(ref, repo);
4974 done:
4975 if (target_ref)
4976 got_ref_close(target_ref);
4977 if (ref)
4978 got_ref_close(ref);
4979 return err;
4982 static const struct got_error *
4983 cmd_ref(int argc, char *argv[])
4985 const struct got_error *error = NULL;
4986 struct got_repository *repo = NULL;
4987 struct got_worktree *worktree = NULL;
4988 char *cwd = NULL, *repo_path = NULL;
4989 int ch, do_list = 0, do_delete = 0;
4990 const char *obj_arg = NULL, *symref_target= NULL;
4991 char *refname = NULL;
4993 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
4994 switch (ch) {
4995 case 'c':
4996 obj_arg = optarg;
4997 break;
4998 case 'd':
4999 do_delete = 1;
5000 break;
5001 case 'r':
5002 repo_path = realpath(optarg, NULL);
5003 if (repo_path == NULL)
5004 return got_error_from_errno2("realpath",
5005 optarg);
5006 got_path_strip_trailing_slashes(repo_path);
5007 break;
5008 case 'l':
5009 do_list = 1;
5010 break;
5011 case 's':
5012 symref_target = optarg;
5013 break;
5014 default:
5015 usage_ref();
5016 /* NOTREACHED */
5020 if (obj_arg && do_list)
5021 errx(1, "-c and -l options are mutually exclusive");
5022 if (obj_arg && do_delete)
5023 errx(1, "-c and -d options are mutually exclusive");
5024 if (obj_arg && symref_target)
5025 errx(1, "-c and -s options are mutually exclusive");
5026 if (symref_target && do_delete)
5027 errx(1, "-s and -d options are mutually exclusive");
5028 if (symref_target && do_list)
5029 errx(1, "-s and -l options are mutually exclusive");
5030 if (do_delete && do_list)
5031 errx(1, "-d and -l options are mutually exclusive");
5033 argc -= optind;
5034 argv += optind;
5036 if (do_list) {
5037 if (argc != 0 && argc != 1)
5038 usage_ref();
5039 if (argc == 1) {
5040 refname = strdup(argv[0]);
5041 if (refname == NULL) {
5042 error = got_error_from_errno("strdup");
5043 goto done;
5046 } else {
5047 if (argc != 1)
5048 usage_ref();
5049 refname = strdup(argv[0]);
5050 if (refname == NULL) {
5051 error = got_error_from_errno("strdup");
5052 goto done;
5056 if (refname)
5057 got_path_strip_trailing_slashes(refname);
5059 #ifndef PROFILE
5060 if (do_list) {
5061 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5062 NULL) == -1)
5063 err(1, "pledge");
5064 } else {
5065 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5066 "sendfd unveil", NULL) == -1)
5067 err(1, "pledge");
5069 #endif
5070 cwd = getcwd(NULL, 0);
5071 if (cwd == NULL) {
5072 error = got_error_from_errno("getcwd");
5073 goto done;
5076 if (repo_path == NULL) {
5077 error = got_worktree_open(&worktree, cwd);
5078 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5079 goto done;
5080 else
5081 error = NULL;
5082 if (worktree) {
5083 repo_path =
5084 strdup(got_worktree_get_repo_path(worktree));
5085 if (repo_path == NULL)
5086 error = got_error_from_errno("strdup");
5087 if (error)
5088 goto done;
5089 } else {
5090 repo_path = strdup(cwd);
5091 if (repo_path == NULL) {
5092 error = got_error_from_errno("strdup");
5093 goto done;
5098 error = got_repo_open(&repo, repo_path, NULL);
5099 if (error != NULL)
5100 goto done;
5102 error = apply_unveil(got_repo_get_path(repo), do_list,
5103 worktree ? got_worktree_get_root_path(worktree) : NULL);
5104 if (error)
5105 goto done;
5107 if (do_list)
5108 error = list_refs(repo, refname);
5109 else if (do_delete)
5110 error = delete_ref(repo, refname);
5111 else if (symref_target)
5112 error = add_symref(repo, refname, symref_target);
5113 else {
5114 if (obj_arg == NULL)
5115 usage_ref();
5116 error = add_ref(repo, refname, obj_arg);
5118 done:
5119 free(refname);
5120 if (repo)
5121 got_repo_close(repo);
5122 if (worktree)
5123 got_worktree_close(worktree);
5124 free(cwd);
5125 free(repo_path);
5126 return error;
5129 __dead static void
5130 usage_branch(void)
5132 fprintf(stderr,
5133 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5134 "[name]\n", getprogname());
5135 exit(1);
5138 static const struct got_error *
5139 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5140 struct got_reference *ref)
5142 const struct got_error *err = NULL;
5143 const char *refname, *marker = " ";
5144 char *refstr;
5146 refname = got_ref_get_name(ref);
5147 if (worktree && strcmp(refname,
5148 got_worktree_get_head_ref_name(worktree)) == 0) {
5149 struct got_object_id *id = NULL;
5151 err = got_ref_resolve(&id, repo, ref);
5152 if (err)
5153 return err;
5154 if (got_object_id_cmp(id,
5155 got_worktree_get_base_commit_id(worktree)) == 0)
5156 marker = "* ";
5157 else
5158 marker = "~ ";
5159 free(id);
5162 if (strncmp(refname, "refs/heads/", 11) == 0)
5163 refname += 11;
5164 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5165 refname += 18;
5167 refstr = got_ref_to_str(ref);
5168 if (refstr == NULL)
5169 return got_error_from_errno("got_ref_to_str");
5171 printf("%s%s: %s\n", marker, refname, refstr);
5172 free(refstr);
5173 return NULL;
5176 static const struct got_error *
5177 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5179 const char *refname;
5181 if (worktree == NULL)
5182 return got_error(GOT_ERR_NOT_WORKTREE);
5184 refname = got_worktree_get_head_ref_name(worktree);
5186 if (strncmp(refname, "refs/heads/", 11) == 0)
5187 refname += 11;
5188 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5189 refname += 18;
5191 printf("%s\n", refname);
5193 return NULL;
5196 static const struct got_error *
5197 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5199 static const struct got_error *err = NULL;
5200 struct got_reflist_head refs;
5201 struct got_reflist_entry *re;
5202 struct got_reference *temp_ref = NULL;
5203 int rebase_in_progress, histedit_in_progress;
5205 SIMPLEQ_INIT(&refs);
5207 if (worktree) {
5208 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5209 worktree);
5210 if (err)
5211 return err;
5213 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5214 worktree);
5215 if (err)
5216 return err;
5218 if (rebase_in_progress || histedit_in_progress) {
5219 err = got_ref_open(&temp_ref, repo,
5220 got_worktree_get_head_ref_name(worktree), 0);
5221 if (err)
5222 return err;
5223 list_branch(repo, worktree, temp_ref);
5224 got_ref_close(temp_ref);
5228 err = got_ref_list(&refs, repo, "refs/heads",
5229 got_ref_cmp_by_name, NULL);
5230 if (err)
5231 return err;
5233 SIMPLEQ_FOREACH(re, &refs, entry)
5234 list_branch(repo, worktree, re->ref);
5236 got_ref_list_free(&refs);
5237 return NULL;
5240 static const struct got_error *
5241 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5242 const char *branch_name)
5244 const struct got_error *err = NULL;
5245 struct got_reference *ref = NULL;
5246 char *refname;
5248 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5249 return got_error_from_errno("asprintf");
5251 err = got_ref_open(&ref, repo, refname, 0);
5252 if (err)
5253 goto done;
5255 if (worktree &&
5256 strcmp(got_worktree_get_head_ref_name(worktree),
5257 got_ref_get_name(ref)) == 0) {
5258 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5259 "will not delete this work tree's current branch");
5260 goto done;
5263 err = got_ref_delete(ref, repo);
5264 done:
5265 if (ref)
5266 got_ref_close(ref);
5267 free(refname);
5268 return err;
5271 static const struct got_error *
5272 add_branch(struct got_repository *repo, const char *branch_name,
5273 struct got_object_id *base_commit_id)
5275 const struct got_error *err = NULL;
5276 struct got_reference *ref = NULL;
5277 char *base_refname = NULL, *refname = NULL;
5280 * Don't let the user create a branch name with a leading '-'.
5281 * While technically a valid reference name, this case is usually
5282 * an unintended typo.
5284 if (branch_name[0] == '-')
5285 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5287 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5288 err = got_error_from_errno("asprintf");
5289 goto done;
5292 err = got_ref_open(&ref, repo, refname, 0);
5293 if (err == NULL) {
5294 err = got_error(GOT_ERR_BRANCH_EXISTS);
5295 goto done;
5296 } else if (err->code != GOT_ERR_NOT_REF)
5297 goto done;
5299 err = got_ref_alloc(&ref, refname, base_commit_id);
5300 if (err)
5301 goto done;
5303 err = got_ref_write(ref, repo);
5304 done:
5305 if (ref)
5306 got_ref_close(ref);
5307 free(base_refname);
5308 free(refname);
5309 return err;
5312 static const struct got_error *
5313 cmd_branch(int argc, char *argv[])
5315 const struct got_error *error = NULL;
5316 struct got_repository *repo = NULL;
5317 struct got_worktree *worktree = NULL;
5318 char *cwd = NULL, *repo_path = NULL;
5319 int ch, do_list = 0, do_show = 0, do_update = 1;
5320 const char *delref = NULL, *commit_id_arg = NULL;
5321 struct got_reference *ref = NULL;
5322 struct got_pathlist_head paths;
5323 struct got_pathlist_entry *pe;
5324 struct got_object_id *commit_id = NULL;
5325 char *commit_id_str = NULL;
5327 TAILQ_INIT(&paths);
5329 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5330 switch (ch) {
5331 case 'c':
5332 commit_id_arg = optarg;
5333 break;
5334 case 'd':
5335 delref = optarg;
5336 break;
5337 case 'r':
5338 repo_path = realpath(optarg, NULL);
5339 if (repo_path == NULL)
5340 return got_error_from_errno2("realpath",
5341 optarg);
5342 got_path_strip_trailing_slashes(repo_path);
5343 break;
5344 case 'l':
5345 do_list = 1;
5346 break;
5347 case 'n':
5348 do_update = 0;
5349 break;
5350 default:
5351 usage_branch();
5352 /* NOTREACHED */
5356 if (do_list && delref)
5357 errx(1, "-l and -d options are mutually exclusive");
5359 argc -= optind;
5360 argv += optind;
5362 if (!do_list && !delref && argc == 0)
5363 do_show = 1;
5365 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5366 errx(1, "-c option can only be used when creating a branch");
5368 if (do_list || delref) {
5369 if (argc > 0)
5370 usage_branch();
5371 } else if (!do_show && argc != 1)
5372 usage_branch();
5374 #ifndef PROFILE
5375 if (do_list || do_show) {
5376 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5377 NULL) == -1)
5378 err(1, "pledge");
5379 } else {
5380 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5381 "sendfd unveil", NULL) == -1)
5382 err(1, "pledge");
5384 #endif
5385 cwd = getcwd(NULL, 0);
5386 if (cwd == NULL) {
5387 error = got_error_from_errno("getcwd");
5388 goto done;
5391 if (repo_path == NULL) {
5392 error = got_worktree_open(&worktree, cwd);
5393 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5394 goto done;
5395 else
5396 error = NULL;
5397 if (worktree) {
5398 repo_path =
5399 strdup(got_worktree_get_repo_path(worktree));
5400 if (repo_path == NULL)
5401 error = got_error_from_errno("strdup");
5402 if (error)
5403 goto done;
5404 } else {
5405 repo_path = strdup(cwd);
5406 if (repo_path == NULL) {
5407 error = got_error_from_errno("strdup");
5408 goto done;
5413 error = got_repo_open(&repo, repo_path, NULL);
5414 if (error != NULL)
5415 goto done;
5417 error = apply_unveil(got_repo_get_path(repo), do_list,
5418 worktree ? got_worktree_get_root_path(worktree) : NULL);
5419 if (error)
5420 goto done;
5422 if (do_show)
5423 error = show_current_branch(repo, worktree);
5424 else if (do_list)
5425 error = list_branches(repo, worktree);
5426 else if (delref)
5427 error = delete_branch(repo, worktree, delref);
5428 else {
5429 if (commit_id_arg == NULL)
5430 commit_id_arg = worktree ?
5431 got_worktree_get_head_ref_name(worktree) :
5432 GOT_REF_HEAD;
5433 error = got_repo_match_object_id(&commit_id, NULL,
5434 commit_id_arg, GOT_OBJ_TYPE_COMMIT, 1, repo);
5435 if (error)
5436 goto done;
5437 error = add_branch(repo, argv[0], commit_id);
5438 if (error)
5439 goto done;
5440 if (worktree && do_update) {
5441 struct got_update_progress_arg upa;
5442 char *branch_refname = NULL;
5444 error = got_object_id_str(&commit_id_str, commit_id);
5445 if (error)
5446 goto done;
5447 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5448 worktree);
5449 if (error)
5450 goto done;
5451 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5452 == -1) {
5453 error = got_error_from_errno("asprintf");
5454 goto done;
5456 error = got_ref_open(&ref, repo, branch_refname, 0);
5457 free(branch_refname);
5458 if (error)
5459 goto done;
5460 error = switch_head_ref(ref, commit_id, worktree,
5461 repo);
5462 if (error)
5463 goto done;
5464 error = got_worktree_set_base_commit_id(worktree, repo,
5465 commit_id);
5466 if (error)
5467 goto done;
5468 memset(&upa, 0, sizeof(upa));
5469 error = got_worktree_checkout_files(worktree, &paths,
5470 repo, update_progress, &upa, check_cancelled,
5471 NULL);
5472 if (error)
5473 goto done;
5474 if (upa.did_something)
5475 printf("Updated to commit %s\n", commit_id_str);
5476 print_update_progress_stats(&upa);
5479 done:
5480 if (ref)
5481 got_ref_close(ref);
5482 if (repo)
5483 got_repo_close(repo);
5484 if (worktree)
5485 got_worktree_close(worktree);
5486 free(cwd);
5487 free(repo_path);
5488 free(commit_id);
5489 free(commit_id_str);
5490 TAILQ_FOREACH(pe, &paths, entry)
5491 free((char *)pe->path);
5492 got_pathlist_free(&paths);
5493 return error;
5497 __dead static void
5498 usage_tag(void)
5500 fprintf(stderr,
5501 "usage: %s tag [-c commit] [-r repository] [-l] "
5502 "[-m message] name\n", getprogname());
5503 exit(1);
5506 #if 0
5507 static const struct got_error *
5508 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5510 const struct got_error *err = NULL;
5511 struct got_reflist_entry *re, *se, *new;
5512 struct got_object_id *re_id, *se_id;
5513 struct got_tag_object *re_tag, *se_tag;
5514 time_t re_time, se_time;
5516 SIMPLEQ_FOREACH(re, tags, entry) {
5517 se = SIMPLEQ_FIRST(sorted);
5518 if (se == NULL) {
5519 err = got_reflist_entry_dup(&new, re);
5520 if (err)
5521 return err;
5522 SIMPLEQ_INSERT_HEAD(sorted, new, entry);
5523 continue;
5524 } else {
5525 err = got_ref_resolve(&re_id, repo, re->ref);
5526 if (err)
5527 break;
5528 err = got_object_open_as_tag(&re_tag, repo, re_id);
5529 free(re_id);
5530 if (err)
5531 break;
5532 re_time = got_object_tag_get_tagger_time(re_tag);
5533 got_object_tag_close(re_tag);
5536 while (se) {
5537 err = got_ref_resolve(&se_id, repo, re->ref);
5538 if (err)
5539 break;
5540 err = got_object_open_as_tag(&se_tag, repo, se_id);
5541 free(se_id);
5542 if (err)
5543 break;
5544 se_time = got_object_tag_get_tagger_time(se_tag);
5545 got_object_tag_close(se_tag);
5547 if (se_time > re_time) {
5548 err = got_reflist_entry_dup(&new, re);
5549 if (err)
5550 return err;
5551 SIMPLEQ_INSERT_AFTER(sorted, se, new, entry);
5552 break;
5554 se = SIMPLEQ_NEXT(se, entry);
5555 continue;
5558 done:
5559 return err;
5561 #endif
5563 static const struct got_error *
5564 list_tags(struct got_repository *repo, struct got_worktree *worktree)
5566 static const struct got_error *err = NULL;
5567 struct got_reflist_head refs;
5568 struct got_reflist_entry *re;
5570 SIMPLEQ_INIT(&refs);
5572 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5573 if (err)
5574 return err;
5576 SIMPLEQ_FOREACH(re, &refs, entry) {
5577 const char *refname;
5578 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5579 char datebuf[26];
5580 const char *tagger;
5581 time_t tagger_time;
5582 struct got_object_id *id;
5583 struct got_tag_object *tag;
5584 struct got_commit_object *commit = NULL;
5586 refname = got_ref_get_name(re->ref);
5587 if (strncmp(refname, "refs/tags/", 10) != 0)
5588 continue;
5589 refname += 10;
5590 refstr = got_ref_to_str(re->ref);
5591 if (refstr == NULL) {
5592 err = got_error_from_errno("got_ref_to_str");
5593 break;
5595 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5596 free(refstr);
5598 err = got_ref_resolve(&id, repo, re->ref);
5599 if (err)
5600 break;
5601 err = got_object_open_as_tag(&tag, repo, id);
5602 if (err) {
5603 if (err->code != GOT_ERR_OBJ_TYPE) {
5604 free(id);
5605 break;
5607 /* "lightweight" tag */
5608 err = got_object_open_as_commit(&commit, repo, id);
5609 if (err) {
5610 free(id);
5611 break;
5613 tagger = got_object_commit_get_committer(commit);
5614 tagger_time =
5615 got_object_commit_get_committer_time(commit);
5616 err = got_object_id_str(&id_str, id);
5617 free(id);
5618 if (err)
5619 break;
5620 } else {
5621 free(id);
5622 tagger = got_object_tag_get_tagger(tag);
5623 tagger_time = got_object_tag_get_tagger_time(tag);
5624 err = got_object_id_str(&id_str,
5625 got_object_tag_get_object_id(tag));
5626 if (err)
5627 break;
5629 printf("from: %s\n", tagger);
5630 datestr = get_datestr(&tagger_time, datebuf);
5631 if (datestr)
5632 printf("date: %s UTC\n", datestr);
5633 if (commit)
5634 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5635 else {
5636 switch (got_object_tag_get_object_type(tag)) {
5637 case GOT_OBJ_TYPE_BLOB:
5638 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5639 id_str);
5640 break;
5641 case GOT_OBJ_TYPE_TREE:
5642 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5643 id_str);
5644 break;
5645 case GOT_OBJ_TYPE_COMMIT:
5646 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5647 id_str);
5648 break;
5649 case GOT_OBJ_TYPE_TAG:
5650 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5651 id_str);
5652 break;
5653 default:
5654 break;
5657 free(id_str);
5658 if (commit) {
5659 err = got_object_commit_get_logmsg(&tagmsg0, commit);
5660 if (err)
5661 break;
5662 got_object_commit_close(commit);
5663 } else {
5664 tagmsg0 = strdup(got_object_tag_get_message(tag));
5665 got_object_tag_close(tag);
5666 if (tagmsg0 == NULL) {
5667 err = got_error_from_errno("strdup");
5668 break;
5672 tagmsg = tagmsg0;
5673 do {
5674 line = strsep(&tagmsg, "\n");
5675 if (line)
5676 printf(" %s\n", line);
5677 } while (line);
5678 free(tagmsg0);
5681 got_ref_list_free(&refs);
5682 return NULL;
5685 static const struct got_error *
5686 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
5687 const char *tag_name, const char *repo_path)
5689 const struct got_error *err = NULL;
5690 char *template = NULL, *initial_content = NULL;
5691 char *editor = NULL;
5692 int initial_content_len;
5693 int fd = -1;
5695 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
5696 err = got_error_from_errno("asprintf");
5697 goto done;
5700 initial_content_len = asprintf(&initial_content,
5701 "\n# tagging commit %s as %s\n",
5702 commit_id_str, tag_name);
5703 if (initial_content_len == -1) {
5704 err = got_error_from_errno("asprintf");
5705 goto done;
5708 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
5709 if (err)
5710 goto done;
5712 if (write(fd, initial_content, initial_content_len) == -1) {
5713 err = got_error_from_errno2("write", *tagmsg_path);
5714 goto done;
5717 err = get_editor(&editor);
5718 if (err)
5719 goto done;
5720 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content);
5721 done:
5722 free(initial_content);
5723 free(template);
5724 free(editor);
5726 if (fd != -1 && close(fd) == -1 && err == NULL)
5727 err = got_error_from_errno2("close", *tagmsg_path);
5729 /* Editor is done; we can now apply unveil(2) */
5730 if (err == NULL) {
5731 err = apply_unveil(repo_path, 0, NULL);
5732 if (err) {
5733 free(*tagmsg);
5734 *tagmsg = NULL;
5737 return err;
5740 static const struct got_error *
5741 add_tag(struct got_repository *repo, struct got_worktree *worktree,
5742 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
5744 const struct got_error *err = NULL;
5745 struct got_object_id *commit_id = NULL, *tag_id = NULL;
5746 char *label = NULL, *commit_id_str = NULL;
5747 struct got_reference *ref = NULL;
5748 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
5749 char *tagmsg_path = NULL, *tag_id_str = NULL;
5750 int preserve_tagmsg = 0;
5753 * Don't let the user create a tag name with a leading '-'.
5754 * While technically a valid reference name, this case is usually
5755 * an unintended typo.
5757 if (tag_name[0] == '-')
5758 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
5760 err = get_author(&tagger, repo, worktree);
5761 if (err)
5762 return err;
5764 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
5765 GOT_OBJ_TYPE_COMMIT, 1, repo);
5766 if (err)
5767 goto done;
5769 err = got_object_id_str(&commit_id_str, commit_id);
5770 if (err)
5771 goto done;
5773 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5774 refname = strdup(tag_name);
5775 if (refname == NULL) {
5776 err = got_error_from_errno("strdup");
5777 goto done;
5779 tag_name += 10;
5780 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
5781 err = got_error_from_errno("asprintf");
5782 goto done;
5785 err = got_ref_open(&ref, repo, refname, 0);
5786 if (err == NULL) {
5787 err = got_error(GOT_ERR_TAG_EXISTS);
5788 goto done;
5789 } else if (err->code != GOT_ERR_NOT_REF)
5790 goto done;
5792 if (tagmsg_arg == NULL) {
5793 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
5794 tag_name, got_repo_get_path(repo));
5795 if (err) {
5796 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
5797 tagmsg_path != NULL)
5798 preserve_tagmsg = 1;
5799 goto done;
5803 err = got_object_tag_create(&tag_id, tag_name, commit_id,
5804 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
5805 if (err) {
5806 if (tagmsg_path)
5807 preserve_tagmsg = 1;
5808 goto done;
5811 err = got_ref_alloc(&ref, refname, tag_id);
5812 if (err) {
5813 if (tagmsg_path)
5814 preserve_tagmsg = 1;
5815 goto done;
5818 err = got_ref_write(ref, repo);
5819 if (err) {
5820 if (tagmsg_path)
5821 preserve_tagmsg = 1;
5822 goto done;
5825 err = got_object_id_str(&tag_id_str, tag_id);
5826 if (err) {
5827 if (tagmsg_path)
5828 preserve_tagmsg = 1;
5829 goto done;
5831 printf("Created tag %s\n", tag_id_str);
5832 done:
5833 if (preserve_tagmsg) {
5834 fprintf(stderr, "%s: tag message preserved in %s\n",
5835 getprogname(), tagmsg_path);
5836 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
5837 err = got_error_from_errno2("unlink", tagmsg_path);
5838 free(tag_id_str);
5839 if (ref)
5840 got_ref_close(ref);
5841 free(commit_id);
5842 free(commit_id_str);
5843 free(refname);
5844 free(tagmsg);
5845 free(tagmsg_path);
5846 free(tagger);
5847 return err;
5850 static const struct got_error *
5851 cmd_tag(int argc, char *argv[])
5853 const struct got_error *error = NULL;
5854 struct got_repository *repo = NULL;
5855 struct got_worktree *worktree = NULL;
5856 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
5857 char *gitconfig_path = NULL;
5858 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
5859 int ch, do_list = 0;
5861 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
5862 switch (ch) {
5863 case 'c':
5864 commit_id_arg = optarg;
5865 break;
5866 case 'm':
5867 tagmsg = optarg;
5868 break;
5869 case 'r':
5870 repo_path = realpath(optarg, NULL);
5871 if (repo_path == NULL)
5872 return got_error_from_errno2("realpath",
5873 optarg);
5874 got_path_strip_trailing_slashes(repo_path);
5875 break;
5876 case 'l':
5877 do_list = 1;
5878 break;
5879 default:
5880 usage_tag();
5881 /* NOTREACHED */
5885 argc -= optind;
5886 argv += optind;
5888 if (do_list) {
5889 if (commit_id_arg != NULL)
5890 errx(1,
5891 "-c option can only be used when creating a tag");
5892 if (tagmsg)
5893 errx(1, "-l and -m options are mutually exclusive");
5894 if (argc > 0)
5895 usage_tag();
5896 } else if (argc != 1)
5897 usage_tag();
5899 tag_name = argv[0];
5901 #ifndef PROFILE
5902 if (do_list) {
5903 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5904 NULL) == -1)
5905 err(1, "pledge");
5906 } else {
5907 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5908 "sendfd unveil", NULL) == -1)
5909 err(1, "pledge");
5911 #endif
5912 cwd = getcwd(NULL, 0);
5913 if (cwd == NULL) {
5914 error = got_error_from_errno("getcwd");
5915 goto done;
5918 if (repo_path == NULL) {
5919 error = got_worktree_open(&worktree, cwd);
5920 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5921 goto done;
5922 else
5923 error = NULL;
5924 if (worktree) {
5925 repo_path =
5926 strdup(got_worktree_get_repo_path(worktree));
5927 if (repo_path == NULL)
5928 error = got_error_from_errno("strdup");
5929 if (error)
5930 goto done;
5931 } else {
5932 repo_path = strdup(cwd);
5933 if (repo_path == NULL) {
5934 error = got_error_from_errno("strdup");
5935 goto done;
5940 if (do_list) {
5941 error = got_repo_open(&repo, repo_path, NULL);
5942 if (error != NULL)
5943 goto done;
5944 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5945 if (error)
5946 goto done;
5947 error = list_tags(repo, worktree);
5948 } else {
5949 error = get_gitconfig_path(&gitconfig_path);
5950 if (error)
5951 goto done;
5952 error = got_repo_open(&repo, repo_path, gitconfig_path);
5953 if (error != NULL)
5954 goto done;
5956 if (tagmsg) {
5957 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5958 if (error)
5959 goto done;
5962 if (commit_id_arg == NULL) {
5963 struct got_reference *head_ref;
5964 struct got_object_id *commit_id;
5965 error = got_ref_open(&head_ref, repo,
5966 worktree ? got_worktree_get_head_ref_name(worktree)
5967 : GOT_REF_HEAD, 0);
5968 if (error)
5969 goto done;
5970 error = got_ref_resolve(&commit_id, repo, head_ref);
5971 got_ref_close(head_ref);
5972 if (error)
5973 goto done;
5974 error = got_object_id_str(&commit_id_str, commit_id);
5975 free(commit_id);
5976 if (error)
5977 goto done;
5980 error = add_tag(repo, worktree, tag_name,
5981 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
5983 done:
5984 if (repo)
5985 got_repo_close(repo);
5986 if (worktree)
5987 got_worktree_close(worktree);
5988 free(cwd);
5989 free(repo_path);
5990 free(gitconfig_path);
5991 free(commit_id_str);
5992 return error;
5995 __dead static void
5996 usage_add(void)
5998 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
5999 getprogname());
6000 exit(1);
6003 static const struct got_error *
6004 add_progress(void *arg, unsigned char status, const char *path)
6006 while (path[0] == '/')
6007 path++;
6008 printf("%c %s\n", status, path);
6009 return NULL;
6012 static const struct got_error *
6013 cmd_add(int argc, char *argv[])
6015 const struct got_error *error = NULL;
6016 struct got_repository *repo = NULL;
6017 struct got_worktree *worktree = NULL;
6018 char *cwd = NULL;
6019 struct got_pathlist_head paths;
6020 struct got_pathlist_entry *pe;
6021 int ch, can_recurse = 0, no_ignores = 0;
6023 TAILQ_INIT(&paths);
6025 while ((ch = getopt(argc, argv, "IR")) != -1) {
6026 switch (ch) {
6027 case 'I':
6028 no_ignores = 1;
6029 break;
6030 case 'R':
6031 can_recurse = 1;
6032 break;
6033 default:
6034 usage_add();
6035 /* NOTREACHED */
6039 argc -= optind;
6040 argv += optind;
6042 #ifndef PROFILE
6043 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6044 NULL) == -1)
6045 err(1, "pledge");
6046 #endif
6047 if (argc < 1)
6048 usage_add();
6050 cwd = getcwd(NULL, 0);
6051 if (cwd == NULL) {
6052 error = got_error_from_errno("getcwd");
6053 goto done;
6056 error = got_worktree_open(&worktree, cwd);
6057 if (error) {
6058 if (error->code == GOT_ERR_NOT_WORKTREE)
6059 error = wrap_not_worktree_error(error, "add", cwd);
6060 goto done;
6063 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6064 NULL);
6065 if (error != NULL)
6066 goto done;
6068 error = apply_unveil(got_repo_get_path(repo), 1,
6069 got_worktree_get_root_path(worktree));
6070 if (error)
6071 goto done;
6073 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6074 if (error)
6075 goto done;
6077 if (!can_recurse && no_ignores) {
6078 error = got_error_msg(GOT_ERR_BAD_PATH,
6079 "disregarding ignores requires -R option");
6080 goto done;
6084 if (!can_recurse) {
6085 char *ondisk_path;
6086 struct stat sb;
6087 TAILQ_FOREACH(pe, &paths, entry) {
6088 if (asprintf(&ondisk_path, "%s/%s",
6089 got_worktree_get_root_path(worktree),
6090 pe->path) == -1) {
6091 error = got_error_from_errno("asprintf");
6092 goto done;
6094 if (lstat(ondisk_path, &sb) == -1) {
6095 if (errno == ENOENT) {
6096 free(ondisk_path);
6097 continue;
6099 error = got_error_from_errno2("lstat",
6100 ondisk_path);
6101 free(ondisk_path);
6102 goto done;
6104 free(ondisk_path);
6105 if (S_ISDIR(sb.st_mode)) {
6106 error = got_error_msg(GOT_ERR_BAD_PATH,
6107 "adding directories requires -R option");
6108 goto done;
6113 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6114 NULL, repo, no_ignores);
6115 done:
6116 if (repo)
6117 got_repo_close(repo);
6118 if (worktree)
6119 got_worktree_close(worktree);
6120 TAILQ_FOREACH(pe, &paths, entry)
6121 free((char *)pe->path);
6122 got_pathlist_free(&paths);
6123 free(cwd);
6124 return error;
6127 __dead static void
6128 usage_remove(void)
6130 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6131 "path ...\n", getprogname());
6132 exit(1);
6135 static const struct got_error *
6136 print_remove_status(void *arg, unsigned char status,
6137 unsigned char staged_status, const char *path)
6139 while (path[0] == '/')
6140 path++;
6141 if (status == GOT_STATUS_NONEXISTENT)
6142 return NULL;
6143 if (status == staged_status && (status == GOT_STATUS_DELETE))
6144 status = GOT_STATUS_NO_CHANGE;
6145 printf("%c%c %s\n", status, staged_status, path);
6146 return NULL;
6149 static const struct got_error *
6150 cmd_remove(int argc, char *argv[])
6152 const struct got_error *error = NULL;
6153 struct got_worktree *worktree = NULL;
6154 struct got_repository *repo = NULL;
6155 const char *status_codes = NULL;
6156 char *cwd = NULL;
6157 struct got_pathlist_head paths;
6158 struct got_pathlist_entry *pe;
6159 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6161 TAILQ_INIT(&paths);
6163 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6164 switch (ch) {
6165 case 'f':
6166 delete_local_mods = 1;
6167 break;
6168 case 'k':
6169 keep_on_disk = 1;
6170 break;
6171 case 'R':
6172 can_recurse = 1;
6173 break;
6174 case 's':
6175 for (i = 0; i < strlen(optarg); i++) {
6176 switch (optarg[i]) {
6177 case GOT_STATUS_MODIFY:
6178 delete_local_mods = 1;
6179 break;
6180 case GOT_STATUS_MISSING:
6181 break;
6182 default:
6183 errx(1, "invalid status code '%c'",
6184 optarg[i]);
6187 status_codes = optarg;
6188 break;
6189 default:
6190 usage_remove();
6191 /* NOTREACHED */
6195 argc -= optind;
6196 argv += optind;
6198 #ifndef PROFILE
6199 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6200 NULL) == -1)
6201 err(1, "pledge");
6202 #endif
6203 if (argc < 1)
6204 usage_remove();
6206 cwd = getcwd(NULL, 0);
6207 if (cwd == NULL) {
6208 error = got_error_from_errno("getcwd");
6209 goto done;
6211 error = got_worktree_open(&worktree, cwd);
6212 if (error) {
6213 if (error->code == GOT_ERR_NOT_WORKTREE)
6214 error = wrap_not_worktree_error(error, "remove", cwd);
6215 goto done;
6218 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6219 NULL);
6220 if (error)
6221 goto done;
6223 error = apply_unveil(got_repo_get_path(repo), 1,
6224 got_worktree_get_root_path(worktree));
6225 if (error)
6226 goto done;
6228 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6229 if (error)
6230 goto done;
6232 if (!can_recurse) {
6233 char *ondisk_path;
6234 struct stat sb;
6235 TAILQ_FOREACH(pe, &paths, entry) {
6236 if (asprintf(&ondisk_path, "%s/%s",
6237 got_worktree_get_root_path(worktree),
6238 pe->path) == -1) {
6239 error = got_error_from_errno("asprintf");
6240 goto done;
6242 if (lstat(ondisk_path, &sb) == -1) {
6243 if (errno == ENOENT) {
6244 free(ondisk_path);
6245 continue;
6247 error = got_error_from_errno2("lstat",
6248 ondisk_path);
6249 free(ondisk_path);
6250 goto done;
6252 free(ondisk_path);
6253 if (S_ISDIR(sb.st_mode)) {
6254 error = got_error_msg(GOT_ERR_BAD_PATH,
6255 "removing directories requires -R option");
6256 goto done;
6261 error = got_worktree_schedule_delete(worktree, &paths,
6262 delete_local_mods, status_codes, print_remove_status, NULL,
6263 repo, keep_on_disk);
6264 done:
6265 if (repo)
6266 got_repo_close(repo);
6267 if (worktree)
6268 got_worktree_close(worktree);
6269 TAILQ_FOREACH(pe, &paths, entry)
6270 free((char *)pe->path);
6271 got_pathlist_free(&paths);
6272 free(cwd);
6273 return error;
6276 __dead static void
6277 usage_revert(void)
6279 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6280 "path ...\n", getprogname());
6281 exit(1);
6284 static const struct got_error *
6285 revert_progress(void *arg, unsigned char status, const char *path)
6287 if (status == GOT_STATUS_UNVERSIONED)
6288 return NULL;
6290 while (path[0] == '/')
6291 path++;
6292 printf("%c %s\n", status, path);
6293 return NULL;
6296 struct choose_patch_arg {
6297 FILE *patch_script_file;
6298 const char *action;
6301 static const struct got_error *
6302 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6303 int nchanges, const char *action)
6305 char *line = NULL;
6306 size_t linesize = 0;
6307 ssize_t linelen;
6309 switch (status) {
6310 case GOT_STATUS_ADD:
6311 printf("A %s\n%s this addition? [y/n] ", path, action);
6312 break;
6313 case GOT_STATUS_DELETE:
6314 printf("D %s\n%s this deletion? [y/n] ", path, action);
6315 break;
6316 case GOT_STATUS_MODIFY:
6317 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6318 return got_error_from_errno("fseek");
6319 printf(GOT_COMMIT_SEP_STR);
6320 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6321 printf("%s", line);
6322 if (ferror(patch_file))
6323 return got_error_from_errno("getline");
6324 printf(GOT_COMMIT_SEP_STR);
6325 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6326 path, n, nchanges, action);
6327 break;
6328 default:
6329 return got_error_path(path, GOT_ERR_FILE_STATUS);
6332 return NULL;
6335 static const struct got_error *
6336 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6337 FILE *patch_file, int n, int nchanges)
6339 const struct got_error *err = NULL;
6340 char *line = NULL;
6341 size_t linesize = 0;
6342 ssize_t linelen;
6343 int resp = ' ';
6344 struct choose_patch_arg *a = arg;
6346 *choice = GOT_PATCH_CHOICE_NONE;
6348 if (a->patch_script_file) {
6349 char *nl;
6350 err = show_change(status, path, patch_file, n, nchanges,
6351 a->action);
6352 if (err)
6353 return err;
6354 linelen = getline(&line, &linesize, a->patch_script_file);
6355 if (linelen == -1) {
6356 if (ferror(a->patch_script_file))
6357 return got_error_from_errno("getline");
6358 return NULL;
6360 nl = strchr(line, '\n');
6361 if (nl)
6362 *nl = '\0';
6363 if (strcmp(line, "y") == 0) {
6364 *choice = GOT_PATCH_CHOICE_YES;
6365 printf("y\n");
6366 } else if (strcmp(line, "n") == 0) {
6367 *choice = GOT_PATCH_CHOICE_NO;
6368 printf("n\n");
6369 } else if (strcmp(line, "q") == 0 &&
6370 status == GOT_STATUS_MODIFY) {
6371 *choice = GOT_PATCH_CHOICE_QUIT;
6372 printf("q\n");
6373 } else
6374 printf("invalid response '%s'\n", line);
6375 free(line);
6376 return NULL;
6379 while (resp != 'y' && resp != 'n' && resp != 'q') {
6380 err = show_change(status, path, patch_file, n, nchanges,
6381 a->action);
6382 if (err)
6383 return err;
6384 resp = getchar();
6385 if (resp == '\n')
6386 resp = getchar();
6387 if (status == GOT_STATUS_MODIFY) {
6388 if (resp != 'y' && resp != 'n' && resp != 'q') {
6389 printf("invalid response '%c'\n", resp);
6390 resp = ' ';
6392 } else if (resp != 'y' && resp != 'n') {
6393 printf("invalid response '%c'\n", resp);
6394 resp = ' ';
6398 if (resp == 'y')
6399 *choice = GOT_PATCH_CHOICE_YES;
6400 else if (resp == 'n')
6401 *choice = GOT_PATCH_CHOICE_NO;
6402 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6403 *choice = GOT_PATCH_CHOICE_QUIT;
6405 return NULL;
6409 static const struct got_error *
6410 cmd_revert(int argc, char *argv[])
6412 const struct got_error *error = NULL;
6413 struct got_worktree *worktree = NULL;
6414 struct got_repository *repo = NULL;
6415 char *cwd = NULL, *path = NULL;
6416 struct got_pathlist_head paths;
6417 struct got_pathlist_entry *pe;
6418 int ch, can_recurse = 0, pflag = 0;
6419 FILE *patch_script_file = NULL;
6420 const char *patch_script_path = NULL;
6421 struct choose_patch_arg cpa;
6423 TAILQ_INIT(&paths);
6425 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6426 switch (ch) {
6427 case 'p':
6428 pflag = 1;
6429 break;
6430 case 'F':
6431 patch_script_path = optarg;
6432 break;
6433 case 'R':
6434 can_recurse = 1;
6435 break;
6436 default:
6437 usage_revert();
6438 /* NOTREACHED */
6442 argc -= optind;
6443 argv += optind;
6445 #ifndef PROFILE
6446 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6447 "unveil", NULL) == -1)
6448 err(1, "pledge");
6449 #endif
6450 if (argc < 1)
6451 usage_revert();
6452 if (patch_script_path && !pflag)
6453 errx(1, "-F option can only be used together with -p option");
6455 cwd = getcwd(NULL, 0);
6456 if (cwd == NULL) {
6457 error = got_error_from_errno("getcwd");
6458 goto done;
6460 error = got_worktree_open(&worktree, cwd);
6461 if (error) {
6462 if (error->code == GOT_ERR_NOT_WORKTREE)
6463 error = wrap_not_worktree_error(error, "revert", cwd);
6464 goto done;
6467 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6468 NULL);
6469 if (error != NULL)
6470 goto done;
6472 if (patch_script_path) {
6473 patch_script_file = fopen(patch_script_path, "r");
6474 if (patch_script_file == NULL) {
6475 error = got_error_from_errno2("fopen",
6476 patch_script_path);
6477 goto done;
6480 error = apply_unveil(got_repo_get_path(repo), 1,
6481 got_worktree_get_root_path(worktree));
6482 if (error)
6483 goto done;
6485 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6486 if (error)
6487 goto done;
6489 if (!can_recurse) {
6490 char *ondisk_path;
6491 struct stat sb;
6492 TAILQ_FOREACH(pe, &paths, entry) {
6493 if (asprintf(&ondisk_path, "%s/%s",
6494 got_worktree_get_root_path(worktree),
6495 pe->path) == -1) {
6496 error = got_error_from_errno("asprintf");
6497 goto done;
6499 if (lstat(ondisk_path, &sb) == -1) {
6500 if (errno == ENOENT) {
6501 free(ondisk_path);
6502 continue;
6504 error = got_error_from_errno2("lstat",
6505 ondisk_path);
6506 free(ondisk_path);
6507 goto done;
6509 free(ondisk_path);
6510 if (S_ISDIR(sb.st_mode)) {
6511 error = got_error_msg(GOT_ERR_BAD_PATH,
6512 "reverting directories requires -R option");
6513 goto done;
6518 cpa.patch_script_file = patch_script_file;
6519 cpa.action = "revert";
6520 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
6521 pflag ? choose_patch : NULL, &cpa, repo);
6522 done:
6523 if (patch_script_file && fclose(patch_script_file) == EOF &&
6524 error == NULL)
6525 error = got_error_from_errno2("fclose", patch_script_path);
6526 if (repo)
6527 got_repo_close(repo);
6528 if (worktree)
6529 got_worktree_close(worktree);
6530 free(path);
6531 free(cwd);
6532 return error;
6535 __dead static void
6536 usage_commit(void)
6538 fprintf(stderr, "usage: %s commit [-m msg] [-S] [path ...]\n",
6539 getprogname());
6540 exit(1);
6543 struct collect_commit_logmsg_arg {
6544 const char *cmdline_log;
6545 const char *editor;
6546 const char *worktree_path;
6547 const char *branch_name;
6548 const char *repo_path;
6549 char *logmsg_path;
6553 static const struct got_error *
6554 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
6555 void *arg)
6557 char *initial_content = NULL;
6558 struct got_pathlist_entry *pe;
6559 const struct got_error *err = NULL;
6560 char *template = NULL;
6561 struct collect_commit_logmsg_arg *a = arg;
6562 int initial_content_len;
6563 int fd = -1;
6564 size_t len;
6566 /* if a message was specified on the command line, just use it */
6567 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
6568 len = strlen(a->cmdline_log) + 1;
6569 *logmsg = malloc(len + 1);
6570 if (*logmsg == NULL)
6571 return got_error_from_errno("malloc");
6572 strlcpy(*logmsg, a->cmdline_log, len);
6573 return NULL;
6576 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
6577 return got_error_from_errno("asprintf");
6579 initial_content_len = asprintf(&initial_content,
6580 "\n# changes to be committed on branch %s:\n",
6581 a->branch_name);
6582 if (initial_content_len == -1)
6583 return got_error_from_errno("asprintf");
6585 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
6586 if (err)
6587 goto done;
6589 if (write(fd, initial_content, initial_content_len) == -1) {
6590 err = got_error_from_errno2("write", a->logmsg_path);
6591 goto done;
6594 TAILQ_FOREACH(pe, commitable_paths, entry) {
6595 struct got_commitable *ct = pe->data;
6596 dprintf(fd, "# %c %s\n",
6597 got_commitable_get_status(ct),
6598 got_commitable_get_path(ct));
6601 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content);
6602 done:
6603 free(initial_content);
6604 free(template);
6606 if (fd != -1 && close(fd) == -1 && err == NULL)
6607 err = got_error_from_errno2("close", a->logmsg_path);
6609 /* Editor is done; we can now apply unveil(2) */
6610 if (err == NULL) {
6611 err = apply_unveil(a->repo_path, 0, a->worktree_path);
6612 if (err) {
6613 free(*logmsg);
6614 *logmsg = NULL;
6617 return err;
6620 static const struct got_error *
6621 cmd_commit(int argc, char *argv[])
6623 const struct got_error *error = NULL;
6624 struct got_worktree *worktree = NULL;
6625 struct got_repository *repo = NULL;
6626 char *cwd = NULL, *id_str = NULL;
6627 struct got_object_id *id = NULL;
6628 const char *logmsg = NULL;
6629 struct collect_commit_logmsg_arg cl_arg;
6630 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
6631 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
6632 int allow_bad_symlinks = 0;
6633 struct got_pathlist_head paths;
6635 TAILQ_INIT(&paths);
6636 cl_arg.logmsg_path = NULL;
6638 while ((ch = getopt(argc, argv, "m:S")) != -1) {
6639 switch (ch) {
6640 case 'm':
6641 logmsg = optarg;
6642 break;
6643 case 'S':
6644 allow_bad_symlinks = 1;
6645 break;
6646 default:
6647 usage_commit();
6648 /* NOTREACHED */
6652 argc -= optind;
6653 argv += optind;
6655 #ifndef PROFILE
6656 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6657 "unveil", NULL) == -1)
6658 err(1, "pledge");
6659 #endif
6660 cwd = getcwd(NULL, 0);
6661 if (cwd == NULL) {
6662 error = got_error_from_errno("getcwd");
6663 goto done;
6665 error = got_worktree_open(&worktree, cwd);
6666 if (error) {
6667 if (error->code == GOT_ERR_NOT_WORKTREE)
6668 error = wrap_not_worktree_error(error, "commit", cwd);
6669 goto done;
6672 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6673 if (error)
6674 goto done;
6675 if (rebase_in_progress) {
6676 error = got_error(GOT_ERR_REBASING);
6677 goto done;
6680 error = got_worktree_histedit_in_progress(&histedit_in_progress,
6681 worktree);
6682 if (error)
6683 goto done;
6685 error = get_gitconfig_path(&gitconfig_path);
6686 if (error)
6687 goto done;
6688 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6689 gitconfig_path);
6690 if (error != NULL)
6691 goto done;
6693 error = get_author(&author, repo, worktree);
6694 if (error)
6695 return error;
6698 * unveil(2) traverses exec(2); if an editor is used we have
6699 * to apply unveil after the log message has been written.
6701 if (logmsg == NULL || strlen(logmsg) == 0)
6702 error = get_editor(&editor);
6703 else
6704 error = apply_unveil(got_repo_get_path(repo), 0,
6705 got_worktree_get_root_path(worktree));
6706 if (error)
6707 goto done;
6709 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6710 if (error)
6711 goto done;
6713 cl_arg.editor = editor;
6714 cl_arg.cmdline_log = logmsg;
6715 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
6716 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
6717 if (!histedit_in_progress) {
6718 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
6719 error = got_error(GOT_ERR_COMMIT_BRANCH);
6720 goto done;
6722 cl_arg.branch_name += 11;
6724 cl_arg.repo_path = got_repo_get_path(repo);
6725 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
6726 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
6727 print_status, NULL, repo);
6728 if (error) {
6729 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6730 cl_arg.logmsg_path != NULL)
6731 preserve_logmsg = 1;
6732 goto done;
6735 error = got_object_id_str(&id_str, id);
6736 if (error)
6737 goto done;
6738 printf("Created commit %s\n", id_str);
6739 done:
6740 if (preserve_logmsg) {
6741 fprintf(stderr, "%s: log message preserved in %s\n",
6742 getprogname(), cl_arg.logmsg_path);
6743 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
6744 error == NULL)
6745 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
6746 free(cl_arg.logmsg_path);
6747 if (repo)
6748 got_repo_close(repo);
6749 if (worktree)
6750 got_worktree_close(worktree);
6751 free(cwd);
6752 free(id_str);
6753 free(gitconfig_path);
6754 free(editor);
6755 free(author);
6756 return error;
6759 __dead static void
6760 usage_cherrypick(void)
6762 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
6763 exit(1);
6766 static const struct got_error *
6767 cmd_cherrypick(int argc, char *argv[])
6769 const struct got_error *error = NULL;
6770 struct got_worktree *worktree = NULL;
6771 struct got_repository *repo = NULL;
6772 char *cwd = NULL, *commit_id_str = NULL;
6773 struct got_object_id *commit_id = NULL;
6774 struct got_commit_object *commit = NULL;
6775 struct got_object_qid *pid;
6776 struct got_reference *head_ref = NULL;
6777 int ch;
6778 struct got_update_progress_arg upa;
6780 while ((ch = getopt(argc, argv, "")) != -1) {
6781 switch (ch) {
6782 default:
6783 usage_cherrypick();
6784 /* NOTREACHED */
6788 argc -= optind;
6789 argv += optind;
6791 #ifndef PROFILE
6792 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6793 "unveil", NULL) == -1)
6794 err(1, "pledge");
6795 #endif
6796 if (argc != 1)
6797 usage_cherrypick();
6799 cwd = getcwd(NULL, 0);
6800 if (cwd == NULL) {
6801 error = got_error_from_errno("getcwd");
6802 goto done;
6804 error = got_worktree_open(&worktree, cwd);
6805 if (error) {
6806 if (error->code == GOT_ERR_NOT_WORKTREE)
6807 error = wrap_not_worktree_error(error, "cherrypick",
6808 cwd);
6809 goto done;
6812 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6813 NULL);
6814 if (error != NULL)
6815 goto done;
6817 error = apply_unveil(got_repo_get_path(repo), 0,
6818 got_worktree_get_root_path(worktree));
6819 if (error)
6820 goto done;
6822 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6823 GOT_OBJ_TYPE_COMMIT, repo);
6824 if (error != NULL) {
6825 struct got_reference *ref;
6826 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6827 goto done;
6828 error = got_ref_open(&ref, repo, argv[0], 0);
6829 if (error != NULL)
6830 goto done;
6831 error = got_ref_resolve(&commit_id, repo, ref);
6832 got_ref_close(ref);
6833 if (error != NULL)
6834 goto done;
6836 error = got_object_id_str(&commit_id_str, commit_id);
6837 if (error)
6838 goto done;
6840 error = got_ref_open(&head_ref, repo,
6841 got_worktree_get_head_ref_name(worktree), 0);
6842 if (error != NULL)
6843 goto done;
6845 error = check_same_branch(commit_id, head_ref, NULL, repo);
6846 if (error) {
6847 if (error->code != GOT_ERR_ANCESTRY)
6848 goto done;
6849 error = NULL;
6850 } else {
6851 error = got_error(GOT_ERR_SAME_BRANCH);
6852 goto done;
6855 error = got_object_open_as_commit(&commit, repo, commit_id);
6856 if (error)
6857 goto done;
6858 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6859 memset(&upa, 0, sizeof(upa));
6860 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
6861 commit_id, repo, update_progress, &upa, check_cancelled,
6862 NULL);
6863 if (error != NULL)
6864 goto done;
6866 if (upa.did_something)
6867 printf("Merged commit %s\n", commit_id_str);
6868 print_update_progress_stats(&upa);
6869 done:
6870 if (commit)
6871 got_object_commit_close(commit);
6872 free(commit_id_str);
6873 if (head_ref)
6874 got_ref_close(head_ref);
6875 if (worktree)
6876 got_worktree_close(worktree);
6877 if (repo)
6878 got_repo_close(repo);
6879 return error;
6882 __dead static void
6883 usage_backout(void)
6885 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
6886 exit(1);
6889 static const struct got_error *
6890 cmd_backout(int argc, char *argv[])
6892 const struct got_error *error = NULL;
6893 struct got_worktree *worktree = NULL;
6894 struct got_repository *repo = NULL;
6895 char *cwd = NULL, *commit_id_str = NULL;
6896 struct got_object_id *commit_id = NULL;
6897 struct got_commit_object *commit = NULL;
6898 struct got_object_qid *pid;
6899 struct got_reference *head_ref = NULL;
6900 int ch;
6901 struct got_update_progress_arg upa;
6903 while ((ch = getopt(argc, argv, "")) != -1) {
6904 switch (ch) {
6905 default:
6906 usage_backout();
6907 /* NOTREACHED */
6911 argc -= optind;
6912 argv += optind;
6914 #ifndef PROFILE
6915 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
6916 "unveil", NULL) == -1)
6917 err(1, "pledge");
6918 #endif
6919 if (argc != 1)
6920 usage_backout();
6922 cwd = getcwd(NULL, 0);
6923 if (cwd == NULL) {
6924 error = got_error_from_errno("getcwd");
6925 goto done;
6927 error = got_worktree_open(&worktree, cwd);
6928 if (error) {
6929 if (error->code == GOT_ERR_NOT_WORKTREE)
6930 error = wrap_not_worktree_error(error, "backout", cwd);
6931 goto done;
6934 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6935 NULL);
6936 if (error != NULL)
6937 goto done;
6939 error = apply_unveil(got_repo_get_path(repo), 0,
6940 got_worktree_get_root_path(worktree));
6941 if (error)
6942 goto done;
6944 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
6945 GOT_OBJ_TYPE_COMMIT, repo);
6946 if (error != NULL) {
6947 struct got_reference *ref;
6948 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
6949 goto done;
6950 error = got_ref_open(&ref, repo, argv[0], 0);
6951 if (error != NULL)
6952 goto done;
6953 error = got_ref_resolve(&commit_id, repo, ref);
6954 got_ref_close(ref);
6955 if (error != NULL)
6956 goto done;
6958 error = got_object_id_str(&commit_id_str, commit_id);
6959 if (error)
6960 goto done;
6962 error = got_ref_open(&head_ref, repo,
6963 got_worktree_get_head_ref_name(worktree), 0);
6964 if (error != NULL)
6965 goto done;
6967 error = check_same_branch(commit_id, head_ref, NULL, repo);
6968 if (error)
6969 goto done;
6971 error = got_object_open_as_commit(&commit, repo, commit_id);
6972 if (error)
6973 goto done;
6974 pid = SIMPLEQ_FIRST(got_object_commit_get_parent_ids(commit));
6975 if (pid == NULL) {
6976 error = got_error(GOT_ERR_ROOT_COMMIT);
6977 goto done;
6980 memset(&upa, 0, sizeof(upa));
6981 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
6982 update_progress, &upa, check_cancelled, NULL);
6983 if (error != NULL)
6984 goto done;
6986 if (upa.did_something)
6987 printf("Backed out commit %s\n", commit_id_str);
6988 print_update_progress_stats(&upa);
6989 done:
6990 if (commit)
6991 got_object_commit_close(commit);
6992 free(commit_id_str);
6993 if (head_ref)
6994 got_ref_close(head_ref);
6995 if (worktree)
6996 got_worktree_close(worktree);
6997 if (repo)
6998 got_repo_close(repo);
6999 return error;
7002 __dead static void
7003 usage_rebase(void)
7005 fprintf(stderr, "usage: %s rebase [-a] | [-c] | branch\n",
7006 getprogname());
7007 exit(1);
7010 void
7011 trim_logmsg(char *logmsg, int limit)
7013 char *nl;
7014 size_t len;
7016 len = strlen(logmsg);
7017 if (len > limit)
7018 len = limit;
7019 logmsg[len] = '\0';
7020 nl = strchr(logmsg, '\n');
7021 if (nl)
7022 *nl = '\0';
7025 static const struct got_error *
7026 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
7028 const struct got_error *err;
7029 char *logmsg0 = NULL;
7030 const char *s;
7032 err = got_object_commit_get_logmsg(&logmsg0, commit);
7033 if (err)
7034 return err;
7036 s = logmsg0;
7037 while (isspace((unsigned char)s[0]))
7038 s++;
7040 *logmsg = strdup(s);
7041 if (*logmsg == NULL) {
7042 err = got_error_from_errno("strdup");
7043 goto done;
7046 trim_logmsg(*logmsg, limit);
7047 done:
7048 free(logmsg0);
7049 return err;
7052 static const struct got_error *
7053 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
7055 const struct got_error *err;
7056 struct got_commit_object *commit = NULL;
7057 char *id_str = NULL, *logmsg = NULL;
7059 err = got_object_open_as_commit(&commit, repo, id);
7060 if (err)
7061 return err;
7063 err = got_object_id_str(&id_str, id);
7064 if (err)
7065 goto done;
7067 id_str[12] = '\0';
7069 err = get_short_logmsg(&logmsg, 42, commit);
7070 if (err)
7071 goto done;
7073 printf("%s -> merge conflict: %s\n", id_str, logmsg);
7074 done:
7075 free(id_str);
7076 got_object_commit_close(commit);
7077 free(logmsg);
7078 return err;
7081 static const struct got_error *
7082 show_rebase_progress(struct got_commit_object *commit,
7083 struct got_object_id *old_id, struct got_object_id *new_id)
7085 const struct got_error *err;
7086 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
7088 err = got_object_id_str(&old_id_str, old_id);
7089 if (err)
7090 goto done;
7092 if (new_id) {
7093 err = got_object_id_str(&new_id_str, new_id);
7094 if (err)
7095 goto done;
7098 old_id_str[12] = '\0';
7099 if (new_id_str)
7100 new_id_str[12] = '\0';
7102 err = get_short_logmsg(&logmsg, 42, commit);
7103 if (err)
7104 goto done;
7106 printf("%s -> %s: %s\n", old_id_str,
7107 new_id_str ? new_id_str : "no-op change", logmsg);
7108 done:
7109 free(old_id_str);
7110 free(new_id_str);
7111 free(logmsg);
7112 return err;
7115 static const struct got_error *
7116 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
7117 struct got_reference *branch, struct got_reference *new_base_branch,
7118 struct got_reference *tmp_branch, struct got_repository *repo)
7120 printf("Switching work tree to %s\n", got_ref_get_name(branch));
7121 return got_worktree_rebase_complete(worktree, fileindex,
7122 new_base_branch, tmp_branch, branch, repo);
7125 static const struct got_error *
7126 rebase_commit(struct got_pathlist_head *merged_paths,
7127 struct got_worktree *worktree, struct got_fileindex *fileindex,
7128 struct got_reference *tmp_branch,
7129 struct got_object_id *commit_id, struct got_repository *repo)
7131 const struct got_error *error;
7132 struct got_commit_object *commit;
7133 struct got_object_id *new_commit_id;
7135 error = got_object_open_as_commit(&commit, repo, commit_id);
7136 if (error)
7137 return error;
7139 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
7140 worktree, fileindex, tmp_branch, commit, commit_id, repo);
7141 if (error) {
7142 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
7143 goto done;
7144 error = show_rebase_progress(commit, commit_id, NULL);
7145 } else {
7146 error = show_rebase_progress(commit, commit_id, new_commit_id);
7147 free(new_commit_id);
7149 done:
7150 got_object_commit_close(commit);
7151 return error;
7154 struct check_path_prefix_arg {
7155 const char *path_prefix;
7156 size_t len;
7157 int errcode;
7160 static const struct got_error *
7161 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
7162 struct got_blob_object *blob2, struct got_object_id *id1,
7163 struct got_object_id *id2, const char *path1, const char *path2,
7164 mode_t mode1, mode_t mode2, struct got_repository *repo)
7166 struct check_path_prefix_arg *a = arg;
7168 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
7169 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
7170 return got_error(a->errcode);
7172 return NULL;
7175 static const struct got_error *
7176 check_path_prefix(struct got_object_id *parent_id,
7177 struct got_object_id *commit_id, const char *path_prefix,
7178 int errcode, struct got_repository *repo)
7180 const struct got_error *err;
7181 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
7182 struct got_commit_object *commit = NULL, *parent_commit = NULL;
7183 struct check_path_prefix_arg cpp_arg;
7185 if (got_path_is_root_dir(path_prefix))
7186 return NULL;
7188 err = got_object_open_as_commit(&commit, repo, commit_id);
7189 if (err)
7190 goto done;
7192 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
7193 if (err)
7194 goto done;
7196 err = got_object_open_as_tree(&tree1, repo,
7197 got_object_commit_get_tree_id(parent_commit));
7198 if (err)
7199 goto done;
7201 err = got_object_open_as_tree(&tree2, repo,
7202 got_object_commit_get_tree_id(commit));
7203 if (err)
7204 goto done;
7206 cpp_arg.path_prefix = path_prefix;
7207 while (cpp_arg.path_prefix[0] == '/')
7208 cpp_arg.path_prefix++;
7209 cpp_arg.len = strlen(cpp_arg.path_prefix);
7210 cpp_arg.errcode = errcode;
7211 err = got_diff_tree(tree1, tree2, "", "", repo,
7212 check_path_prefix_in_diff, &cpp_arg, 0);
7213 done:
7214 if (tree1)
7215 got_object_tree_close(tree1);
7216 if (tree2)
7217 got_object_tree_close(tree2);
7218 if (commit)
7219 got_object_commit_close(commit);
7220 if (parent_commit)
7221 got_object_commit_close(parent_commit);
7222 return err;
7225 static const struct got_error *
7226 collect_commits(struct got_object_id_queue *commits,
7227 struct got_object_id *initial_commit_id,
7228 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
7229 const char *path_prefix, int path_prefix_errcode,
7230 struct got_repository *repo)
7232 const struct got_error *err = NULL;
7233 struct got_commit_graph *graph = NULL;
7234 struct got_object_id *parent_id = NULL;
7235 struct got_object_qid *qid;
7236 struct got_object_id *commit_id = initial_commit_id;
7238 err = got_commit_graph_open(&graph, "/", 1);
7239 if (err)
7240 return err;
7242 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
7243 check_cancelled, NULL);
7244 if (err)
7245 goto done;
7246 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
7247 err = got_commit_graph_iter_next(&parent_id, graph, repo,
7248 check_cancelled, NULL);
7249 if (err) {
7250 if (err->code == GOT_ERR_ITER_COMPLETED) {
7251 err = got_error_msg(GOT_ERR_ANCESTRY,
7252 "ran out of commits to rebase before "
7253 "youngest common ancestor commit has "
7254 "been reached?!?");
7256 goto done;
7257 } else {
7258 err = check_path_prefix(parent_id, commit_id,
7259 path_prefix, path_prefix_errcode, repo);
7260 if (err)
7261 goto done;
7263 err = got_object_qid_alloc(&qid, commit_id);
7264 if (err)
7265 goto done;
7266 SIMPLEQ_INSERT_HEAD(commits, qid, entry);
7267 commit_id = parent_id;
7270 done:
7271 got_commit_graph_close(graph);
7272 return err;
7275 static const struct got_error *
7276 cmd_rebase(int argc, char *argv[])
7278 const struct got_error *error = NULL;
7279 struct got_worktree *worktree = NULL;
7280 struct got_repository *repo = NULL;
7281 struct got_fileindex *fileindex = NULL;
7282 char *cwd = NULL;
7283 struct got_reference *branch = NULL;
7284 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
7285 struct got_object_id *commit_id = NULL, *parent_id = NULL;
7286 struct got_object_id *resume_commit_id = NULL;
7287 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
7288 struct got_commit_object *commit = NULL;
7289 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
7290 int histedit_in_progress = 0;
7291 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
7292 struct got_object_id_queue commits;
7293 struct got_pathlist_head merged_paths;
7294 const struct got_object_id_queue *parent_ids;
7295 struct got_object_qid *qid, *pid;
7297 SIMPLEQ_INIT(&commits);
7298 TAILQ_INIT(&merged_paths);
7300 while ((ch = getopt(argc, argv, "ac")) != -1) {
7301 switch (ch) {
7302 case 'a':
7303 abort_rebase = 1;
7304 break;
7305 case 'c':
7306 continue_rebase = 1;
7307 break;
7308 default:
7309 usage_rebase();
7310 /* NOTREACHED */
7314 argc -= optind;
7315 argv += optind;
7317 #ifndef PROFILE
7318 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7319 "unveil", NULL) == -1)
7320 err(1, "pledge");
7321 #endif
7322 if (abort_rebase && continue_rebase)
7323 usage_rebase();
7324 else if (abort_rebase || continue_rebase) {
7325 if (argc != 0)
7326 usage_rebase();
7327 } else if (argc != 1)
7328 usage_rebase();
7330 cwd = getcwd(NULL, 0);
7331 if (cwd == NULL) {
7332 error = got_error_from_errno("getcwd");
7333 goto done;
7335 error = got_worktree_open(&worktree, cwd);
7336 if (error) {
7337 if (error->code == GOT_ERR_NOT_WORKTREE)
7338 error = wrap_not_worktree_error(error, "rebase", cwd);
7339 goto done;
7342 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7343 NULL);
7344 if (error != NULL)
7345 goto done;
7347 error = apply_unveil(got_repo_get_path(repo), 0,
7348 got_worktree_get_root_path(worktree));
7349 if (error)
7350 goto done;
7352 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7353 worktree);
7354 if (error)
7355 goto done;
7356 if (histedit_in_progress) {
7357 error = got_error(GOT_ERR_HISTEDIT_BUSY);
7358 goto done;
7361 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7362 if (error)
7363 goto done;
7365 if (abort_rebase) {
7366 struct got_update_progress_arg upa;
7367 if (!rebase_in_progress) {
7368 error = got_error(GOT_ERR_NOT_REBASING);
7369 goto done;
7371 error = got_worktree_rebase_continue(&resume_commit_id,
7372 &new_base_branch, &tmp_branch, &branch, &fileindex,
7373 worktree, repo);
7374 if (error)
7375 goto done;
7376 printf("Switching work tree to %s\n",
7377 got_ref_get_symref_target(new_base_branch));
7378 memset(&upa, 0, sizeof(upa));
7379 error = got_worktree_rebase_abort(worktree, fileindex, repo,
7380 new_base_branch, update_progress, &upa);
7381 if (error)
7382 goto done;
7383 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
7384 print_update_progress_stats(&upa);
7385 goto done; /* nothing else to do */
7388 if (continue_rebase) {
7389 if (!rebase_in_progress) {
7390 error = got_error(GOT_ERR_NOT_REBASING);
7391 goto done;
7393 error = got_worktree_rebase_continue(&resume_commit_id,
7394 &new_base_branch, &tmp_branch, &branch, &fileindex,
7395 worktree, repo);
7396 if (error)
7397 goto done;
7399 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
7400 resume_commit_id, repo);
7401 if (error)
7402 goto done;
7404 yca_id = got_object_id_dup(resume_commit_id);
7405 if (yca_id == NULL) {
7406 error = got_error_from_errno("got_object_id_dup");
7407 goto done;
7409 } else {
7410 error = got_ref_open(&branch, repo, argv[0], 0);
7411 if (error != NULL)
7412 goto done;
7415 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
7416 if (error)
7417 goto done;
7419 if (!continue_rebase) {
7420 struct got_object_id *base_commit_id;
7422 base_commit_id = got_worktree_get_base_commit_id(worktree);
7423 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
7424 base_commit_id, branch_head_commit_id, repo,
7425 check_cancelled, NULL);
7426 if (error)
7427 goto done;
7428 if (yca_id == NULL) {
7429 error = got_error_msg(GOT_ERR_ANCESTRY,
7430 "specified branch shares no common ancestry "
7431 "with work tree's branch");
7432 goto done;
7435 error = check_same_branch(base_commit_id, branch, yca_id, repo);
7436 if (error) {
7437 if (error->code != GOT_ERR_ANCESTRY)
7438 goto done;
7439 error = NULL;
7440 } else {
7441 error = got_error_msg(GOT_ERR_SAME_BRANCH,
7442 "specified branch resolves to a commit which "
7443 "is already contained in work tree's branch");
7444 goto done;
7446 error = got_worktree_rebase_prepare(&new_base_branch,
7447 &tmp_branch, &fileindex, worktree, branch, repo);
7448 if (error)
7449 goto done;
7452 commit_id = branch_head_commit_id;
7453 error = got_object_open_as_commit(&commit, repo, commit_id);
7454 if (error)
7455 goto done;
7457 parent_ids = got_object_commit_get_parent_ids(commit);
7458 pid = SIMPLEQ_FIRST(parent_ids);
7459 if (pid == NULL) {
7460 if (!continue_rebase) {
7461 struct got_update_progress_arg upa;
7462 memset(&upa, 0, sizeof(upa));
7463 error = got_worktree_rebase_abort(worktree, fileindex,
7464 repo, new_base_branch, update_progress, &upa);
7465 if (error)
7466 goto done;
7467 printf("Rebase of %s aborted\n",
7468 got_ref_get_name(branch));
7469 print_update_progress_stats(&upa);
7472 error = got_error(GOT_ERR_EMPTY_REBASE);
7473 goto done;
7475 error = collect_commits(&commits, commit_id, pid->id,
7476 yca_id, got_worktree_get_path_prefix(worktree),
7477 GOT_ERR_REBASE_PATH, repo);
7478 got_object_commit_close(commit);
7479 commit = NULL;
7480 if (error)
7481 goto done;
7483 if (SIMPLEQ_EMPTY(&commits)) {
7484 if (continue_rebase) {
7485 error = rebase_complete(worktree, fileindex,
7486 branch, new_base_branch, tmp_branch, repo);
7487 goto done;
7488 } else {
7489 /* Fast-forward the reference of the branch. */
7490 struct got_object_id *new_head_commit_id;
7491 char *id_str;
7492 error = got_ref_resolve(&new_head_commit_id, repo,
7493 new_base_branch);
7494 if (error)
7495 goto done;
7496 error = got_object_id_str(&id_str, new_head_commit_id);
7497 printf("Forwarding %s to commit %s\n",
7498 got_ref_get_name(branch), id_str);
7499 free(id_str);
7500 error = got_ref_change_ref(branch,
7501 new_head_commit_id);
7502 if (error)
7503 goto done;
7507 pid = NULL;
7508 SIMPLEQ_FOREACH(qid, &commits, entry) {
7509 struct got_update_progress_arg upa;
7511 commit_id = qid->id;
7512 parent_id = pid ? pid->id : yca_id;
7513 pid = qid;
7515 memset(&upa, 0, sizeof(upa));
7516 error = got_worktree_rebase_merge_files(&merged_paths,
7517 worktree, fileindex, parent_id, commit_id, repo,
7518 update_progress, &upa, check_cancelled, NULL);
7519 if (error)
7520 goto done;
7522 print_update_progress_stats(&upa);
7523 if (upa.conflicts > 0)
7524 rebase_status = GOT_STATUS_CONFLICT;
7526 if (rebase_status == GOT_STATUS_CONFLICT) {
7527 error = show_rebase_merge_conflict(qid->id, repo);
7528 if (error)
7529 goto done;
7530 got_worktree_rebase_pathlist_free(&merged_paths);
7531 break;
7534 error = rebase_commit(&merged_paths, worktree, fileindex,
7535 tmp_branch, commit_id, repo);
7536 got_worktree_rebase_pathlist_free(&merged_paths);
7537 if (error)
7538 goto done;
7541 if (rebase_status == GOT_STATUS_CONFLICT) {
7542 error = got_worktree_rebase_postpone(worktree, fileindex);
7543 if (error)
7544 goto done;
7545 error = got_error_msg(GOT_ERR_CONFLICTS,
7546 "conflicts must be resolved before rebasing can continue");
7547 } else
7548 error = rebase_complete(worktree, fileindex, branch,
7549 new_base_branch, tmp_branch, repo);
7550 done:
7551 got_object_id_queue_free(&commits);
7552 free(branch_head_commit_id);
7553 free(resume_commit_id);
7554 free(yca_id);
7555 if (commit)
7556 got_object_commit_close(commit);
7557 if (branch)
7558 got_ref_close(branch);
7559 if (new_base_branch)
7560 got_ref_close(new_base_branch);
7561 if (tmp_branch)
7562 got_ref_close(tmp_branch);
7563 if (worktree)
7564 got_worktree_close(worktree);
7565 if (repo)
7566 got_repo_close(repo);
7567 return error;
7570 __dead static void
7571 usage_histedit(void)
7573 fprintf(stderr, "usage: %s histedit [-a] [-c] [-F histedit-script] [-m]\n",
7574 getprogname());
7575 exit(1);
7578 #define GOT_HISTEDIT_PICK 'p'
7579 #define GOT_HISTEDIT_EDIT 'e'
7580 #define GOT_HISTEDIT_FOLD 'f'
7581 #define GOT_HISTEDIT_DROP 'd'
7582 #define GOT_HISTEDIT_MESG 'm'
7584 static struct got_histedit_cmd {
7585 unsigned char code;
7586 const char *name;
7587 const char *desc;
7588 } got_histedit_cmds[] = {
7589 { GOT_HISTEDIT_PICK, "pick", "use commit" },
7590 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
7591 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
7592 "be used" },
7593 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
7594 { GOT_HISTEDIT_MESG, "mesg",
7595 "single-line log message for commit above (open editor if empty)" },
7598 struct got_histedit_list_entry {
7599 TAILQ_ENTRY(got_histedit_list_entry) entry;
7600 struct got_object_id *commit_id;
7601 const struct got_histedit_cmd *cmd;
7602 char *logmsg;
7604 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
7606 static const struct got_error *
7607 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
7608 FILE *f, struct got_repository *repo)
7610 const struct got_error *err = NULL;
7611 char *logmsg = NULL, *id_str = NULL;
7612 struct got_commit_object *commit = NULL;
7613 int n;
7615 err = got_object_open_as_commit(&commit, repo, commit_id);
7616 if (err)
7617 goto done;
7619 err = get_short_logmsg(&logmsg, 34, commit);
7620 if (err)
7621 goto done;
7623 err = got_object_id_str(&id_str, commit_id);
7624 if (err)
7625 goto done;
7627 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
7628 if (n < 0)
7629 err = got_ferror(f, GOT_ERR_IO);
7630 done:
7631 if (commit)
7632 got_object_commit_close(commit);
7633 free(id_str);
7634 free(logmsg);
7635 return err;
7638 static const struct got_error *
7639 histedit_write_commit_list(struct got_object_id_queue *commits,
7640 FILE *f, int edit_logmsg_only, struct got_repository *repo)
7642 const struct got_error *err = NULL;
7643 struct got_object_qid *qid;
7645 if (SIMPLEQ_EMPTY(commits))
7646 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7648 SIMPLEQ_FOREACH(qid, commits, entry) {
7649 err = histedit_write_commit(qid->id, got_histedit_cmds[0].name,
7650 f, repo);
7651 if (err)
7652 break;
7653 if (edit_logmsg_only) {
7654 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
7655 if (n < 0) {
7656 err = got_ferror(f, GOT_ERR_IO);
7657 break;
7662 return err;
7665 static const struct got_error *
7666 write_cmd_list(FILE *f, const char *branch_name,
7667 struct got_object_id_queue *commits)
7669 const struct got_error *err = NULL;
7670 int n, i;
7671 char *id_str;
7672 struct got_object_qid *qid;
7674 qid = SIMPLEQ_FIRST(commits);
7675 err = got_object_id_str(&id_str, qid->id);
7676 if (err)
7677 return err;
7679 n = fprintf(f,
7680 "# Editing the history of branch '%s' starting at\n"
7681 "# commit %s\n"
7682 "# Commits will be processed in order from top to "
7683 "bottom of this file.\n", branch_name, id_str);
7684 if (n < 0) {
7685 err = got_ferror(f, GOT_ERR_IO);
7686 goto done;
7689 n = fprintf(f, "# Available histedit commands:\n");
7690 if (n < 0) {
7691 err = got_ferror(f, GOT_ERR_IO);
7692 goto done;
7695 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7696 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
7697 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
7698 cmd->desc);
7699 if (n < 0) {
7700 err = got_ferror(f, GOT_ERR_IO);
7701 break;
7704 done:
7705 free(id_str);
7706 return err;
7709 static const struct got_error *
7710 histedit_syntax_error(int lineno)
7712 static char msg[42];
7713 int ret;
7715 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
7716 lineno);
7717 if (ret == -1 || ret >= sizeof(msg))
7718 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
7720 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
7723 static const struct got_error *
7724 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
7725 char *logmsg, struct got_repository *repo)
7727 const struct got_error *err;
7728 struct got_commit_object *folded_commit = NULL;
7729 char *id_str, *folded_logmsg = NULL;
7731 err = got_object_id_str(&id_str, hle->commit_id);
7732 if (err)
7733 return err;
7735 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
7736 if (err)
7737 goto done;
7739 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
7740 if (err)
7741 goto done;
7742 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
7743 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
7744 folded_logmsg) == -1) {
7745 err = got_error_from_errno("asprintf");
7747 done:
7748 if (folded_commit)
7749 got_object_commit_close(folded_commit);
7750 free(id_str);
7751 free(folded_logmsg);
7752 return err;
7755 static struct got_histedit_list_entry *
7756 get_folded_commits(struct got_histedit_list_entry *hle)
7758 struct got_histedit_list_entry *prev, *folded = NULL;
7760 prev = TAILQ_PREV(hle, got_histedit_list, entry);
7761 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
7762 prev->cmd->code == GOT_HISTEDIT_DROP)) {
7763 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
7764 folded = prev;
7765 prev = TAILQ_PREV(prev, got_histedit_list, entry);
7768 return folded;
7771 static const struct got_error *
7772 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
7773 struct got_repository *repo)
7775 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
7776 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
7777 const struct got_error *err = NULL;
7778 struct got_commit_object *commit = NULL;
7779 int logmsg_len;
7780 int fd;
7781 struct got_histedit_list_entry *folded = NULL;
7783 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
7784 if (err)
7785 return err;
7787 folded = get_folded_commits(hle);
7788 if (folded) {
7789 while (folded != hle) {
7790 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
7791 folded = TAILQ_NEXT(folded, entry);
7792 continue;
7794 err = append_folded_commit_msg(&new_msg, folded,
7795 logmsg, repo);
7796 if (err)
7797 goto done;
7798 free(logmsg);
7799 logmsg = new_msg;
7800 folded = TAILQ_NEXT(folded, entry);
7804 err = got_object_id_str(&id_str, hle->commit_id);
7805 if (err)
7806 goto done;
7807 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
7808 if (err)
7809 goto done;
7810 logmsg_len = asprintf(&new_msg,
7811 "%s\n# original log message of commit %s: %s",
7812 logmsg ? logmsg : "", id_str, orig_logmsg);
7813 if (logmsg_len == -1) {
7814 err = got_error_from_errno("asprintf");
7815 goto done;
7817 free(logmsg);
7818 logmsg = new_msg;
7820 err = got_object_id_str(&id_str, hle->commit_id);
7821 if (err)
7822 goto done;
7824 err = got_opentemp_named_fd(&logmsg_path, &fd,
7825 GOT_TMPDIR_STR "/got-logmsg");
7826 if (err)
7827 goto done;
7829 write(fd, logmsg, logmsg_len);
7830 close(fd);
7832 err = get_editor(&editor);
7833 if (err)
7834 goto done;
7836 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg);
7837 if (err) {
7838 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
7839 goto done;
7840 err = got_object_commit_get_logmsg(&hle->logmsg, commit);
7842 done:
7843 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
7844 err = got_error_from_errno2("unlink", logmsg_path);
7845 free(logmsg_path);
7846 free(logmsg);
7847 free(orig_logmsg);
7848 free(editor);
7849 if (commit)
7850 got_object_commit_close(commit);
7851 return err;
7854 static const struct got_error *
7855 histedit_parse_list(struct got_histedit_list *histedit_cmds,
7856 FILE *f, struct got_repository *repo)
7858 const struct got_error *err = NULL;
7859 char *line = NULL, *p, *end;
7860 size_t size;
7861 ssize_t len;
7862 int lineno = 0, i;
7863 const struct got_histedit_cmd *cmd;
7864 struct got_object_id *commit_id = NULL;
7865 struct got_histedit_list_entry *hle = NULL;
7867 for (;;) {
7868 len = getline(&line, &size, f);
7869 if (len == -1) {
7870 const struct got_error *getline_err;
7871 if (feof(f))
7872 break;
7873 getline_err = got_error_from_errno("getline");
7874 err = got_ferror(f, getline_err->code);
7875 break;
7877 lineno++;
7878 p = line;
7879 while (isspace((unsigned char)p[0]))
7880 p++;
7881 if (p[0] == '#' || p[0] == '\0') {
7882 free(line);
7883 line = NULL;
7884 continue;
7886 cmd = NULL;
7887 for (i = 0; i < nitems(got_histedit_cmds); i++) {
7888 cmd = &got_histedit_cmds[i];
7889 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
7890 isspace((unsigned char)p[strlen(cmd->name)])) {
7891 p += strlen(cmd->name);
7892 break;
7894 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
7895 p++;
7896 break;
7899 if (i == nitems(got_histedit_cmds)) {
7900 err = histedit_syntax_error(lineno);
7901 break;
7903 while (isspace((unsigned char)p[0]))
7904 p++;
7905 if (cmd->code == GOT_HISTEDIT_MESG) {
7906 if (hle == NULL || hle->logmsg != NULL) {
7907 err = got_error(GOT_ERR_HISTEDIT_CMD);
7908 break;
7910 if (p[0] == '\0') {
7911 err = histedit_edit_logmsg(hle, repo);
7912 if (err)
7913 break;
7914 } else {
7915 hle->logmsg = strdup(p);
7916 if (hle->logmsg == NULL) {
7917 err = got_error_from_errno("strdup");
7918 break;
7921 free(line);
7922 line = NULL;
7923 continue;
7924 } else {
7925 end = p;
7926 while (end[0] && !isspace((unsigned char)end[0]))
7927 end++;
7928 *end = '\0';
7930 err = got_object_resolve_id_str(&commit_id, repo, p);
7931 if (err) {
7932 /* override error code */
7933 err = histedit_syntax_error(lineno);
7934 break;
7937 hle = malloc(sizeof(*hle));
7938 if (hle == NULL) {
7939 err = got_error_from_errno("malloc");
7940 break;
7942 hle->cmd = cmd;
7943 hle->commit_id = commit_id;
7944 hle->logmsg = NULL;
7945 commit_id = NULL;
7946 free(line);
7947 line = NULL;
7948 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
7951 free(line);
7952 free(commit_id);
7953 return err;
7956 static const struct got_error *
7957 histedit_check_script(struct got_histedit_list *histedit_cmds,
7958 struct got_object_id_queue *commits, struct got_repository *repo)
7960 const struct got_error *err = NULL;
7961 struct got_object_qid *qid;
7962 struct got_histedit_list_entry *hle;
7963 static char msg[92];
7964 char *id_str;
7966 if (TAILQ_EMPTY(histedit_cmds))
7967 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
7968 "histedit script contains no commands");
7969 if (SIMPLEQ_EMPTY(commits))
7970 return got_error(GOT_ERR_EMPTY_HISTEDIT);
7972 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7973 struct got_histedit_list_entry *hle2;
7974 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
7975 if (hle == hle2)
7976 continue;
7977 if (got_object_id_cmp(hle->commit_id,
7978 hle2->commit_id) != 0)
7979 continue;
7980 err = got_object_id_str(&id_str, hle->commit_id);
7981 if (err)
7982 return err;
7983 snprintf(msg, sizeof(msg), "commit %s is listed "
7984 "more than once in histedit script", id_str);
7985 free(id_str);
7986 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
7990 SIMPLEQ_FOREACH(qid, commits, entry) {
7991 TAILQ_FOREACH(hle, histedit_cmds, entry) {
7992 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
7993 break;
7995 if (hle == NULL) {
7996 err = got_object_id_str(&id_str, qid->id);
7997 if (err)
7998 return err;
7999 snprintf(msg, sizeof(msg),
8000 "commit %s missing from histedit script", id_str);
8001 free(id_str);
8002 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
8006 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
8007 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
8008 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
8009 "last commit in histedit script cannot be folded");
8011 return NULL;
8014 static const struct got_error *
8015 histedit_run_editor(struct got_histedit_list *histedit_cmds,
8016 const char *path, struct got_object_id_queue *commits,
8017 struct got_repository *repo)
8019 const struct got_error *err = NULL;
8020 char *editor;
8021 FILE *f = NULL;
8023 err = get_editor(&editor);
8024 if (err)
8025 return err;
8027 if (spawn_editor(editor, path) == -1) {
8028 err = got_error_from_errno("failed spawning editor");
8029 goto done;
8032 f = fopen(path, "r");
8033 if (f == NULL) {
8034 err = got_error_from_errno("fopen");
8035 goto done;
8037 err = histedit_parse_list(histedit_cmds, f, repo);
8038 if (err)
8039 goto done;
8041 err = histedit_check_script(histedit_cmds, commits, repo);
8042 done:
8043 if (f && fclose(f) != 0 && err == NULL)
8044 err = got_error_from_errno("fclose");
8045 free(editor);
8046 return err;
8049 static const struct got_error *
8050 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
8051 struct got_object_id_queue *, const char *, const char *,
8052 struct got_repository *);
8054 static const struct got_error *
8055 histedit_edit_script(struct got_histedit_list *histedit_cmds,
8056 struct got_object_id_queue *commits, const char *branch_name,
8057 int edit_logmsg_only, struct got_repository *repo)
8059 const struct got_error *err;
8060 FILE *f = NULL;
8061 char *path = NULL;
8063 err = got_opentemp_named(&path, &f, "got-histedit");
8064 if (err)
8065 return err;
8067 err = write_cmd_list(f, branch_name, commits);
8068 if (err)
8069 goto done;
8071 err = histedit_write_commit_list(commits, f, edit_logmsg_only, repo);
8072 if (err)
8073 goto done;
8075 if (edit_logmsg_only) {
8076 rewind(f);
8077 err = histedit_parse_list(histedit_cmds, f, repo);
8078 } else {
8079 if (fclose(f) != 0) {
8080 err = got_error_from_errno("fclose");
8081 goto done;
8083 f = NULL;
8084 err = histedit_run_editor(histedit_cmds, path, commits, repo);
8085 if (err) {
8086 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8087 err->code != GOT_ERR_HISTEDIT_CMD)
8088 goto done;
8089 err = histedit_edit_list_retry(histedit_cmds, err,
8090 commits, path, branch_name, repo);
8093 done:
8094 if (f && fclose(f) != 0 && err == NULL)
8095 err = got_error_from_errno("fclose");
8096 if (path && unlink(path) != 0 && err == NULL)
8097 err = got_error_from_errno2("unlink", path);
8098 free(path);
8099 return err;
8102 static const struct got_error *
8103 histedit_save_list(struct got_histedit_list *histedit_cmds,
8104 struct got_worktree *worktree, struct got_repository *repo)
8106 const struct got_error *err = NULL;
8107 char *path = NULL;
8108 FILE *f = NULL;
8109 struct got_histedit_list_entry *hle;
8110 struct got_commit_object *commit = NULL;
8112 err = got_worktree_get_histedit_script_path(&path, worktree);
8113 if (err)
8114 return err;
8116 f = fopen(path, "w");
8117 if (f == NULL) {
8118 err = got_error_from_errno2("fopen", path);
8119 goto done;
8121 TAILQ_FOREACH(hle, histedit_cmds, entry) {
8122 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
8123 repo);
8124 if (err)
8125 break;
8127 if (hle->logmsg) {
8128 int n = fprintf(f, "%c %s\n",
8129 GOT_HISTEDIT_MESG, hle->logmsg);
8130 if (n < 0) {
8131 err = got_ferror(f, GOT_ERR_IO);
8132 break;
8136 done:
8137 if (f && fclose(f) != 0 && err == NULL)
8138 err = got_error_from_errno("fclose");
8139 free(path);
8140 if (commit)
8141 got_object_commit_close(commit);
8142 return err;
8145 void
8146 histedit_free_list(struct got_histedit_list *histedit_cmds)
8148 struct got_histedit_list_entry *hle;
8150 while ((hle = TAILQ_FIRST(histedit_cmds))) {
8151 TAILQ_REMOVE(histedit_cmds, hle, entry);
8152 free(hle);
8156 static const struct got_error *
8157 histedit_load_list(struct got_histedit_list *histedit_cmds,
8158 const char *path, struct got_repository *repo)
8160 const struct got_error *err = NULL;
8161 FILE *f = NULL;
8163 f = fopen(path, "r");
8164 if (f == NULL) {
8165 err = got_error_from_errno2("fopen", path);
8166 goto done;
8169 err = histedit_parse_list(histedit_cmds, f, repo);
8170 done:
8171 if (f && fclose(f) != 0 && err == NULL)
8172 err = got_error_from_errno("fclose");
8173 return err;
8176 static const struct got_error *
8177 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
8178 const struct got_error *edit_err, struct got_object_id_queue *commits,
8179 const char *path, const char *branch_name, struct got_repository *repo)
8181 const struct got_error *err = NULL, *prev_err = edit_err;
8182 int resp = ' ';
8184 while (resp != 'c' && resp != 'r' && resp != 'a') {
8185 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
8186 "or (a)bort: ", getprogname(), prev_err->msg);
8187 resp = getchar();
8188 if (resp == '\n')
8189 resp = getchar();
8190 if (resp == 'c') {
8191 histedit_free_list(histedit_cmds);
8192 err = histedit_run_editor(histedit_cmds, path, commits,
8193 repo);
8194 if (err) {
8195 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8196 err->code != GOT_ERR_HISTEDIT_CMD)
8197 break;
8198 prev_err = err;
8199 resp = ' ';
8200 continue;
8202 break;
8203 } else if (resp == 'r') {
8204 histedit_free_list(histedit_cmds);
8205 err = histedit_edit_script(histedit_cmds,
8206 commits, branch_name, 0, repo);
8207 if (err) {
8208 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
8209 err->code != GOT_ERR_HISTEDIT_CMD)
8210 break;
8211 prev_err = err;
8212 resp = ' ';
8213 continue;
8215 break;
8216 } else if (resp == 'a') {
8217 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
8218 break;
8219 } else
8220 printf("invalid response '%c'\n", resp);
8223 return err;
8226 static const struct got_error *
8227 histedit_complete(struct got_worktree *worktree,
8228 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
8229 struct got_reference *branch, struct got_repository *repo)
8231 printf("Switching work tree to %s\n",
8232 got_ref_get_symref_target(branch));
8233 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
8234 branch, repo);
8237 static const struct got_error *
8238 show_histedit_progress(struct got_commit_object *commit,
8239 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
8241 const struct got_error *err;
8242 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8244 err = got_object_id_str(&old_id_str, hle->commit_id);
8245 if (err)
8246 goto done;
8248 if (new_id) {
8249 err = got_object_id_str(&new_id_str, new_id);
8250 if (err)
8251 goto done;
8254 old_id_str[12] = '\0';
8255 if (new_id_str)
8256 new_id_str[12] = '\0';
8258 if (hle->logmsg) {
8259 logmsg = strdup(hle->logmsg);
8260 if (logmsg == NULL) {
8261 err = got_error_from_errno("strdup");
8262 goto done;
8264 trim_logmsg(logmsg, 42);
8265 } else {
8266 err = get_short_logmsg(&logmsg, 42, commit);
8267 if (err)
8268 goto done;
8271 switch (hle->cmd->code) {
8272 case GOT_HISTEDIT_PICK:
8273 case GOT_HISTEDIT_EDIT:
8274 printf("%s -> %s: %s\n", old_id_str,
8275 new_id_str ? new_id_str : "no-op change", logmsg);
8276 break;
8277 case GOT_HISTEDIT_DROP:
8278 case GOT_HISTEDIT_FOLD:
8279 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
8280 logmsg);
8281 break;
8282 default:
8283 break;
8285 done:
8286 free(old_id_str);
8287 free(new_id_str);
8288 return err;
8291 static const struct got_error *
8292 histedit_commit(struct got_pathlist_head *merged_paths,
8293 struct got_worktree *worktree, struct got_fileindex *fileindex,
8294 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
8295 struct got_repository *repo)
8297 const struct got_error *err;
8298 struct got_commit_object *commit;
8299 struct got_object_id *new_commit_id;
8301 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
8302 && hle->logmsg == NULL) {
8303 err = histedit_edit_logmsg(hle, repo);
8304 if (err)
8305 return err;
8308 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
8309 if (err)
8310 return err;
8312 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
8313 worktree, fileindex, tmp_branch, commit, hle->commit_id,
8314 hle->logmsg, repo);
8315 if (err) {
8316 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
8317 goto done;
8318 err = show_histedit_progress(commit, hle, NULL);
8319 } else {
8320 err = show_histedit_progress(commit, hle, new_commit_id);
8321 free(new_commit_id);
8323 done:
8324 got_object_commit_close(commit);
8325 return err;
8328 static const struct got_error *
8329 histedit_skip_commit(struct got_histedit_list_entry *hle,
8330 struct got_worktree *worktree, struct got_repository *repo)
8332 const struct got_error *error;
8333 struct got_commit_object *commit;
8335 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
8336 repo);
8337 if (error)
8338 return error;
8340 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
8341 if (error)
8342 return error;
8344 error = show_histedit_progress(commit, hle, NULL);
8345 got_object_commit_close(commit);
8346 return error;
8349 static const struct got_error *
8350 check_local_changes(void *arg, unsigned char status,
8351 unsigned char staged_status, const char *path,
8352 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8353 struct got_object_id *commit_id, int dirfd, const char *de_name)
8355 int *have_local_changes = arg;
8357 switch (status) {
8358 case GOT_STATUS_ADD:
8359 case GOT_STATUS_DELETE:
8360 case GOT_STATUS_MODIFY:
8361 case GOT_STATUS_CONFLICT:
8362 *have_local_changes = 1;
8363 return got_error(GOT_ERR_CANCELLED);
8364 default:
8365 break;
8368 switch (staged_status) {
8369 case GOT_STATUS_ADD:
8370 case GOT_STATUS_DELETE:
8371 case GOT_STATUS_MODIFY:
8372 *have_local_changes = 1;
8373 return got_error(GOT_ERR_CANCELLED);
8374 default:
8375 break;
8378 return NULL;
8381 static const struct got_error *
8382 cmd_histedit(int argc, char *argv[])
8384 const struct got_error *error = NULL;
8385 struct got_worktree *worktree = NULL;
8386 struct got_fileindex *fileindex = NULL;
8387 struct got_repository *repo = NULL;
8388 char *cwd = NULL;
8389 struct got_reference *branch = NULL;
8390 struct got_reference *tmp_branch = NULL;
8391 struct got_object_id *resume_commit_id = NULL;
8392 struct got_object_id *base_commit_id = NULL;
8393 struct got_object_id *head_commit_id = NULL;
8394 struct got_commit_object *commit = NULL;
8395 int ch, rebase_in_progress = 0;
8396 struct got_update_progress_arg upa;
8397 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
8398 int edit_logmsg_only = 0;
8399 const char *edit_script_path = NULL;
8400 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8401 struct got_object_id_queue commits;
8402 struct got_pathlist_head merged_paths;
8403 const struct got_object_id_queue *parent_ids;
8404 struct got_object_qid *pid;
8405 struct got_histedit_list histedit_cmds;
8406 struct got_histedit_list_entry *hle;
8408 SIMPLEQ_INIT(&commits);
8409 TAILQ_INIT(&histedit_cmds);
8410 TAILQ_INIT(&merged_paths);
8411 memset(&upa, 0, sizeof(upa));
8413 while ((ch = getopt(argc, argv, "acF:m")) != -1) {
8414 switch (ch) {
8415 case 'a':
8416 abort_edit = 1;
8417 break;
8418 case 'c':
8419 continue_edit = 1;
8420 break;
8421 case 'F':
8422 edit_script_path = optarg;
8423 break;
8424 case 'm':
8425 edit_logmsg_only = 1;
8426 break;
8427 default:
8428 usage_histedit();
8429 /* NOTREACHED */
8433 argc -= optind;
8434 argv += optind;
8436 #ifndef PROFILE
8437 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8438 "unveil", NULL) == -1)
8439 err(1, "pledge");
8440 #endif
8441 if (abort_edit && continue_edit)
8442 errx(1, "histedit's -a and -c options are mutually exclusive");
8443 if (edit_script_path && edit_logmsg_only)
8444 errx(1, "histedit's -F and -m options are mutually exclusive");
8445 if (abort_edit && edit_logmsg_only)
8446 errx(1, "histedit's -a and -m options are mutually exclusive");
8447 if (continue_edit && edit_logmsg_only)
8448 errx(1, "histedit's -c and -m options are mutually exclusive");
8449 if (argc != 0)
8450 usage_histedit();
8453 * This command cannot apply unveil(2) in all cases because the
8454 * user may choose to run an editor to edit the histedit script
8455 * and to edit individual commit log messages.
8456 * unveil(2) traverses exec(2); if an editor is used we have to
8457 * apply unveil after edit script and log messages have been written.
8458 * XXX TODO: Make use of unveil(2) where possible.
8461 cwd = getcwd(NULL, 0);
8462 if (cwd == NULL) {
8463 error = got_error_from_errno("getcwd");
8464 goto done;
8466 error = got_worktree_open(&worktree, cwd);
8467 if (error) {
8468 if (error->code == GOT_ERR_NOT_WORKTREE)
8469 error = wrap_not_worktree_error(error, "histedit", cwd);
8470 goto done;
8473 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8474 NULL);
8475 if (error != NULL)
8476 goto done;
8478 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8479 if (error)
8480 goto done;
8481 if (rebase_in_progress) {
8482 error = got_error(GOT_ERR_REBASING);
8483 goto done;
8486 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
8487 if (error)
8488 goto done;
8490 if (edit_in_progress && edit_logmsg_only) {
8491 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
8492 "histedit operation is in progress in this "
8493 "work tree and must be continued or aborted "
8494 "before the -m option can be used");
8495 goto done;
8498 if (edit_in_progress && abort_edit) {
8499 error = got_worktree_histedit_continue(&resume_commit_id,
8500 &tmp_branch, &branch, &base_commit_id, &fileindex,
8501 worktree, repo);
8502 if (error)
8503 goto done;
8504 printf("Switching work tree to %s\n",
8505 got_ref_get_symref_target(branch));
8506 error = got_worktree_histedit_abort(worktree, fileindex, repo,
8507 branch, base_commit_id, update_progress, &upa);
8508 if (error)
8509 goto done;
8510 printf("Histedit of %s aborted\n",
8511 got_ref_get_symref_target(branch));
8512 print_update_progress_stats(&upa);
8513 goto done; /* nothing else to do */
8514 } else if (abort_edit) {
8515 error = got_error(GOT_ERR_NOT_HISTEDIT);
8516 goto done;
8519 if (continue_edit) {
8520 char *path;
8522 if (!edit_in_progress) {
8523 error = got_error(GOT_ERR_NOT_HISTEDIT);
8524 goto done;
8527 error = got_worktree_get_histedit_script_path(&path, worktree);
8528 if (error)
8529 goto done;
8531 error = histedit_load_list(&histedit_cmds, path, repo);
8532 free(path);
8533 if (error)
8534 goto done;
8536 error = got_worktree_histedit_continue(&resume_commit_id,
8537 &tmp_branch, &branch, &base_commit_id, &fileindex,
8538 worktree, repo);
8539 if (error)
8540 goto done;
8542 error = got_ref_resolve(&head_commit_id, repo, branch);
8543 if (error)
8544 goto done;
8546 error = got_object_open_as_commit(&commit, repo,
8547 head_commit_id);
8548 if (error)
8549 goto done;
8550 parent_ids = got_object_commit_get_parent_ids(commit);
8551 pid = SIMPLEQ_FIRST(parent_ids);
8552 if (pid == NULL) {
8553 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8554 goto done;
8556 error = collect_commits(&commits, head_commit_id, pid->id,
8557 base_commit_id, got_worktree_get_path_prefix(worktree),
8558 GOT_ERR_HISTEDIT_PATH, repo);
8559 got_object_commit_close(commit);
8560 commit = NULL;
8561 if (error)
8562 goto done;
8563 } else {
8564 if (edit_in_progress) {
8565 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8566 goto done;
8569 error = got_ref_open(&branch, repo,
8570 got_worktree_get_head_ref_name(worktree), 0);
8571 if (error != NULL)
8572 goto done;
8574 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
8575 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
8576 "will not edit commit history of a branch outside "
8577 "the \"refs/heads/\" reference namespace");
8578 goto done;
8581 error = got_ref_resolve(&head_commit_id, repo, branch);
8582 got_ref_close(branch);
8583 branch = NULL;
8584 if (error)
8585 goto done;
8587 error = got_object_open_as_commit(&commit, repo,
8588 head_commit_id);
8589 if (error)
8590 goto done;
8591 parent_ids = got_object_commit_get_parent_ids(commit);
8592 pid = SIMPLEQ_FIRST(parent_ids);
8593 if (pid == NULL) {
8594 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8595 goto done;
8597 error = collect_commits(&commits, head_commit_id, pid->id,
8598 got_worktree_get_base_commit_id(worktree),
8599 got_worktree_get_path_prefix(worktree),
8600 GOT_ERR_HISTEDIT_PATH, repo);
8601 got_object_commit_close(commit);
8602 commit = NULL;
8603 if (error)
8604 goto done;
8606 if (SIMPLEQ_EMPTY(&commits)) {
8607 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
8608 goto done;
8611 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
8612 &base_commit_id, &fileindex, worktree, repo);
8613 if (error)
8614 goto done;
8616 if (edit_script_path) {
8617 error = histedit_load_list(&histedit_cmds,
8618 edit_script_path, repo);
8619 if (error) {
8620 got_worktree_histedit_abort(worktree, fileindex,
8621 repo, branch, base_commit_id,
8622 update_progress, &upa);
8623 print_update_progress_stats(&upa);
8624 goto done;
8626 } else {
8627 const char *branch_name;
8628 branch_name = got_ref_get_symref_target(branch);
8629 if (strncmp(branch_name, "refs/heads/", 11) == 0)
8630 branch_name += 11;
8631 error = histedit_edit_script(&histedit_cmds, &commits,
8632 branch_name, edit_logmsg_only, repo);
8633 if (error) {
8634 got_worktree_histedit_abort(worktree, fileindex,
8635 repo, branch, base_commit_id,
8636 update_progress, &upa);
8637 print_update_progress_stats(&upa);
8638 goto done;
8643 error = histedit_save_list(&histedit_cmds, worktree,
8644 repo);
8645 if (error) {
8646 got_worktree_histedit_abort(worktree, fileindex,
8647 repo, branch, base_commit_id,
8648 update_progress, &upa);
8649 print_update_progress_stats(&upa);
8650 goto done;
8655 error = histedit_check_script(&histedit_cmds, &commits, repo);
8656 if (error)
8657 goto done;
8659 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
8660 if (resume_commit_id) {
8661 if (got_object_id_cmp(hle->commit_id,
8662 resume_commit_id) != 0)
8663 continue;
8665 resume_commit_id = NULL;
8666 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
8667 hle->cmd->code == GOT_HISTEDIT_FOLD) {
8668 error = histedit_skip_commit(hle, worktree,
8669 repo);
8670 if (error)
8671 goto done;
8672 } else {
8673 struct got_pathlist_head paths;
8674 int have_changes = 0;
8676 TAILQ_INIT(&paths);
8677 error = got_pathlist_append(&paths, "", NULL);
8678 if (error)
8679 goto done;
8680 error = got_worktree_status(worktree, &paths,
8681 repo, check_local_changes, &have_changes,
8682 check_cancelled, NULL);
8683 got_pathlist_free(&paths);
8684 if (error) {
8685 if (error->code != GOT_ERR_CANCELLED)
8686 goto done;
8687 if (sigint_received || sigpipe_received)
8688 goto done;
8690 if (have_changes) {
8691 error = histedit_commit(NULL, worktree,
8692 fileindex, tmp_branch, hle, repo);
8693 if (error)
8694 goto done;
8695 } else {
8696 error = got_object_open_as_commit(
8697 &commit, repo, hle->commit_id);
8698 if (error)
8699 goto done;
8700 error = show_histedit_progress(commit,
8701 hle, NULL);
8702 got_object_commit_close(commit);
8703 commit = NULL;
8704 if (error)
8705 goto done;
8708 continue;
8711 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
8712 error = histedit_skip_commit(hle, worktree, repo);
8713 if (error)
8714 goto done;
8715 continue;
8718 error = got_object_open_as_commit(&commit, repo,
8719 hle->commit_id);
8720 if (error)
8721 goto done;
8722 parent_ids = got_object_commit_get_parent_ids(commit);
8723 pid = SIMPLEQ_FIRST(parent_ids);
8725 error = got_worktree_histedit_merge_files(&merged_paths,
8726 worktree, fileindex, pid->id, hle->commit_id, repo,
8727 update_progress, &upa, check_cancelled, NULL);
8728 if (error)
8729 goto done;
8730 got_object_commit_close(commit);
8731 commit = NULL;
8733 print_update_progress_stats(&upa);
8734 if (upa.conflicts > 0)
8735 rebase_status = GOT_STATUS_CONFLICT;
8737 if (rebase_status == GOT_STATUS_CONFLICT) {
8738 error = show_rebase_merge_conflict(hle->commit_id,
8739 repo);
8740 if (error)
8741 goto done;
8742 got_worktree_rebase_pathlist_free(&merged_paths);
8743 break;
8746 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
8747 char *id_str;
8748 error = got_object_id_str(&id_str, hle->commit_id);
8749 if (error)
8750 goto done;
8751 printf("Stopping histedit for amending commit %s\n",
8752 id_str);
8753 free(id_str);
8754 got_worktree_rebase_pathlist_free(&merged_paths);
8755 error = got_worktree_histedit_postpone(worktree,
8756 fileindex);
8757 goto done;
8760 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
8761 error = histedit_skip_commit(hle, worktree, repo);
8762 if (error)
8763 goto done;
8764 continue;
8767 error = histedit_commit(&merged_paths, worktree, fileindex,
8768 tmp_branch, hle, repo);
8769 got_worktree_rebase_pathlist_free(&merged_paths);
8770 if (error)
8771 goto done;
8774 if (rebase_status == GOT_STATUS_CONFLICT) {
8775 error = got_worktree_histedit_postpone(worktree, fileindex);
8776 if (error)
8777 goto done;
8778 error = got_error_msg(GOT_ERR_CONFLICTS,
8779 "conflicts must be resolved before histedit can continue");
8780 } else
8781 error = histedit_complete(worktree, fileindex, tmp_branch,
8782 branch, repo);
8783 done:
8784 got_object_id_queue_free(&commits);
8785 histedit_free_list(&histedit_cmds);
8786 free(head_commit_id);
8787 free(base_commit_id);
8788 free(resume_commit_id);
8789 if (commit)
8790 got_object_commit_close(commit);
8791 if (branch)
8792 got_ref_close(branch);
8793 if (tmp_branch)
8794 got_ref_close(tmp_branch);
8795 if (worktree)
8796 got_worktree_close(worktree);
8797 if (repo)
8798 got_repo_close(repo);
8799 return error;
8802 __dead static void
8803 usage_integrate(void)
8805 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
8806 exit(1);
8809 static const struct got_error *
8810 cmd_integrate(int argc, char *argv[])
8812 const struct got_error *error = NULL;
8813 struct got_repository *repo = NULL;
8814 struct got_worktree *worktree = NULL;
8815 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
8816 const char *branch_arg = NULL;
8817 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
8818 struct got_fileindex *fileindex = NULL;
8819 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
8820 int ch;
8821 struct got_update_progress_arg upa;
8823 while ((ch = getopt(argc, argv, "")) != -1) {
8824 switch (ch) {
8825 default:
8826 usage_integrate();
8827 /* NOTREACHED */
8831 argc -= optind;
8832 argv += optind;
8834 if (argc != 1)
8835 usage_integrate();
8836 branch_arg = argv[0];
8838 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8839 "unveil", NULL) == -1)
8840 err(1, "pledge");
8842 cwd = getcwd(NULL, 0);
8843 if (cwd == NULL) {
8844 error = got_error_from_errno("getcwd");
8845 goto done;
8848 error = got_worktree_open(&worktree, cwd);
8849 if (error) {
8850 if (error->code == GOT_ERR_NOT_WORKTREE)
8851 error = wrap_not_worktree_error(error, "integrate",
8852 cwd);
8853 goto done;
8856 error = check_rebase_or_histedit_in_progress(worktree);
8857 if (error)
8858 goto done;
8860 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8861 NULL);
8862 if (error != NULL)
8863 goto done;
8865 error = apply_unveil(got_repo_get_path(repo), 0,
8866 got_worktree_get_root_path(worktree));
8867 if (error)
8868 goto done;
8870 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
8871 error = got_error_from_errno("asprintf");
8872 goto done;
8875 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
8876 &base_branch_ref, worktree, refname, repo);
8877 if (error)
8878 goto done;
8880 refname = strdup(got_ref_get_name(branch_ref));
8881 if (refname == NULL) {
8882 error = got_error_from_errno("strdup");
8883 got_worktree_integrate_abort(worktree, fileindex, repo,
8884 branch_ref, base_branch_ref);
8885 goto done;
8887 base_refname = strdup(got_ref_get_name(base_branch_ref));
8888 if (base_refname == NULL) {
8889 error = got_error_from_errno("strdup");
8890 got_worktree_integrate_abort(worktree, fileindex, repo,
8891 branch_ref, base_branch_ref);
8892 goto done;
8895 error = got_ref_resolve(&commit_id, repo, branch_ref);
8896 if (error)
8897 goto done;
8899 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
8900 if (error)
8901 goto done;
8903 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
8904 error = got_error_msg(GOT_ERR_SAME_BRANCH,
8905 "specified branch has already been integrated");
8906 got_worktree_integrate_abort(worktree, fileindex, repo,
8907 branch_ref, base_branch_ref);
8908 goto done;
8911 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
8912 if (error) {
8913 if (error->code == GOT_ERR_ANCESTRY)
8914 error = got_error(GOT_ERR_REBASE_REQUIRED);
8915 got_worktree_integrate_abort(worktree, fileindex, repo,
8916 branch_ref, base_branch_ref);
8917 goto done;
8920 memset(&upa, 0, sizeof(upa));
8921 error = got_worktree_integrate_continue(worktree, fileindex, repo,
8922 branch_ref, base_branch_ref, update_progress, &upa,
8923 check_cancelled, NULL);
8924 if (error)
8925 goto done;
8927 printf("Integrated %s into %s\n", refname, base_refname);
8928 print_update_progress_stats(&upa);
8929 done:
8930 if (repo)
8931 got_repo_close(repo);
8932 if (worktree)
8933 got_worktree_close(worktree);
8934 free(cwd);
8935 free(base_commit_id);
8936 free(commit_id);
8937 free(refname);
8938 free(base_refname);
8939 return error;
8942 __dead static void
8943 usage_stage(void)
8945 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
8946 "[-S] [file-path ...]\n",
8947 getprogname());
8948 exit(1);
8951 static const struct got_error *
8952 print_stage(void *arg, unsigned char status, unsigned char staged_status,
8953 const char *path, struct got_object_id *blob_id,
8954 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
8955 int dirfd, const char *de_name)
8957 const struct got_error *err = NULL;
8958 char *id_str = NULL;
8960 if (staged_status != GOT_STATUS_ADD &&
8961 staged_status != GOT_STATUS_MODIFY &&
8962 staged_status != GOT_STATUS_DELETE)
8963 return NULL;
8965 if (staged_status == GOT_STATUS_ADD ||
8966 staged_status == GOT_STATUS_MODIFY)
8967 err = got_object_id_str(&id_str, staged_blob_id);
8968 else
8969 err = got_object_id_str(&id_str, blob_id);
8970 if (err)
8971 return err;
8973 printf("%s %c %s\n", id_str, staged_status, path);
8974 free(id_str);
8975 return NULL;
8978 static const struct got_error *
8979 cmd_stage(int argc, char *argv[])
8981 const struct got_error *error = NULL;
8982 struct got_repository *repo = NULL;
8983 struct got_worktree *worktree = NULL;
8984 char *cwd = NULL;
8985 struct got_pathlist_head paths;
8986 struct got_pathlist_entry *pe;
8987 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
8988 FILE *patch_script_file = NULL;
8989 const char *patch_script_path = NULL;
8990 struct choose_patch_arg cpa;
8992 TAILQ_INIT(&paths);
8994 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
8995 switch (ch) {
8996 case 'l':
8997 list_stage = 1;
8998 break;
8999 case 'p':
9000 pflag = 1;
9001 break;
9002 case 'F':
9003 patch_script_path = optarg;
9004 break;
9005 case 'S':
9006 allow_bad_symlinks = 1;
9007 break;
9008 default:
9009 usage_stage();
9010 /* NOTREACHED */
9014 argc -= optind;
9015 argv += optind;
9017 #ifndef PROFILE
9018 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9019 "unveil", NULL) == -1)
9020 err(1, "pledge");
9021 #endif
9022 if (list_stage && (pflag || patch_script_path))
9023 errx(1, "-l option cannot be used with other options");
9024 if (patch_script_path && !pflag)
9025 errx(1, "-F option can only be used together with -p option");
9027 cwd = getcwd(NULL, 0);
9028 if (cwd == NULL) {
9029 error = got_error_from_errno("getcwd");
9030 goto done;
9033 error = got_worktree_open(&worktree, cwd);
9034 if (error) {
9035 if (error->code == GOT_ERR_NOT_WORKTREE)
9036 error = wrap_not_worktree_error(error, "stage", cwd);
9037 goto done;
9040 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9041 NULL);
9042 if (error != NULL)
9043 goto done;
9045 if (patch_script_path) {
9046 patch_script_file = fopen(patch_script_path, "r");
9047 if (patch_script_file == NULL) {
9048 error = got_error_from_errno2("fopen",
9049 patch_script_path);
9050 goto done;
9053 error = apply_unveil(got_repo_get_path(repo), 0,
9054 got_worktree_get_root_path(worktree));
9055 if (error)
9056 goto done;
9058 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9059 if (error)
9060 goto done;
9062 if (list_stage)
9063 error = got_worktree_status(worktree, &paths, repo,
9064 print_stage, NULL, check_cancelled, NULL);
9065 else {
9066 cpa.patch_script_file = patch_script_file;
9067 cpa.action = "stage";
9068 error = got_worktree_stage(worktree, &paths,
9069 pflag ? NULL : print_status, NULL,
9070 pflag ? choose_patch : NULL, &cpa,
9071 allow_bad_symlinks, repo);
9073 done:
9074 if (patch_script_file && fclose(patch_script_file) == EOF &&
9075 error == NULL)
9076 error = got_error_from_errno2("fclose", patch_script_path);
9077 if (repo)
9078 got_repo_close(repo);
9079 if (worktree)
9080 got_worktree_close(worktree);
9081 TAILQ_FOREACH(pe, &paths, entry)
9082 free((char *)pe->path);
9083 got_pathlist_free(&paths);
9084 free(cwd);
9085 return error;
9088 __dead static void
9089 usage_unstage(void)
9091 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
9092 "[file-path ...]\n",
9093 getprogname());
9094 exit(1);
9098 static const struct got_error *
9099 cmd_unstage(int argc, char *argv[])
9101 const struct got_error *error = NULL;
9102 struct got_repository *repo = NULL;
9103 struct got_worktree *worktree = NULL;
9104 char *cwd = NULL;
9105 struct got_pathlist_head paths;
9106 struct got_pathlist_entry *pe;
9107 int ch, pflag = 0;
9108 struct got_update_progress_arg upa;
9109 FILE *patch_script_file = NULL;
9110 const char *patch_script_path = NULL;
9111 struct choose_patch_arg cpa;
9113 TAILQ_INIT(&paths);
9115 while ((ch = getopt(argc, argv, "pF:")) != -1) {
9116 switch (ch) {
9117 case 'p':
9118 pflag = 1;
9119 break;
9120 case 'F':
9121 patch_script_path = optarg;
9122 break;
9123 default:
9124 usage_unstage();
9125 /* NOTREACHED */
9129 argc -= optind;
9130 argv += optind;
9132 #ifndef PROFILE
9133 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9134 "unveil", NULL) == -1)
9135 err(1, "pledge");
9136 #endif
9137 if (patch_script_path && !pflag)
9138 errx(1, "-F option can only be used together with -p option");
9140 cwd = getcwd(NULL, 0);
9141 if (cwd == NULL) {
9142 error = got_error_from_errno("getcwd");
9143 goto done;
9146 error = got_worktree_open(&worktree, cwd);
9147 if (error) {
9148 if (error->code == GOT_ERR_NOT_WORKTREE)
9149 error = wrap_not_worktree_error(error, "unstage", cwd);
9150 goto done;
9153 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9154 NULL);
9155 if (error != NULL)
9156 goto done;
9158 if (patch_script_path) {
9159 patch_script_file = fopen(patch_script_path, "r");
9160 if (patch_script_file == NULL) {
9161 error = got_error_from_errno2("fopen",
9162 patch_script_path);
9163 goto done;
9167 error = apply_unveil(got_repo_get_path(repo), 0,
9168 got_worktree_get_root_path(worktree));
9169 if (error)
9170 goto done;
9172 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9173 if (error)
9174 goto done;
9176 cpa.patch_script_file = patch_script_file;
9177 cpa.action = "unstage";
9178 memset(&upa, 0, sizeof(upa));
9179 error = got_worktree_unstage(worktree, &paths, update_progress,
9180 &upa, pflag ? choose_patch : NULL, &cpa, repo);
9181 if (!error)
9182 print_update_progress_stats(&upa);
9183 done:
9184 if (patch_script_file && fclose(patch_script_file) == EOF &&
9185 error == NULL)
9186 error = got_error_from_errno2("fclose", patch_script_path);
9187 if (repo)
9188 got_repo_close(repo);
9189 if (worktree)
9190 got_worktree_close(worktree);
9191 TAILQ_FOREACH(pe, &paths, entry)
9192 free((char *)pe->path);
9193 got_pathlist_free(&paths);
9194 free(cwd);
9195 return error;
9198 __dead static void
9199 usage_cat(void)
9201 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
9202 "arg1 [arg2 ...]\n", getprogname());
9203 exit(1);
9206 static const struct got_error *
9207 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9209 const struct got_error *err;
9210 struct got_blob_object *blob;
9212 err = got_object_open_as_blob(&blob, repo, id, 8192);
9213 if (err)
9214 return err;
9216 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
9217 got_object_blob_close(blob);
9218 return err;
9221 static const struct got_error *
9222 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9224 const struct got_error *err;
9225 struct got_tree_object *tree;
9226 int nentries, i;
9228 err = got_object_open_as_tree(&tree, repo, id);
9229 if (err)
9230 return err;
9232 nentries = got_object_tree_get_nentries(tree);
9233 for (i = 0; i < nentries; i++) {
9234 struct got_tree_entry *te;
9235 char *id_str;
9236 if (sigint_received || sigpipe_received)
9237 break;
9238 te = got_object_tree_get_entry(tree, i);
9239 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
9240 if (err)
9241 break;
9242 fprintf(outfile, "%s %.7o %s\n", id_str,
9243 got_tree_entry_get_mode(te),
9244 got_tree_entry_get_name(te));
9245 free(id_str);
9248 got_object_tree_close(tree);
9249 return err;
9252 static const struct got_error *
9253 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9255 const struct got_error *err;
9256 struct got_commit_object *commit;
9257 const struct got_object_id_queue *parent_ids;
9258 struct got_object_qid *pid;
9259 char *id_str = NULL;
9260 const char *logmsg = NULL;
9262 err = got_object_open_as_commit(&commit, repo, id);
9263 if (err)
9264 return err;
9266 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
9267 if (err)
9268 goto done;
9270 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
9271 parent_ids = got_object_commit_get_parent_ids(commit);
9272 fprintf(outfile, "numparents %d\n",
9273 got_object_commit_get_nparents(commit));
9274 SIMPLEQ_FOREACH(pid, parent_ids, entry) {
9275 char *pid_str;
9276 err = got_object_id_str(&pid_str, pid->id);
9277 if (err)
9278 goto done;
9279 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
9280 free(pid_str);
9282 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
9283 got_object_commit_get_author(commit),
9284 got_object_commit_get_author_time(commit));
9286 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
9287 got_object_commit_get_author(commit),
9288 got_object_commit_get_committer_time(commit));
9290 logmsg = got_object_commit_get_logmsg_raw(commit);
9291 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
9292 fprintf(outfile, "%s", logmsg);
9293 done:
9294 free(id_str);
9295 got_object_commit_close(commit);
9296 return err;
9299 static const struct got_error *
9300 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
9302 const struct got_error *err;
9303 struct got_tag_object *tag;
9304 char *id_str = NULL;
9305 const char *tagmsg = NULL;
9307 err = got_object_open_as_tag(&tag, repo, id);
9308 if (err)
9309 return err;
9311 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
9312 if (err)
9313 goto done;
9315 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
9317 switch (got_object_tag_get_object_type(tag)) {
9318 case GOT_OBJ_TYPE_BLOB:
9319 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9320 GOT_OBJ_LABEL_BLOB);
9321 break;
9322 case GOT_OBJ_TYPE_TREE:
9323 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9324 GOT_OBJ_LABEL_TREE);
9325 break;
9326 case GOT_OBJ_TYPE_COMMIT:
9327 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9328 GOT_OBJ_LABEL_COMMIT);
9329 break;
9330 case GOT_OBJ_TYPE_TAG:
9331 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
9332 GOT_OBJ_LABEL_TAG);
9333 break;
9334 default:
9335 break;
9338 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
9339 got_object_tag_get_name(tag));
9341 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
9342 got_object_tag_get_tagger(tag),
9343 got_object_tag_get_tagger_time(tag));
9345 tagmsg = got_object_tag_get_message(tag);
9346 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
9347 fprintf(outfile, "%s", tagmsg);
9348 done:
9349 free(id_str);
9350 got_object_tag_close(tag);
9351 return err;
9354 static const struct got_error *
9355 cmd_cat(int argc, char *argv[])
9357 const struct got_error *error;
9358 struct got_repository *repo = NULL;
9359 struct got_worktree *worktree = NULL;
9360 char *cwd = NULL, *repo_path = NULL, *label = NULL;
9361 const char *commit_id_str = NULL;
9362 struct got_object_id *id = NULL, *commit_id = NULL;
9363 int ch, obj_type, i, force_path = 0;
9365 #ifndef PROFILE
9366 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9367 NULL) == -1)
9368 err(1, "pledge");
9369 #endif
9371 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
9372 switch (ch) {
9373 case 'c':
9374 commit_id_str = optarg;
9375 break;
9376 case 'r':
9377 repo_path = realpath(optarg, NULL);
9378 if (repo_path == NULL)
9379 return got_error_from_errno2("realpath",
9380 optarg);
9381 got_path_strip_trailing_slashes(repo_path);
9382 break;
9383 case 'P':
9384 force_path = 1;
9385 break;
9386 default:
9387 usage_cat();
9388 /* NOTREACHED */
9392 argc -= optind;
9393 argv += optind;
9395 cwd = getcwd(NULL, 0);
9396 if (cwd == NULL) {
9397 error = got_error_from_errno("getcwd");
9398 goto done;
9400 error = got_worktree_open(&worktree, cwd);
9401 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9402 goto done;
9403 if (worktree) {
9404 if (repo_path == NULL) {
9405 repo_path = strdup(
9406 got_worktree_get_repo_path(worktree));
9407 if (repo_path == NULL) {
9408 error = got_error_from_errno("strdup");
9409 goto done;
9414 if (repo_path == NULL) {
9415 repo_path = getcwd(NULL, 0);
9416 if (repo_path == NULL)
9417 return got_error_from_errno("getcwd");
9420 error = got_repo_open(&repo, repo_path, NULL);
9421 free(repo_path);
9422 if (error != NULL)
9423 goto done;
9425 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
9426 if (error)
9427 goto done;
9429 if (commit_id_str == NULL)
9430 commit_id_str = GOT_REF_HEAD;
9431 error = got_repo_match_object_id(&commit_id, NULL,
9432 commit_id_str, GOT_OBJ_TYPE_COMMIT, 1, repo);
9433 if (error)
9434 goto done;
9436 for (i = 0; i < argc; i++) {
9437 if (force_path) {
9438 error = got_object_id_by_path(&id, repo, commit_id,
9439 argv[i]);
9440 if (error)
9441 break;
9442 } else {
9443 error = got_repo_match_object_id(&id, &label, argv[i],
9444 GOT_OBJ_TYPE_ANY, 0, repo);
9445 if (error) {
9446 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
9447 error->code != GOT_ERR_NOT_REF)
9448 break;
9449 error = got_object_id_by_path(&id, repo,
9450 commit_id, argv[i]);
9451 if (error)
9452 break;
9456 error = got_object_get_type(&obj_type, repo, id);
9457 if (error)
9458 break;
9460 switch (obj_type) {
9461 case GOT_OBJ_TYPE_BLOB:
9462 error = cat_blob(id, repo, stdout);
9463 break;
9464 case GOT_OBJ_TYPE_TREE:
9465 error = cat_tree(id, repo, stdout);
9466 break;
9467 case GOT_OBJ_TYPE_COMMIT:
9468 error = cat_commit(id, repo, stdout);
9469 break;
9470 case GOT_OBJ_TYPE_TAG:
9471 error = cat_tag(id, repo, stdout);
9472 break;
9473 default:
9474 error = got_error(GOT_ERR_OBJ_TYPE);
9475 break;
9477 if (error)
9478 break;
9479 free(label);
9480 label = NULL;
9481 free(id);
9482 id = NULL;
9484 done:
9485 free(label);
9486 free(id);
9487 free(commit_id);
9488 if (worktree)
9489 got_worktree_close(worktree);
9490 if (repo) {
9491 const struct got_error *repo_error;
9492 repo_error = got_repo_close(repo);
9493 if (error == NULL)
9494 error = repo_error;
9496 return error;
9499 __dead static void
9500 usage_info(void)
9502 fprintf(stderr, "usage: %s info [path ...]\n",
9503 getprogname());
9504 exit(1);
9507 static const struct got_error *
9508 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
9509 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9510 struct got_object_id *commit_id)
9512 const struct got_error *err = NULL;
9513 char *id_str = NULL;
9514 char datebuf[128];
9515 struct tm mytm, *tm;
9516 struct got_pathlist_head *paths = arg;
9517 struct got_pathlist_entry *pe;
9520 * Clear error indication from any of the path arguments which
9521 * would cause this file index entry to be displayed.
9523 TAILQ_FOREACH(pe, paths, entry) {
9524 if (got_path_cmp(path, pe->path, strlen(path),
9525 pe->path_len) == 0 ||
9526 got_path_is_child(path, pe->path, pe->path_len))
9527 pe->data = NULL; /* no error */
9530 printf(GOT_COMMIT_SEP_STR);
9531 if (S_ISLNK(mode))
9532 printf("symlink: %s\n", path);
9533 else if (S_ISREG(mode)) {
9534 printf("file: %s\n", path);
9535 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9536 } else if (S_ISDIR(mode))
9537 printf("directory: %s\n", path);
9538 else
9539 printf("something: %s\n", path);
9541 tm = localtime_r(&mtime, &mytm);
9542 if (tm == NULL)
9543 return NULL;
9544 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) >= sizeof(datebuf))
9545 return got_error(GOT_ERR_NO_SPACE);
9546 printf("timestamp: %s\n", datebuf);
9548 if (blob_id) {
9549 err = got_object_id_str(&id_str, blob_id);
9550 if (err)
9551 return err;
9552 printf("based on blob: %s\n", id_str);
9553 free(id_str);
9556 if (staged_blob_id) {
9557 err = got_object_id_str(&id_str, staged_blob_id);
9558 if (err)
9559 return err;
9560 printf("based on staged blob: %s\n", id_str);
9561 free(id_str);
9564 if (commit_id) {
9565 err = got_object_id_str(&id_str, commit_id);
9566 if (err)
9567 return err;
9568 printf("based on commit: %s\n", id_str);
9569 free(id_str);
9572 return NULL;
9575 static const struct got_error *
9576 cmd_info(int argc, char *argv[])
9578 const struct got_error *error = NULL;
9579 struct got_worktree *worktree = NULL;
9580 char *cwd = NULL, *id_str = NULL;
9581 struct got_pathlist_head paths;
9582 struct got_pathlist_entry *pe;
9583 char *uuidstr = NULL;
9584 int ch, show_files = 0;
9586 TAILQ_INIT(&paths);
9588 while ((ch = getopt(argc, argv, "")) != -1) {
9589 switch (ch) {
9590 default:
9591 usage_info();
9592 /* NOTREACHED */
9596 argc -= optind;
9597 argv += optind;
9599 #ifndef PROFILE
9600 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
9601 NULL) == -1)
9602 err(1, "pledge");
9603 #endif
9604 cwd = getcwd(NULL, 0);
9605 if (cwd == NULL) {
9606 error = got_error_from_errno("getcwd");
9607 goto done;
9610 error = got_worktree_open(&worktree, cwd);
9611 if (error) {
9612 if (error->code == GOT_ERR_NOT_WORKTREE)
9613 error = wrap_not_worktree_error(error, "status", cwd);
9614 goto done;
9617 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9618 if (error)
9619 goto done;
9621 if (argc >= 1) {
9622 error = get_worktree_paths_from_argv(&paths, argc, argv,
9623 worktree);
9624 if (error)
9625 goto done;
9626 show_files = 1;
9629 error = got_object_id_str(&id_str,
9630 got_worktree_get_base_commit_id(worktree));
9631 if (error)
9632 goto done;
9634 error = got_worktree_get_uuid(&uuidstr, worktree);
9635 if (error)
9636 goto done;
9638 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9639 printf("work tree base commit: %s\n", id_str);
9640 printf("work tree path prefix: %s\n",
9641 got_worktree_get_path_prefix(worktree));
9642 printf("work tree branch reference: %s\n",
9643 got_worktree_get_head_ref_name(worktree));
9644 printf("work tree UUID: %s\n", uuidstr);
9645 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9647 if (show_files) {
9648 struct got_pathlist_entry *pe;
9649 TAILQ_FOREACH(pe, &paths, entry) {
9650 if (pe->path_len == 0)
9651 continue;
9653 * Assume this path will fail. This will be corrected
9654 * in print_path_info() in case the path does suceeed.
9656 pe->data = (void *)got_error_path(pe->path,
9657 GOT_ERR_BAD_PATH);
9659 error = got_worktree_path_info(worktree, &paths,
9660 print_path_info, &paths, check_cancelled, NULL);
9661 if (error)
9662 goto done;
9663 TAILQ_FOREACH(pe, &paths, entry) {
9664 if (pe->data != NULL) {
9665 error = pe->data; /* bad path */
9666 break;
9670 done:
9671 TAILQ_FOREACH(pe, &paths, entry)
9672 free((char *)pe->path);
9673 got_pathlist_free(&paths);
9674 free(cwd);
9675 free(id_str);
9676 free(uuidstr);
9677 return error;