Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
40 #include <util.h>
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
60 #ifndef nitems
61 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
62 #endif
64 static volatile sig_atomic_t sigint_received;
65 static volatile sig_atomic_t sigpipe_received;
67 static void
68 catch_sigint(int signo)
69 {
70 sigint_received = 1;
71 }
73 static void
74 catch_sigpipe(int signo)
75 {
76 sigpipe_received = 1;
77 }
80 struct got_cmd {
81 const char *cmd_name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 const char *cmd_alias;
85 };
87 __dead static void usage(int, int);
88 __dead static void usage_init(void);
89 __dead static void usage_import(void);
90 __dead static void usage_clone(void);
91 __dead static void usage_fetch(void);
92 __dead static void usage_checkout(void);
93 __dead static void usage_update(void);
94 __dead static void usage_log(void);
95 __dead static void usage_diff(void);
96 __dead static void usage_blame(void);
97 __dead static void usage_tree(void);
98 __dead static void usage_status(void);
99 __dead static void usage_ref(void);
100 __dead static void usage_branch(void);
101 __dead static void usage_tag(void);
102 __dead static void usage_add(void);
103 __dead static void usage_remove(void);
104 __dead static void usage_revert(void);
105 __dead static void usage_commit(void);
106 __dead static void usage_send(void);
107 __dead static void usage_cherrypick(void);
108 __dead static void usage_backout(void);
109 __dead static void usage_rebase(void);
110 __dead static void usage_histedit(void);
111 __dead static void usage_integrate(void);
112 __dead static void usage_stage(void);
113 __dead static void usage_unstage(void);
114 __dead static void usage_cat(void);
115 __dead static void usage_info(void);
117 static const struct got_error* cmd_init(int, char *[]);
118 static const struct got_error* cmd_import(int, char *[]);
119 static const struct got_error* cmd_clone(int, char *[]);
120 static const struct got_error* cmd_fetch(int, char *[]);
121 static const struct got_error* cmd_checkout(int, char *[]);
122 static const struct got_error* cmd_update(int, char *[]);
123 static const struct got_error* cmd_log(int, char *[]);
124 static const struct got_error* cmd_diff(int, char *[]);
125 static const struct got_error* cmd_blame(int, char *[]);
126 static const struct got_error* cmd_tree(int, char *[]);
127 static const struct got_error* cmd_status(int, char *[]);
128 static const struct got_error* cmd_ref(int, char *[]);
129 static const struct got_error* cmd_branch(int, char *[]);
130 static const struct got_error* cmd_tag(int, char *[]);
131 static const struct got_error* cmd_add(int, char *[]);
132 static const struct got_error* cmd_remove(int, char *[]);
133 static const struct got_error* cmd_revert(int, char *[]);
134 static const struct got_error* cmd_commit(int, char *[]);
135 static const struct got_error* cmd_send(int, char *[]);
136 static const struct got_error* cmd_cherrypick(int, char *[]);
137 static const struct got_error* cmd_backout(int, char *[]);
138 static const struct got_error* cmd_rebase(int, char *[]);
139 static const struct got_error* cmd_histedit(int, char *[]);
140 static const struct got_error* cmd_integrate(int, char *[]);
141 static const struct got_error* cmd_stage(int, char *[]);
142 static const struct got_error* cmd_unstage(int, char *[]);
143 static const struct got_error* cmd_cat(int, char *[]);
144 static const struct got_error* cmd_info(int, char *[]);
146 static struct got_cmd got_commands[] = {
147 { "init", cmd_init, usage_init, "" },
148 { "import", cmd_import, usage_import, "im" },
149 { "clone", cmd_clone, usage_clone, "cl" },
150 { "fetch", cmd_fetch, usage_fetch, "fe" },
151 { "checkout", cmd_checkout, usage_checkout, "co" },
152 { "update", cmd_update, usage_update, "up" },
153 { "log", cmd_log, usage_log, "" },
154 { "diff", cmd_diff, usage_diff, "di" },
155 { "blame", cmd_blame, usage_blame, "bl" },
156 { "tree", cmd_tree, usage_tree, "tr" },
157 { "status", cmd_status, usage_status, "st" },
158 { "ref", cmd_ref, usage_ref, "" },
159 { "branch", cmd_branch, usage_branch, "br" },
160 { "tag", cmd_tag, usage_tag, "" },
161 { "add", cmd_add, usage_add, "" },
162 { "remove", cmd_remove, usage_remove, "rm" },
163 { "revert", cmd_revert, usage_revert, "rv" },
164 { "commit", cmd_commit, usage_commit, "ci" },
165 { "send", cmd_send, usage_send, "se" },
166 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
167 { "backout", cmd_backout, usage_backout, "bo" },
168 { "rebase", cmd_rebase, usage_rebase, "rb" },
169 { "histedit", cmd_histedit, usage_histedit, "he" },
170 { "integrate", cmd_integrate, usage_integrate,"ig" },
171 { "stage", cmd_stage, usage_stage, "sg" },
172 { "unstage", cmd_unstage, usage_unstage, "ug" },
173 { "cat", cmd_cat, usage_cat, "" },
174 { "info", cmd_info, usage_info, "" },
175 };
177 static void
178 list_commands(FILE *fp)
180 size_t i;
182 fprintf(fp, "commands:");
183 for (i = 0; i < nitems(got_commands); i++) {
184 struct got_cmd *cmd = &got_commands[i];
185 fprintf(fp, " %s", cmd->cmd_name);
187 fputc('\n', fp);
190 __dead static void
191 option_conflict(char a, char b)
193 errx(1, "-%c and -%c options are mutually exclusive", a, b);
196 int
197 main(int argc, char *argv[])
199 struct got_cmd *cmd;
200 size_t i;
201 int ch;
202 int hflag = 0, Vflag = 0;
203 static struct option longopts[] = {
204 { "version", no_argument, NULL, 'V' },
205 { NULL, 0, NULL, 0 }
206 };
208 setlocale(LC_CTYPE, "");
210 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
211 switch (ch) {
212 case 'h':
213 hflag = 1;
214 break;
215 case 'V':
216 Vflag = 1;
217 break;
218 default:
219 usage(hflag, 1);
220 /* NOTREACHED */
224 argc -= optind;
225 argv += optind;
226 optind = 1;
227 optreset = 1;
229 if (Vflag) {
230 got_version_print_str();
231 return 0;
234 if (argc <= 0)
235 usage(hflag, hflag ? 0 : 1);
237 signal(SIGINT, catch_sigint);
238 signal(SIGPIPE, catch_sigpipe);
240 for (i = 0; i < nitems(got_commands); i++) {
241 const struct got_error *error;
243 cmd = &got_commands[i];
245 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
246 strcmp(cmd->cmd_alias, argv[0]) != 0)
247 continue;
249 if (hflag)
250 got_commands[i].cmd_usage();
252 error = got_commands[i].cmd_main(argc, argv);
253 if (error && error->code != GOT_ERR_CANCELLED &&
254 error->code != GOT_ERR_PRIVSEP_EXIT &&
255 !(sigpipe_received &&
256 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
257 !(sigint_received &&
258 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
259 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
260 return 1;
263 return 0;
266 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
267 list_commands(stderr);
268 return 1;
271 __dead static void
272 usage(int hflag, int status)
274 FILE *fp = (status == 0) ? stdout : stderr;
276 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
277 getprogname());
278 if (hflag)
279 list_commands(fp);
280 exit(status);
283 static const struct got_error *
284 get_editor(char **abspath)
286 const struct got_error *err = NULL;
287 const char *editor;
289 *abspath = NULL;
291 editor = getenv("VISUAL");
292 if (editor == NULL)
293 editor = getenv("EDITOR");
295 if (editor) {
296 err = got_path_find_prog(abspath, editor);
297 if (err)
298 return err;
301 if (*abspath == NULL) {
302 *abspath = strdup("/bin/ed");
303 if (*abspath == NULL)
304 return got_error_from_errno("strdup");
307 return NULL;
310 static const struct got_error *
311 apply_unveil(const char *repo_path, int repo_read_only,
312 const char *worktree_path)
314 const struct got_error *err;
316 #ifdef PROFILE
317 if (unveil("gmon.out", "rwc") != 0)
318 return got_error_from_errno2("unveil", "gmon.out");
319 #endif
320 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
321 return got_error_from_errno2("unveil", repo_path);
323 if (worktree_path && unveil(worktree_path, "rwc") != 0)
324 return got_error_from_errno2("unveil", worktree_path);
326 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
327 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
329 err = got_privsep_unveil_exec_helpers();
330 if (err != NULL)
331 return err;
333 if (unveil(NULL, NULL) != 0)
334 return got_error_from_errno("unveil");
336 return NULL;
339 __dead static void
340 usage_init(void)
342 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
343 exit(1);
346 static const struct got_error *
347 cmd_init(int argc, char *argv[])
349 const struct got_error *error = NULL;
350 char *repo_path = NULL;
351 int ch;
353 while ((ch = getopt(argc, argv, "")) != -1) {
354 switch (ch) {
355 default:
356 usage_init();
357 /* NOTREACHED */
361 argc -= optind;
362 argv += optind;
364 #ifndef PROFILE
365 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
366 err(1, "pledge");
367 #endif
368 if (argc != 1)
369 usage_init();
371 repo_path = strdup(argv[0]);
372 if (repo_path == NULL)
373 return got_error_from_errno("strdup");
375 got_path_strip_trailing_slashes(repo_path);
377 error = got_path_mkdir(repo_path);
378 if (error &&
379 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
380 goto done;
382 error = apply_unveil(repo_path, 0, NULL);
383 if (error)
384 goto done;
386 error = got_repo_init(repo_path);
387 done:
388 free(repo_path);
389 return error;
392 __dead static void
393 usage_import(void)
395 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
396 "[-r repository-path] [-I pattern] path\n", getprogname());
397 exit(1);
400 int
401 spawn_editor(const char *editor, const char *file)
403 pid_t pid;
404 sig_t sighup, sigint, sigquit;
405 int st = -1;
407 sighup = signal(SIGHUP, SIG_IGN);
408 sigint = signal(SIGINT, SIG_IGN);
409 sigquit = signal(SIGQUIT, SIG_IGN);
411 switch (pid = fork()) {
412 case -1:
413 goto doneediting;
414 case 0:
415 execl(editor, editor, file, (char *)NULL);
416 _exit(127);
419 while (waitpid(pid, &st, 0) == -1)
420 if (errno != EINTR)
421 break;
423 doneediting:
424 (void)signal(SIGHUP, sighup);
425 (void)signal(SIGINT, sigint);
426 (void)signal(SIGQUIT, sigquit);
428 if (!WIFEXITED(st)) {
429 errno = EINTR;
430 return -1;
433 return WEXITSTATUS(st);
436 static const struct got_error *
437 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
438 const char *initial_content, size_t initial_content_len,
439 int require_modification)
441 const struct got_error *err = NULL;
442 char *line = NULL;
443 size_t linesize = 0;
444 ssize_t linelen;
445 struct stat st, st2;
446 FILE *fp = NULL;
447 size_t len, logmsg_len;
448 char *initial_content_stripped = NULL, *buf = NULL, *s;
450 *logmsg = NULL;
452 if (stat(logmsg_path, &st) == -1)
453 return got_error_from_errno2("stat", logmsg_path);
455 if (spawn_editor(editor, logmsg_path) == -1)
456 return got_error_from_errno("failed spawning editor");
458 if (stat(logmsg_path, &st2) == -1)
459 return got_error_from_errno("stat");
461 if (require_modification &&
462 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
463 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
464 "no changes made to commit message, aborting");
466 /*
467 * Set up a stripped version of the initial content without comments
468 * and blank lines. We need this in order to check if the message
469 * has in fact been edited.
470 */
471 initial_content_stripped = malloc(initial_content_len + 1);
472 if (initial_content_stripped == NULL)
473 return got_error_from_errno("malloc");
474 initial_content_stripped[0] = '\0';
476 buf = strdup(initial_content);
477 if (buf == NULL) {
478 err = got_error_from_errno("strdup");
479 goto done;
481 s = buf;
482 len = 0;
483 while ((line = strsep(&s, "\n")) != NULL) {
484 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
485 continue; /* remove comments and leading empty lines */
486 len = strlcat(initial_content_stripped, line,
487 initial_content_len + 1);
488 if (len >= initial_content_len + 1) {
489 err = got_error(GOT_ERR_NO_SPACE);
490 goto done;
493 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
494 initial_content_stripped[len - 1] = '\0';
495 len--;
498 logmsg_len = st2.st_size;
499 *logmsg = malloc(logmsg_len + 1);
500 if (*logmsg == NULL)
501 return got_error_from_errno("malloc");
502 (*logmsg)[0] = '\0';
504 fp = fopen(logmsg_path, "r");
505 if (fp == NULL) {
506 err = got_error_from_errno("fopen");
507 goto done;
510 len = 0;
511 while ((linelen = getline(&line, &linesize, fp)) != -1) {
512 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
513 continue; /* remove comments and leading empty lines */
514 len = strlcat(*logmsg, line, logmsg_len + 1);
515 if (len >= logmsg_len + 1) {
516 err = got_error(GOT_ERR_NO_SPACE);
517 goto done;
520 free(line);
521 if (ferror(fp)) {
522 err = got_ferror(fp, GOT_ERR_IO);
523 goto done;
525 while (len > 0 && (*logmsg)[len - 1] == '\n') {
526 (*logmsg)[len - 1] = '\0';
527 len--;
530 if (len == 0) {
531 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
532 "commit message cannot be empty, aborting");
533 goto done;
535 if (require_modification &&
536 strcmp(*logmsg, initial_content_stripped) == 0)
537 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
538 "no changes made to commit message, aborting");
539 done:
540 free(initial_content_stripped);
541 free(buf);
542 if (fp && fclose(fp) == EOF && err == NULL)
543 err = got_error_from_errno("fclose");
544 if (err) {
545 free(*logmsg);
546 *logmsg = NULL;
548 return err;
551 static const struct got_error *
552 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
553 const char *path_dir, const char *branch_name)
555 char *initial_content = NULL;
556 const struct got_error *err = NULL;
557 int initial_content_len;
558 int fd = -1;
560 initial_content_len = asprintf(&initial_content,
561 "\n# %s to be imported to branch %s\n", path_dir,
562 branch_name);
563 if (initial_content_len == -1)
564 return got_error_from_errno("asprintf");
566 err = got_opentemp_named_fd(logmsg_path, &fd,
567 GOT_TMPDIR_STR "/got-importmsg");
568 if (err)
569 goto done;
571 if (write(fd, initial_content, initial_content_len) == -1) {
572 err = got_error_from_errno2("write", *logmsg_path);
573 goto done;
576 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
577 initial_content_len, 1);
578 done:
579 if (fd != -1 && close(fd) == -1 && err == NULL)
580 err = got_error_from_errno2("close", *logmsg_path);
581 free(initial_content);
582 if (err) {
583 free(*logmsg_path);
584 *logmsg_path = NULL;
586 return err;
589 static const struct got_error *
590 import_progress(void *arg, const char *path)
592 printf("A %s\n", path);
593 return NULL;
596 static const struct got_error *
597 get_author(char **author, struct got_repository *repo,
598 struct got_worktree *worktree)
600 const struct got_error *err = NULL;
601 const char *got_author = NULL, *name, *email;
602 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
604 *author = NULL;
606 if (worktree)
607 worktree_conf = got_worktree_get_gotconfig(worktree);
608 repo_conf = got_repo_get_gotconfig(repo);
610 /*
611 * Priority of potential author information sources, from most
612 * significant to least significant:
613 * 1) work tree's .got/got.conf file
614 * 2) repository's got.conf file
615 * 3) repository's git config file
616 * 4) environment variables
617 * 5) global git config files (in user's home directory or /etc)
618 */
620 if (worktree_conf)
621 got_author = got_gotconfig_get_author(worktree_conf);
622 if (got_author == NULL)
623 got_author = got_gotconfig_get_author(repo_conf);
624 if (got_author == NULL) {
625 name = got_repo_get_gitconfig_author_name(repo);
626 email = got_repo_get_gitconfig_author_email(repo);
627 if (name && email) {
628 if (asprintf(author, "%s <%s>", name, email) == -1)
629 return got_error_from_errno("asprintf");
630 return NULL;
633 got_author = getenv("GOT_AUTHOR");
634 if (got_author == NULL) {
635 name = got_repo_get_global_gitconfig_author_name(repo);
636 email = got_repo_get_global_gitconfig_author_email(
637 repo);
638 if (name && email) {
639 if (asprintf(author, "%s <%s>", name, email)
640 == -1)
641 return got_error_from_errno("asprintf");
642 return NULL;
644 /* TODO: Look up user in password database? */
645 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
649 *author = strdup(got_author);
650 if (*author == NULL)
651 return got_error_from_errno("strdup");
653 /*
654 * Really dumb email address check; we're only doing this to
655 * avoid git's object parser breaking on commits we create.
656 */
657 while (*got_author && *got_author != '<')
658 got_author++;
659 if (*got_author != '<') {
660 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
661 goto done;
663 while (*got_author && *got_author != '@')
664 got_author++;
665 if (*got_author != '@') {
666 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
667 goto done;
669 while (*got_author && *got_author != '>')
670 got_author++;
671 if (*got_author != '>')
672 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
673 done:
674 if (err) {
675 free(*author);
676 *author = NULL;
678 return err;
681 static const struct got_error *
682 get_gitconfig_path(char **gitconfig_path)
684 const char *homedir = getenv("HOME");
686 *gitconfig_path = NULL;
687 if (homedir) {
688 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
689 return got_error_from_errno("asprintf");
692 return NULL;
695 static const struct got_error *
696 cmd_import(int argc, char *argv[])
698 const struct got_error *error = NULL;
699 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
700 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
701 const char *branch_name = "main";
702 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
703 struct got_repository *repo = NULL;
704 struct got_reference *branch_ref = NULL, *head_ref = NULL;
705 struct got_object_id *new_commit_id = NULL;
706 int ch;
707 struct got_pathlist_head ignores;
708 struct got_pathlist_entry *pe;
709 int preserve_logmsg = 0;
711 TAILQ_INIT(&ignores);
713 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
714 switch (ch) {
715 case 'b':
716 branch_name = optarg;
717 break;
718 case 'm':
719 logmsg = strdup(optarg);
720 if (logmsg == NULL) {
721 error = got_error_from_errno("strdup");
722 goto done;
724 break;
725 case 'r':
726 repo_path = realpath(optarg, NULL);
727 if (repo_path == NULL) {
728 error = got_error_from_errno2("realpath",
729 optarg);
730 goto done;
732 break;
733 case 'I':
734 if (optarg[0] == '\0')
735 break;
736 error = got_pathlist_insert(&pe, &ignores, optarg,
737 NULL);
738 if (error)
739 goto done;
740 break;
741 default:
742 usage_import();
743 /* NOTREACHED */
747 argc -= optind;
748 argv += optind;
750 #ifndef PROFILE
751 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
752 "unveil",
753 NULL) == -1)
754 err(1, "pledge");
755 #endif
756 if (argc != 1)
757 usage_import();
759 if (repo_path == NULL) {
760 repo_path = getcwd(NULL, 0);
761 if (repo_path == NULL)
762 return got_error_from_errno("getcwd");
764 got_path_strip_trailing_slashes(repo_path);
765 error = get_gitconfig_path(&gitconfig_path);
766 if (error)
767 goto done;
768 error = got_repo_open(&repo, repo_path, gitconfig_path);
769 if (error)
770 goto done;
772 error = get_author(&author, repo, NULL);
773 if (error)
774 return error;
776 /*
777 * Don't let the user create a branch name with a leading '-'.
778 * While technically a valid reference name, this case is usually
779 * an unintended typo.
780 */
781 if (branch_name[0] == '-')
782 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
784 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
785 error = got_error_from_errno("asprintf");
786 goto done;
789 error = got_ref_open(&branch_ref, repo, refname, 0);
790 if (error) {
791 if (error->code != GOT_ERR_NOT_REF)
792 goto done;
793 } else {
794 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
795 "import target branch already exists");
796 goto done;
799 path_dir = realpath(argv[0], NULL);
800 if (path_dir == NULL) {
801 error = got_error_from_errno2("realpath", argv[0]);
802 goto done;
804 got_path_strip_trailing_slashes(path_dir);
806 /*
807 * unveil(2) traverses exec(2); if an editor is used we have
808 * to apply unveil after the log message has been written.
809 */
810 if (logmsg == NULL || strlen(logmsg) == 0) {
811 error = get_editor(&editor);
812 if (error)
813 goto done;
814 free(logmsg);
815 error = collect_import_msg(&logmsg, &logmsg_path, editor,
816 path_dir, refname);
817 if (error) {
818 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
819 logmsg_path != NULL)
820 preserve_logmsg = 1;
821 goto done;
825 if (unveil(path_dir, "r") != 0) {
826 error = got_error_from_errno2("unveil", path_dir);
827 if (logmsg_path)
828 preserve_logmsg = 1;
829 goto done;
832 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
833 if (error) {
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = got_repo_import(&new_commit_id, path_dir, logmsg,
840 author, &ignores, repo, import_progress, NULL);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_write(branch_ref, repo);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_object_id_str(&id_str, new_commit_id);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
869 if (error) {
870 if (error->code != GOT_ERR_NOT_REF) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
877 branch_ref);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_ref_write(head_ref, repo);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
892 printf("Created branch %s with commit %s\n",
893 got_ref_get_name(branch_ref), id_str);
894 done:
895 if (preserve_logmsg) {
896 fprintf(stderr, "%s: log message preserved in %s\n",
897 getprogname(), logmsg_path);
898 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
899 error = got_error_from_errno2("unlink", logmsg_path);
900 free(logmsg);
901 free(logmsg_path);
902 free(repo_path);
903 free(editor);
904 free(refname);
905 free(new_commit_id);
906 free(id_str);
907 free(author);
908 free(gitconfig_path);
909 if (branch_ref)
910 got_ref_close(branch_ref);
911 if (head_ref)
912 got_ref_close(head_ref);
913 return error;
916 __dead static void
917 usage_clone(void)
919 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
920 "[-R reference] repository-url [directory]\n", getprogname());
921 exit(1);
924 struct got_fetch_progress_arg {
925 char last_scaled_size[FMT_SCALED_STRSIZE];
926 int last_p_indexed;
927 int last_p_resolved;
928 int verbosity;
930 struct got_repository *repo;
932 int create_configs;
933 int configs_created;
934 struct {
935 struct got_pathlist_head *symrefs;
936 struct got_pathlist_head *wanted_branches;
937 struct got_pathlist_head *wanted_refs;
938 const char *proto;
939 const char *host;
940 const char *port;
941 const char *remote_repo_path;
942 const char *git_url;
943 int fetch_all_branches;
944 int mirror_references;
945 } config_info;
946 };
948 /* XXX forward declaration */
949 static const struct got_error *
950 create_config_files(const char *proto, const char *host, const char *port,
951 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
952 int mirror_references, struct got_pathlist_head *symrefs,
953 struct got_pathlist_head *wanted_branches,
954 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
956 static const struct got_error *
957 fetch_progress(void *arg, const char *message, off_t packfile_size,
958 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
960 const struct got_error *err = NULL;
961 struct got_fetch_progress_arg *a = arg;
962 char scaled_size[FMT_SCALED_STRSIZE];
963 int p_indexed, p_resolved;
964 int print_size = 0, print_indexed = 0, print_resolved = 0;
966 /*
967 * In order to allow a failed clone to be resumed with 'got fetch'
968 * we try to create configuration files as soon as possible.
969 * Once the server has sent information about its default branch
970 * we have all required information.
971 */
972 if (a->create_configs && !a->configs_created &&
973 !TAILQ_EMPTY(a->config_info.symrefs)) {
974 err = create_config_files(a->config_info.proto,
975 a->config_info.host, a->config_info.port,
976 a->config_info.remote_repo_path,
977 a->config_info.git_url,
978 a->config_info.fetch_all_branches,
979 a->config_info.mirror_references,
980 a->config_info.symrefs,
981 a->config_info.wanted_branches,
982 a->config_info.wanted_refs, a->repo);
983 if (err)
984 return err;
985 a->configs_created = 1;
988 if (a->verbosity < 0)
989 return NULL;
991 if (message && message[0] != '\0') {
992 printf("\rserver: %s", message);
993 fflush(stdout);
994 return NULL;
997 if (packfile_size > 0 || nobj_indexed > 0) {
998 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
999 (a->last_scaled_size[0] == '\0' ||
1000 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1001 print_size = 1;
1002 if (strlcpy(a->last_scaled_size, scaled_size,
1003 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1004 return got_error(GOT_ERR_NO_SPACE);
1006 if (nobj_indexed > 0) {
1007 p_indexed = (nobj_indexed * 100) / nobj_total;
1008 if (p_indexed != a->last_p_indexed) {
1009 a->last_p_indexed = p_indexed;
1010 print_indexed = 1;
1011 print_size = 1;
1014 if (nobj_resolved > 0) {
1015 p_resolved = (nobj_resolved * 100) /
1016 (nobj_total - nobj_loose);
1017 if (p_resolved != a->last_p_resolved) {
1018 a->last_p_resolved = p_resolved;
1019 print_resolved = 1;
1020 print_indexed = 1;
1021 print_size = 1;
1026 if (print_size || print_indexed || print_resolved)
1027 printf("\r");
1028 if (print_size)
1029 printf("%*s fetched", FMT_SCALED_STRSIZE, scaled_size);
1030 if (print_indexed)
1031 printf("; indexing %d%%", p_indexed);
1032 if (print_resolved)
1033 printf("; resolving deltas %d%%", p_resolved);
1034 if (print_size || print_indexed || print_resolved)
1035 fflush(stdout);
1037 return NULL;
1040 static const struct got_error *
1041 create_symref(const char *refname, struct got_reference *target_ref,
1042 int verbosity, struct got_repository *repo)
1044 const struct got_error *err;
1045 struct got_reference *head_symref;
1047 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1048 if (err)
1049 return err;
1051 err = got_ref_write(head_symref, repo);
1052 if (err == NULL && verbosity > 0) {
1053 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1054 got_ref_get_name(target_ref));
1056 got_ref_close(head_symref);
1057 return err;
1060 static const struct got_error *
1061 list_remote_refs(struct got_pathlist_head *symrefs,
1062 struct got_pathlist_head *refs)
1064 const struct got_error *err;
1065 struct got_pathlist_entry *pe;
1067 TAILQ_FOREACH(pe, symrefs, entry) {
1068 const char *refname = pe->path;
1069 const char *targetref = pe->data;
1071 printf("%s: %s\n", refname, targetref);
1074 TAILQ_FOREACH(pe, refs, entry) {
1075 const char *refname = pe->path;
1076 struct got_object_id *id = pe->data;
1077 char *id_str;
1079 err = got_object_id_str(&id_str, id);
1080 if (err)
1081 return err;
1082 printf("%s: %s\n", refname, id_str);
1083 free(id_str);
1086 return NULL;
1089 static const struct got_error *
1090 create_ref(const char *refname, struct got_object_id *id,
1091 int verbosity, struct got_repository *repo)
1093 const struct got_error *err = NULL;
1094 struct got_reference *ref;
1095 char *id_str;
1097 err = got_object_id_str(&id_str, id);
1098 if (err)
1099 return err;
1101 err = got_ref_alloc(&ref, refname, id);
1102 if (err)
1103 goto done;
1105 err = got_ref_write(ref, repo);
1106 got_ref_close(ref);
1108 if (err == NULL && verbosity >= 0)
1109 printf("Created reference %s: %s\n", refname, id_str);
1110 done:
1111 free(id_str);
1112 return err;
1115 static int
1116 match_wanted_ref(const char *refname, const char *wanted_ref)
1118 if (strncmp(refname, "refs/", 5) != 0)
1119 return 0;
1120 refname += 5;
1123 * Prevent fetching of references that won't make any
1124 * sense outside of the remote repository's context.
1126 if (strncmp(refname, "got/", 4) == 0)
1127 return 0;
1128 if (strncmp(refname, "remotes/", 8) == 0)
1129 return 0;
1131 if (strncmp(wanted_ref, "refs/", 5) == 0)
1132 wanted_ref += 5;
1134 /* Allow prefix match. */
1135 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1136 return 1;
1138 /* Allow exact match. */
1139 return (strcmp(refname, wanted_ref) == 0);
1142 static int
1143 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1145 struct got_pathlist_entry *pe;
1147 TAILQ_FOREACH(pe, wanted_refs, entry) {
1148 if (match_wanted_ref(refname, pe->path))
1149 return 1;
1152 return 0;
1155 static const struct got_error *
1156 create_wanted_ref(const char *refname, struct got_object_id *id,
1157 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1159 const struct got_error *err;
1160 char *remote_refname;
1162 if (strncmp("refs/", refname, 5) == 0)
1163 refname += 5;
1165 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1166 remote_repo_name, refname) == -1)
1167 return got_error_from_errno("asprintf");
1169 err = create_ref(remote_refname, id, verbosity, repo);
1170 free(remote_refname);
1171 return err;
1174 static const struct got_error *
1175 create_gotconfig(const char *proto, const char *host, const char *port,
1176 const char *remote_repo_path, const char *default_branch,
1177 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1178 struct got_pathlist_head *wanted_refs, int mirror_references,
1179 struct got_repository *repo)
1181 const struct got_error *err = NULL;
1182 char *gotconfig_path = NULL;
1183 char *gotconfig = NULL;
1184 FILE *gotconfig_file = NULL;
1185 const char *branchname = NULL;
1186 char *branches = NULL, *refs = NULL;
1187 ssize_t n;
1189 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1190 struct got_pathlist_entry *pe;
1191 TAILQ_FOREACH(pe, wanted_branches, entry) {
1192 char *s;
1193 branchname = pe->path;
1194 if (strncmp(branchname, "refs/heads/", 11) == 0)
1195 branchname += 11;
1196 if (asprintf(&s, "%s\"%s\" ",
1197 branches ? branches : "", branchname) == -1) {
1198 err = got_error_from_errno("asprintf");
1199 goto done;
1201 free(branches);
1202 branches = s;
1204 } else if (!fetch_all_branches && default_branch) {
1205 branchname = default_branch;
1206 if (strncmp(branchname, "refs/heads/", 11) == 0)
1207 branchname += 11;
1208 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1209 err = got_error_from_errno("asprintf");
1210 goto done;
1213 if (!TAILQ_EMPTY(wanted_refs)) {
1214 struct got_pathlist_entry *pe;
1215 TAILQ_FOREACH(pe, wanted_refs, entry) {
1216 char *s;
1217 const char *refname = pe->path;
1218 if (strncmp(refname, "refs/", 5) == 0)
1219 branchname += 5;
1220 if (asprintf(&s, "%s\"%s\" ",
1221 refs ? refs : "", refname) == -1) {
1222 err = got_error_from_errno("asprintf");
1223 goto done;
1225 free(refs);
1226 refs = s;
1230 /* Create got.conf(5). */
1231 gotconfig_path = got_repo_get_path_gotconfig(repo);
1232 if (gotconfig_path == NULL) {
1233 err = got_error_from_errno("got_repo_get_path_gotconfig");
1234 goto done;
1236 gotconfig_file = fopen(gotconfig_path, "a");
1237 if (gotconfig_file == NULL) {
1238 err = got_error_from_errno2("fopen", gotconfig_path);
1239 goto done;
1241 if (asprintf(&gotconfig,
1242 "remote \"%s\" {\n"
1243 "\tserver %s\n"
1244 "\tprotocol %s\n"
1245 "%s%s%s"
1246 "\trepository \"%s\"\n"
1247 "%s%s%s"
1248 "%s%s%s"
1249 "%s"
1250 "%s"
1251 "}\n",
1252 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1253 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1254 remote_repo_path, branches ? "\tbranch { " : "",
1255 branches ? branches : "", branches ? "}\n" : "",
1256 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1257 mirror_references ? "\tmirror-references yes\n" : "",
1258 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1259 err = got_error_from_errno("asprintf");
1260 goto done;
1262 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1263 if (n != strlen(gotconfig)) {
1264 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1265 goto done;
1268 done:
1269 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1270 err = got_error_from_errno2("fclose", gotconfig_path);
1271 free(gotconfig_path);
1272 free(branches);
1273 return err;
1276 static const struct got_error *
1277 create_gitconfig(const char *git_url, const char *default_branch,
1278 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1279 struct got_pathlist_head *wanted_refs, int mirror_references,
1280 struct got_repository *repo)
1282 const struct got_error *err = NULL;
1283 char *gitconfig_path = NULL;
1284 char *gitconfig = NULL;
1285 FILE *gitconfig_file = NULL;
1286 char *branches = NULL, *refs = NULL;
1287 const char *branchname;
1288 ssize_t n;
1290 /* Create a config file Git can understand. */
1291 gitconfig_path = got_repo_get_path_gitconfig(repo);
1292 if (gitconfig_path == NULL) {
1293 err = got_error_from_errno("got_repo_get_path_gitconfig");
1294 goto done;
1296 gitconfig_file = fopen(gitconfig_path, "a");
1297 if (gitconfig_file == NULL) {
1298 err = got_error_from_errno2("fopen", gitconfig_path);
1299 goto done;
1301 if (fetch_all_branches) {
1302 if (mirror_references) {
1303 if (asprintf(&branches,
1304 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1305 err = got_error_from_errno("asprintf");
1306 goto done;
1308 } else if (asprintf(&branches,
1309 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1310 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1311 err = got_error_from_errno("asprintf");
1312 goto done;
1314 } else if (!TAILQ_EMPTY(wanted_branches)) {
1315 struct got_pathlist_entry *pe;
1316 TAILQ_FOREACH(pe, wanted_branches, entry) {
1317 char *s;
1318 branchname = pe->path;
1319 if (strncmp(branchname, "refs/heads/", 11) == 0)
1320 branchname += 11;
1321 if (mirror_references) {
1322 if (asprintf(&s,
1323 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1324 branches ? branches : "",
1325 branchname, branchname) == -1) {
1326 err = got_error_from_errno("asprintf");
1327 goto done;
1329 } else if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1331 branches ? branches : "",
1332 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1333 branchname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 free(branches);
1338 branches = s;
1340 } else {
1342 * If the server specified a default branch, use just that one.
1343 * Otherwise fall back to fetching all branches on next fetch.
1345 if (default_branch) {
1346 branchname = default_branch;
1347 if (strncmp(branchname, "refs/heads/", 11) == 0)
1348 branchname += 11;
1349 } else
1350 branchname = "*"; /* fall back to all branches */
1351 if (mirror_references) {
1352 if (asprintf(&branches,
1353 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1354 branchname, branchname) == -1) {
1355 err = got_error_from_errno("asprintf");
1356 goto done;
1358 } else if (asprintf(&branches,
1359 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1360 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1361 branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1366 if (!TAILQ_EMPTY(wanted_refs)) {
1367 struct got_pathlist_entry *pe;
1368 TAILQ_FOREACH(pe, wanted_refs, entry) {
1369 char *s;
1370 const char *refname = pe->path;
1371 if (strncmp(refname, "refs/", 5) == 0)
1372 refname += 5;
1373 if (mirror_references) {
1374 if (asprintf(&s,
1375 "%s\tfetch = refs/%s:refs/%s\n",
1376 refs ? refs : "", refname, refname) == -1) {
1377 err = got_error_from_errno("asprintf");
1378 goto done;
1380 } else if (asprintf(&s,
1381 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1382 refs ? refs : "",
1383 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1384 refname) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 free(refs);
1389 refs = s;
1393 if (asprintf(&gitconfig,
1394 "[remote \"%s\"]\n"
1395 "\turl = %s\n"
1396 "%s"
1397 "%s"
1398 "\tfetch = refs/tags/*:refs/tags/*\n",
1399 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1400 refs ? refs : "") == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1405 if (n != strlen(gitconfig)) {
1406 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1407 goto done;
1409 done:
1410 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1411 err = got_error_from_errno2("fclose", gitconfig_path);
1412 free(gitconfig_path);
1413 free(branches);
1414 return err;
1417 static const struct got_error *
1418 create_config_files(const char *proto, const char *host, const char *port,
1419 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1420 int mirror_references, struct got_pathlist_head *symrefs,
1421 struct got_pathlist_head *wanted_branches,
1422 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1424 const struct got_error *err = NULL;
1425 const char *default_branch = NULL;
1426 struct got_pathlist_entry *pe;
1429 * If we asked for a set of wanted branches then use the first
1430 * one of those.
1432 if (!TAILQ_EMPTY(wanted_branches)) {
1433 pe = TAILQ_FIRST(wanted_branches);
1434 default_branch = pe->path;
1435 } else {
1436 /* First HEAD ref listed by server is the default branch. */
1437 TAILQ_FOREACH(pe, symrefs, entry) {
1438 const char *refname = pe->path;
1439 const char *target = pe->data;
1441 if (strcmp(refname, GOT_REF_HEAD) != 0)
1442 continue;
1444 default_branch = target;
1445 break;
1449 /* Create got.conf(5). */
1450 err = create_gotconfig(proto, host, port, remote_repo_path,
1451 default_branch, fetch_all_branches, wanted_branches,
1452 wanted_refs, mirror_references, repo);
1453 if (err)
1454 return err;
1456 /* Create a config file Git can understand. */
1457 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1458 wanted_branches, wanted_refs, mirror_references, repo);
1461 static const struct got_error *
1462 cmd_clone(int argc, char *argv[])
1464 const struct got_error *error = NULL;
1465 const char *uri, *dirname;
1466 char *proto, *host, *port, *repo_name, *server_path;
1467 char *default_destdir = NULL, *id_str = NULL;
1468 const char *repo_path;
1469 struct got_repository *repo = NULL;
1470 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1471 struct got_pathlist_entry *pe;
1472 struct got_object_id *pack_hash = NULL;
1473 int ch, fetchfd = -1, fetchstatus;
1474 pid_t fetchpid = -1;
1475 struct got_fetch_progress_arg fpa;
1476 char *git_url = NULL;
1477 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1478 int list_refs_only = 0;
1480 TAILQ_INIT(&refs);
1481 TAILQ_INIT(&symrefs);
1482 TAILQ_INIT(&wanted_branches);
1483 TAILQ_INIT(&wanted_refs);
1485 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1486 switch (ch) {
1487 case 'a':
1488 fetch_all_branches = 1;
1489 break;
1490 case 'b':
1491 error = got_pathlist_append(&wanted_branches,
1492 optarg, NULL);
1493 if (error)
1494 return error;
1495 break;
1496 case 'l':
1497 list_refs_only = 1;
1498 break;
1499 case 'm':
1500 mirror_references = 1;
1501 break;
1502 case 'v':
1503 if (verbosity < 0)
1504 verbosity = 0;
1505 else if (verbosity < 3)
1506 verbosity++;
1507 break;
1508 case 'q':
1509 verbosity = -1;
1510 break;
1511 case 'R':
1512 error = got_pathlist_append(&wanted_refs,
1513 optarg, NULL);
1514 if (error)
1515 return error;
1516 break;
1517 default:
1518 usage_clone();
1519 break;
1522 argc -= optind;
1523 argv += optind;
1525 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1526 option_conflict('a', 'b');
1527 if (list_refs_only) {
1528 if (!TAILQ_EMPTY(&wanted_branches))
1529 option_conflict('l', 'b');
1530 if (fetch_all_branches)
1531 option_conflict('l', 'a');
1532 if (mirror_references)
1533 option_conflict('l', 'm');
1534 if (!TAILQ_EMPTY(&wanted_refs))
1535 option_conflict('l', 'R');
1538 uri = argv[0];
1540 if (argc == 1)
1541 dirname = NULL;
1542 else if (argc == 2)
1543 dirname = argv[1];
1544 else
1545 usage_clone();
1547 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1548 &repo_name, uri);
1549 if (error)
1550 goto done;
1552 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1553 host, port ? ":" : "", port ? port : "",
1554 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1555 error = got_error_from_errno("asprintf");
1556 goto done;
1559 if (strcmp(proto, "git") == 0) {
1560 #ifndef PROFILE
1561 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1562 "sendfd dns inet unveil", NULL) == -1)
1563 err(1, "pledge");
1564 #endif
1565 } else if (strcmp(proto, "git+ssh") == 0 ||
1566 strcmp(proto, "ssh") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "http") == 0 ||
1573 strcmp(proto, "git+http") == 0) {
1574 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1575 goto done;
1576 } else {
1577 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1578 goto done;
1580 if (dirname == NULL) {
1581 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1582 error = got_error_from_errno("asprintf");
1583 goto done;
1585 repo_path = default_destdir;
1586 } else
1587 repo_path = dirname;
1589 if (!list_refs_only) {
1590 error = got_path_mkdir(repo_path);
1591 if (error &&
1592 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1593 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1594 goto done;
1595 if (!got_path_dir_is_empty(repo_path)) {
1596 error = got_error_path(repo_path,
1597 GOT_ERR_DIR_NOT_EMPTY);
1598 goto done;
1602 error = got_dial_apply_unveil(proto);
1603 if (error)
1604 goto done;
1606 error = apply_unveil(repo_path, 0, NULL);
1607 if (error)
1608 goto done;
1610 if (verbosity >= 0)
1611 printf("Connecting to %s%s%s\n", host,
1612 port ? ":" : "", port ? port : "");
1614 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1615 server_path, verbosity);
1616 if (error)
1617 goto done;
1619 if (!list_refs_only) {
1620 error = got_repo_init(repo_path);
1621 if (error)
1622 goto done;
1623 error = got_repo_open(&repo, repo_path, NULL);
1624 if (error)
1625 goto done;
1628 fpa.last_scaled_size[0] = '\0';
1629 fpa.last_p_indexed = -1;
1630 fpa.last_p_resolved = -1;
1631 fpa.verbosity = verbosity;
1632 fpa.create_configs = 1;
1633 fpa.configs_created = 0;
1634 fpa.repo = repo;
1635 fpa.config_info.symrefs = &symrefs;
1636 fpa.config_info.wanted_branches = &wanted_branches;
1637 fpa.config_info.wanted_refs = &wanted_refs;
1638 fpa.config_info.proto = proto;
1639 fpa.config_info.host = host;
1640 fpa.config_info.port = port;
1641 fpa.config_info.remote_repo_path = server_path;
1642 fpa.config_info.git_url = git_url;
1643 fpa.config_info.fetch_all_branches = fetch_all_branches;
1644 fpa.config_info.mirror_references = mirror_references;
1645 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1646 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1647 fetch_all_branches, &wanted_branches, &wanted_refs,
1648 list_refs_only, verbosity, fetchfd, repo,
1649 fetch_progress, &fpa);
1650 if (error)
1651 goto done;
1653 if (list_refs_only) {
1654 error = list_remote_refs(&symrefs, &refs);
1655 goto done;
1658 error = got_object_id_str(&id_str, pack_hash);
1659 if (error)
1660 goto done;
1661 if (verbosity >= 0)
1662 printf("\nFetched %s.pack\n", id_str);
1663 free(id_str);
1665 /* Set up references provided with the pack file. */
1666 TAILQ_FOREACH(pe, &refs, entry) {
1667 const char *refname = pe->path;
1668 struct got_object_id *id = pe->data;
1669 char *remote_refname;
1671 if (is_wanted_ref(&wanted_refs, refname) &&
1672 !mirror_references) {
1673 error = create_wanted_ref(refname, id,
1674 GOT_FETCH_DEFAULT_REMOTE_NAME,
1675 verbosity - 1, repo);
1676 if (error)
1677 goto done;
1678 continue;
1681 error = create_ref(refname, id, verbosity - 1, repo);
1682 if (error)
1683 goto done;
1685 if (mirror_references)
1686 continue;
1688 if (strncmp("refs/heads/", refname, 11) != 0)
1689 continue;
1691 if (asprintf(&remote_refname,
1692 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1693 refname + 11) == -1) {
1694 error = got_error_from_errno("asprintf");
1695 goto done;
1697 error = create_ref(remote_refname, id, verbosity - 1, repo);
1698 free(remote_refname);
1699 if (error)
1700 goto done;
1703 /* Set the HEAD reference if the server provided one. */
1704 TAILQ_FOREACH(pe, &symrefs, entry) {
1705 struct got_reference *target_ref;
1706 const char *refname = pe->path;
1707 const char *target = pe->data;
1708 char *remote_refname = NULL, *remote_target = NULL;
1710 if (strcmp(refname, GOT_REF_HEAD) != 0)
1711 continue;
1713 error = got_ref_open(&target_ref, repo, target, 0);
1714 if (error) {
1715 if (error->code == GOT_ERR_NOT_REF) {
1716 error = NULL;
1717 continue;
1719 goto done;
1722 error = create_symref(refname, target_ref, verbosity, repo);
1723 got_ref_close(target_ref);
1724 if (error)
1725 goto done;
1727 if (mirror_references)
1728 continue;
1730 if (strncmp("refs/heads/", target, 11) != 0)
1731 continue;
1733 if (asprintf(&remote_refname,
1734 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1735 refname) == -1) {
1736 error = got_error_from_errno("asprintf");
1737 goto done;
1739 if (asprintf(&remote_target,
1740 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1741 target + 11) == -1) {
1742 error = got_error_from_errno("asprintf");
1743 free(remote_refname);
1744 goto done;
1746 error = got_ref_open(&target_ref, repo, remote_target, 0);
1747 if (error) {
1748 free(remote_refname);
1749 free(remote_target);
1750 if (error->code == GOT_ERR_NOT_REF) {
1751 error = NULL;
1752 continue;
1754 goto done;
1756 error = create_symref(remote_refname, target_ref,
1757 verbosity - 1, repo);
1758 free(remote_refname);
1759 free(remote_target);
1760 got_ref_close(target_ref);
1761 if (error)
1762 goto done;
1764 if (pe == NULL) {
1766 * We failed to set the HEAD reference. If we asked for
1767 * a set of wanted branches use the first of one of those
1768 * which could be fetched instead.
1770 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1771 const char *target = pe->path;
1772 struct got_reference *target_ref;
1774 error = got_ref_open(&target_ref, repo, target, 0);
1775 if (error) {
1776 if (error->code == GOT_ERR_NOT_REF) {
1777 error = NULL;
1778 continue;
1780 goto done;
1783 error = create_symref(GOT_REF_HEAD, target_ref,
1784 verbosity, repo);
1785 got_ref_close(target_ref);
1786 if (error)
1787 goto done;
1788 break;
1792 if (verbosity >= 0)
1793 printf("Created %s repository '%s'\n",
1794 mirror_references ? "mirrored" : "cloned", repo_path);
1795 done:
1796 if (fetchpid > 0) {
1797 if (kill(fetchpid, SIGTERM) == -1)
1798 error = got_error_from_errno("kill");
1799 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1800 error = got_error_from_errno("waitpid");
1802 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1803 error = got_error_from_errno("close");
1804 if (repo) {
1805 const struct got_error *close_err = got_repo_close(repo);
1806 if (error == NULL)
1807 error = close_err;
1809 TAILQ_FOREACH(pe, &refs, entry) {
1810 free((void *)pe->path);
1811 free(pe->data);
1813 got_pathlist_free(&refs);
1814 TAILQ_FOREACH(pe, &symrefs, entry) {
1815 free((void *)pe->path);
1816 free(pe->data);
1818 got_pathlist_free(&symrefs);
1819 got_pathlist_free(&wanted_branches);
1820 got_pathlist_free(&wanted_refs);
1821 free(pack_hash);
1822 free(proto);
1823 free(host);
1824 free(port);
1825 free(server_path);
1826 free(repo_name);
1827 free(default_destdir);
1828 free(git_url);
1829 return error;
1832 static const struct got_error *
1833 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1834 int replace_tags, int verbosity, struct got_repository *repo)
1836 const struct got_error *err = NULL;
1837 char *new_id_str = NULL;
1838 struct got_object_id *old_id = NULL;
1840 err = got_object_id_str(&new_id_str, new_id);
1841 if (err)
1842 goto done;
1844 if (!replace_tags &&
1845 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1846 err = got_ref_resolve(&old_id, repo, ref);
1847 if (err)
1848 goto done;
1849 if (got_object_id_cmp(old_id, new_id) == 0)
1850 goto done;
1851 if (verbosity >= 0) {
1852 printf("Rejecting update of existing tag %s: %s\n",
1853 got_ref_get_name(ref), new_id_str);
1855 goto done;
1858 if (got_ref_is_symbolic(ref)) {
1859 if (verbosity >= 0) {
1860 printf("Replacing reference %s: %s\n",
1861 got_ref_get_name(ref),
1862 got_ref_get_symref_target(ref));
1864 err = got_ref_change_symref_to_ref(ref, new_id);
1865 if (err)
1866 goto done;
1867 err = got_ref_write(ref, repo);
1868 if (err)
1869 goto done;
1870 } else {
1871 err = got_ref_resolve(&old_id, repo, ref);
1872 if (err)
1873 goto done;
1874 if (got_object_id_cmp(old_id, new_id) == 0)
1875 goto done;
1877 err = got_ref_change_ref(ref, new_id);
1878 if (err)
1879 goto done;
1880 err = got_ref_write(ref, repo);
1881 if (err)
1882 goto done;
1885 if (verbosity >= 0)
1886 printf("Updated %s: %s\n", got_ref_get_name(ref),
1887 new_id_str);
1888 done:
1889 free(old_id);
1890 free(new_id_str);
1891 return err;
1894 static const struct got_error *
1895 update_symref(const char *refname, struct got_reference *target_ref,
1896 int verbosity, struct got_repository *repo)
1898 const struct got_error *err = NULL, *unlock_err;
1899 struct got_reference *symref;
1900 int symref_is_locked = 0;
1902 err = got_ref_open(&symref, repo, refname, 1);
1903 if (err) {
1904 if (err->code != GOT_ERR_NOT_REF)
1905 return err;
1906 err = got_ref_alloc_symref(&symref, refname, target_ref);
1907 if (err)
1908 goto done;
1910 err = got_ref_write(symref, repo);
1911 if (err)
1912 goto done;
1914 if (verbosity >= 0)
1915 printf("Created reference %s: %s\n",
1916 got_ref_get_name(symref),
1917 got_ref_get_symref_target(symref));
1918 } else {
1919 symref_is_locked = 1;
1921 if (strcmp(got_ref_get_symref_target(symref),
1922 got_ref_get_name(target_ref)) == 0)
1923 goto done;
1925 err = got_ref_change_symref(symref,
1926 got_ref_get_name(target_ref));
1927 if (err)
1928 goto done;
1930 err = got_ref_write(symref, repo);
1931 if (err)
1932 goto done;
1934 if (verbosity >= 0)
1935 printf("Updated %s: %s\n", got_ref_get_name(symref),
1936 got_ref_get_symref_target(symref));
1939 done:
1940 if (symref_is_locked) {
1941 unlock_err = got_ref_unlock(symref);
1942 if (unlock_err && err == NULL)
1943 err = unlock_err;
1945 got_ref_close(symref);
1946 return err;
1949 __dead static void
1950 usage_fetch(void)
1952 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1953 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1954 "[remote-repository-name]\n",
1955 getprogname());
1956 exit(1);
1959 static const struct got_error *
1960 delete_missing_ref(struct got_reference *ref,
1961 int verbosity, struct got_repository *repo)
1963 const struct got_error *err = NULL;
1964 struct got_object_id *id = NULL;
1965 char *id_str = NULL;
1967 if (got_ref_is_symbolic(ref)) {
1968 err = got_ref_delete(ref, repo);
1969 if (err)
1970 return err;
1971 if (verbosity >= 0) {
1972 printf("Deleted %s: %s\n",
1973 got_ref_get_name(ref),
1974 got_ref_get_symref_target(ref));
1976 } else {
1977 err = got_ref_resolve(&id, repo, ref);
1978 if (err)
1979 return err;
1980 err = got_object_id_str(&id_str, id);
1981 if (err)
1982 goto done;
1984 err = got_ref_delete(ref, repo);
1985 if (err)
1986 goto done;
1987 if (verbosity >= 0) {
1988 printf("Deleted %s: %s\n",
1989 got_ref_get_name(ref), id_str);
1992 done:
1993 free(id);
1994 free(id_str);
1995 return NULL;
1998 static const struct got_error *
1999 delete_missing_refs(struct got_pathlist_head *their_refs,
2000 struct got_pathlist_head *their_symrefs,
2001 const struct got_remote_repo *remote,
2002 int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL, *unlock_err;
2005 struct got_reflist_head my_refs;
2006 struct got_reflist_entry *re;
2007 struct got_pathlist_entry *pe;
2008 char *remote_namespace = NULL;
2009 char *local_refname = NULL;
2011 TAILQ_INIT(&my_refs);
2013 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2014 == -1)
2015 return got_error_from_errno("asprintf");
2017 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2018 if (err)
2019 goto done;
2021 TAILQ_FOREACH(re, &my_refs, entry) {
2022 const char *refname = got_ref_get_name(re->ref);
2023 const char *their_refname;
2025 if (remote->mirror_references) {
2026 their_refname = refname;
2027 } else {
2028 if (strncmp(refname, remote_namespace,
2029 strlen(remote_namespace)) == 0) {
2030 if (strcmp(refname + strlen(remote_namespace),
2031 GOT_REF_HEAD) == 0)
2032 continue;
2033 if (asprintf(&local_refname, "refs/heads/%s",
2034 refname + strlen(remote_namespace)) == -1) {
2035 err = got_error_from_errno("asprintf");
2036 goto done;
2038 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2039 continue;
2041 their_refname = local_refname;
2044 TAILQ_FOREACH(pe, their_refs, entry) {
2045 if (strcmp(their_refname, pe->path) == 0)
2046 break;
2048 if (pe != NULL)
2049 continue;
2051 TAILQ_FOREACH(pe, their_symrefs, entry) {
2052 if (strcmp(their_refname, pe->path) == 0)
2053 break;
2055 if (pe != NULL)
2056 continue;
2058 err = delete_missing_ref(re->ref, verbosity, repo);
2059 if (err)
2060 break;
2062 if (local_refname) {
2063 struct got_reference *ref;
2064 err = got_ref_open(&ref, repo, local_refname, 1);
2065 if (err) {
2066 if (err->code != GOT_ERR_NOT_REF)
2067 break;
2068 free(local_refname);
2069 local_refname = NULL;
2070 continue;
2072 err = delete_missing_ref(ref, verbosity, repo);
2073 if (err)
2074 break;
2075 unlock_err = got_ref_unlock(ref);
2076 got_ref_close(ref);
2077 if (unlock_err && err == NULL) {
2078 err = unlock_err;
2079 break;
2082 free(local_refname);
2083 local_refname = NULL;
2086 done:
2087 free(remote_namespace);
2088 free(local_refname);
2089 return err;
2092 static const struct got_error *
2093 update_wanted_ref(const char *refname, struct got_object_id *id,
2094 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2096 const struct got_error *err, *unlock_err;
2097 char *remote_refname;
2098 struct got_reference *ref;
2100 if (strncmp("refs/", refname, 5) == 0)
2101 refname += 5;
2103 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2104 remote_repo_name, refname) == -1)
2105 return got_error_from_errno("asprintf");
2107 err = got_ref_open(&ref, repo, remote_refname, 1);
2108 if (err) {
2109 if (err->code != GOT_ERR_NOT_REF)
2110 goto done;
2111 err = create_ref(remote_refname, id, verbosity, repo);
2112 } else {
2113 err = update_ref(ref, id, 0, verbosity, repo);
2114 unlock_err = got_ref_unlock(ref);
2115 if (unlock_err && err == NULL)
2116 err = unlock_err;
2117 got_ref_close(ref);
2119 done:
2120 free(remote_refname);
2121 return err;
2124 static const struct got_error *
2125 delete_ref(struct got_repository *repo, struct got_reference *ref)
2127 const struct got_error *err = NULL;
2128 struct got_object_id *id = NULL;
2129 char *id_str = NULL;
2130 const char *target;
2132 if (got_ref_is_symbolic(ref)) {
2133 target = got_ref_get_symref_target(ref);
2134 } else {
2135 err = got_ref_resolve(&id, repo, ref);
2136 if (err)
2137 goto done;
2138 err = got_object_id_str(&id_str, id);
2139 if (err)
2140 goto done;
2141 target = id_str;
2144 err = got_ref_delete(ref, repo);
2145 if (err)
2146 goto done;
2148 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2149 done:
2150 free(id);
2151 free(id_str);
2152 return err;
2155 static const struct got_error *
2156 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2158 const struct got_error *err = NULL;
2159 struct got_reflist_head refs;
2160 struct got_reflist_entry *re;
2161 char *prefix;
2163 TAILQ_INIT(&refs);
2165 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2166 err = got_error_from_errno("asprintf");
2167 goto done;
2169 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2170 if (err)
2171 goto done;
2173 TAILQ_FOREACH(re, &refs, entry)
2174 delete_ref(repo, re->ref);
2175 done:
2176 got_ref_list_free(&refs);
2177 return err;
2180 static const struct got_error *
2181 cmd_fetch(int argc, char *argv[])
2183 const struct got_error *error = NULL, *unlock_err;
2184 char *cwd = NULL, *repo_path = NULL;
2185 const char *remote_name;
2186 char *proto = NULL, *host = NULL, *port = NULL;
2187 char *repo_name = NULL, *server_path = NULL;
2188 const struct got_remote_repo *remotes, *remote = NULL;
2189 int nremotes;
2190 char *id_str = NULL;
2191 struct got_repository *repo = NULL;
2192 struct got_worktree *worktree = NULL;
2193 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2194 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2195 struct got_pathlist_entry *pe;
2196 struct got_object_id *pack_hash = NULL;
2197 int i, ch, fetchfd = -1, fetchstatus;
2198 pid_t fetchpid = -1;
2199 struct got_fetch_progress_arg fpa;
2200 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2201 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2203 TAILQ_INIT(&refs);
2204 TAILQ_INIT(&symrefs);
2205 TAILQ_INIT(&wanted_branches);
2206 TAILQ_INIT(&wanted_refs);
2208 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2209 switch (ch) {
2210 case 'a':
2211 fetch_all_branches = 1;
2212 break;
2213 case 'b':
2214 error = got_pathlist_append(&wanted_branches,
2215 optarg, NULL);
2216 if (error)
2217 return error;
2218 break;
2219 case 'd':
2220 delete_refs = 1;
2221 break;
2222 case 'l':
2223 list_refs_only = 1;
2224 break;
2225 case 'r':
2226 repo_path = realpath(optarg, NULL);
2227 if (repo_path == NULL)
2228 return got_error_from_errno2("realpath",
2229 optarg);
2230 got_path_strip_trailing_slashes(repo_path);
2231 break;
2232 case 't':
2233 replace_tags = 1;
2234 break;
2235 case 'v':
2236 if (verbosity < 0)
2237 verbosity = 0;
2238 else if (verbosity < 3)
2239 verbosity++;
2240 break;
2241 case 'q':
2242 verbosity = -1;
2243 break;
2244 case 'R':
2245 error = got_pathlist_append(&wanted_refs,
2246 optarg, NULL);
2247 if (error)
2248 return error;
2249 break;
2250 case 'X':
2251 delete_remote = 1;
2252 break;
2253 default:
2254 usage_fetch();
2255 break;
2258 argc -= optind;
2259 argv += optind;
2261 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2262 option_conflict('a', 'b');
2263 if (list_refs_only) {
2264 if (!TAILQ_EMPTY(&wanted_branches))
2265 option_conflict('l', 'b');
2266 if (fetch_all_branches)
2267 option_conflict('l', 'a');
2268 if (delete_refs)
2269 option_conflict('l', 'd');
2270 if (delete_remote)
2271 option_conflict('l', 'X');
2273 if (delete_remote) {
2274 if (fetch_all_branches)
2275 option_conflict('X', 'a');
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('X', 'b');
2278 if (delete_refs)
2279 option_conflict('X', 'd');
2280 if (replace_tags)
2281 option_conflict('X', 't');
2282 if (!TAILQ_EMPTY(&wanted_refs))
2283 option_conflict('X', 'R');
2286 if (argc == 0) {
2287 if (delete_remote)
2288 errx(1, "-X option requires a remote name");
2289 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2290 } else if (argc == 1)
2291 remote_name = argv[0];
2292 else
2293 usage_fetch();
2295 cwd = getcwd(NULL, 0);
2296 if (cwd == NULL) {
2297 error = got_error_from_errno("getcwd");
2298 goto done;
2301 if (repo_path == NULL) {
2302 error = got_worktree_open(&worktree, cwd);
2303 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2304 goto done;
2305 else
2306 error = NULL;
2307 if (worktree) {
2308 repo_path =
2309 strdup(got_worktree_get_repo_path(worktree));
2310 if (repo_path == NULL)
2311 error = got_error_from_errno("strdup");
2312 if (error)
2313 goto done;
2314 } else {
2315 repo_path = strdup(cwd);
2316 if (repo_path == NULL) {
2317 error = got_error_from_errno("strdup");
2318 goto done;
2323 error = got_repo_open(&repo, repo_path, NULL);
2324 if (error)
2325 goto done;
2327 if (delete_remote) {
2328 error = delete_refs_for_remote(repo, remote_name);
2329 goto done; /* nothing else to do */
2332 if (worktree) {
2333 worktree_conf = got_worktree_get_gotconfig(worktree);
2334 if (worktree_conf) {
2335 got_gotconfig_get_remotes(&nremotes, &remotes,
2336 worktree_conf);
2337 for (i = 0; i < nremotes; i++) {
2338 if (strcmp(remotes[i].name, remote_name) == 0) {
2339 remote = &remotes[i];
2340 break;
2345 if (remote == NULL) {
2346 repo_conf = got_repo_get_gotconfig(repo);
2347 if (repo_conf) {
2348 got_gotconfig_get_remotes(&nremotes, &remotes,
2349 repo_conf);
2350 for (i = 0; i < nremotes; i++) {
2351 if (strcmp(remotes[i].name, remote_name) == 0) {
2352 remote = &remotes[i];
2353 break;
2358 if (remote == NULL) {
2359 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2360 for (i = 0; i < nremotes; i++) {
2361 if (strcmp(remotes[i].name, remote_name) == 0) {
2362 remote = &remotes[i];
2363 break;
2367 if (remote == NULL) {
2368 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2369 goto done;
2372 if (TAILQ_EMPTY(&wanted_branches)) {
2373 if (!fetch_all_branches)
2374 fetch_all_branches = remote->fetch_all_branches;
2375 for (i = 0; i < remote->nfetch_branches; i++) {
2376 got_pathlist_append(&wanted_branches,
2377 remote->fetch_branches[i], NULL);
2380 if (TAILQ_EMPTY(&wanted_refs)) {
2381 for (i = 0; i < remote->nfetch_refs; i++) {
2382 got_pathlist_append(&wanted_refs,
2383 remote->fetch_refs[i], NULL);
2387 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2388 &repo_name, remote->fetch_url);
2389 if (error)
2390 goto done;
2392 if (strcmp(proto, "git") == 0) {
2393 #ifndef PROFILE
2394 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2395 "sendfd dns inet unveil", NULL) == -1)
2396 err(1, "pledge");
2397 #endif
2398 } else if (strcmp(proto, "git+ssh") == 0 ||
2399 strcmp(proto, "ssh") == 0) {
2400 #ifndef PROFILE
2401 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2402 "sendfd unveil", NULL) == -1)
2403 err(1, "pledge");
2404 #endif
2405 } else if (strcmp(proto, "http") == 0 ||
2406 strcmp(proto, "git+http") == 0) {
2407 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2408 goto done;
2409 } else {
2410 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2411 goto done;
2414 error = got_dial_apply_unveil(proto);
2415 if (error)
2416 goto done;
2418 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2419 if (error)
2420 goto done;
2422 if (verbosity >= 0)
2423 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2424 port ? ":" : "", port ? port : "");
2426 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2427 server_path, verbosity);
2428 if (error)
2429 goto done;
2431 fpa.last_scaled_size[0] = '\0';
2432 fpa.last_p_indexed = -1;
2433 fpa.last_p_resolved = -1;
2434 fpa.verbosity = verbosity;
2435 fpa.repo = repo;
2436 fpa.create_configs = 0;
2437 fpa.configs_created = 0;
2438 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2439 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2440 remote->mirror_references, fetch_all_branches, &wanted_branches,
2441 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2442 fetch_progress, &fpa);
2443 if (error)
2444 goto done;
2446 if (list_refs_only) {
2447 error = list_remote_refs(&symrefs, &refs);
2448 goto done;
2451 if (pack_hash == NULL) {
2452 if (verbosity >= 0)
2453 printf("Already up-to-date\n");
2454 } else if (verbosity >= 0) {
2455 error = got_object_id_str(&id_str, pack_hash);
2456 if (error)
2457 goto done;
2458 printf("\nFetched %s.pack\n", id_str);
2459 free(id_str);
2460 id_str = NULL;
2463 /* Update references provided with the pack file. */
2464 TAILQ_FOREACH(pe, &refs, entry) {
2465 const char *refname = pe->path;
2466 struct got_object_id *id = pe->data;
2467 struct got_reference *ref;
2468 char *remote_refname;
2470 if (is_wanted_ref(&wanted_refs, refname) &&
2471 !remote->mirror_references) {
2472 error = update_wanted_ref(refname, id,
2473 remote->name, verbosity, repo);
2474 if (error)
2475 goto done;
2476 continue;
2479 if (remote->mirror_references ||
2480 strncmp("refs/tags/", refname, 10) == 0) {
2481 error = got_ref_open(&ref, repo, refname, 1);
2482 if (error) {
2483 if (error->code != GOT_ERR_NOT_REF)
2484 goto done;
2485 error = create_ref(refname, id, verbosity,
2486 repo);
2487 if (error)
2488 goto done;
2489 } else {
2490 error = update_ref(ref, id, replace_tags,
2491 verbosity, repo);
2492 unlock_err = got_ref_unlock(ref);
2493 if (unlock_err && error == NULL)
2494 error = unlock_err;
2495 got_ref_close(ref);
2496 if (error)
2497 goto done;
2499 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2500 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2501 remote_name, refname + 11) == -1) {
2502 error = got_error_from_errno("asprintf");
2503 goto done;
2506 error = got_ref_open(&ref, repo, remote_refname, 1);
2507 if (error) {
2508 if (error->code != GOT_ERR_NOT_REF)
2509 goto done;
2510 error = create_ref(remote_refname, id,
2511 verbosity, repo);
2512 if (error)
2513 goto done;
2514 } else {
2515 error = update_ref(ref, id, replace_tags,
2516 verbosity, repo);
2517 unlock_err = got_ref_unlock(ref);
2518 if (unlock_err && error == NULL)
2519 error = unlock_err;
2520 got_ref_close(ref);
2521 if (error)
2522 goto done;
2525 /* Also create a local branch if none exists yet. */
2526 error = got_ref_open(&ref, repo, refname, 1);
2527 if (error) {
2528 if (error->code != GOT_ERR_NOT_REF)
2529 goto done;
2530 error = create_ref(refname, id, verbosity,
2531 repo);
2532 if (error)
2533 goto done;
2534 } else {
2535 unlock_err = got_ref_unlock(ref);
2536 if (unlock_err && error == NULL)
2537 error = unlock_err;
2538 got_ref_close(ref);
2542 if (delete_refs) {
2543 error = delete_missing_refs(&refs, &symrefs, remote,
2544 verbosity, repo);
2545 if (error)
2546 goto done;
2549 if (!remote->mirror_references) {
2550 /* Update remote HEAD reference if the server provided one. */
2551 TAILQ_FOREACH(pe, &symrefs, entry) {
2552 struct got_reference *target_ref;
2553 const char *refname = pe->path;
2554 const char *target = pe->data;
2555 char *remote_refname = NULL, *remote_target = NULL;
2557 if (strcmp(refname, GOT_REF_HEAD) != 0)
2558 continue;
2560 if (strncmp("refs/heads/", target, 11) != 0)
2561 continue;
2563 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2564 remote->name, refname) == -1) {
2565 error = got_error_from_errno("asprintf");
2566 goto done;
2568 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2569 remote->name, target + 11) == -1) {
2570 error = got_error_from_errno("asprintf");
2571 free(remote_refname);
2572 goto done;
2575 error = got_ref_open(&target_ref, repo, remote_target,
2576 0);
2577 if (error) {
2578 free(remote_refname);
2579 free(remote_target);
2580 if (error->code == GOT_ERR_NOT_REF) {
2581 error = NULL;
2582 continue;
2584 goto done;
2586 error = update_symref(remote_refname, target_ref,
2587 verbosity, repo);
2588 free(remote_refname);
2589 free(remote_target);
2590 got_ref_close(target_ref);
2591 if (error)
2592 goto done;
2595 done:
2596 if (fetchpid > 0) {
2597 if (kill(fetchpid, SIGTERM) == -1)
2598 error = got_error_from_errno("kill");
2599 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2600 error = got_error_from_errno("waitpid");
2602 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2603 error = got_error_from_errno("close");
2604 if (repo) {
2605 const struct got_error *close_err = got_repo_close(repo);
2606 if (error == NULL)
2607 error = close_err;
2609 if (worktree)
2610 got_worktree_close(worktree);
2611 TAILQ_FOREACH(pe, &refs, entry) {
2612 free((void *)pe->path);
2613 free(pe->data);
2615 got_pathlist_free(&refs);
2616 TAILQ_FOREACH(pe, &symrefs, entry) {
2617 free((void *)pe->path);
2618 free(pe->data);
2620 got_pathlist_free(&symrefs);
2621 got_pathlist_free(&wanted_branches);
2622 got_pathlist_free(&wanted_refs);
2623 free(id_str);
2624 free(cwd);
2625 free(repo_path);
2626 free(pack_hash);
2627 free(proto);
2628 free(host);
2629 free(port);
2630 free(server_path);
2631 free(repo_name);
2632 return error;
2636 __dead static void
2637 usage_checkout(void)
2639 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2640 "[-p prefix] [-q] repository-path [worktree-path]\n",
2641 getprogname());
2642 exit(1);
2645 static void
2646 show_worktree_base_ref_warning(void)
2648 fprintf(stderr, "%s: warning: could not create a reference "
2649 "to the work tree's base commit; the commit could be "
2650 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2651 "repository writable and running 'got update' will prevent this\n",
2652 getprogname());
2655 struct got_checkout_progress_arg {
2656 const char *worktree_path;
2657 int had_base_commit_ref_error;
2658 int verbosity;
2661 static const struct got_error *
2662 checkout_progress(void *arg, unsigned char status, const char *path)
2664 struct got_checkout_progress_arg *a = arg;
2666 /* Base commit bump happens silently. */
2667 if (status == GOT_STATUS_BUMP_BASE)
2668 return NULL;
2670 if (status == GOT_STATUS_BASE_REF_ERR) {
2671 a->had_base_commit_ref_error = 1;
2672 return NULL;
2675 while (path[0] == '/')
2676 path++;
2678 if (a->verbosity >= 0)
2679 printf("%c %s/%s\n", status, a->worktree_path, path);
2681 return NULL;
2684 static const struct got_error *
2685 check_cancelled(void *arg)
2687 if (sigint_received || sigpipe_received)
2688 return got_error(GOT_ERR_CANCELLED);
2689 return NULL;
2692 static const struct got_error *
2693 check_linear_ancestry(struct got_object_id *commit_id,
2694 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2695 struct got_repository *repo)
2697 const struct got_error *err = NULL;
2698 struct got_object_id *yca_id;
2700 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2701 commit_id, base_commit_id, repo, check_cancelled, NULL);
2702 if (err)
2703 return err;
2705 if (yca_id == NULL)
2706 return got_error(GOT_ERR_ANCESTRY);
2709 * Require a straight line of history between the target commit
2710 * and the work tree's base commit.
2712 * Non-linear situations such as this require a rebase:
2714 * (commit) D F (base_commit)
2715 * \ /
2716 * C E
2717 * \ /
2718 * B (yca)
2719 * |
2720 * A
2722 * 'got update' only handles linear cases:
2723 * Update forwards in time: A (base/yca) - B - C - D (commit)
2724 * Update backwards in time: D (base) - C - B - A (commit/yca)
2726 if (allow_forwards_in_time_only) {
2727 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2728 return got_error(GOT_ERR_ANCESTRY);
2729 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2730 got_object_id_cmp(base_commit_id, yca_id) != 0)
2731 return got_error(GOT_ERR_ANCESTRY);
2733 free(yca_id);
2734 return NULL;
2737 static const struct got_error *
2738 check_same_branch(struct got_object_id *commit_id,
2739 struct got_reference *head_ref, struct got_object_id *yca_id,
2740 struct got_repository *repo)
2742 const struct got_error *err = NULL;
2743 struct got_commit_graph *graph = NULL;
2744 struct got_object_id *head_commit_id = NULL;
2745 int is_same_branch = 0;
2747 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2748 if (err)
2749 goto done;
2751 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2752 is_same_branch = 1;
2753 goto done;
2755 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2756 is_same_branch = 1;
2757 goto done;
2760 err = got_commit_graph_open(&graph, "/", 1);
2761 if (err)
2762 goto done;
2764 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2765 check_cancelled, NULL);
2766 if (err)
2767 goto done;
2769 for (;;) {
2770 struct got_object_id *id;
2771 err = got_commit_graph_iter_next(&id, graph, repo,
2772 check_cancelled, NULL);
2773 if (err) {
2774 if (err->code == GOT_ERR_ITER_COMPLETED)
2775 err = NULL;
2776 break;
2779 if (id) {
2780 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2781 break;
2782 if (got_object_id_cmp(id, commit_id) == 0) {
2783 is_same_branch = 1;
2784 break;
2788 done:
2789 if (graph)
2790 got_commit_graph_close(graph);
2791 free(head_commit_id);
2792 if (!err && !is_same_branch)
2793 err = got_error(GOT_ERR_ANCESTRY);
2794 return err;
2797 static const struct got_error *
2798 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2800 static char msg[512];
2801 const char *branch_name;
2803 if (got_ref_is_symbolic(ref))
2804 branch_name = got_ref_get_symref_target(ref);
2805 else
2806 branch_name = got_ref_get_name(ref);
2808 if (strncmp("refs/heads/", branch_name, 11) == 0)
2809 branch_name += 11;
2811 snprintf(msg, sizeof(msg),
2812 "target commit is not contained in branch '%s'; "
2813 "the branch to use must be specified with -b; "
2814 "if necessary a new branch can be created for "
2815 "this commit with 'got branch -c %s BRANCH_NAME'",
2816 branch_name, commit_id_str);
2818 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2821 static const struct got_error *
2822 cmd_checkout(int argc, char *argv[])
2824 const struct got_error *error = NULL;
2825 struct got_repository *repo = NULL;
2826 struct got_reference *head_ref = NULL;
2827 struct got_worktree *worktree = NULL;
2828 char *repo_path = NULL;
2829 char *worktree_path = NULL;
2830 const char *path_prefix = "";
2831 const char *branch_name = GOT_REF_HEAD;
2832 char *commit_id_str = NULL;
2833 char *cwd = NULL;
2834 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2835 struct got_pathlist_head paths;
2836 struct got_checkout_progress_arg cpa;
2838 TAILQ_INIT(&paths);
2840 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2841 switch (ch) {
2842 case 'b':
2843 branch_name = optarg;
2844 break;
2845 case 'c':
2846 commit_id_str = strdup(optarg);
2847 if (commit_id_str == NULL)
2848 return got_error_from_errno("strdup");
2849 break;
2850 case 'E':
2851 allow_nonempty = 1;
2852 break;
2853 case 'p':
2854 path_prefix = optarg;
2855 break;
2856 case 'q':
2857 verbosity = -1;
2858 break;
2859 default:
2860 usage_checkout();
2861 /* NOTREACHED */
2865 argc -= optind;
2866 argv += optind;
2868 #ifndef PROFILE
2869 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2870 "unveil", NULL) == -1)
2871 err(1, "pledge");
2872 #endif
2873 if (argc == 1) {
2874 char *base, *dotgit;
2875 const char *path;
2876 repo_path = realpath(argv[0], NULL);
2877 if (repo_path == NULL)
2878 return got_error_from_errno2("realpath", argv[0]);
2879 cwd = getcwd(NULL, 0);
2880 if (cwd == NULL) {
2881 error = got_error_from_errno("getcwd");
2882 goto done;
2884 if (path_prefix[0])
2885 path = path_prefix;
2886 else
2887 path = repo_path;
2888 error = got_path_basename(&base, path);
2889 if (error)
2890 goto done;
2891 dotgit = strstr(base, ".git");
2892 if (dotgit)
2893 *dotgit = '\0';
2894 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2895 error = got_error_from_errno("asprintf");
2896 free(base);
2897 goto done;
2899 free(base);
2900 } else if (argc == 2) {
2901 repo_path = realpath(argv[0], NULL);
2902 if (repo_path == NULL) {
2903 error = got_error_from_errno2("realpath", argv[0]);
2904 goto done;
2906 worktree_path = realpath(argv[1], NULL);
2907 if (worktree_path == NULL) {
2908 if (errno != ENOENT) {
2909 error = got_error_from_errno2("realpath",
2910 argv[1]);
2911 goto done;
2913 worktree_path = strdup(argv[1]);
2914 if (worktree_path == NULL) {
2915 error = got_error_from_errno("strdup");
2916 goto done;
2919 } else
2920 usage_checkout();
2922 got_path_strip_trailing_slashes(repo_path);
2923 got_path_strip_trailing_slashes(worktree_path);
2925 error = got_repo_open(&repo, repo_path, NULL);
2926 if (error != NULL)
2927 goto done;
2929 /* Pre-create work tree path for unveil(2) */
2930 error = got_path_mkdir(worktree_path);
2931 if (error) {
2932 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2933 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2934 goto done;
2935 if (!allow_nonempty &&
2936 !got_path_dir_is_empty(worktree_path)) {
2937 error = got_error_path(worktree_path,
2938 GOT_ERR_DIR_NOT_EMPTY);
2939 goto done;
2943 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2944 if (error)
2945 goto done;
2947 error = got_ref_open(&head_ref, repo, branch_name, 0);
2948 if (error != NULL)
2949 goto done;
2951 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2952 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2953 goto done;
2955 error = got_worktree_open(&worktree, worktree_path);
2956 if (error != NULL)
2957 goto done;
2959 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2960 path_prefix);
2961 if (error != NULL)
2962 goto done;
2963 if (!same_path_prefix) {
2964 error = got_error(GOT_ERR_PATH_PREFIX);
2965 goto done;
2968 if (commit_id_str) {
2969 struct got_object_id *commit_id;
2970 struct got_reflist_head refs;
2971 TAILQ_INIT(&refs);
2972 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2973 NULL);
2974 if (error)
2975 goto done;
2976 error = got_repo_match_object_id(&commit_id, NULL,
2977 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2978 got_ref_list_free(&refs);
2979 if (error)
2980 goto done;
2981 error = check_linear_ancestry(commit_id,
2982 got_worktree_get_base_commit_id(worktree), 0, repo);
2983 if (error != NULL) {
2984 free(commit_id);
2985 if (error->code == GOT_ERR_ANCESTRY) {
2986 error = checkout_ancestry_error(
2987 head_ref, commit_id_str);
2989 goto done;
2991 error = check_same_branch(commit_id, head_ref, NULL, repo);
2992 if (error) {
2993 if (error->code == GOT_ERR_ANCESTRY) {
2994 error = checkout_ancestry_error(
2995 head_ref, commit_id_str);
2997 goto done;
2999 error = got_worktree_set_base_commit_id(worktree, repo,
3000 commit_id);
3001 free(commit_id);
3002 if (error)
3003 goto done;
3006 error = got_pathlist_append(&paths, "", NULL);
3007 if (error)
3008 goto done;
3009 cpa.worktree_path = worktree_path;
3010 cpa.had_base_commit_ref_error = 0;
3011 cpa.verbosity = verbosity;
3012 error = got_worktree_checkout_files(worktree, &paths, repo,
3013 checkout_progress, &cpa, check_cancelled, NULL);
3014 if (error != NULL)
3015 goto done;
3017 printf("Now shut up and hack\n");
3018 if (cpa.had_base_commit_ref_error)
3019 show_worktree_base_ref_warning();
3020 done:
3021 got_pathlist_free(&paths);
3022 free(commit_id_str);
3023 free(repo_path);
3024 free(worktree_path);
3025 free(cwd);
3026 return error;
3029 struct got_update_progress_arg {
3030 int did_something;
3031 int conflicts;
3032 int obstructed;
3033 int not_updated;
3034 int verbosity;
3037 void
3038 print_update_progress_stats(struct got_update_progress_arg *upa)
3040 if (!upa->did_something)
3041 return;
3043 if (upa->conflicts > 0)
3044 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3045 if (upa->obstructed > 0)
3046 printf("File paths obstructed by a non-regular file: %d\n",
3047 upa->obstructed);
3048 if (upa->not_updated > 0)
3049 printf("Files not updated because of existing merge "
3050 "conflicts: %d\n", upa->not_updated);
3053 __dead static void
3054 usage_update(void)
3056 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3057 "[path ...]\n",
3058 getprogname());
3059 exit(1);
3062 static const struct got_error *
3063 update_progress(void *arg, unsigned char status, const char *path)
3065 struct got_update_progress_arg *upa = arg;
3067 if (status == GOT_STATUS_EXISTS ||
3068 status == GOT_STATUS_BASE_REF_ERR)
3069 return NULL;
3071 upa->did_something = 1;
3073 /* Base commit bump happens silently. */
3074 if (status == GOT_STATUS_BUMP_BASE)
3075 return NULL;
3077 if (status == GOT_STATUS_CONFLICT)
3078 upa->conflicts++;
3079 if (status == GOT_STATUS_OBSTRUCTED)
3080 upa->obstructed++;
3081 if (status == GOT_STATUS_CANNOT_UPDATE)
3082 upa->not_updated++;
3084 while (path[0] == '/')
3085 path++;
3086 if (upa->verbosity >= 0)
3087 printf("%c %s\n", status, path);
3089 return NULL;
3092 static const struct got_error *
3093 switch_head_ref(struct got_reference *head_ref,
3094 struct got_object_id *commit_id, struct got_worktree *worktree,
3095 struct got_repository *repo)
3097 const struct got_error *err = NULL;
3098 char *base_id_str;
3099 int ref_has_moved = 0;
3101 /* Trivial case: switching between two different references. */
3102 if (strcmp(got_ref_get_name(head_ref),
3103 got_worktree_get_head_ref_name(worktree)) != 0) {
3104 printf("Switching work tree from %s to %s\n",
3105 got_worktree_get_head_ref_name(worktree),
3106 got_ref_get_name(head_ref));
3107 return got_worktree_set_head_ref(worktree, head_ref);
3110 err = check_linear_ancestry(commit_id,
3111 got_worktree_get_base_commit_id(worktree), 0, repo);
3112 if (err) {
3113 if (err->code != GOT_ERR_ANCESTRY)
3114 return err;
3115 ref_has_moved = 1;
3117 if (!ref_has_moved)
3118 return NULL;
3120 /* Switching to a rebased branch with the same reference name. */
3121 err = got_object_id_str(&base_id_str,
3122 got_worktree_get_base_commit_id(worktree));
3123 if (err)
3124 return err;
3125 printf("Reference %s now points at a different branch\n",
3126 got_worktree_get_head_ref_name(worktree));
3127 printf("Switching work tree from %s to %s\n", base_id_str,
3128 got_worktree_get_head_ref_name(worktree));
3129 return NULL;
3132 static const struct got_error *
3133 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3135 const struct got_error *err;
3136 int in_progress;
3138 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3139 if (err)
3140 return err;
3141 if (in_progress)
3142 return got_error(GOT_ERR_REBASING);
3144 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3145 if (err)
3146 return err;
3147 if (in_progress)
3148 return got_error(GOT_ERR_HISTEDIT_BUSY);
3150 return NULL;
3153 static const struct got_error *
3154 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3155 char *argv[], struct got_worktree *worktree)
3157 const struct got_error *err = NULL;
3158 char *path;
3159 int i;
3161 if (argc == 0) {
3162 path = strdup("");
3163 if (path == NULL)
3164 return got_error_from_errno("strdup");
3165 return got_pathlist_append(paths, path, NULL);
3168 for (i = 0; i < argc; i++) {
3169 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3170 if (err)
3171 break;
3172 err = got_pathlist_append(paths, path, NULL);
3173 if (err) {
3174 free(path);
3175 break;
3179 return err;
3182 static const struct got_error *
3183 wrap_not_worktree_error(const struct got_error *orig_err,
3184 const char *cmdname, const char *path)
3186 const struct got_error *err;
3187 struct got_repository *repo;
3188 static char msg[512];
3190 err = got_repo_open(&repo, path, NULL);
3191 if (err)
3192 return orig_err;
3194 snprintf(msg, sizeof(msg),
3195 "'got %s' needs a work tree in addition to a git repository\n"
3196 "Work trees can be checked out from this Git repository with "
3197 "'got checkout'.\n"
3198 "The got(1) manual page contains more information.", cmdname);
3199 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3200 got_repo_close(repo);
3201 return err;
3204 static const struct got_error *
3205 cmd_update(int argc, char *argv[])
3207 const struct got_error *error = NULL;
3208 struct got_repository *repo = NULL;
3209 struct got_worktree *worktree = NULL;
3210 char *worktree_path = NULL;
3211 struct got_object_id *commit_id = NULL;
3212 char *commit_id_str = NULL;
3213 const char *branch_name = NULL;
3214 struct got_reference *head_ref = NULL;
3215 struct got_pathlist_head paths;
3216 struct got_pathlist_entry *pe;
3217 int ch, verbosity = 0;
3218 struct got_update_progress_arg upa;
3220 TAILQ_INIT(&paths);
3222 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3223 switch (ch) {
3224 case 'b':
3225 branch_name = optarg;
3226 break;
3227 case 'c':
3228 commit_id_str = strdup(optarg);
3229 if (commit_id_str == NULL)
3230 return got_error_from_errno("strdup");
3231 break;
3232 case 'q':
3233 verbosity = -1;
3234 break;
3235 default:
3236 usage_update();
3237 /* NOTREACHED */
3241 argc -= optind;
3242 argv += optind;
3244 #ifndef PROFILE
3245 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3246 "unveil", NULL) == -1)
3247 err(1, "pledge");
3248 #endif
3249 worktree_path = getcwd(NULL, 0);
3250 if (worktree_path == NULL) {
3251 error = got_error_from_errno("getcwd");
3252 goto done;
3254 error = got_worktree_open(&worktree, worktree_path);
3255 if (error) {
3256 if (error->code == GOT_ERR_NOT_WORKTREE)
3257 error = wrap_not_worktree_error(error, "update",
3258 worktree_path);
3259 goto done;
3262 error = check_rebase_or_histedit_in_progress(worktree);
3263 if (error)
3264 goto done;
3266 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3267 NULL);
3268 if (error != NULL)
3269 goto done;
3271 error = apply_unveil(got_repo_get_path(repo), 0,
3272 got_worktree_get_root_path(worktree));
3273 if (error)
3274 goto done;
3276 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3277 if (error)
3278 goto done;
3280 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3281 got_worktree_get_head_ref_name(worktree), 0);
3282 if (error != NULL)
3283 goto done;
3284 if (commit_id_str == NULL) {
3285 error = got_ref_resolve(&commit_id, repo, head_ref);
3286 if (error != NULL)
3287 goto done;
3288 error = got_object_id_str(&commit_id_str, commit_id);
3289 if (error != NULL)
3290 goto done;
3291 } else {
3292 struct got_reflist_head refs;
3293 TAILQ_INIT(&refs);
3294 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3295 NULL);
3296 if (error)
3297 goto done;
3298 error = got_repo_match_object_id(&commit_id, NULL,
3299 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3300 got_ref_list_free(&refs);
3301 free(commit_id_str);
3302 commit_id_str = NULL;
3303 if (error)
3304 goto done;
3305 error = got_object_id_str(&commit_id_str, commit_id);
3306 if (error)
3307 goto done;
3310 if (branch_name) {
3311 struct got_object_id *head_commit_id;
3312 TAILQ_FOREACH(pe, &paths, entry) {
3313 if (pe->path_len == 0)
3314 continue;
3315 error = got_error_msg(GOT_ERR_BAD_PATH,
3316 "switching between branches requires that "
3317 "the entire work tree gets updated");
3318 goto done;
3320 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3321 if (error)
3322 goto done;
3323 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3324 repo);
3325 free(head_commit_id);
3326 if (error != NULL)
3327 goto done;
3328 error = check_same_branch(commit_id, head_ref, NULL, repo);
3329 if (error)
3330 goto done;
3331 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3332 if (error)
3333 goto done;
3334 } else {
3335 error = check_linear_ancestry(commit_id,
3336 got_worktree_get_base_commit_id(worktree), 0, repo);
3337 if (error != NULL) {
3338 if (error->code == GOT_ERR_ANCESTRY)
3339 error = got_error(GOT_ERR_BRANCH_MOVED);
3340 goto done;
3342 error = check_same_branch(commit_id, head_ref, NULL, repo);
3343 if (error)
3344 goto done;
3347 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3348 commit_id) != 0) {
3349 error = got_worktree_set_base_commit_id(worktree, repo,
3350 commit_id);
3351 if (error)
3352 goto done;
3355 memset(&upa, 0, sizeof(upa));
3356 upa.verbosity = verbosity;
3357 error = got_worktree_checkout_files(worktree, &paths, repo,
3358 update_progress, &upa, check_cancelled, NULL);
3359 if (error != NULL)
3360 goto done;
3362 if (upa.did_something)
3363 printf("Updated to commit %s\n", commit_id_str);
3364 else
3365 printf("Already up-to-date\n");
3366 print_update_progress_stats(&upa);
3367 done:
3368 free(worktree_path);
3369 TAILQ_FOREACH(pe, &paths, entry)
3370 free((char *)pe->path);
3371 got_pathlist_free(&paths);
3372 free(commit_id);
3373 free(commit_id_str);
3374 return error;
3377 static const struct got_error *
3378 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3379 const char *path, int diff_context, int ignore_whitespace,
3380 int force_text_diff, struct got_repository *repo)
3382 const struct got_error *err = NULL;
3383 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3385 if (blob_id1) {
3386 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3387 if (err)
3388 goto done;
3391 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3392 if (err)
3393 goto done;
3395 while (path[0] == '/')
3396 path++;
3397 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3398 diff_context, ignore_whitespace, force_text_diff, stdout);
3399 done:
3400 if (blob1)
3401 got_object_blob_close(blob1);
3402 got_object_blob_close(blob2);
3403 return err;
3406 static const struct got_error *
3407 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3408 const char *path, int diff_context, int ignore_whitespace,
3409 int force_text_diff, struct got_repository *repo)
3411 const struct got_error *err = NULL;
3412 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3413 struct got_diff_blob_output_unidiff_arg arg;
3415 if (tree_id1) {
3416 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3417 if (err)
3418 goto done;
3421 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3422 if (err)
3423 goto done;
3425 arg.diff_context = diff_context;
3426 arg.ignore_whitespace = ignore_whitespace;
3427 arg.force_text_diff = force_text_diff;
3428 arg.outfile = stdout;
3429 arg.line_offsets = NULL;
3430 arg.nlines = 0;
3431 while (path[0] == '/')
3432 path++;
3433 err = got_diff_tree(tree1, tree2, path, path, repo,
3434 got_diff_blob_output_unidiff, &arg, 1);
3435 done:
3436 if (tree1)
3437 got_object_tree_close(tree1);
3438 if (tree2)
3439 got_object_tree_close(tree2);
3440 return err;
3443 static const struct got_error *
3444 get_changed_paths(struct got_pathlist_head *paths,
3445 struct got_commit_object *commit, struct got_repository *repo)
3447 const struct got_error *err = NULL;
3448 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3449 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3450 struct got_object_qid *qid;
3452 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3453 if (qid != NULL) {
3454 struct got_commit_object *pcommit;
3455 err = got_object_open_as_commit(&pcommit, repo,
3456 qid->id);
3457 if (err)
3458 return err;
3460 tree_id1 = got_object_id_dup(
3461 got_object_commit_get_tree_id(pcommit));
3462 if (tree_id1 == NULL) {
3463 got_object_commit_close(pcommit);
3464 return got_error_from_errno("got_object_id_dup");
3466 got_object_commit_close(pcommit);
3470 if (tree_id1) {
3471 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3472 if (err)
3473 goto done;
3476 tree_id2 = got_object_commit_get_tree_id(commit);
3477 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3478 if (err)
3479 goto done;
3481 err = got_diff_tree(tree1, tree2, "", "", repo,
3482 got_diff_tree_collect_changed_paths, paths, 0);
3483 done:
3484 if (tree1)
3485 got_object_tree_close(tree1);
3486 if (tree2)
3487 got_object_tree_close(tree2);
3488 free(tree_id1);
3489 return err;
3492 static const struct got_error *
3493 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3494 const char *path, int diff_context, struct got_repository *repo)
3496 const struct got_error *err = NULL;
3497 struct got_commit_object *pcommit = NULL;
3498 char *id_str1 = NULL, *id_str2 = NULL;
3499 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3500 struct got_object_qid *qid;
3502 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3503 if (qid != NULL) {
3504 err = got_object_open_as_commit(&pcommit, repo,
3505 qid->id);
3506 if (err)
3507 return err;
3510 if (path && path[0] != '\0') {
3511 int obj_type;
3512 err = got_object_id_by_path(&obj_id2, repo, id, path);
3513 if (err)
3514 goto done;
3515 err = got_object_id_str(&id_str2, obj_id2);
3516 if (err) {
3517 free(obj_id2);
3518 goto done;
3520 if (pcommit) {
3521 err = got_object_id_by_path(&obj_id1, repo,
3522 qid->id, path);
3523 if (err) {
3524 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3525 free(obj_id2);
3526 goto done;
3528 } else {
3529 err = got_object_id_str(&id_str1, obj_id1);
3530 if (err) {
3531 free(obj_id2);
3532 goto done;
3536 err = got_object_get_type(&obj_type, repo, obj_id2);
3537 if (err) {
3538 free(obj_id2);
3539 goto done;
3541 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3542 switch (obj_type) {
3543 case GOT_OBJ_TYPE_BLOB:
3544 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3545 0, 0, repo);
3546 break;
3547 case GOT_OBJ_TYPE_TREE:
3548 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3549 0, 0, repo);
3550 break;
3551 default:
3552 err = got_error(GOT_ERR_OBJ_TYPE);
3553 break;
3555 free(obj_id1);
3556 free(obj_id2);
3557 } else {
3558 obj_id2 = got_object_commit_get_tree_id(commit);
3559 err = got_object_id_str(&id_str2, obj_id2);
3560 if (err)
3561 goto done;
3562 if (pcommit) {
3563 obj_id1 = got_object_commit_get_tree_id(pcommit);
3564 err = got_object_id_str(&id_str1, obj_id1);
3565 if (err)
3566 goto done;
3568 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3569 id_str2);
3570 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3571 repo);
3573 done:
3574 free(id_str1);
3575 free(id_str2);
3576 if (pcommit)
3577 got_object_commit_close(pcommit);
3578 return err;
3581 static char *
3582 get_datestr(time_t *time, char *datebuf)
3584 struct tm mytm, *tm;
3585 char *p, *s;
3587 tm = gmtime_r(time, &mytm);
3588 if (tm == NULL)
3589 return NULL;
3590 s = asctime_r(tm, datebuf);
3591 if (s == NULL)
3592 return NULL;
3593 p = strchr(s, '\n');
3594 if (p)
3595 *p = '\0';
3596 return s;
3599 static const struct got_error *
3600 match_logmsg(int *have_match, struct got_object_id *id,
3601 struct got_commit_object *commit, regex_t *regex)
3603 const struct got_error *err = NULL;
3604 regmatch_t regmatch;
3605 char *id_str = NULL, *logmsg = NULL;
3607 *have_match = 0;
3609 err = got_object_id_str(&id_str, id);
3610 if (err)
3611 return err;
3613 err = got_object_commit_get_logmsg(&logmsg, commit);
3614 if (err)
3615 goto done;
3617 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3618 *have_match = 1;
3619 done:
3620 free(id_str);
3621 free(logmsg);
3622 return err;
3625 static void
3626 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3627 regex_t *regex)
3629 regmatch_t regmatch;
3630 struct got_pathlist_entry *pe;
3632 *have_match = 0;
3634 TAILQ_FOREACH(pe, changed_paths, entry) {
3635 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3636 *have_match = 1;
3637 break;
3642 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3644 static const struct got_error*
3645 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3646 struct got_object_id *id, struct got_repository *repo)
3648 static const struct got_error *err = NULL;
3649 struct got_reflist_entry *re;
3650 char *s;
3651 const char *name;
3653 *refs_str = NULL;
3655 TAILQ_FOREACH(re, refs, entry) {
3656 struct got_tag_object *tag = NULL;
3657 struct got_object_id *ref_id;
3658 int cmp;
3660 name = got_ref_get_name(re->ref);
3661 if (strcmp(name, GOT_REF_HEAD) == 0)
3662 continue;
3663 if (strncmp(name, "refs/", 5) == 0)
3664 name += 5;
3665 if (strncmp(name, "got/", 4) == 0)
3666 continue;
3667 if (strncmp(name, "heads/", 6) == 0)
3668 name += 6;
3669 if (strncmp(name, "remotes/", 8) == 0) {
3670 name += 8;
3671 s = strstr(name, "/" GOT_REF_HEAD);
3672 if (s != NULL && s[strlen(s)] == '\0')
3673 continue;
3675 err = got_ref_resolve(&ref_id, repo, re->ref);
3676 if (err)
3677 break;
3678 if (strncmp(name, "tags/", 5) == 0) {
3679 err = got_object_open_as_tag(&tag, repo, ref_id);
3680 if (err) {
3681 if (err->code != GOT_ERR_OBJ_TYPE) {
3682 free(ref_id);
3683 break;
3685 /* Ref points at something other than a tag. */
3686 err = NULL;
3687 tag = NULL;
3690 cmp = got_object_id_cmp(tag ?
3691 got_object_tag_get_object_id(tag) : ref_id, id);
3692 free(ref_id);
3693 if (tag)
3694 got_object_tag_close(tag);
3695 if (cmp != 0)
3696 continue;
3697 s = *refs_str;
3698 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3699 s ? ", " : "", name) == -1) {
3700 err = got_error_from_errno("asprintf");
3701 free(s);
3702 *refs_str = NULL;
3703 break;
3705 free(s);
3708 return err;
3711 static const struct got_error *
3712 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3713 struct got_repository *repo, const char *path,
3714 struct got_pathlist_head *changed_paths, int show_patch,
3715 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3716 const char *custom_refs_str)
3718 const struct got_error *err = NULL;
3719 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3720 char datebuf[26];
3721 time_t committer_time;
3722 const char *author, *committer;
3723 char *refs_str = NULL;
3725 err = got_object_id_str(&id_str, id);
3726 if (err)
3727 return err;
3729 if (custom_refs_str == NULL) {
3730 struct got_reflist_head *refs;
3731 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3732 if (refs) {
3733 err = build_refs_str(&refs_str, refs, id, repo);
3734 if (err)
3735 goto done;
3739 printf(GOT_COMMIT_SEP_STR);
3740 if (custom_refs_str)
3741 printf("commit %s (%s)\n", id_str, custom_refs_str);
3742 else
3743 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3744 refs_str ? refs_str : "", refs_str ? ")" : "");
3745 free(id_str);
3746 id_str = NULL;
3747 free(refs_str);
3748 refs_str = NULL;
3749 printf("from: %s\n", got_object_commit_get_author(commit));
3750 committer_time = got_object_commit_get_committer_time(commit);
3751 datestr = get_datestr(&committer_time, datebuf);
3752 if (datestr)
3753 printf("date: %s UTC\n", datestr);
3754 author = got_object_commit_get_author(commit);
3755 committer = got_object_commit_get_committer(commit);
3756 if (strcmp(author, committer) != 0)
3757 printf("via: %s\n", committer);
3758 if (got_object_commit_get_nparents(commit) > 1) {
3759 const struct got_object_id_queue *parent_ids;
3760 struct got_object_qid *qid;
3761 int n = 1;
3762 parent_ids = got_object_commit_get_parent_ids(commit);
3763 STAILQ_FOREACH(qid, parent_ids, entry) {
3764 err = got_object_id_str(&id_str, qid->id);
3765 if (err)
3766 goto done;
3767 printf("parent %d: %s\n", n++, id_str);
3768 free(id_str);
3769 id_str = NULL;
3773 err = got_object_commit_get_logmsg(&logmsg0, commit);
3774 if (err)
3775 goto done;
3777 logmsg = logmsg0;
3778 do {
3779 line = strsep(&logmsg, "\n");
3780 if (line)
3781 printf(" %s\n", line);
3782 } while (line);
3783 free(logmsg0);
3785 if (changed_paths) {
3786 struct got_pathlist_entry *pe;
3787 TAILQ_FOREACH(pe, changed_paths, entry) {
3788 struct got_diff_changed_path *cp = pe->data;
3789 printf(" %c %s\n", cp->status, pe->path);
3791 printf("\n");
3793 if (show_patch) {
3794 err = print_patch(commit, id, path, diff_context, repo);
3795 if (err == 0)
3796 printf("\n");
3799 if (fflush(stdout) != 0 && err == NULL)
3800 err = got_error_from_errno("fflush");
3801 done:
3802 free(id_str);
3803 free(refs_str);
3804 return err;
3807 static const struct got_error *
3808 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3809 struct got_repository *repo, const char *path, int show_changed_paths,
3810 int show_patch, const char *search_pattern, int diff_context, int limit,
3811 int log_branches, int reverse_display_order,
3812 struct got_reflist_object_id_map *refs_idmap)
3814 const struct got_error *err;
3815 struct got_commit_graph *graph;
3816 regex_t regex;
3817 int have_match;
3818 struct got_object_id_queue reversed_commits;
3819 struct got_object_qid *qid;
3820 struct got_commit_object *commit;
3821 struct got_pathlist_head changed_paths;
3822 struct got_pathlist_entry *pe;
3824 STAILQ_INIT(&reversed_commits);
3825 TAILQ_INIT(&changed_paths);
3827 if (search_pattern && regcomp(&regex, search_pattern,
3828 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3829 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3831 err = got_commit_graph_open(&graph, path, !log_branches);
3832 if (err)
3833 return err;
3834 err = got_commit_graph_iter_start(graph, root_id, repo,
3835 check_cancelled, NULL);
3836 if (err)
3837 goto done;
3838 for (;;) {
3839 struct got_object_id *id;
3841 if (sigint_received || sigpipe_received)
3842 break;
3844 err = got_commit_graph_iter_next(&id, graph, repo,
3845 check_cancelled, NULL);
3846 if (err) {
3847 if (err->code == GOT_ERR_ITER_COMPLETED)
3848 err = NULL;
3849 break;
3851 if (id == NULL)
3852 break;
3854 err = got_object_open_as_commit(&commit, repo, id);
3855 if (err)
3856 break;
3858 if (show_changed_paths && !reverse_display_order) {
3859 err = get_changed_paths(&changed_paths, commit, repo);
3860 if (err)
3861 break;
3864 if (search_pattern) {
3865 err = match_logmsg(&have_match, id, commit, &regex);
3866 if (err) {
3867 got_object_commit_close(commit);
3868 break;
3870 if (have_match == 0 && show_changed_paths)
3871 match_changed_paths(&have_match,
3872 &changed_paths, &regex);
3873 if (have_match == 0) {
3874 got_object_commit_close(commit);
3875 TAILQ_FOREACH(pe, &changed_paths, entry) {
3876 free((char *)pe->path);
3877 free(pe->data);
3879 got_pathlist_free(&changed_paths);
3880 continue;
3884 if (reverse_display_order) {
3885 err = got_object_qid_alloc(&qid, id);
3886 if (err)
3887 break;
3888 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3889 got_object_commit_close(commit);
3890 } else {
3891 err = print_commit(commit, id, repo, path,
3892 show_changed_paths ? &changed_paths : NULL,
3893 show_patch, diff_context, refs_idmap, NULL);
3894 got_object_commit_close(commit);
3895 if (err)
3896 break;
3898 if ((limit && --limit == 0) ||
3899 (end_id && got_object_id_cmp(id, end_id) == 0))
3900 break;
3902 TAILQ_FOREACH(pe, &changed_paths, entry) {
3903 free((char *)pe->path);
3904 free(pe->data);
3906 got_pathlist_free(&changed_paths);
3908 if (reverse_display_order) {
3909 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3910 err = got_object_open_as_commit(&commit, repo, qid->id);
3911 if (err)
3912 break;
3913 if (show_changed_paths) {
3914 err = get_changed_paths(&changed_paths,
3915 commit, repo);
3916 if (err)
3917 break;
3919 err = print_commit(commit, qid->id, repo, path,
3920 show_changed_paths ? &changed_paths : NULL,
3921 show_patch, diff_context, refs_idmap, NULL);
3922 got_object_commit_close(commit);
3923 if (err)
3924 break;
3925 TAILQ_FOREACH(pe, &changed_paths, entry) {
3926 free((char *)pe->path);
3927 free(pe->data);
3929 got_pathlist_free(&changed_paths);
3932 done:
3933 while (!STAILQ_EMPTY(&reversed_commits)) {
3934 qid = STAILQ_FIRST(&reversed_commits);
3935 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3936 got_object_qid_free(qid);
3938 TAILQ_FOREACH(pe, &changed_paths, entry) {
3939 free((char *)pe->path);
3940 free(pe->data);
3942 got_pathlist_free(&changed_paths);
3943 if (search_pattern)
3944 regfree(&regex);
3945 got_commit_graph_close(graph);
3946 return err;
3949 __dead static void
3950 usage_log(void)
3952 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
3953 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
3954 "[-R] [path]\n", getprogname());
3955 exit(1);
3958 static int
3959 get_default_log_limit(void)
3961 const char *got_default_log_limit;
3962 long long n;
3963 const char *errstr;
3965 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3966 if (got_default_log_limit == NULL)
3967 return 0;
3968 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3969 if (errstr != NULL)
3970 return 0;
3971 return n;
3974 static const struct got_error *
3975 cmd_log(int argc, char *argv[])
3977 const struct got_error *error;
3978 struct got_repository *repo = NULL;
3979 struct got_worktree *worktree = NULL;
3980 struct got_object_id *start_id = NULL, *end_id = NULL;
3981 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3982 const char *start_commit = NULL, *end_commit = NULL;
3983 const char *search_pattern = NULL;
3984 int diff_context = -1, ch;
3985 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3986 int reverse_display_order = 0;
3987 const char *errstr;
3988 struct got_reflist_head refs;
3989 struct got_reflist_object_id_map *refs_idmap = NULL;
3991 TAILQ_INIT(&refs);
3993 #ifndef PROFILE
3994 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3995 NULL)
3996 == -1)
3997 err(1, "pledge");
3998 #endif
4000 limit = get_default_log_limit();
4002 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4003 switch (ch) {
4004 case 'p':
4005 show_patch = 1;
4006 break;
4007 case 'P':
4008 show_changed_paths = 1;
4009 break;
4010 case 'c':
4011 start_commit = optarg;
4012 break;
4013 case 'C':
4014 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4015 &errstr);
4016 if (errstr != NULL)
4017 err(1, "-C option %s", errstr);
4018 break;
4019 case 'l':
4020 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4021 if (errstr != NULL)
4022 err(1, "-l option %s", errstr);
4023 break;
4024 case 'b':
4025 log_branches = 1;
4026 break;
4027 case 'r':
4028 repo_path = realpath(optarg, NULL);
4029 if (repo_path == NULL)
4030 return got_error_from_errno2("realpath",
4031 optarg);
4032 got_path_strip_trailing_slashes(repo_path);
4033 break;
4034 case 'R':
4035 reverse_display_order = 1;
4036 break;
4037 case 's':
4038 search_pattern = optarg;
4039 break;
4040 case 'x':
4041 end_commit = optarg;
4042 break;
4043 default:
4044 usage_log();
4045 /* NOTREACHED */
4049 argc -= optind;
4050 argv += optind;
4052 if (diff_context == -1)
4053 diff_context = 3;
4054 else if (!show_patch)
4055 errx(1, "-C requires -p");
4057 cwd = getcwd(NULL, 0);
4058 if (cwd == NULL) {
4059 error = got_error_from_errno("getcwd");
4060 goto done;
4063 if (repo_path == NULL) {
4064 error = got_worktree_open(&worktree, cwd);
4065 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4066 goto done;
4067 error = NULL;
4070 if (argc == 1) {
4071 if (worktree) {
4072 error = got_worktree_resolve_path(&path, worktree,
4073 argv[0]);
4074 if (error)
4075 goto done;
4076 } else {
4077 path = strdup(argv[0]);
4078 if (path == NULL) {
4079 error = got_error_from_errno("strdup");
4080 goto done;
4083 } else if (argc != 0)
4084 usage_log();
4086 if (repo_path == NULL) {
4087 repo_path = worktree ?
4088 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4090 if (repo_path == NULL) {
4091 error = got_error_from_errno("strdup");
4092 goto done;
4095 error = got_repo_open(&repo, repo_path, NULL);
4096 if (error != NULL)
4097 goto done;
4099 error = apply_unveil(got_repo_get_path(repo), 1,
4100 worktree ? got_worktree_get_root_path(worktree) : NULL);
4101 if (error)
4102 goto done;
4104 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4105 if (error)
4106 goto done;
4108 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4109 if (error)
4110 goto done;
4112 if (start_commit == NULL) {
4113 struct got_reference *head_ref;
4114 struct got_commit_object *commit = NULL;
4115 error = got_ref_open(&head_ref, repo,
4116 worktree ? got_worktree_get_head_ref_name(worktree)
4117 : GOT_REF_HEAD, 0);
4118 if (error != NULL)
4119 goto done;
4120 error = got_ref_resolve(&start_id, repo, head_ref);
4121 got_ref_close(head_ref);
4122 if (error != NULL)
4123 goto done;
4124 error = got_object_open_as_commit(&commit, repo,
4125 start_id);
4126 if (error != NULL)
4127 goto done;
4128 got_object_commit_close(commit);
4129 } else {
4130 error = got_repo_match_object_id(&start_id, NULL,
4131 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4132 if (error != NULL)
4133 goto done;
4135 if (end_commit != NULL) {
4136 error = got_repo_match_object_id(&end_id, NULL,
4137 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4138 if (error != NULL)
4139 goto done;
4142 if (worktree) {
4144 * If a path was specified on the command line it was resolved
4145 * to a path in the work tree above. Prepend the work tree's
4146 * path prefix to obtain the corresponding in-repository path.
4148 if (path) {
4149 const char *prefix;
4150 prefix = got_worktree_get_path_prefix(worktree);
4151 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4152 (path[0] != '\0') ? "/" : "", path) == -1) {
4153 error = got_error_from_errno("asprintf");
4154 goto done;
4157 } else
4158 error = got_repo_map_path(&in_repo_path, repo,
4159 path ? path : "");
4160 if (error != NULL)
4161 goto done;
4162 if (in_repo_path) {
4163 free(path);
4164 path = in_repo_path;
4167 error = print_commits(start_id, end_id, repo, path ? path : "",
4168 show_changed_paths, show_patch, search_pattern, diff_context,
4169 limit, log_branches, reverse_display_order, refs_idmap);
4170 done:
4171 free(path);
4172 free(repo_path);
4173 free(cwd);
4174 if (worktree)
4175 got_worktree_close(worktree);
4176 if (repo) {
4177 const struct got_error *close_err = got_repo_close(repo);
4178 if (error == NULL)
4179 error = close_err;
4181 if (refs_idmap)
4182 got_reflist_object_id_map_free(refs_idmap);
4183 got_ref_list_free(&refs);
4184 return error;
4187 __dead static void
4188 usage_diff(void)
4190 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
4191 "[-s] [-w] [object1 object2 | path]\n", getprogname());
4192 exit(1);
4195 struct print_diff_arg {
4196 struct got_repository *repo;
4197 struct got_worktree *worktree;
4198 int diff_context;
4199 const char *id_str;
4200 int header_shown;
4201 int diff_staged;
4202 int ignore_whitespace;
4203 int force_text_diff;
4207 * Create a file which contains the target path of a symlink so we can feed
4208 * it as content to the diff engine.
4210 static const struct got_error *
4211 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4212 const char *abspath)
4214 const struct got_error *err = NULL;
4215 char target_path[PATH_MAX];
4216 ssize_t target_len, outlen;
4218 *fd = -1;
4220 if (dirfd != -1) {
4221 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4222 if (target_len == -1)
4223 return got_error_from_errno2("readlinkat", abspath);
4224 } else {
4225 target_len = readlink(abspath, target_path, PATH_MAX);
4226 if (target_len == -1)
4227 return got_error_from_errno2("readlink", abspath);
4230 *fd = got_opentempfd();
4231 if (*fd == -1)
4232 return got_error_from_errno("got_opentempfd");
4234 outlen = write(*fd, target_path, target_len);
4235 if (outlen == -1) {
4236 err = got_error_from_errno("got_opentempfd");
4237 goto done;
4240 if (lseek(*fd, 0, SEEK_SET) == -1) {
4241 err = got_error_from_errno2("lseek", abspath);
4242 goto done;
4244 done:
4245 if (err) {
4246 close(*fd);
4247 *fd = -1;
4249 return err;
4252 static const struct got_error *
4253 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4254 const char *path, struct got_object_id *blob_id,
4255 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4256 int dirfd, const char *de_name)
4258 struct print_diff_arg *a = arg;
4259 const struct got_error *err = NULL;
4260 struct got_blob_object *blob1 = NULL;
4261 int fd = -1;
4262 FILE *f2 = NULL;
4263 char *abspath = NULL, *label1 = NULL;
4264 struct stat sb;
4266 if (a->diff_staged) {
4267 if (staged_status != GOT_STATUS_MODIFY &&
4268 staged_status != GOT_STATUS_ADD &&
4269 staged_status != GOT_STATUS_DELETE)
4270 return NULL;
4271 } else {
4272 if (staged_status == GOT_STATUS_DELETE)
4273 return NULL;
4274 if (status == GOT_STATUS_NONEXISTENT)
4275 return got_error_set_errno(ENOENT, path);
4276 if (status != GOT_STATUS_MODIFY &&
4277 status != GOT_STATUS_ADD &&
4278 status != GOT_STATUS_DELETE &&
4279 status != GOT_STATUS_CONFLICT)
4280 return NULL;
4283 if (!a->header_shown) {
4284 printf("diff %s %s%s\n", a->id_str,
4285 got_worktree_get_root_path(a->worktree),
4286 a->diff_staged ? " (staged changes)" : "");
4287 a->header_shown = 1;
4290 if (a->diff_staged) {
4291 const char *label1 = NULL, *label2 = NULL;
4292 switch (staged_status) {
4293 case GOT_STATUS_MODIFY:
4294 label1 = path;
4295 label2 = path;
4296 break;
4297 case GOT_STATUS_ADD:
4298 label2 = path;
4299 break;
4300 case GOT_STATUS_DELETE:
4301 label1 = path;
4302 break;
4303 default:
4304 return got_error(GOT_ERR_FILE_STATUS);
4306 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4307 staged_blob_id, label1, label2, a->diff_context,
4308 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4311 if (staged_status == GOT_STATUS_ADD ||
4312 staged_status == GOT_STATUS_MODIFY) {
4313 char *id_str;
4314 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4315 8192);
4316 if (err)
4317 goto done;
4318 err = got_object_id_str(&id_str, staged_blob_id);
4319 if (err)
4320 goto done;
4321 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4322 err = got_error_from_errno("asprintf");
4323 free(id_str);
4324 goto done;
4326 free(id_str);
4327 } else if (status != GOT_STATUS_ADD) {
4328 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4329 if (err)
4330 goto done;
4333 if (status != GOT_STATUS_DELETE) {
4334 if (asprintf(&abspath, "%s/%s",
4335 got_worktree_get_root_path(a->worktree), path) == -1) {
4336 err = got_error_from_errno("asprintf");
4337 goto done;
4340 if (dirfd != -1) {
4341 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4342 if (fd == -1) {
4343 if (errno != ELOOP) {
4344 err = got_error_from_errno2("openat",
4345 abspath);
4346 goto done;
4348 err = get_symlink_target_file(&fd, dirfd,
4349 de_name, abspath);
4350 if (err)
4351 goto done;
4353 } else {
4354 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4355 if (fd == -1) {
4356 if (errno != ELOOP) {
4357 err = got_error_from_errno2("open",
4358 abspath);
4359 goto done;
4361 err = get_symlink_target_file(&fd, dirfd,
4362 de_name, abspath);
4363 if (err)
4364 goto done;
4367 if (fstat(fd, &sb) == -1) {
4368 err = got_error_from_errno2("fstat", abspath);
4369 goto done;
4371 f2 = fdopen(fd, "r");
4372 if (f2 == NULL) {
4373 err = got_error_from_errno2("fdopen", abspath);
4374 goto done;
4376 fd = -1;
4377 } else
4378 sb.st_size = 0;
4380 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4381 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4382 done:
4383 if (blob1)
4384 got_object_blob_close(blob1);
4385 if (f2 && fclose(f2) == EOF && err == NULL)
4386 err = got_error_from_errno("fclose");
4387 if (fd != -1 && close(fd) == -1 && err == NULL)
4388 err = got_error_from_errno("close");
4389 free(abspath);
4390 return err;
4393 static const struct got_error *
4394 cmd_diff(int argc, char *argv[])
4396 const struct got_error *error;
4397 struct got_repository *repo = NULL;
4398 struct got_worktree *worktree = NULL;
4399 char *cwd = NULL, *repo_path = NULL;
4400 struct got_object_id *id1 = NULL, *id2 = NULL;
4401 const char *id_str1 = NULL, *id_str2 = NULL;
4402 char *label1 = NULL, *label2 = NULL;
4403 int type1, type2;
4404 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch;
4405 int force_text_diff = 0;
4406 const char *errstr;
4407 char *path = NULL;
4408 struct got_reflist_head refs;
4410 TAILQ_INIT(&refs);
4412 #ifndef PROFILE
4413 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4414 NULL) == -1)
4415 err(1, "pledge");
4416 #endif
4418 while ((ch = getopt(argc, argv, "aC:r:sw")) != -1) {
4419 switch (ch) {
4420 case 'a':
4421 force_text_diff = 1;
4422 break;
4423 case 'C':
4424 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4425 &errstr);
4426 if (errstr != NULL)
4427 err(1, "-C option %s", errstr);
4428 break;
4429 case 'r':
4430 repo_path = realpath(optarg, NULL);
4431 if (repo_path == NULL)
4432 return got_error_from_errno2("realpath",
4433 optarg);
4434 got_path_strip_trailing_slashes(repo_path);
4435 break;
4436 case 's':
4437 diff_staged = 1;
4438 break;
4439 case 'w':
4440 ignore_whitespace = 1;
4441 break;
4442 default:
4443 usage_diff();
4444 /* NOTREACHED */
4448 argc -= optind;
4449 argv += optind;
4451 cwd = getcwd(NULL, 0);
4452 if (cwd == NULL) {
4453 error = got_error_from_errno("getcwd");
4454 goto done;
4456 if (argc <= 1) {
4457 if (repo_path)
4458 errx(1,
4459 "-r option can't be used when diffing a work tree");
4460 error = got_worktree_open(&worktree, cwd);
4461 if (error) {
4462 if (error->code == GOT_ERR_NOT_WORKTREE)
4463 error = wrap_not_worktree_error(error, "diff",
4464 cwd);
4465 goto done;
4467 repo_path = strdup(got_worktree_get_repo_path(worktree));
4468 if (repo_path == NULL) {
4469 error = got_error_from_errno("strdup");
4470 goto done;
4472 if (argc == 1) {
4473 error = got_worktree_resolve_path(&path, worktree,
4474 argv[0]);
4475 if (error)
4476 goto done;
4477 } else {
4478 path = strdup("");
4479 if (path == NULL) {
4480 error = got_error_from_errno("strdup");
4481 goto done;
4484 } else if (argc == 2) {
4485 if (diff_staged)
4486 errx(1, "-s option can't be used when diffing "
4487 "objects in repository");
4488 id_str1 = argv[0];
4489 id_str2 = argv[1];
4490 if (repo_path == NULL) {
4491 error = got_worktree_open(&worktree, cwd);
4492 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4493 goto done;
4494 repo_path = strdup(worktree ?
4495 got_worktree_get_repo_path(worktree) : cwd);
4496 if (repo_path == NULL) {
4497 error = got_error_from_errno("strdup");
4498 goto done;
4501 } else
4502 usage_diff();
4504 error = got_repo_open(&repo, repo_path, NULL);
4505 free(repo_path);
4506 if (error != NULL)
4507 goto done;
4509 error = apply_unveil(got_repo_get_path(repo), 1,
4510 worktree ? got_worktree_get_root_path(worktree) : NULL);
4511 if (error)
4512 goto done;
4514 if (argc <= 1) {
4515 struct print_diff_arg arg;
4516 struct got_pathlist_head paths;
4517 char *id_str;
4519 TAILQ_INIT(&paths);
4521 error = got_object_id_str(&id_str,
4522 got_worktree_get_base_commit_id(worktree));
4523 if (error)
4524 goto done;
4525 arg.repo = repo;
4526 arg.worktree = worktree;
4527 arg.diff_context = diff_context;
4528 arg.id_str = id_str;
4529 arg.header_shown = 0;
4530 arg.diff_staged = diff_staged;
4531 arg.ignore_whitespace = ignore_whitespace;
4532 arg.force_text_diff = force_text_diff;
4534 error = got_pathlist_append(&paths, path, NULL);
4535 if (error)
4536 goto done;
4538 error = got_worktree_status(worktree, &paths, repo, 0,
4539 print_diff, &arg, check_cancelled, NULL);
4540 free(id_str);
4541 got_pathlist_free(&paths);
4542 goto done;
4545 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4546 if (error)
4547 return error;
4549 error = got_repo_match_object_id(&id1, &label1, id_str1,
4550 GOT_OBJ_TYPE_ANY, &refs, repo);
4551 if (error)
4552 goto done;
4554 error = got_repo_match_object_id(&id2, &label2, id_str2,
4555 GOT_OBJ_TYPE_ANY, &refs, repo);
4556 if (error)
4557 goto done;
4559 error = got_object_get_type(&type1, repo, id1);
4560 if (error)
4561 goto done;
4563 error = got_object_get_type(&type2, repo, id2);
4564 if (error)
4565 goto done;
4567 if (type1 != type2) {
4568 error = got_error(GOT_ERR_OBJ_TYPE);
4569 goto done;
4572 switch (type1) {
4573 case GOT_OBJ_TYPE_BLOB:
4574 error = got_diff_objects_as_blobs(NULL, NULL, id1, id2,
4575 NULL, NULL, diff_context, ignore_whitespace,
4576 force_text_diff, repo, stdout);
4577 break;
4578 case GOT_OBJ_TYPE_TREE:
4579 error = got_diff_objects_as_trees(NULL, NULL, id1, id2,
4580 "", "", diff_context, ignore_whitespace, force_text_diff,
4581 repo, stdout);
4582 break;
4583 case GOT_OBJ_TYPE_COMMIT:
4584 printf("diff %s %s\n", label1, label2);
4585 error = got_diff_objects_as_commits(NULL, NULL, id1, id2,
4586 diff_context, ignore_whitespace, force_text_diff, repo,
4587 stdout);
4588 break;
4589 default:
4590 error = got_error(GOT_ERR_OBJ_TYPE);
4592 done:
4593 free(label1);
4594 free(label2);
4595 free(id1);
4596 free(id2);
4597 free(path);
4598 if (worktree)
4599 got_worktree_close(worktree);
4600 if (repo) {
4601 const struct got_error *close_err = got_repo_close(repo);
4602 if (error == NULL)
4603 error = close_err;
4605 got_ref_list_free(&refs);
4606 return error;
4609 __dead static void
4610 usage_blame(void)
4612 fprintf(stderr,
4613 "usage: %s blame [-c commit] [-r repository-path] path\n",
4614 getprogname());
4615 exit(1);
4618 struct blame_line {
4619 int annotated;
4620 char *id_str;
4621 char *committer;
4622 char datebuf[11]; /* YYYY-MM-DD + NUL */
4625 struct blame_cb_args {
4626 struct blame_line *lines;
4627 int nlines;
4628 int nlines_prec;
4629 int lineno_cur;
4630 off_t *line_offsets;
4631 FILE *f;
4632 struct got_repository *repo;
4635 static const struct got_error *
4636 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4638 const struct got_error *err = NULL;
4639 struct blame_cb_args *a = arg;
4640 struct blame_line *bline;
4641 char *line = NULL;
4642 size_t linesize = 0;
4643 struct got_commit_object *commit = NULL;
4644 off_t offset;
4645 struct tm tm;
4646 time_t committer_time;
4648 if (nlines != a->nlines ||
4649 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4650 return got_error(GOT_ERR_RANGE);
4652 if (sigint_received)
4653 return got_error(GOT_ERR_ITER_COMPLETED);
4655 if (lineno == -1)
4656 return NULL; /* no change in this commit */
4658 /* Annotate this line. */
4659 bline = &a->lines[lineno - 1];
4660 if (bline->annotated)
4661 return NULL;
4662 err = got_object_id_str(&bline->id_str, id);
4663 if (err)
4664 return err;
4666 err = got_object_open_as_commit(&commit, a->repo, id);
4667 if (err)
4668 goto done;
4670 bline->committer = strdup(got_object_commit_get_committer(commit));
4671 if (bline->committer == NULL) {
4672 err = got_error_from_errno("strdup");
4673 goto done;
4676 committer_time = got_object_commit_get_committer_time(commit);
4677 if (gmtime_r(&committer_time, &tm) == NULL)
4678 return got_error_from_errno("gmtime_r");
4679 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4680 &tm) == 0) {
4681 err = got_error(GOT_ERR_NO_SPACE);
4682 goto done;
4684 bline->annotated = 1;
4686 /* Print lines annotated so far. */
4687 bline = &a->lines[a->lineno_cur - 1];
4688 if (!bline->annotated)
4689 goto done;
4691 offset = a->line_offsets[a->lineno_cur - 1];
4692 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4693 err = got_error_from_errno("fseeko");
4694 goto done;
4697 while (bline->annotated) {
4698 char *smallerthan, *at, *nl, *committer;
4699 size_t len;
4701 if (getline(&line, &linesize, a->f) == -1) {
4702 if (ferror(a->f))
4703 err = got_error_from_errno("getline");
4704 break;
4707 committer = bline->committer;
4708 smallerthan = strchr(committer, '<');
4709 if (smallerthan && smallerthan[1] != '\0')
4710 committer = smallerthan + 1;
4711 at = strchr(committer, '@');
4712 if (at)
4713 *at = '\0';
4714 len = strlen(committer);
4715 if (len >= 9)
4716 committer[8] = '\0';
4718 nl = strchr(line, '\n');
4719 if (nl)
4720 *nl = '\0';
4721 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4722 bline->id_str, bline->datebuf, committer, line);
4724 a->lineno_cur++;
4725 bline = &a->lines[a->lineno_cur - 1];
4727 done:
4728 if (commit)
4729 got_object_commit_close(commit);
4730 free(line);
4731 return err;
4734 static const struct got_error *
4735 cmd_blame(int argc, char *argv[])
4737 const struct got_error *error;
4738 struct got_repository *repo = NULL;
4739 struct got_worktree *worktree = NULL;
4740 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4741 char *link_target = NULL;
4742 struct got_object_id *obj_id = NULL;
4743 struct got_object_id *commit_id = NULL;
4744 struct got_blob_object *blob = NULL;
4745 char *commit_id_str = NULL;
4746 struct blame_cb_args bca;
4747 int ch, obj_type, i;
4748 off_t filesize;
4750 memset(&bca, 0, sizeof(bca));
4752 #ifndef PROFILE
4753 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4754 NULL) == -1)
4755 err(1, "pledge");
4756 #endif
4758 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4759 switch (ch) {
4760 case 'c':
4761 commit_id_str = optarg;
4762 break;
4763 case 'r':
4764 repo_path = realpath(optarg, NULL);
4765 if (repo_path == NULL)
4766 return got_error_from_errno2("realpath",
4767 optarg);
4768 got_path_strip_trailing_slashes(repo_path);
4769 break;
4770 default:
4771 usage_blame();
4772 /* NOTREACHED */
4776 argc -= optind;
4777 argv += optind;
4779 if (argc == 1)
4780 path = argv[0];
4781 else
4782 usage_blame();
4784 cwd = getcwd(NULL, 0);
4785 if (cwd == NULL) {
4786 error = got_error_from_errno("getcwd");
4787 goto done;
4789 if (repo_path == NULL) {
4790 error = got_worktree_open(&worktree, cwd);
4791 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4792 goto done;
4793 else
4794 error = NULL;
4795 if (worktree) {
4796 repo_path =
4797 strdup(got_worktree_get_repo_path(worktree));
4798 if (repo_path == NULL) {
4799 error = got_error_from_errno("strdup");
4800 if (error)
4801 goto done;
4803 } else {
4804 repo_path = strdup(cwd);
4805 if (repo_path == NULL) {
4806 error = got_error_from_errno("strdup");
4807 goto done;
4812 error = got_repo_open(&repo, repo_path, NULL);
4813 if (error != NULL)
4814 goto done;
4816 if (worktree) {
4817 const char *prefix = got_worktree_get_path_prefix(worktree);
4818 char *p;
4820 error = got_worktree_resolve_path(&p, worktree, path);
4821 if (error)
4822 goto done;
4823 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4824 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4825 p) == -1) {
4826 error = got_error_from_errno("asprintf");
4827 free(p);
4828 goto done;
4830 free(p);
4831 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4832 } else {
4833 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
4834 if (error)
4835 goto done;
4836 error = got_repo_map_path(&in_repo_path, repo, path);
4838 if (error)
4839 goto done;
4841 if (commit_id_str == NULL) {
4842 struct got_reference *head_ref;
4843 error = got_ref_open(&head_ref, repo, worktree ?
4844 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
4845 if (error != NULL)
4846 goto done;
4847 error = got_ref_resolve(&commit_id, repo, head_ref);
4848 got_ref_close(head_ref);
4849 if (error != NULL)
4850 goto done;
4851 } else {
4852 struct got_reflist_head refs;
4853 TAILQ_INIT(&refs);
4854 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4855 NULL);
4856 if (error)
4857 goto done;
4858 error = got_repo_match_object_id(&commit_id, NULL,
4859 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4860 got_ref_list_free(&refs);
4861 if (error)
4862 goto done;
4865 error = got_object_resolve_symlinks(&link_target, in_repo_path,
4866 commit_id, repo);
4867 if (error)
4868 goto done;
4870 error = got_object_id_by_path(&obj_id, repo, commit_id,
4871 link_target ? link_target : in_repo_path);
4872 if (error)
4873 goto done;
4875 error = got_object_get_type(&obj_type, repo, obj_id);
4876 if (error)
4877 goto done;
4879 if (obj_type != GOT_OBJ_TYPE_BLOB) {
4880 error = got_error_path(link_target ? link_target : in_repo_path,
4881 GOT_ERR_OBJ_TYPE);
4882 goto done;
4885 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
4886 if (error)
4887 goto done;
4888 bca.f = got_opentemp();
4889 if (bca.f == NULL) {
4890 error = got_error_from_errno("got_opentemp");
4891 goto done;
4893 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
4894 &bca.line_offsets, bca.f, blob);
4895 if (error || bca.nlines == 0)
4896 goto done;
4898 /* Don't include \n at EOF in the blame line count. */
4899 if (bca.line_offsets[bca.nlines - 1] == filesize)
4900 bca.nlines--;
4902 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
4903 if (bca.lines == NULL) {
4904 error = got_error_from_errno("calloc");
4905 goto done;
4907 bca.lineno_cur = 1;
4908 bca.nlines_prec = 0;
4909 i = bca.nlines;
4910 while (i > 0) {
4911 i /= 10;
4912 bca.nlines_prec++;
4914 bca.repo = repo;
4916 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
4917 repo, blame_cb, &bca, check_cancelled, NULL);
4918 done:
4919 free(in_repo_path);
4920 free(link_target);
4921 free(repo_path);
4922 free(cwd);
4923 free(commit_id);
4924 free(obj_id);
4925 if (blob)
4926 got_object_blob_close(blob);
4927 if (worktree)
4928 got_worktree_close(worktree);
4929 if (repo) {
4930 const struct got_error *close_err = got_repo_close(repo);
4931 if (error == NULL)
4932 error = close_err;
4934 if (bca.lines) {
4935 for (i = 0; i < bca.nlines; i++) {
4936 struct blame_line *bline = &bca.lines[i];
4937 free(bline->id_str);
4938 free(bline->committer);
4940 free(bca.lines);
4942 free(bca.line_offsets);
4943 if (bca.f && fclose(bca.f) == EOF && error == NULL)
4944 error = got_error_from_errno("fclose");
4945 return error;
4948 __dead static void
4949 usage_tree(void)
4951 fprintf(stderr,
4952 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
4953 getprogname());
4954 exit(1);
4957 static const struct got_error *
4958 print_entry(struct got_tree_entry *te, const char *id, const char *path,
4959 const char *root_path, struct got_repository *repo)
4961 const struct got_error *err = NULL;
4962 int is_root_path = (strcmp(path, root_path) == 0);
4963 const char *modestr = "";
4964 mode_t mode = got_tree_entry_get_mode(te);
4965 char *link_target = NULL;
4967 path += strlen(root_path);
4968 while (path[0] == '/')
4969 path++;
4971 if (got_object_tree_entry_is_submodule(te))
4972 modestr = "$";
4973 else if (S_ISLNK(mode)) {
4974 int i;
4976 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
4977 if (err)
4978 return err;
4979 for (i = 0; i < strlen(link_target); i++) {
4980 if (!isprint((unsigned char)link_target[i]))
4981 link_target[i] = '?';
4984 modestr = "@";
4986 else if (S_ISDIR(mode))
4987 modestr = "/";
4988 else if (mode & S_IXUSR)
4989 modestr = "*";
4991 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
4992 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
4993 link_target ? " -> ": "", link_target ? link_target : "");
4995 free(link_target);
4996 return NULL;
4999 static const struct got_error *
5000 print_tree(const char *path, struct got_object_id *commit_id,
5001 int show_ids, int recurse, const char *root_path,
5002 struct got_repository *repo)
5004 const struct got_error *err = NULL;
5005 struct got_object_id *tree_id = NULL;
5006 struct got_tree_object *tree = NULL;
5007 int nentries, i;
5009 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5010 if (err)
5011 goto done;
5013 err = got_object_open_as_tree(&tree, repo, tree_id);
5014 if (err)
5015 goto done;
5016 nentries = got_object_tree_get_nentries(tree);
5017 for (i = 0; i < nentries; i++) {
5018 struct got_tree_entry *te;
5019 char *id = NULL;
5021 if (sigint_received || sigpipe_received)
5022 break;
5024 te = got_object_tree_get_entry(tree, i);
5025 if (show_ids) {
5026 char *id_str;
5027 err = got_object_id_str(&id_str,
5028 got_tree_entry_get_id(te));
5029 if (err)
5030 goto done;
5031 if (asprintf(&id, "%s ", id_str) == -1) {
5032 err = got_error_from_errno("asprintf");
5033 free(id_str);
5034 goto done;
5036 free(id_str);
5038 err = print_entry(te, id, path, root_path, repo);
5039 free(id);
5040 if (err)
5041 goto done;
5043 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5044 char *child_path;
5045 if (asprintf(&child_path, "%s%s%s", path,
5046 path[0] == '/' && path[1] == '\0' ? "" : "/",
5047 got_tree_entry_get_name(te)) == -1) {
5048 err = got_error_from_errno("asprintf");
5049 goto done;
5051 err = print_tree(child_path, commit_id, show_ids, 1,
5052 root_path, repo);
5053 free(child_path);
5054 if (err)
5055 goto done;
5058 done:
5059 if (tree)
5060 got_object_tree_close(tree);
5061 free(tree_id);
5062 return err;
5065 static const struct got_error *
5066 cmd_tree(int argc, char *argv[])
5068 const struct got_error *error;
5069 struct got_repository *repo = NULL;
5070 struct got_worktree *worktree = NULL;
5071 const char *path, *refname = NULL;
5072 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5073 struct got_object_id *commit_id = NULL;
5074 char *commit_id_str = NULL;
5075 int show_ids = 0, recurse = 0;
5076 int ch;
5078 #ifndef PROFILE
5079 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5080 NULL) == -1)
5081 err(1, "pledge");
5082 #endif
5084 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5085 switch (ch) {
5086 case 'c':
5087 commit_id_str = optarg;
5088 break;
5089 case 'r':
5090 repo_path = realpath(optarg, NULL);
5091 if (repo_path == NULL)
5092 return got_error_from_errno2("realpath",
5093 optarg);
5094 got_path_strip_trailing_slashes(repo_path);
5095 break;
5096 case 'i':
5097 show_ids = 1;
5098 break;
5099 case 'R':
5100 recurse = 1;
5101 break;
5102 default:
5103 usage_tree();
5104 /* NOTREACHED */
5108 argc -= optind;
5109 argv += optind;
5111 if (argc == 1)
5112 path = argv[0];
5113 else if (argc > 1)
5114 usage_tree();
5115 else
5116 path = NULL;
5118 cwd = getcwd(NULL, 0);
5119 if (cwd == NULL) {
5120 error = got_error_from_errno("getcwd");
5121 goto done;
5123 if (repo_path == NULL) {
5124 error = got_worktree_open(&worktree, cwd);
5125 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5126 goto done;
5127 else
5128 error = NULL;
5129 if (worktree) {
5130 repo_path =
5131 strdup(got_worktree_get_repo_path(worktree));
5132 if (repo_path == NULL)
5133 error = got_error_from_errno("strdup");
5134 if (error)
5135 goto done;
5136 } else {
5137 repo_path = strdup(cwd);
5138 if (repo_path == NULL) {
5139 error = got_error_from_errno("strdup");
5140 goto done;
5145 error = got_repo_open(&repo, repo_path, NULL);
5146 if (error != NULL)
5147 goto done;
5149 if (worktree) {
5150 const char *prefix = got_worktree_get_path_prefix(worktree);
5151 char *p;
5153 if (path == NULL)
5154 path = "";
5155 error = got_worktree_resolve_path(&p, worktree, path);
5156 if (error)
5157 goto done;
5158 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5159 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5160 p) == -1) {
5161 error = got_error_from_errno("asprintf");
5162 free(p);
5163 goto done;
5165 free(p);
5166 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5167 if (error)
5168 goto done;
5169 } else {
5170 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5171 if (error)
5172 goto done;
5173 if (path == NULL)
5174 path = "/";
5175 error = got_repo_map_path(&in_repo_path, repo, path);
5176 if (error != NULL)
5177 goto done;
5180 if (commit_id_str == NULL) {
5181 struct got_reference *head_ref;
5182 if (worktree)
5183 refname = got_worktree_get_head_ref_name(worktree);
5184 else
5185 refname = GOT_REF_HEAD;
5186 error = got_ref_open(&head_ref, repo, refname, 0);
5187 if (error != NULL)
5188 goto done;
5189 error = got_ref_resolve(&commit_id, repo, head_ref);
5190 got_ref_close(head_ref);
5191 if (error != NULL)
5192 goto done;
5193 } else {
5194 struct got_reflist_head refs;
5195 TAILQ_INIT(&refs);
5196 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5197 NULL);
5198 if (error)
5199 goto done;
5200 error = got_repo_match_object_id(&commit_id, NULL,
5201 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5202 got_ref_list_free(&refs);
5203 if (error)
5204 goto done;
5207 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5208 in_repo_path, repo);
5209 done:
5210 free(in_repo_path);
5211 free(repo_path);
5212 free(cwd);
5213 free(commit_id);
5214 if (worktree)
5215 got_worktree_close(worktree);
5216 if (repo) {
5217 const struct got_error *close_err = got_repo_close(repo);
5218 if (error == NULL)
5219 error = close_err;
5221 return error;
5224 __dead static void
5225 usage_status(void)
5227 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] [path ...]\n",
5228 getprogname());
5229 exit(1);
5232 static const struct got_error *
5233 print_status(void *arg, unsigned char status, unsigned char staged_status,
5234 const char *path, struct got_object_id *blob_id,
5235 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5236 int dirfd, const char *de_name)
5238 if (status == staged_status && (status == GOT_STATUS_DELETE))
5239 status = GOT_STATUS_NO_CHANGE;
5240 if (arg) {
5241 char *status_codes = arg;
5242 size_t ncodes = strlen(status_codes);
5243 int i;
5244 for (i = 0; i < ncodes ; i++) {
5245 if (status == status_codes[i] ||
5246 staged_status == status_codes[i])
5247 break;
5249 if (i == ncodes)
5250 return NULL;
5252 printf("%c%c %s\n", status, staged_status, path);
5253 return NULL;
5256 static const struct got_error *
5257 cmd_status(int argc, char *argv[])
5259 const struct got_error *error = NULL;
5260 struct got_repository *repo = NULL;
5261 struct got_worktree *worktree = NULL;
5262 char *cwd = NULL, *status_codes = NULL;;
5263 struct got_pathlist_head paths;
5264 struct got_pathlist_entry *pe;
5265 int ch, i, no_ignores = 0;
5267 TAILQ_INIT(&paths);
5269 while ((ch = getopt(argc, argv, "Is:")) != -1) {
5270 switch (ch) {
5271 case 'I':
5272 no_ignores = 1;
5273 break;
5274 case 's':
5275 for (i = 0; i < strlen(optarg); i++) {
5276 switch (optarg[i]) {
5277 case GOT_STATUS_MODIFY:
5278 case GOT_STATUS_ADD:
5279 case GOT_STATUS_DELETE:
5280 case GOT_STATUS_CONFLICT:
5281 case GOT_STATUS_MISSING:
5282 case GOT_STATUS_OBSTRUCTED:
5283 case GOT_STATUS_UNVERSIONED:
5284 case GOT_STATUS_MODE_CHANGE:
5285 case GOT_STATUS_NONEXISTENT:
5286 break;
5287 default:
5288 errx(1, "invalid status code '%c'",
5289 optarg[i]);
5292 status_codes = optarg;
5293 break;
5294 default:
5295 usage_status();
5296 /* NOTREACHED */
5300 argc -= optind;
5301 argv += optind;
5303 #ifndef PROFILE
5304 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5305 NULL) == -1)
5306 err(1, "pledge");
5307 #endif
5308 cwd = getcwd(NULL, 0);
5309 if (cwd == NULL) {
5310 error = got_error_from_errno("getcwd");
5311 goto done;
5314 error = got_worktree_open(&worktree, cwd);
5315 if (error) {
5316 if (error->code == GOT_ERR_NOT_WORKTREE)
5317 error = wrap_not_worktree_error(error, "status", cwd);
5318 goto done;
5321 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5322 NULL);
5323 if (error != NULL)
5324 goto done;
5326 error = apply_unveil(got_repo_get_path(repo), 1,
5327 got_worktree_get_root_path(worktree));
5328 if (error)
5329 goto done;
5331 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5332 if (error)
5333 goto done;
5335 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5336 print_status, status_codes, check_cancelled, NULL);
5337 done:
5338 TAILQ_FOREACH(pe, &paths, entry)
5339 free((char *)pe->path);
5340 got_pathlist_free(&paths);
5341 free(cwd);
5342 return error;
5345 __dead static void
5346 usage_ref(void)
5348 fprintf(stderr,
5349 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5350 "[-d] [name]\n",
5351 getprogname());
5352 exit(1);
5355 static const struct got_error *
5356 list_refs(struct got_repository *repo, const char *refname)
5358 static const struct got_error *err = NULL;
5359 struct got_reflist_head refs;
5360 struct got_reflist_entry *re;
5362 TAILQ_INIT(&refs);
5363 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5364 if (err)
5365 return err;
5367 TAILQ_FOREACH(re, &refs, entry) {
5368 char *refstr;
5369 refstr = got_ref_to_str(re->ref);
5370 if (refstr == NULL)
5371 return got_error_from_errno("got_ref_to_str");
5372 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5373 free(refstr);
5376 got_ref_list_free(&refs);
5377 return NULL;
5380 static const struct got_error *
5381 delete_ref_by_name(struct got_repository *repo, const char *refname)
5383 const struct got_error *err;
5384 struct got_reference *ref;
5386 err = got_ref_open(&ref, repo, refname, 0);
5387 if (err)
5388 return err;
5390 err = delete_ref(repo, ref);
5391 got_ref_close(ref);
5392 return err;
5395 static const struct got_error *
5396 add_ref(struct got_repository *repo, const char *refname, const char *target)
5398 const struct got_error *err = NULL;
5399 struct got_object_id *id;
5400 struct got_reference *ref = NULL;
5403 * Don't let the user create a reference name with a leading '-'.
5404 * While technically a valid reference name, this case is usually
5405 * an unintended typo.
5407 if (refname[0] == '-')
5408 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5410 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5411 repo);
5412 if (err) {
5413 struct got_reference *target_ref;
5415 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5416 return err;
5417 err = got_ref_open(&target_ref, repo, target, 0);
5418 if (err)
5419 return err;
5420 err = got_ref_resolve(&id, repo, target_ref);
5421 got_ref_close(target_ref);
5422 if (err)
5423 return err;
5426 err = got_ref_alloc(&ref, refname, id);
5427 if (err)
5428 goto done;
5430 err = got_ref_write(ref, repo);
5431 done:
5432 if (ref)
5433 got_ref_close(ref);
5434 free(id);
5435 return err;
5438 static const struct got_error *
5439 add_symref(struct got_repository *repo, const char *refname, const char *target)
5441 const struct got_error *err = NULL;
5442 struct got_reference *ref = NULL;
5443 struct got_reference *target_ref = NULL;
5446 * Don't let the user create a reference name with a leading '-'.
5447 * While technically a valid reference name, this case is usually
5448 * an unintended typo.
5450 if (refname[0] == '-')
5451 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5453 err = got_ref_open(&target_ref, repo, target, 0);
5454 if (err)
5455 return err;
5457 err = got_ref_alloc_symref(&ref, refname, target_ref);
5458 if (err)
5459 goto done;
5461 err = got_ref_write(ref, repo);
5462 done:
5463 if (target_ref)
5464 got_ref_close(target_ref);
5465 if (ref)
5466 got_ref_close(ref);
5467 return err;
5470 static const struct got_error *
5471 cmd_ref(int argc, char *argv[])
5473 const struct got_error *error = NULL;
5474 struct got_repository *repo = NULL;
5475 struct got_worktree *worktree = NULL;
5476 char *cwd = NULL, *repo_path = NULL;
5477 int ch, do_list = 0, do_delete = 0;
5478 const char *obj_arg = NULL, *symref_target= NULL;
5479 char *refname = NULL;
5481 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5482 switch (ch) {
5483 case 'c':
5484 obj_arg = optarg;
5485 break;
5486 case 'd':
5487 do_delete = 1;
5488 break;
5489 case 'r':
5490 repo_path = realpath(optarg, NULL);
5491 if (repo_path == NULL)
5492 return got_error_from_errno2("realpath",
5493 optarg);
5494 got_path_strip_trailing_slashes(repo_path);
5495 break;
5496 case 'l':
5497 do_list = 1;
5498 break;
5499 case 's':
5500 symref_target = optarg;
5501 break;
5502 default:
5503 usage_ref();
5504 /* NOTREACHED */
5508 if (obj_arg && do_list)
5509 option_conflict('c', 'l');
5510 if (obj_arg && do_delete)
5511 option_conflict('c', 'd');
5512 if (obj_arg && symref_target)
5513 option_conflict('c', 's');
5514 if (symref_target && do_delete)
5515 option_conflict('s', 'd');
5516 if (symref_target && do_list)
5517 option_conflict('s', 'l');
5518 if (do_delete && do_list)
5519 option_conflict('d', 'l');
5521 argc -= optind;
5522 argv += optind;
5524 if (do_list) {
5525 if (argc != 0 && argc != 1)
5526 usage_ref();
5527 if (argc == 1) {
5528 refname = strdup(argv[0]);
5529 if (refname == NULL) {
5530 error = got_error_from_errno("strdup");
5531 goto done;
5534 } else {
5535 if (argc != 1)
5536 usage_ref();
5537 refname = strdup(argv[0]);
5538 if (refname == NULL) {
5539 error = got_error_from_errno("strdup");
5540 goto done;
5544 if (refname)
5545 got_path_strip_trailing_slashes(refname);
5547 #ifndef PROFILE
5548 if (do_list) {
5549 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5550 NULL) == -1)
5551 err(1, "pledge");
5552 } else {
5553 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5554 "sendfd unveil", NULL) == -1)
5555 err(1, "pledge");
5557 #endif
5558 cwd = getcwd(NULL, 0);
5559 if (cwd == NULL) {
5560 error = got_error_from_errno("getcwd");
5561 goto done;
5564 if (repo_path == NULL) {
5565 error = got_worktree_open(&worktree, cwd);
5566 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5567 goto done;
5568 else
5569 error = NULL;
5570 if (worktree) {
5571 repo_path =
5572 strdup(got_worktree_get_repo_path(worktree));
5573 if (repo_path == NULL)
5574 error = got_error_from_errno("strdup");
5575 if (error)
5576 goto done;
5577 } else {
5578 repo_path = strdup(cwd);
5579 if (repo_path == NULL) {
5580 error = got_error_from_errno("strdup");
5581 goto done;
5586 error = got_repo_open(&repo, repo_path, NULL);
5587 if (error != NULL)
5588 goto done;
5590 error = apply_unveil(got_repo_get_path(repo), do_list,
5591 worktree ? got_worktree_get_root_path(worktree) : NULL);
5592 if (error)
5593 goto done;
5595 if (do_list)
5596 error = list_refs(repo, refname);
5597 else if (do_delete)
5598 error = delete_ref_by_name(repo, refname);
5599 else if (symref_target)
5600 error = add_symref(repo, refname, symref_target);
5601 else {
5602 if (obj_arg == NULL)
5603 usage_ref();
5604 error = add_ref(repo, refname, obj_arg);
5606 done:
5607 free(refname);
5608 if (repo) {
5609 const struct got_error *close_err = got_repo_close(repo);
5610 if (error == NULL)
5611 error = close_err;
5613 if (worktree)
5614 got_worktree_close(worktree);
5615 free(cwd);
5616 free(repo_path);
5617 return error;
5620 __dead static void
5621 usage_branch(void)
5623 fprintf(stderr,
5624 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5625 "[name]\n", getprogname());
5626 exit(1);
5629 static const struct got_error *
5630 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5631 struct got_reference *ref)
5633 const struct got_error *err = NULL;
5634 const char *refname, *marker = " ";
5635 char *refstr;
5637 refname = got_ref_get_name(ref);
5638 if (worktree && strcmp(refname,
5639 got_worktree_get_head_ref_name(worktree)) == 0) {
5640 struct got_object_id *id = NULL;
5642 err = got_ref_resolve(&id, repo, ref);
5643 if (err)
5644 return err;
5645 if (got_object_id_cmp(id,
5646 got_worktree_get_base_commit_id(worktree)) == 0)
5647 marker = "* ";
5648 else
5649 marker = "~ ";
5650 free(id);
5653 if (strncmp(refname, "refs/heads/", 11) == 0)
5654 refname += 11;
5655 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5656 refname += 18;
5657 if (strncmp(refname, "refs/remotes/", 13) == 0)
5658 refname += 13;
5660 refstr = got_ref_to_str(ref);
5661 if (refstr == NULL)
5662 return got_error_from_errno("got_ref_to_str");
5664 printf("%s%s: %s\n", marker, refname, refstr);
5665 free(refstr);
5666 return NULL;
5669 static const struct got_error *
5670 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5672 const char *refname;
5674 if (worktree == NULL)
5675 return got_error(GOT_ERR_NOT_WORKTREE);
5677 refname = got_worktree_get_head_ref_name(worktree);
5679 if (strncmp(refname, "refs/heads/", 11) == 0)
5680 refname += 11;
5681 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5682 refname += 18;
5684 printf("%s\n", refname);
5686 return NULL;
5689 static const struct got_error *
5690 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5692 static const struct got_error *err = NULL;
5693 struct got_reflist_head refs;
5694 struct got_reflist_entry *re;
5695 struct got_reference *temp_ref = NULL;
5696 int rebase_in_progress, histedit_in_progress;
5698 TAILQ_INIT(&refs);
5700 if (worktree) {
5701 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5702 worktree);
5703 if (err)
5704 return err;
5706 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5707 worktree);
5708 if (err)
5709 return err;
5711 if (rebase_in_progress || histedit_in_progress) {
5712 err = got_ref_open(&temp_ref, repo,
5713 got_worktree_get_head_ref_name(worktree), 0);
5714 if (err)
5715 return err;
5716 list_branch(repo, worktree, temp_ref);
5717 got_ref_close(temp_ref);
5721 err = got_ref_list(&refs, repo, "refs/heads",
5722 got_ref_cmp_by_name, NULL);
5723 if (err)
5724 return err;
5726 TAILQ_FOREACH(re, &refs, entry)
5727 list_branch(repo, worktree, re->ref);
5729 got_ref_list_free(&refs);
5731 err = got_ref_list(&refs, repo, "refs/remotes",
5732 got_ref_cmp_by_name, NULL);
5733 if (err)
5734 return err;
5736 TAILQ_FOREACH(re, &refs, entry)
5737 list_branch(repo, worktree, re->ref);
5739 got_ref_list_free(&refs);
5741 return NULL;
5744 static const struct got_error *
5745 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5746 const char *branch_name)
5748 const struct got_error *err = NULL;
5749 struct got_reference *ref = NULL;
5750 char *refname, *remote_refname = NULL;
5752 if (strncmp(branch_name, "refs/", 5) == 0)
5753 branch_name += 5;
5754 if (strncmp(branch_name, "heads/", 6) == 0)
5755 branch_name += 6;
5756 else if (strncmp(branch_name, "remotes/", 8) == 0)
5757 branch_name += 8;
5759 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
5760 return got_error_from_errno("asprintf");
5762 if (asprintf(&remote_refname, "refs/remotes/%s",
5763 branch_name) == -1) {
5764 err = got_error_from_errno("asprintf");
5765 goto done;
5768 err = got_ref_open(&ref, repo, refname, 0);
5769 if (err) {
5770 const struct got_error *err2;
5771 if (err->code != GOT_ERR_NOT_REF)
5772 goto done;
5774 * Keep 'err' intact such that if neither branch exists
5775 * we report "refs/heads" rather than "refs/remotes" in
5776 * our error message.
5778 err2 = got_ref_open(&ref, repo, remote_refname, 0);
5779 if (err2)
5780 goto done;
5781 err = NULL;
5784 if (worktree &&
5785 strcmp(got_worktree_get_head_ref_name(worktree),
5786 got_ref_get_name(ref)) == 0) {
5787 err = got_error_msg(GOT_ERR_SAME_BRANCH,
5788 "will not delete this work tree's current branch");
5789 goto done;
5792 err = delete_ref(repo, ref);
5793 done:
5794 if (ref)
5795 got_ref_close(ref);
5796 free(refname);
5797 free(remote_refname);
5798 return err;
5801 static const struct got_error *
5802 add_branch(struct got_repository *repo, const char *branch_name,
5803 struct got_object_id *base_commit_id)
5805 const struct got_error *err = NULL;
5806 struct got_reference *ref = NULL;
5807 char *base_refname = NULL, *refname = NULL;
5810 * Don't let the user create a branch name with a leading '-'.
5811 * While technically a valid reference name, this case is usually
5812 * an unintended typo.
5814 if (branch_name[0] == '-')
5815 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
5817 if (strncmp(branch_name, "refs/heads/", 11) == 0)
5818 branch_name += 11;
5820 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
5821 err = got_error_from_errno("asprintf");
5822 goto done;
5825 err = got_ref_open(&ref, repo, refname, 0);
5826 if (err == NULL) {
5827 err = got_error(GOT_ERR_BRANCH_EXISTS);
5828 goto done;
5829 } else if (err->code != GOT_ERR_NOT_REF)
5830 goto done;
5832 err = got_ref_alloc(&ref, refname, base_commit_id);
5833 if (err)
5834 goto done;
5836 err = got_ref_write(ref, repo);
5837 done:
5838 if (ref)
5839 got_ref_close(ref);
5840 free(base_refname);
5841 free(refname);
5842 return err;
5845 static const struct got_error *
5846 cmd_branch(int argc, char *argv[])
5848 const struct got_error *error = NULL;
5849 struct got_repository *repo = NULL;
5850 struct got_worktree *worktree = NULL;
5851 char *cwd = NULL, *repo_path = NULL;
5852 int ch, do_list = 0, do_show = 0, do_update = 1;
5853 const char *delref = NULL, *commit_id_arg = NULL;
5854 struct got_reference *ref = NULL;
5855 struct got_pathlist_head paths;
5856 struct got_pathlist_entry *pe;
5857 struct got_object_id *commit_id = NULL;
5858 char *commit_id_str = NULL;
5860 TAILQ_INIT(&paths);
5862 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
5863 switch (ch) {
5864 case 'c':
5865 commit_id_arg = optarg;
5866 break;
5867 case 'd':
5868 delref = optarg;
5869 break;
5870 case 'r':
5871 repo_path = realpath(optarg, NULL);
5872 if (repo_path == NULL)
5873 return got_error_from_errno2("realpath",
5874 optarg);
5875 got_path_strip_trailing_slashes(repo_path);
5876 break;
5877 case 'l':
5878 do_list = 1;
5879 break;
5880 case 'n':
5881 do_update = 0;
5882 break;
5883 default:
5884 usage_branch();
5885 /* NOTREACHED */
5889 if (do_list && delref)
5890 option_conflict('l', 'd');
5892 argc -= optind;
5893 argv += optind;
5895 if (!do_list && !delref && argc == 0)
5896 do_show = 1;
5898 if ((do_list || delref || do_show) && commit_id_arg != NULL)
5899 errx(1, "-c option can only be used when creating a branch");
5901 if (do_list || delref) {
5902 if (argc > 0)
5903 usage_branch();
5904 } else if (!do_show && argc != 1)
5905 usage_branch();
5907 #ifndef PROFILE
5908 if (do_list || do_show) {
5909 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5910 NULL) == -1)
5911 err(1, "pledge");
5912 } else {
5913 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5914 "sendfd unveil", NULL) == -1)
5915 err(1, "pledge");
5917 #endif
5918 cwd = getcwd(NULL, 0);
5919 if (cwd == NULL) {
5920 error = got_error_from_errno("getcwd");
5921 goto done;
5924 if (repo_path == NULL) {
5925 error = got_worktree_open(&worktree, cwd);
5926 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5927 goto done;
5928 else
5929 error = NULL;
5930 if (worktree) {
5931 repo_path =
5932 strdup(got_worktree_get_repo_path(worktree));
5933 if (repo_path == NULL)
5934 error = got_error_from_errno("strdup");
5935 if (error)
5936 goto done;
5937 } else {
5938 repo_path = strdup(cwd);
5939 if (repo_path == NULL) {
5940 error = got_error_from_errno("strdup");
5941 goto done;
5946 error = got_repo_open(&repo, repo_path, NULL);
5947 if (error != NULL)
5948 goto done;
5950 error = apply_unveil(got_repo_get_path(repo), do_list,
5951 worktree ? got_worktree_get_root_path(worktree) : NULL);
5952 if (error)
5953 goto done;
5955 if (do_show)
5956 error = show_current_branch(repo, worktree);
5957 else if (do_list)
5958 error = list_branches(repo, worktree);
5959 else if (delref)
5960 error = delete_branch(repo, worktree, delref);
5961 else {
5962 struct got_reflist_head refs;
5963 TAILQ_INIT(&refs);
5964 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5965 NULL);
5966 if (error)
5967 goto done;
5968 if (commit_id_arg == NULL)
5969 commit_id_arg = worktree ?
5970 got_worktree_get_head_ref_name(worktree) :
5971 GOT_REF_HEAD;
5972 error = got_repo_match_object_id(&commit_id, NULL,
5973 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5974 got_ref_list_free(&refs);
5975 if (error)
5976 goto done;
5977 error = add_branch(repo, argv[0], commit_id);
5978 if (error)
5979 goto done;
5980 if (worktree && do_update) {
5981 struct got_update_progress_arg upa;
5982 char *branch_refname = NULL;
5984 error = got_object_id_str(&commit_id_str, commit_id);
5985 if (error)
5986 goto done;
5987 error = get_worktree_paths_from_argv(&paths, 0, NULL,
5988 worktree);
5989 if (error)
5990 goto done;
5991 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
5992 == -1) {
5993 error = got_error_from_errno("asprintf");
5994 goto done;
5996 error = got_ref_open(&ref, repo, branch_refname, 0);
5997 free(branch_refname);
5998 if (error)
5999 goto done;
6000 error = switch_head_ref(ref, commit_id, worktree,
6001 repo);
6002 if (error)
6003 goto done;
6004 error = got_worktree_set_base_commit_id(worktree, repo,
6005 commit_id);
6006 if (error)
6007 goto done;
6008 memset(&upa, 0, sizeof(upa));
6009 error = got_worktree_checkout_files(worktree, &paths,
6010 repo, update_progress, &upa, check_cancelled,
6011 NULL);
6012 if (error)
6013 goto done;
6014 if (upa.did_something)
6015 printf("Updated to commit %s\n", commit_id_str);
6016 print_update_progress_stats(&upa);
6019 done:
6020 if (ref)
6021 got_ref_close(ref);
6022 if (repo) {
6023 const struct got_error *close_err = got_repo_close(repo);
6024 if (error == NULL)
6025 error = close_err;
6027 if (worktree)
6028 got_worktree_close(worktree);
6029 free(cwd);
6030 free(repo_path);
6031 free(commit_id);
6032 free(commit_id_str);
6033 TAILQ_FOREACH(pe, &paths, entry)
6034 free((char *)pe->path);
6035 got_pathlist_free(&paths);
6036 return error;
6040 __dead static void
6041 usage_tag(void)
6043 fprintf(stderr,
6044 "usage: %s tag [-c commit] [-r repository] [-l] "
6045 "[-m message] name\n", getprogname());
6046 exit(1);
6049 #if 0
6050 static const struct got_error *
6051 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6053 const struct got_error *err = NULL;
6054 struct got_reflist_entry *re, *se, *new;
6055 struct got_object_id *re_id, *se_id;
6056 struct got_tag_object *re_tag, *se_tag;
6057 time_t re_time, se_time;
6059 STAILQ_FOREACH(re, tags, entry) {
6060 se = STAILQ_FIRST(sorted);
6061 if (se == NULL) {
6062 err = got_reflist_entry_dup(&new, re);
6063 if (err)
6064 return err;
6065 STAILQ_INSERT_HEAD(sorted, new, entry);
6066 continue;
6067 } else {
6068 err = got_ref_resolve(&re_id, repo, re->ref);
6069 if (err)
6070 break;
6071 err = got_object_open_as_tag(&re_tag, repo, re_id);
6072 free(re_id);
6073 if (err)
6074 break;
6075 re_time = got_object_tag_get_tagger_time(re_tag);
6076 got_object_tag_close(re_tag);
6079 while (se) {
6080 err = got_ref_resolve(&se_id, repo, re->ref);
6081 if (err)
6082 break;
6083 err = got_object_open_as_tag(&se_tag, repo, se_id);
6084 free(se_id);
6085 if (err)
6086 break;
6087 se_time = got_object_tag_get_tagger_time(se_tag);
6088 got_object_tag_close(se_tag);
6090 if (se_time > re_time) {
6091 err = got_reflist_entry_dup(&new, re);
6092 if (err)
6093 return err;
6094 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6095 break;
6097 se = STAILQ_NEXT(se, entry);
6098 continue;
6101 done:
6102 return err;
6104 #endif
6106 static const struct got_error *
6107 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6109 static const struct got_error *err = NULL;
6110 struct got_reflist_head refs;
6111 struct got_reflist_entry *re;
6113 TAILQ_INIT(&refs);
6115 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6116 if (err)
6117 return err;
6119 TAILQ_FOREACH(re, &refs, entry) {
6120 const char *refname;
6121 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6122 char datebuf[26];
6123 const char *tagger;
6124 time_t tagger_time;
6125 struct got_object_id *id;
6126 struct got_tag_object *tag;
6127 struct got_commit_object *commit = NULL;
6129 refname = got_ref_get_name(re->ref);
6130 if (strncmp(refname, "refs/tags/", 10) != 0)
6131 continue;
6132 refname += 10;
6133 refstr = got_ref_to_str(re->ref);
6134 if (refstr == NULL) {
6135 err = got_error_from_errno("got_ref_to_str");
6136 break;
6138 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6139 free(refstr);
6141 err = got_ref_resolve(&id, repo, re->ref);
6142 if (err)
6143 break;
6144 err = got_object_open_as_tag(&tag, repo, id);
6145 if (err) {
6146 if (err->code != GOT_ERR_OBJ_TYPE) {
6147 free(id);
6148 break;
6150 /* "lightweight" tag */
6151 err = got_object_open_as_commit(&commit, repo, id);
6152 if (err) {
6153 free(id);
6154 break;
6156 tagger = got_object_commit_get_committer(commit);
6157 tagger_time =
6158 got_object_commit_get_committer_time(commit);
6159 err = got_object_id_str(&id_str, id);
6160 free(id);
6161 if (err)
6162 break;
6163 } else {
6164 free(id);
6165 tagger = got_object_tag_get_tagger(tag);
6166 tagger_time = got_object_tag_get_tagger_time(tag);
6167 err = got_object_id_str(&id_str,
6168 got_object_tag_get_object_id(tag));
6169 if (err)
6170 break;
6172 printf("from: %s\n", tagger);
6173 datestr = get_datestr(&tagger_time, datebuf);
6174 if (datestr)
6175 printf("date: %s UTC\n", datestr);
6176 if (commit)
6177 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6178 else {
6179 switch (got_object_tag_get_object_type(tag)) {
6180 case GOT_OBJ_TYPE_BLOB:
6181 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6182 id_str);
6183 break;
6184 case GOT_OBJ_TYPE_TREE:
6185 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6186 id_str);
6187 break;
6188 case GOT_OBJ_TYPE_COMMIT:
6189 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6190 id_str);
6191 break;
6192 case GOT_OBJ_TYPE_TAG:
6193 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6194 id_str);
6195 break;
6196 default:
6197 break;
6200 free(id_str);
6201 if (commit) {
6202 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6203 if (err)
6204 break;
6205 got_object_commit_close(commit);
6206 } else {
6207 tagmsg0 = strdup(got_object_tag_get_message(tag));
6208 got_object_tag_close(tag);
6209 if (tagmsg0 == NULL) {
6210 err = got_error_from_errno("strdup");
6211 break;
6215 tagmsg = tagmsg0;
6216 do {
6217 line = strsep(&tagmsg, "\n");
6218 if (line)
6219 printf(" %s\n", line);
6220 } while (line);
6221 free(tagmsg0);
6224 got_ref_list_free(&refs);
6225 return NULL;
6228 static const struct got_error *
6229 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6230 const char *tag_name, const char *repo_path)
6232 const struct got_error *err = NULL;
6233 char *template = NULL, *initial_content = NULL;
6234 char *editor = NULL;
6235 int initial_content_len;
6236 int fd = -1;
6238 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6239 err = got_error_from_errno("asprintf");
6240 goto done;
6243 initial_content_len = asprintf(&initial_content,
6244 "\n# tagging commit %s as %s\n",
6245 commit_id_str, tag_name);
6246 if (initial_content_len == -1) {
6247 err = got_error_from_errno("asprintf");
6248 goto done;
6251 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6252 if (err)
6253 goto done;
6255 if (write(fd, initial_content, initial_content_len) == -1) {
6256 err = got_error_from_errno2("write", *tagmsg_path);
6257 goto done;
6260 err = get_editor(&editor);
6261 if (err)
6262 goto done;
6263 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6264 initial_content_len, 1);
6265 done:
6266 free(initial_content);
6267 free(template);
6268 free(editor);
6270 if (fd != -1 && close(fd) == -1 && err == NULL)
6271 err = got_error_from_errno2("close", *tagmsg_path);
6273 /* Editor is done; we can now apply unveil(2) */
6274 if (err == NULL)
6275 err = apply_unveil(repo_path, 0, NULL);
6276 if (err) {
6277 free(*tagmsg);
6278 *tagmsg = NULL;
6280 return err;
6283 static const struct got_error *
6284 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6285 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6287 const struct got_error *err = NULL;
6288 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6289 char *label = NULL, *commit_id_str = NULL;
6290 struct got_reference *ref = NULL;
6291 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6292 char *tagmsg_path = NULL, *tag_id_str = NULL;
6293 int preserve_tagmsg = 0;
6294 struct got_reflist_head refs;
6296 TAILQ_INIT(&refs);
6299 * Don't let the user create a tag name with a leading '-'.
6300 * While technically a valid reference name, this case is usually
6301 * an unintended typo.
6303 if (tag_name[0] == '-')
6304 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6306 err = get_author(&tagger, repo, worktree);
6307 if (err)
6308 return err;
6310 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6311 if (err)
6312 goto done;
6314 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6315 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6316 if (err)
6317 goto done;
6319 err = got_object_id_str(&commit_id_str, commit_id);
6320 if (err)
6321 goto done;
6323 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6324 refname = strdup(tag_name);
6325 if (refname == NULL) {
6326 err = got_error_from_errno("strdup");
6327 goto done;
6329 tag_name += 10;
6330 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6331 err = got_error_from_errno("asprintf");
6332 goto done;
6335 err = got_ref_open(&ref, repo, refname, 0);
6336 if (err == NULL) {
6337 err = got_error(GOT_ERR_TAG_EXISTS);
6338 goto done;
6339 } else if (err->code != GOT_ERR_NOT_REF)
6340 goto done;
6342 if (tagmsg_arg == NULL) {
6343 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6344 tag_name, got_repo_get_path(repo));
6345 if (err) {
6346 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6347 tagmsg_path != NULL)
6348 preserve_tagmsg = 1;
6349 goto done;
6353 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6354 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6355 if (err) {
6356 if (tagmsg_path)
6357 preserve_tagmsg = 1;
6358 goto done;
6361 err = got_ref_alloc(&ref, refname, tag_id);
6362 if (err) {
6363 if (tagmsg_path)
6364 preserve_tagmsg = 1;
6365 goto done;
6368 err = got_ref_write(ref, repo);
6369 if (err) {
6370 if (tagmsg_path)
6371 preserve_tagmsg = 1;
6372 goto done;
6375 err = got_object_id_str(&tag_id_str, tag_id);
6376 if (err) {
6377 if (tagmsg_path)
6378 preserve_tagmsg = 1;
6379 goto done;
6381 printf("Created tag %s\n", tag_id_str);
6382 done:
6383 if (preserve_tagmsg) {
6384 fprintf(stderr, "%s: tag message preserved in %s\n",
6385 getprogname(), tagmsg_path);
6386 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6387 err = got_error_from_errno2("unlink", tagmsg_path);
6388 free(tag_id_str);
6389 if (ref)
6390 got_ref_close(ref);
6391 free(commit_id);
6392 free(commit_id_str);
6393 free(refname);
6394 free(tagmsg);
6395 free(tagmsg_path);
6396 free(tagger);
6397 got_ref_list_free(&refs);
6398 return err;
6401 static const struct got_error *
6402 cmd_tag(int argc, char *argv[])
6404 const struct got_error *error = NULL;
6405 struct got_repository *repo = NULL;
6406 struct got_worktree *worktree = NULL;
6407 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6408 char *gitconfig_path = NULL;
6409 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6410 int ch, do_list = 0;
6412 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6413 switch (ch) {
6414 case 'c':
6415 commit_id_arg = optarg;
6416 break;
6417 case 'm':
6418 tagmsg = optarg;
6419 break;
6420 case 'r':
6421 repo_path = realpath(optarg, NULL);
6422 if (repo_path == NULL)
6423 return got_error_from_errno2("realpath",
6424 optarg);
6425 got_path_strip_trailing_slashes(repo_path);
6426 break;
6427 case 'l':
6428 do_list = 1;
6429 break;
6430 default:
6431 usage_tag();
6432 /* NOTREACHED */
6436 argc -= optind;
6437 argv += optind;
6439 if (do_list) {
6440 if (commit_id_arg != NULL)
6441 errx(1,
6442 "-c option can only be used when creating a tag");
6443 if (tagmsg)
6444 option_conflict('l', 'm');
6445 if (argc > 0)
6446 usage_tag();
6447 } else if (argc != 1)
6448 usage_tag();
6450 tag_name = argv[0];
6452 #ifndef PROFILE
6453 if (do_list) {
6454 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6455 NULL) == -1)
6456 err(1, "pledge");
6457 } else {
6458 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6459 "sendfd unveil", NULL) == -1)
6460 err(1, "pledge");
6462 #endif
6463 cwd = getcwd(NULL, 0);
6464 if (cwd == NULL) {
6465 error = got_error_from_errno("getcwd");
6466 goto done;
6469 if (repo_path == NULL) {
6470 error = got_worktree_open(&worktree, cwd);
6471 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6472 goto done;
6473 else
6474 error = NULL;
6475 if (worktree) {
6476 repo_path =
6477 strdup(got_worktree_get_repo_path(worktree));
6478 if (repo_path == NULL)
6479 error = got_error_from_errno("strdup");
6480 if (error)
6481 goto done;
6482 } else {
6483 repo_path = strdup(cwd);
6484 if (repo_path == NULL) {
6485 error = got_error_from_errno("strdup");
6486 goto done;
6491 if (do_list) {
6492 error = got_repo_open(&repo, repo_path, NULL);
6493 if (error != NULL)
6494 goto done;
6495 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6496 if (error)
6497 goto done;
6498 error = list_tags(repo, worktree);
6499 } else {
6500 error = get_gitconfig_path(&gitconfig_path);
6501 if (error)
6502 goto done;
6503 error = got_repo_open(&repo, repo_path, gitconfig_path);
6504 if (error != NULL)
6505 goto done;
6507 if (tagmsg) {
6508 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6509 if (error)
6510 goto done;
6513 if (commit_id_arg == NULL) {
6514 struct got_reference *head_ref;
6515 struct got_object_id *commit_id;
6516 error = got_ref_open(&head_ref, repo,
6517 worktree ? got_worktree_get_head_ref_name(worktree)
6518 : GOT_REF_HEAD, 0);
6519 if (error)
6520 goto done;
6521 error = got_ref_resolve(&commit_id, repo, head_ref);
6522 got_ref_close(head_ref);
6523 if (error)
6524 goto done;
6525 error = got_object_id_str(&commit_id_str, commit_id);
6526 free(commit_id);
6527 if (error)
6528 goto done;
6531 error = add_tag(repo, worktree, tag_name,
6532 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6534 done:
6535 if (repo) {
6536 const struct got_error *close_err = got_repo_close(repo);
6537 if (error == NULL)
6538 error = close_err;
6540 if (worktree)
6541 got_worktree_close(worktree);
6542 free(cwd);
6543 free(repo_path);
6544 free(gitconfig_path);
6545 free(commit_id_str);
6546 return error;
6549 __dead static void
6550 usage_add(void)
6552 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6553 getprogname());
6554 exit(1);
6557 static const struct got_error *
6558 add_progress(void *arg, unsigned char status, const char *path)
6560 while (path[0] == '/')
6561 path++;
6562 printf("%c %s\n", status, path);
6563 return NULL;
6566 static const struct got_error *
6567 cmd_add(int argc, char *argv[])
6569 const struct got_error *error = NULL;
6570 struct got_repository *repo = NULL;
6571 struct got_worktree *worktree = NULL;
6572 char *cwd = NULL;
6573 struct got_pathlist_head paths;
6574 struct got_pathlist_entry *pe;
6575 int ch, can_recurse = 0, no_ignores = 0;
6577 TAILQ_INIT(&paths);
6579 while ((ch = getopt(argc, argv, "IR")) != -1) {
6580 switch (ch) {
6581 case 'I':
6582 no_ignores = 1;
6583 break;
6584 case 'R':
6585 can_recurse = 1;
6586 break;
6587 default:
6588 usage_add();
6589 /* NOTREACHED */
6593 argc -= optind;
6594 argv += optind;
6596 #ifndef PROFILE
6597 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6598 NULL) == -1)
6599 err(1, "pledge");
6600 #endif
6601 if (argc < 1)
6602 usage_add();
6604 cwd = getcwd(NULL, 0);
6605 if (cwd == NULL) {
6606 error = got_error_from_errno("getcwd");
6607 goto done;
6610 error = got_worktree_open(&worktree, cwd);
6611 if (error) {
6612 if (error->code == GOT_ERR_NOT_WORKTREE)
6613 error = wrap_not_worktree_error(error, "add", cwd);
6614 goto done;
6617 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6618 NULL);
6619 if (error != NULL)
6620 goto done;
6622 error = apply_unveil(got_repo_get_path(repo), 1,
6623 got_worktree_get_root_path(worktree));
6624 if (error)
6625 goto done;
6627 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6628 if (error)
6629 goto done;
6631 if (!can_recurse) {
6632 char *ondisk_path;
6633 struct stat sb;
6634 TAILQ_FOREACH(pe, &paths, entry) {
6635 if (asprintf(&ondisk_path, "%s/%s",
6636 got_worktree_get_root_path(worktree),
6637 pe->path) == -1) {
6638 error = got_error_from_errno("asprintf");
6639 goto done;
6641 if (lstat(ondisk_path, &sb) == -1) {
6642 if (errno == ENOENT) {
6643 free(ondisk_path);
6644 continue;
6646 error = got_error_from_errno2("lstat",
6647 ondisk_path);
6648 free(ondisk_path);
6649 goto done;
6651 free(ondisk_path);
6652 if (S_ISDIR(sb.st_mode)) {
6653 error = got_error_msg(GOT_ERR_BAD_PATH,
6654 "adding directories requires -R option");
6655 goto done;
6660 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6661 NULL, repo, no_ignores);
6662 done:
6663 if (repo) {
6664 const struct got_error *close_err = got_repo_close(repo);
6665 if (error == NULL)
6666 error = close_err;
6668 if (worktree)
6669 got_worktree_close(worktree);
6670 TAILQ_FOREACH(pe, &paths, entry)
6671 free((char *)pe->path);
6672 got_pathlist_free(&paths);
6673 free(cwd);
6674 return error;
6677 __dead static void
6678 usage_remove(void)
6680 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6681 "path ...\n", getprogname());
6682 exit(1);
6685 static const struct got_error *
6686 print_remove_status(void *arg, unsigned char status,
6687 unsigned char staged_status, const char *path)
6689 while (path[0] == '/')
6690 path++;
6691 if (status == GOT_STATUS_NONEXISTENT)
6692 return NULL;
6693 if (status == staged_status && (status == GOT_STATUS_DELETE))
6694 status = GOT_STATUS_NO_CHANGE;
6695 printf("%c%c %s\n", status, staged_status, path);
6696 return NULL;
6699 static const struct got_error *
6700 cmd_remove(int argc, char *argv[])
6702 const struct got_error *error = NULL;
6703 struct got_worktree *worktree = NULL;
6704 struct got_repository *repo = NULL;
6705 const char *status_codes = NULL;
6706 char *cwd = NULL;
6707 struct got_pathlist_head paths;
6708 struct got_pathlist_entry *pe;
6709 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6711 TAILQ_INIT(&paths);
6713 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6714 switch (ch) {
6715 case 'f':
6716 delete_local_mods = 1;
6717 break;
6718 case 'k':
6719 keep_on_disk = 1;
6720 break;
6721 case 'R':
6722 can_recurse = 1;
6723 break;
6724 case 's':
6725 for (i = 0; i < strlen(optarg); i++) {
6726 switch (optarg[i]) {
6727 case GOT_STATUS_MODIFY:
6728 delete_local_mods = 1;
6729 break;
6730 case GOT_STATUS_MISSING:
6731 break;
6732 default:
6733 errx(1, "invalid status code '%c'",
6734 optarg[i]);
6737 status_codes = optarg;
6738 break;
6739 default:
6740 usage_remove();
6741 /* NOTREACHED */
6745 argc -= optind;
6746 argv += optind;
6748 #ifndef PROFILE
6749 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6750 NULL) == -1)
6751 err(1, "pledge");
6752 #endif
6753 if (argc < 1)
6754 usage_remove();
6756 cwd = getcwd(NULL, 0);
6757 if (cwd == NULL) {
6758 error = got_error_from_errno("getcwd");
6759 goto done;
6761 error = got_worktree_open(&worktree, cwd);
6762 if (error) {
6763 if (error->code == GOT_ERR_NOT_WORKTREE)
6764 error = wrap_not_worktree_error(error, "remove", cwd);
6765 goto done;
6768 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6769 NULL);
6770 if (error)
6771 goto done;
6773 error = apply_unveil(got_repo_get_path(repo), 1,
6774 got_worktree_get_root_path(worktree));
6775 if (error)
6776 goto done;
6778 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6779 if (error)
6780 goto done;
6782 if (!can_recurse) {
6783 char *ondisk_path;
6784 struct stat sb;
6785 TAILQ_FOREACH(pe, &paths, entry) {
6786 if (asprintf(&ondisk_path, "%s/%s",
6787 got_worktree_get_root_path(worktree),
6788 pe->path) == -1) {
6789 error = got_error_from_errno("asprintf");
6790 goto done;
6792 if (lstat(ondisk_path, &sb) == -1) {
6793 if (errno == ENOENT) {
6794 free(ondisk_path);
6795 continue;
6797 error = got_error_from_errno2("lstat",
6798 ondisk_path);
6799 free(ondisk_path);
6800 goto done;
6802 free(ondisk_path);
6803 if (S_ISDIR(sb.st_mode)) {
6804 error = got_error_msg(GOT_ERR_BAD_PATH,
6805 "removing directories requires -R option");
6806 goto done;
6811 error = got_worktree_schedule_delete(worktree, &paths,
6812 delete_local_mods, status_codes, print_remove_status, NULL,
6813 repo, keep_on_disk);
6814 done:
6815 if (repo) {
6816 const struct got_error *close_err = got_repo_close(repo);
6817 if (error == NULL)
6818 error = close_err;
6820 if (worktree)
6821 got_worktree_close(worktree);
6822 TAILQ_FOREACH(pe, &paths, entry)
6823 free((char *)pe->path);
6824 got_pathlist_free(&paths);
6825 free(cwd);
6826 return error;
6829 __dead static void
6830 usage_revert(void)
6832 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
6833 "path ...\n", getprogname());
6834 exit(1);
6837 static const struct got_error *
6838 revert_progress(void *arg, unsigned char status, const char *path)
6840 if (status == GOT_STATUS_UNVERSIONED)
6841 return NULL;
6843 while (path[0] == '/')
6844 path++;
6845 printf("%c %s\n", status, path);
6846 return NULL;
6849 struct choose_patch_arg {
6850 FILE *patch_script_file;
6851 const char *action;
6854 static const struct got_error *
6855 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
6856 int nchanges, const char *action)
6858 char *line = NULL;
6859 size_t linesize = 0;
6860 ssize_t linelen;
6862 switch (status) {
6863 case GOT_STATUS_ADD:
6864 printf("A %s\n%s this addition? [y/n] ", path, action);
6865 break;
6866 case GOT_STATUS_DELETE:
6867 printf("D %s\n%s this deletion? [y/n] ", path, action);
6868 break;
6869 case GOT_STATUS_MODIFY:
6870 if (fseek(patch_file, 0L, SEEK_SET) == -1)
6871 return got_error_from_errno("fseek");
6872 printf(GOT_COMMIT_SEP_STR);
6873 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
6874 printf("%s", line);
6875 if (ferror(patch_file))
6876 return got_error_from_errno("getline");
6877 printf(GOT_COMMIT_SEP_STR);
6878 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
6879 path, n, nchanges, action);
6880 break;
6881 default:
6882 return got_error_path(path, GOT_ERR_FILE_STATUS);
6885 return NULL;
6888 static const struct got_error *
6889 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
6890 FILE *patch_file, int n, int nchanges)
6892 const struct got_error *err = NULL;
6893 char *line = NULL;
6894 size_t linesize = 0;
6895 ssize_t linelen;
6896 int resp = ' ';
6897 struct choose_patch_arg *a = arg;
6899 *choice = GOT_PATCH_CHOICE_NONE;
6901 if (a->patch_script_file) {
6902 char *nl;
6903 err = show_change(status, path, patch_file, n, nchanges,
6904 a->action);
6905 if (err)
6906 return err;
6907 linelen = getline(&line, &linesize, a->patch_script_file);
6908 if (linelen == -1) {
6909 if (ferror(a->patch_script_file))
6910 return got_error_from_errno("getline");
6911 return NULL;
6913 nl = strchr(line, '\n');
6914 if (nl)
6915 *nl = '\0';
6916 if (strcmp(line, "y") == 0) {
6917 *choice = GOT_PATCH_CHOICE_YES;
6918 printf("y\n");
6919 } else if (strcmp(line, "n") == 0) {
6920 *choice = GOT_PATCH_CHOICE_NO;
6921 printf("n\n");
6922 } else if (strcmp(line, "q") == 0 &&
6923 status == GOT_STATUS_MODIFY) {
6924 *choice = GOT_PATCH_CHOICE_QUIT;
6925 printf("q\n");
6926 } else
6927 printf("invalid response '%s'\n", line);
6928 free(line);
6929 return NULL;
6932 while (resp != 'y' && resp != 'n' && resp != 'q') {
6933 err = show_change(status, path, patch_file, n, nchanges,
6934 a->action);
6935 if (err)
6936 return err;
6937 resp = getchar();
6938 if (resp == '\n')
6939 resp = getchar();
6940 if (status == GOT_STATUS_MODIFY) {
6941 if (resp != 'y' && resp != 'n' && resp != 'q') {
6942 printf("invalid response '%c'\n", resp);
6943 resp = ' ';
6945 } else if (resp != 'y' && resp != 'n') {
6946 printf("invalid response '%c'\n", resp);
6947 resp = ' ';
6951 if (resp == 'y')
6952 *choice = GOT_PATCH_CHOICE_YES;
6953 else if (resp == 'n')
6954 *choice = GOT_PATCH_CHOICE_NO;
6955 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
6956 *choice = GOT_PATCH_CHOICE_QUIT;
6958 return NULL;
6962 static const struct got_error *
6963 cmd_revert(int argc, char *argv[])
6965 const struct got_error *error = NULL;
6966 struct got_worktree *worktree = NULL;
6967 struct got_repository *repo = NULL;
6968 char *cwd = NULL, *path = NULL;
6969 struct got_pathlist_head paths;
6970 struct got_pathlist_entry *pe;
6971 int ch, can_recurse = 0, pflag = 0;
6972 FILE *patch_script_file = NULL;
6973 const char *patch_script_path = NULL;
6974 struct choose_patch_arg cpa;
6976 TAILQ_INIT(&paths);
6978 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
6979 switch (ch) {
6980 case 'p':
6981 pflag = 1;
6982 break;
6983 case 'F':
6984 patch_script_path = optarg;
6985 break;
6986 case 'R':
6987 can_recurse = 1;
6988 break;
6989 default:
6990 usage_revert();
6991 /* NOTREACHED */
6995 argc -= optind;
6996 argv += optind;
6998 #ifndef PROFILE
6999 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7000 "unveil", NULL) == -1)
7001 err(1, "pledge");
7002 #endif
7003 if (argc < 1)
7004 usage_revert();
7005 if (patch_script_path && !pflag)
7006 errx(1, "-F option can only be used together with -p option");
7008 cwd = getcwd(NULL, 0);
7009 if (cwd == NULL) {
7010 error = got_error_from_errno("getcwd");
7011 goto done;
7013 error = got_worktree_open(&worktree, cwd);
7014 if (error) {
7015 if (error->code == GOT_ERR_NOT_WORKTREE)
7016 error = wrap_not_worktree_error(error, "revert", cwd);
7017 goto done;
7020 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7021 NULL);
7022 if (error != NULL)
7023 goto done;
7025 if (patch_script_path) {
7026 patch_script_file = fopen(patch_script_path, "r");
7027 if (patch_script_file == NULL) {
7028 error = got_error_from_errno2("fopen",
7029 patch_script_path);
7030 goto done;
7033 error = apply_unveil(got_repo_get_path(repo), 1,
7034 got_worktree_get_root_path(worktree));
7035 if (error)
7036 goto done;
7038 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7039 if (error)
7040 goto done;
7042 if (!can_recurse) {
7043 char *ondisk_path;
7044 struct stat sb;
7045 TAILQ_FOREACH(pe, &paths, entry) {
7046 if (asprintf(&ondisk_path, "%s/%s",
7047 got_worktree_get_root_path(worktree),
7048 pe->path) == -1) {
7049 error = got_error_from_errno("asprintf");
7050 goto done;
7052 if (lstat(ondisk_path, &sb) == -1) {
7053 if (errno == ENOENT) {
7054 free(ondisk_path);
7055 continue;
7057 error = got_error_from_errno2("lstat",
7058 ondisk_path);
7059 free(ondisk_path);
7060 goto done;
7062 free(ondisk_path);
7063 if (S_ISDIR(sb.st_mode)) {
7064 error = got_error_msg(GOT_ERR_BAD_PATH,
7065 "reverting directories requires -R option");
7066 goto done;
7071 cpa.patch_script_file = patch_script_file;
7072 cpa.action = "revert";
7073 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7074 pflag ? choose_patch : NULL, &cpa, repo);
7075 done:
7076 if (patch_script_file && fclose(patch_script_file) == EOF &&
7077 error == NULL)
7078 error = got_error_from_errno2("fclose", patch_script_path);
7079 if (repo) {
7080 const struct got_error *close_err = got_repo_close(repo);
7081 if (error == NULL)
7082 error = close_err;
7084 if (worktree)
7085 got_worktree_close(worktree);
7086 free(path);
7087 free(cwd);
7088 return error;
7091 __dead static void
7092 usage_commit(void)
7094 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7095 "[path ...]\n", getprogname());
7096 exit(1);
7099 struct collect_commit_logmsg_arg {
7100 const char *cmdline_log;
7101 const char *prepared_log;
7102 int non_interactive;
7103 const char *editor;
7104 const char *worktree_path;
7105 const char *branch_name;
7106 const char *repo_path;
7107 char *logmsg_path;
7111 static const struct got_error *
7112 read_prepared_logmsg(char **logmsg, const char *path)
7114 const struct got_error *err = NULL;
7115 FILE *f = NULL;
7116 struct stat sb;
7117 size_t r;
7119 *logmsg = NULL;
7120 memset(&sb, 0, sizeof(sb));
7122 f = fopen(path, "r");
7123 if (f == NULL)
7124 return got_error_from_errno2("fopen", path);
7126 if (fstat(fileno(f), &sb) == -1) {
7127 err = got_error_from_errno2("fstat", path);
7128 goto done;
7130 if (sb.st_size == 0) {
7131 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7132 goto done;
7135 *logmsg = malloc(sb.st_size + 1);
7136 if (*logmsg == NULL) {
7137 err = got_error_from_errno("malloc");
7138 goto done;
7141 r = fread(*logmsg, 1, sb.st_size, f);
7142 if (r != sb.st_size) {
7143 if (ferror(f))
7144 err = got_error_from_errno2("fread", path);
7145 else
7146 err = got_error(GOT_ERR_IO);
7147 goto done;
7149 (*logmsg)[sb.st_size] = '\0';
7150 done:
7151 if (fclose(f) == EOF && err == NULL)
7152 err = got_error_from_errno2("fclose", path);
7153 if (err) {
7154 free(*logmsg);
7155 *logmsg = NULL;
7157 return err;
7161 static const struct got_error *
7162 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7163 void *arg)
7165 char *initial_content = NULL;
7166 struct got_pathlist_entry *pe;
7167 const struct got_error *err = NULL;
7168 char *template = NULL;
7169 struct collect_commit_logmsg_arg *a = arg;
7170 int initial_content_len;
7171 int fd = -1;
7172 size_t len;
7174 /* if a message was specified on the command line, just use it */
7175 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7176 len = strlen(a->cmdline_log) + 1;
7177 *logmsg = malloc(len + 1);
7178 if (*logmsg == NULL)
7179 return got_error_from_errno("malloc");
7180 strlcpy(*logmsg, a->cmdline_log, len);
7181 return NULL;
7182 } else if (a->prepared_log != NULL && a->non_interactive)
7183 return read_prepared_logmsg(logmsg, a->prepared_log);
7185 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7186 return got_error_from_errno("asprintf");
7188 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7189 if (err)
7190 goto done;
7192 if (a->prepared_log) {
7193 char *msg;
7194 err = read_prepared_logmsg(&msg, a->prepared_log);
7195 if (err)
7196 goto done;
7197 if (write(fd, msg, strlen(msg)) == -1) {
7198 err = got_error_from_errno2("write", a->logmsg_path);
7199 free(msg);
7200 goto done;
7202 free(msg);
7205 initial_content_len = asprintf(&initial_content,
7206 "\n# changes to be committed on branch %s:\n",
7207 a->branch_name);
7208 if (initial_content_len == -1) {
7209 err = got_error_from_errno("asprintf");
7210 goto done;
7213 if (write(fd, initial_content, initial_content_len) == -1) {
7214 err = got_error_from_errno2("write", a->logmsg_path);
7215 goto done;
7218 TAILQ_FOREACH(pe, commitable_paths, entry) {
7219 struct got_commitable *ct = pe->data;
7220 dprintf(fd, "# %c %s\n",
7221 got_commitable_get_status(ct),
7222 got_commitable_get_path(ct));
7225 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7226 initial_content_len, a->prepared_log ? 0 : 1);
7227 done:
7228 free(initial_content);
7229 free(template);
7231 if (fd != -1 && close(fd) == -1 && err == NULL)
7232 err = got_error_from_errno2("close", a->logmsg_path);
7234 /* Editor is done; we can now apply unveil(2) */
7235 if (err == NULL)
7236 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7237 if (err) {
7238 free(*logmsg);
7239 *logmsg = NULL;
7241 return err;
7244 static const struct got_error *
7245 cmd_commit(int argc, char *argv[])
7247 const struct got_error *error = NULL;
7248 struct got_worktree *worktree = NULL;
7249 struct got_repository *repo = NULL;
7250 char *cwd = NULL, *id_str = NULL;
7251 struct got_object_id *id = NULL;
7252 const char *logmsg = NULL;
7253 char *prepared_logmsg = NULL;
7254 struct collect_commit_logmsg_arg cl_arg;
7255 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7256 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7257 int allow_bad_symlinks = 0, non_interactive = 0;
7258 struct got_pathlist_head paths;
7260 TAILQ_INIT(&paths);
7261 cl_arg.logmsg_path = NULL;
7263 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7264 switch (ch) {
7265 case 'F':
7266 if (logmsg != NULL)
7267 option_conflict('F', 'm');
7268 prepared_logmsg = realpath(optarg, NULL);
7269 if (prepared_logmsg == NULL)
7270 return got_error_from_errno2("realpath",
7271 optarg);
7272 break;
7273 case 'm':
7274 if (prepared_logmsg)
7275 option_conflict('m', 'F');
7276 logmsg = optarg;
7277 break;
7278 case 'N':
7279 non_interactive = 1;
7280 break;
7281 case 'S':
7282 allow_bad_symlinks = 1;
7283 break;
7284 default:
7285 usage_commit();
7286 /* NOTREACHED */
7290 argc -= optind;
7291 argv += optind;
7293 #ifndef PROFILE
7294 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7295 "unveil", NULL) == -1)
7296 err(1, "pledge");
7297 #endif
7298 cwd = getcwd(NULL, 0);
7299 if (cwd == NULL) {
7300 error = got_error_from_errno("getcwd");
7301 goto done;
7303 error = got_worktree_open(&worktree, cwd);
7304 if (error) {
7305 if (error->code == GOT_ERR_NOT_WORKTREE)
7306 error = wrap_not_worktree_error(error, "commit", cwd);
7307 goto done;
7310 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7311 if (error)
7312 goto done;
7313 if (rebase_in_progress) {
7314 error = got_error(GOT_ERR_REBASING);
7315 goto done;
7318 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7319 worktree);
7320 if (error)
7321 goto done;
7323 error = get_gitconfig_path(&gitconfig_path);
7324 if (error)
7325 goto done;
7326 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7327 gitconfig_path);
7328 if (error != NULL)
7329 goto done;
7331 error = get_author(&author, repo, worktree);
7332 if (error)
7333 return error;
7336 * unveil(2) traverses exec(2); if an editor is used we have
7337 * to apply unveil after the log message has been written.
7339 if (logmsg == NULL || strlen(logmsg) == 0)
7340 error = get_editor(&editor);
7341 else
7342 error = apply_unveil(got_repo_get_path(repo), 0,
7343 got_worktree_get_root_path(worktree));
7344 if (error)
7345 goto done;
7347 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7348 if (error)
7349 goto done;
7351 cl_arg.editor = editor;
7352 cl_arg.cmdline_log = logmsg;
7353 cl_arg.prepared_log = prepared_logmsg;
7354 cl_arg.non_interactive = non_interactive;
7355 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7356 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7357 if (!histedit_in_progress) {
7358 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7359 error = got_error(GOT_ERR_COMMIT_BRANCH);
7360 goto done;
7362 cl_arg.branch_name += 11;
7364 cl_arg.repo_path = got_repo_get_path(repo);
7365 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7366 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7367 print_status, NULL, repo);
7368 if (error) {
7369 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7370 cl_arg.logmsg_path != NULL)
7371 preserve_logmsg = 1;
7372 goto done;
7375 error = got_object_id_str(&id_str, id);
7376 if (error)
7377 goto done;
7378 printf("Created commit %s\n", id_str);
7379 done:
7380 if (preserve_logmsg) {
7381 fprintf(stderr, "%s: log message preserved in %s\n",
7382 getprogname(), cl_arg.logmsg_path);
7383 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7384 error == NULL)
7385 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7386 free(cl_arg.logmsg_path);
7387 if (repo) {
7388 const struct got_error *close_err = got_repo_close(repo);
7389 if (error == NULL)
7390 error = close_err;
7392 if (worktree)
7393 got_worktree_close(worktree);
7394 free(cwd);
7395 free(id_str);
7396 free(gitconfig_path);
7397 free(editor);
7398 free(author);
7399 free(prepared_logmsg);
7400 return error;
7403 __dead static void
7404 usage_send(void)
7406 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7407 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7408 "[remote-repository]\n", getprogname());
7409 exit(1);
7412 struct got_send_progress_arg {
7413 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7414 int verbosity;
7415 int last_ncommits;
7416 int last_nobj_total;
7417 int last_p_deltify;
7418 int last_p_written;
7419 int last_p_sent;
7420 int printed_something;
7421 int sent_something;
7422 struct got_pathlist_head *delete_branches;
7425 static const struct got_error *
7426 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7427 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7428 int success)
7430 struct got_send_progress_arg *a = arg;
7431 char scaled_packsize[FMT_SCALED_STRSIZE];
7432 char scaled_sent[FMT_SCALED_STRSIZE];
7433 int p_deltify = 0, p_written = 0, p_sent = 0;
7434 int print_searching = 0, print_total = 0;
7435 int print_deltify = 0, print_written = 0, print_sent = 0;
7437 if (a->verbosity < 0)
7438 return NULL;
7440 if (refname) {
7441 const char *status = success ? "accepted" : "rejected";
7443 if (success) {
7444 struct got_pathlist_entry *pe;
7445 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7446 const char *branchname = pe->path;
7447 if (got_path_cmp(branchname, refname,
7448 strlen(branchname), strlen(refname)) == 0) {
7449 status = "deleted";
7450 a->sent_something = 1;
7451 break;
7456 if (a->printed_something)
7457 putchar('\n');
7458 printf("Server has %s %s", status, refname);
7459 a->printed_something = 1;
7460 return NULL;
7463 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7464 return got_error_from_errno("fmt_scaled");
7465 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7466 return got_error_from_errno("fmt_scaled");
7468 if (a->last_ncommits != ncommits) {
7469 print_searching = 1;
7470 a->last_ncommits = ncommits;
7473 if (a->last_nobj_total != nobj_total) {
7474 print_searching = 1;
7475 print_total = 1;
7476 a->last_nobj_total = nobj_total;
7479 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7480 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7481 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7482 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7483 return got_error(GOT_ERR_NO_SPACE);
7486 if (nobj_deltify > 0 || nobj_written > 0) {
7487 if (nobj_deltify > 0) {
7488 p_deltify = (nobj_deltify * 100) / nobj_total;
7489 if (p_deltify != a->last_p_deltify) {
7490 a->last_p_deltify = p_deltify;
7491 print_searching = 1;
7492 print_total = 1;
7493 print_deltify = 1;
7496 if (nobj_written > 0) {
7497 p_written = (nobj_written * 100) / nobj_total;
7498 if (p_written != a->last_p_written) {
7499 a->last_p_written = p_written;
7500 print_searching = 1;
7501 print_total = 1;
7502 print_deltify = 1;
7503 print_written = 1;
7508 if (bytes_sent > 0) {
7509 p_sent = (bytes_sent * 100) / packfile_size;
7510 if (p_sent != a->last_p_sent) {
7511 a->last_p_sent = p_sent;
7512 print_searching = 1;
7513 print_total = 1;
7514 print_deltify = 1;
7515 print_written = 1;
7516 print_sent = 1;
7518 a->sent_something = 1;
7521 if (print_searching || print_total || print_deltify || print_written ||
7522 print_sent)
7523 printf("\r");
7524 if (print_searching)
7525 printf("packing %d reference%s", ncommits,
7526 ncommits == 1 ? "" : "s");
7527 if (print_total)
7528 printf("; %d object%s", nobj_total,
7529 nobj_total == 1 ? "" : "s");
7530 if (print_deltify)
7531 printf("; deltify: %d%%", p_deltify);
7532 if (print_sent)
7533 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7534 scaled_packsize, p_sent);
7535 else if (print_written)
7536 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7537 scaled_packsize, p_written);
7538 if (print_searching || print_total || print_deltify ||
7539 print_written || print_sent) {
7540 a->printed_something = 1;
7541 fflush(stdout);
7543 return NULL;
7546 static const struct got_error *
7547 cmd_send(int argc, char *argv[])
7549 const struct got_error *error = NULL;
7550 char *cwd = NULL, *repo_path = NULL;
7551 const char *remote_name;
7552 char *proto = NULL, *host = NULL, *port = NULL;
7553 char *repo_name = NULL, *server_path = NULL;
7554 const struct got_remote_repo *remotes, *remote = NULL;
7555 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7556 struct got_repository *repo = NULL;
7557 struct got_worktree *worktree = NULL;
7558 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7559 struct got_pathlist_head branches;
7560 struct got_pathlist_head tags;
7561 struct got_reflist_head all_branches;
7562 struct got_reflist_head all_tags;
7563 struct got_pathlist_head delete_args;
7564 struct got_pathlist_head delete_branches;
7565 struct got_reflist_entry *re;
7566 struct got_pathlist_entry *pe;
7567 int i, ch, sendfd = -1, sendstatus;
7568 pid_t sendpid = -1;
7569 struct got_send_progress_arg spa;
7570 int verbosity = 0, overwrite_refs = 0;
7571 int send_all_branches = 0, send_all_tags = 0;
7572 struct got_reference *ref = NULL;
7574 TAILQ_INIT(&branches);
7575 TAILQ_INIT(&tags);
7576 TAILQ_INIT(&all_branches);
7577 TAILQ_INIT(&all_tags);
7578 TAILQ_INIT(&delete_args);
7579 TAILQ_INIT(&delete_branches);
7581 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7582 switch (ch) {
7583 case 'a':
7584 send_all_branches = 1;
7585 break;
7586 case 'b':
7587 error = got_pathlist_append(&branches, optarg, NULL);
7588 if (error)
7589 return error;
7590 nbranches++;
7591 break;
7592 case 'd':
7593 error = got_pathlist_append(&delete_args, optarg, NULL);
7594 if (error)
7595 return error;
7596 break;
7597 case 'f':
7598 overwrite_refs = 1;
7599 break;
7600 case 'r':
7601 repo_path = realpath(optarg, NULL);
7602 if (repo_path == NULL)
7603 return got_error_from_errno2("realpath",
7604 optarg);
7605 got_path_strip_trailing_slashes(repo_path);
7606 break;
7607 case 't':
7608 error = got_pathlist_append(&tags, optarg, NULL);
7609 if (error)
7610 return error;
7611 ntags++;
7612 break;
7613 case 'T':
7614 send_all_tags = 1;
7615 break;
7616 case 'v':
7617 if (verbosity < 0)
7618 verbosity = 0;
7619 else if (verbosity < 3)
7620 verbosity++;
7621 break;
7622 case 'q':
7623 verbosity = -1;
7624 break;
7625 default:
7626 usage_send();
7627 /* NOTREACHED */
7630 argc -= optind;
7631 argv += optind;
7633 if (send_all_branches && !TAILQ_EMPTY(&branches))
7634 option_conflict('a', 'b');
7635 if (send_all_tags && !TAILQ_EMPTY(&tags))
7636 option_conflict('T', 't');
7639 if (argc == 0)
7640 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7641 else if (argc == 1)
7642 remote_name = argv[0];
7643 else
7644 usage_send();
7646 cwd = getcwd(NULL, 0);
7647 if (cwd == NULL) {
7648 error = got_error_from_errno("getcwd");
7649 goto done;
7652 if (repo_path == NULL) {
7653 error = got_worktree_open(&worktree, cwd);
7654 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7655 goto done;
7656 else
7657 error = NULL;
7658 if (worktree) {
7659 repo_path =
7660 strdup(got_worktree_get_repo_path(worktree));
7661 if (repo_path == NULL)
7662 error = got_error_from_errno("strdup");
7663 if (error)
7664 goto done;
7665 } else {
7666 repo_path = strdup(cwd);
7667 if (repo_path == NULL) {
7668 error = got_error_from_errno("strdup");
7669 goto done;
7674 error = got_repo_open(&repo, repo_path, NULL);
7675 if (error)
7676 goto done;
7678 if (worktree) {
7679 worktree_conf = got_worktree_get_gotconfig(worktree);
7680 if (worktree_conf) {
7681 got_gotconfig_get_remotes(&nremotes, &remotes,
7682 worktree_conf);
7683 for (i = 0; i < nremotes; i++) {
7684 if (strcmp(remotes[i].name, remote_name) == 0) {
7685 remote = &remotes[i];
7686 break;
7691 if (remote == NULL) {
7692 repo_conf = got_repo_get_gotconfig(repo);
7693 if (repo_conf) {
7694 got_gotconfig_get_remotes(&nremotes, &remotes,
7695 repo_conf);
7696 for (i = 0; i < nremotes; i++) {
7697 if (strcmp(remotes[i].name, remote_name) == 0) {
7698 remote = &remotes[i];
7699 break;
7704 if (remote == NULL) {
7705 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7706 for (i = 0; i < nremotes; i++) {
7707 if (strcmp(remotes[i].name, remote_name) == 0) {
7708 remote = &remotes[i];
7709 break;
7713 if (remote == NULL) {
7714 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7715 goto done;
7718 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7719 &repo_name, remote->send_url);
7720 if (error)
7721 goto done;
7723 if (strcmp(proto, "git") == 0) {
7724 #ifndef PROFILE
7725 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7726 "sendfd dns inet unveil", NULL) == -1)
7727 err(1, "pledge");
7728 #endif
7729 } else if (strcmp(proto, "git+ssh") == 0 ||
7730 strcmp(proto, "ssh") == 0) {
7731 #ifndef PROFILE
7732 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7733 "sendfd unveil", NULL) == -1)
7734 err(1, "pledge");
7735 #endif
7736 } else if (strcmp(proto, "http") == 0 ||
7737 strcmp(proto, "git+http") == 0) {
7738 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7739 goto done;
7740 } else {
7741 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7742 goto done;
7745 error = got_dial_apply_unveil(proto);
7746 if (error)
7747 goto done;
7749 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7750 if (error)
7751 goto done;
7753 if (send_all_branches) {
7754 error = got_ref_list(&all_branches, repo, "refs/heads",
7755 got_ref_cmp_by_name, NULL);
7756 if (error)
7757 goto done;
7758 TAILQ_FOREACH(re, &all_branches, entry) {
7759 const char *branchname = got_ref_get_name(re->ref);
7760 error = got_pathlist_append(&branches,
7761 branchname, NULL);
7762 if (error)
7763 goto done;
7764 nbranches++;
7766 } else if (nbranches == 0) {
7767 for (i = 0; i < remote->nsend_branches; i++) {
7768 got_pathlist_append(&branches,
7769 remote->send_branches[i], NULL);
7773 if (send_all_tags) {
7774 error = got_ref_list(&all_tags, repo, "refs/tags",
7775 got_ref_cmp_by_name, NULL);
7776 if (error)
7777 goto done;
7778 TAILQ_FOREACH(re, &all_tags, entry) {
7779 const char *tagname = got_ref_get_name(re->ref);
7780 error = got_pathlist_append(&tags,
7781 tagname, NULL);
7782 if (error)
7783 goto done;
7784 ntags++;
7789 * To prevent accidents only branches in refs/heads/ can be deleted
7790 * with 'got send -d'.
7791 * Deleting anything else requires local repository access or Git.
7793 TAILQ_FOREACH(pe, &delete_args, entry) {
7794 const char *branchname = pe->path;
7795 char *s;
7796 struct got_pathlist_entry *new;
7797 if (strncmp(branchname, "refs/heads/", 11) == 0) {
7798 s = strdup(branchname);
7799 if (s == NULL) {
7800 error = got_error_from_errno("strdup");
7801 goto done;
7803 } else {
7804 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
7805 error = got_error_from_errno("asprintf");
7806 goto done;
7809 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
7810 if (error || new == NULL /* duplicate */)
7811 free(s);
7812 if (error)
7813 goto done;
7814 ndelete_branches++;
7817 if (nbranches == 0 && ndelete_branches == 0) {
7818 struct got_reference *head_ref;
7819 if (worktree)
7820 error = got_ref_open(&head_ref, repo,
7821 got_worktree_get_head_ref_name(worktree), 0);
7822 else
7823 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
7824 if (error)
7825 goto done;
7826 if (got_ref_is_symbolic(head_ref)) {
7827 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
7828 got_ref_close(head_ref);
7829 if (error)
7830 goto done;
7831 } else
7832 ref = head_ref;
7833 error = got_pathlist_append(&branches, got_ref_get_name(ref),
7834 NULL);
7835 if (error)
7836 goto done;
7837 nbranches++;
7840 if (verbosity >= 0)
7841 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
7842 port ? ":" : "", port ? port : "");
7844 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
7845 server_path, verbosity);
7846 if (error)
7847 goto done;
7849 memset(&spa, 0, sizeof(spa));
7850 spa.last_scaled_packsize[0] = '\0';
7851 spa.last_p_deltify = -1;
7852 spa.last_p_written = -1;
7853 spa.verbosity = verbosity;
7854 spa.delete_branches = &delete_branches;
7855 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
7856 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
7857 check_cancelled, NULL);
7858 if (spa.printed_something)
7859 putchar('\n');
7860 if (error)
7861 goto done;
7862 if (!spa.sent_something && verbosity >= 0)
7863 printf("Already up-to-date\n");
7864 done:
7865 if (sendpid > 0) {
7866 if (kill(sendpid, SIGTERM) == -1)
7867 error = got_error_from_errno("kill");
7868 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
7869 error = got_error_from_errno("waitpid");
7871 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
7872 error = got_error_from_errno("close");
7873 if (repo) {
7874 const struct got_error *close_err = got_repo_close(repo);
7875 if (error == NULL)
7876 error = close_err;
7878 if (worktree)
7879 got_worktree_close(worktree);
7880 if (ref)
7881 got_ref_close(ref);
7882 got_pathlist_free(&branches);
7883 got_pathlist_free(&tags);
7884 got_ref_list_free(&all_branches);
7885 got_ref_list_free(&all_tags);
7886 got_pathlist_free(&delete_args);
7887 TAILQ_FOREACH(pe, &delete_branches, entry)
7888 free((char *)pe->path);
7889 got_pathlist_free(&delete_branches);
7890 free(cwd);
7891 free(repo_path);
7892 free(proto);
7893 free(host);
7894 free(port);
7895 free(server_path);
7896 free(repo_name);
7897 return error;
7900 __dead static void
7901 usage_cherrypick(void)
7903 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
7904 exit(1);
7907 static const struct got_error *
7908 cmd_cherrypick(int argc, char *argv[])
7910 const struct got_error *error = NULL;
7911 struct got_worktree *worktree = NULL;
7912 struct got_repository *repo = NULL;
7913 char *cwd = NULL, *commit_id_str = NULL;
7914 struct got_object_id *commit_id = NULL;
7915 struct got_commit_object *commit = NULL;
7916 struct got_object_qid *pid;
7917 int ch;
7918 struct got_update_progress_arg upa;
7920 while ((ch = getopt(argc, argv, "")) != -1) {
7921 switch (ch) {
7922 default:
7923 usage_cherrypick();
7924 /* NOTREACHED */
7928 argc -= optind;
7929 argv += optind;
7931 #ifndef PROFILE
7932 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7933 "unveil", NULL) == -1)
7934 err(1, "pledge");
7935 #endif
7936 if (argc != 1)
7937 usage_cherrypick();
7939 cwd = getcwd(NULL, 0);
7940 if (cwd == NULL) {
7941 error = got_error_from_errno("getcwd");
7942 goto done;
7944 error = got_worktree_open(&worktree, cwd);
7945 if (error) {
7946 if (error->code == GOT_ERR_NOT_WORKTREE)
7947 error = wrap_not_worktree_error(error, "cherrypick",
7948 cwd);
7949 goto done;
7952 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7953 NULL);
7954 if (error != NULL)
7955 goto done;
7957 error = apply_unveil(got_repo_get_path(repo), 0,
7958 got_worktree_get_root_path(worktree));
7959 if (error)
7960 goto done;
7962 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
7963 GOT_OBJ_TYPE_COMMIT, repo);
7964 if (error != NULL) {
7965 struct got_reference *ref;
7966 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
7967 goto done;
7968 error = got_ref_open(&ref, repo, argv[0], 0);
7969 if (error != NULL)
7970 goto done;
7971 error = got_ref_resolve(&commit_id, repo, ref);
7972 got_ref_close(ref);
7973 if (error != NULL)
7974 goto done;
7976 error = got_object_id_str(&commit_id_str, commit_id);
7977 if (error)
7978 goto done;
7980 error = got_object_open_as_commit(&commit, repo, commit_id);
7981 if (error)
7982 goto done;
7983 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7984 memset(&upa, 0, sizeof(upa));
7985 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
7986 commit_id, repo, update_progress, &upa, check_cancelled,
7987 NULL);
7988 if (error != NULL)
7989 goto done;
7991 if (upa.did_something)
7992 printf("Merged commit %s\n", commit_id_str);
7993 print_update_progress_stats(&upa);
7994 done:
7995 if (commit)
7996 got_object_commit_close(commit);
7997 free(commit_id_str);
7998 if (worktree)
7999 got_worktree_close(worktree);
8000 if (repo) {
8001 const struct got_error *close_err = got_repo_close(repo);
8002 if (error == NULL)
8003 error = close_err;
8005 return error;
8008 __dead static void
8009 usage_backout(void)
8011 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8012 exit(1);
8015 static const struct got_error *
8016 cmd_backout(int argc, char *argv[])
8018 const struct got_error *error = NULL;
8019 struct got_worktree *worktree = NULL;
8020 struct got_repository *repo = NULL;
8021 char *cwd = NULL, *commit_id_str = NULL;
8022 struct got_object_id *commit_id = NULL;
8023 struct got_commit_object *commit = NULL;
8024 struct got_object_qid *pid;
8025 int ch;
8026 struct got_update_progress_arg upa;
8028 while ((ch = getopt(argc, argv, "")) != -1) {
8029 switch (ch) {
8030 default:
8031 usage_backout();
8032 /* NOTREACHED */
8036 argc -= optind;
8037 argv += optind;
8039 #ifndef PROFILE
8040 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8041 "unveil", NULL) == -1)
8042 err(1, "pledge");
8043 #endif
8044 if (argc != 1)
8045 usage_backout();
8047 cwd = getcwd(NULL, 0);
8048 if (cwd == NULL) {
8049 error = got_error_from_errno("getcwd");
8050 goto done;
8052 error = got_worktree_open(&worktree, cwd);
8053 if (error) {
8054 if (error->code == GOT_ERR_NOT_WORKTREE)
8055 error = wrap_not_worktree_error(error, "backout", cwd);
8056 goto done;
8059 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8060 NULL);
8061 if (error != NULL)
8062 goto done;
8064 error = apply_unveil(got_repo_get_path(repo), 0,
8065 got_worktree_get_root_path(worktree));
8066 if (error)
8067 goto done;
8069 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8070 GOT_OBJ_TYPE_COMMIT, repo);
8071 if (error != NULL) {
8072 struct got_reference *ref;
8073 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8074 goto done;
8075 error = got_ref_open(&ref, repo, argv[0], 0);
8076 if (error != NULL)
8077 goto done;
8078 error = got_ref_resolve(&commit_id, repo, ref);
8079 got_ref_close(ref);
8080 if (error != NULL)
8081 goto done;
8083 error = got_object_id_str(&commit_id_str, commit_id);
8084 if (error)
8085 goto done;
8087 error = got_object_open_as_commit(&commit, repo, commit_id);
8088 if (error)
8089 goto done;
8090 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8091 if (pid == NULL) {
8092 error = got_error(GOT_ERR_ROOT_COMMIT);
8093 goto done;
8096 memset(&upa, 0, sizeof(upa));
8097 error = got_worktree_merge_files(worktree, commit_id, pid->id, repo,
8098 update_progress, &upa, check_cancelled, NULL);
8099 if (error != NULL)
8100 goto done;
8102 if (upa.did_something)
8103 printf("Backed out commit %s\n", commit_id_str);
8104 print_update_progress_stats(&upa);
8105 done:
8106 if (commit)
8107 got_object_commit_close(commit);
8108 free(commit_id_str);
8109 if (worktree)
8110 got_worktree_close(worktree);
8111 if (repo) {
8112 const struct got_error *close_err = got_repo_close(repo);
8113 if (error == NULL)
8114 error = close_err;
8116 return error;
8119 __dead static void
8120 usage_rebase(void)
8122 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8123 getprogname());
8124 exit(1);
8127 void
8128 trim_logmsg(char *logmsg, int limit)
8130 char *nl;
8131 size_t len;
8133 len = strlen(logmsg);
8134 if (len > limit)
8135 len = limit;
8136 logmsg[len] = '\0';
8137 nl = strchr(logmsg, '\n');
8138 if (nl)
8139 *nl = '\0';
8142 static const struct got_error *
8143 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8145 const struct got_error *err;
8146 char *logmsg0 = NULL;
8147 const char *s;
8149 err = got_object_commit_get_logmsg(&logmsg0, commit);
8150 if (err)
8151 return err;
8153 s = logmsg0;
8154 while (isspace((unsigned char)s[0]))
8155 s++;
8157 *logmsg = strdup(s);
8158 if (*logmsg == NULL) {
8159 err = got_error_from_errno("strdup");
8160 goto done;
8163 trim_logmsg(*logmsg, limit);
8164 done:
8165 free(logmsg0);
8166 return err;
8169 static const struct got_error *
8170 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8172 const struct got_error *err;
8173 struct got_commit_object *commit = NULL;
8174 char *id_str = NULL, *logmsg = NULL;
8176 err = got_object_open_as_commit(&commit, repo, id);
8177 if (err)
8178 return err;
8180 err = got_object_id_str(&id_str, id);
8181 if (err)
8182 goto done;
8184 id_str[12] = '\0';
8186 err = get_short_logmsg(&logmsg, 42, commit);
8187 if (err)
8188 goto done;
8190 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8191 done:
8192 free(id_str);
8193 got_object_commit_close(commit);
8194 free(logmsg);
8195 return err;
8198 static const struct got_error *
8199 show_rebase_progress(struct got_commit_object *commit,
8200 struct got_object_id *old_id, struct got_object_id *new_id)
8202 const struct got_error *err;
8203 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8205 err = got_object_id_str(&old_id_str, old_id);
8206 if (err)
8207 goto done;
8209 if (new_id) {
8210 err = got_object_id_str(&new_id_str, new_id);
8211 if (err)
8212 goto done;
8215 old_id_str[12] = '\0';
8216 if (new_id_str)
8217 new_id_str[12] = '\0';
8219 err = get_short_logmsg(&logmsg, 42, commit);
8220 if (err)
8221 goto done;
8223 printf("%s -> %s: %s\n", old_id_str,
8224 new_id_str ? new_id_str : "no-op change", logmsg);
8225 done:
8226 free(old_id_str);
8227 free(new_id_str);
8228 free(logmsg);
8229 return err;
8232 static const struct got_error *
8233 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8234 struct got_reference *branch, struct got_reference *new_base_branch,
8235 struct got_reference *tmp_branch, struct got_repository *repo,
8236 int create_backup)
8238 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8239 return got_worktree_rebase_complete(worktree, fileindex,
8240 new_base_branch, tmp_branch, branch, repo, create_backup);
8243 static const struct got_error *
8244 rebase_commit(struct got_pathlist_head *merged_paths,
8245 struct got_worktree *worktree, struct got_fileindex *fileindex,
8246 struct got_reference *tmp_branch,
8247 struct got_object_id *commit_id, struct got_repository *repo)
8249 const struct got_error *error;
8250 struct got_commit_object *commit;
8251 struct got_object_id *new_commit_id;
8253 error = got_object_open_as_commit(&commit, repo, commit_id);
8254 if (error)
8255 return error;
8257 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8258 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8259 if (error) {
8260 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8261 goto done;
8262 error = show_rebase_progress(commit, commit_id, NULL);
8263 } else {
8264 error = show_rebase_progress(commit, commit_id, new_commit_id);
8265 free(new_commit_id);
8267 done:
8268 got_object_commit_close(commit);
8269 return error;
8272 struct check_path_prefix_arg {
8273 const char *path_prefix;
8274 size_t len;
8275 int errcode;
8278 static const struct got_error *
8279 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8280 struct got_blob_object *blob2, struct got_object_id *id1,
8281 struct got_object_id *id2, const char *path1, const char *path2,
8282 mode_t mode1, mode_t mode2, struct got_repository *repo)
8284 struct check_path_prefix_arg *a = arg;
8286 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8287 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8288 return got_error(a->errcode);
8290 return NULL;
8293 static const struct got_error *
8294 check_path_prefix(struct got_object_id *parent_id,
8295 struct got_object_id *commit_id, const char *path_prefix,
8296 int errcode, struct got_repository *repo)
8298 const struct got_error *err;
8299 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8300 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8301 struct check_path_prefix_arg cpp_arg;
8303 if (got_path_is_root_dir(path_prefix))
8304 return NULL;
8306 err = got_object_open_as_commit(&commit, repo, commit_id);
8307 if (err)
8308 goto done;
8310 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8311 if (err)
8312 goto done;
8314 err = got_object_open_as_tree(&tree1, repo,
8315 got_object_commit_get_tree_id(parent_commit));
8316 if (err)
8317 goto done;
8319 err = got_object_open_as_tree(&tree2, repo,
8320 got_object_commit_get_tree_id(commit));
8321 if (err)
8322 goto done;
8324 cpp_arg.path_prefix = path_prefix;
8325 while (cpp_arg.path_prefix[0] == '/')
8326 cpp_arg.path_prefix++;
8327 cpp_arg.len = strlen(cpp_arg.path_prefix);
8328 cpp_arg.errcode = errcode;
8329 err = got_diff_tree(tree1, tree2, "", "", repo,
8330 check_path_prefix_in_diff, &cpp_arg, 0);
8331 done:
8332 if (tree1)
8333 got_object_tree_close(tree1);
8334 if (tree2)
8335 got_object_tree_close(tree2);
8336 if (commit)
8337 got_object_commit_close(commit);
8338 if (parent_commit)
8339 got_object_commit_close(parent_commit);
8340 return err;
8343 static const struct got_error *
8344 collect_commits(struct got_object_id_queue *commits,
8345 struct got_object_id *initial_commit_id,
8346 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8347 const char *path_prefix, int path_prefix_errcode,
8348 struct got_repository *repo)
8350 const struct got_error *err = NULL;
8351 struct got_commit_graph *graph = NULL;
8352 struct got_object_id *parent_id = NULL;
8353 struct got_object_qid *qid;
8354 struct got_object_id *commit_id = initial_commit_id;
8356 err = got_commit_graph_open(&graph, "/", 1);
8357 if (err)
8358 return err;
8360 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8361 check_cancelled, NULL);
8362 if (err)
8363 goto done;
8364 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8365 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8366 check_cancelled, NULL);
8367 if (err) {
8368 if (err->code == GOT_ERR_ITER_COMPLETED) {
8369 err = got_error_msg(GOT_ERR_ANCESTRY,
8370 "ran out of commits to rebase before "
8371 "youngest common ancestor commit has "
8372 "been reached?!?");
8374 goto done;
8375 } else {
8376 err = check_path_prefix(parent_id, commit_id,
8377 path_prefix, path_prefix_errcode, repo);
8378 if (err)
8379 goto done;
8381 err = got_object_qid_alloc(&qid, commit_id);
8382 if (err)
8383 goto done;
8384 STAILQ_INSERT_HEAD(commits, qid, entry);
8385 commit_id = parent_id;
8388 done:
8389 got_commit_graph_close(graph);
8390 return err;
8393 static const struct got_error *
8394 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8396 const struct got_error *err = NULL;
8397 time_t committer_time;
8398 struct tm tm;
8399 char datebuf[11]; /* YYYY-MM-DD + NUL */
8400 char *author0 = NULL, *author, *smallerthan;
8401 char *logmsg0 = NULL, *logmsg, *newline;
8403 committer_time = got_object_commit_get_committer_time(commit);
8404 if (gmtime_r(&committer_time, &tm) == NULL)
8405 return got_error_from_errno("gmtime_r");
8406 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8407 return got_error(GOT_ERR_NO_SPACE);
8409 author0 = strdup(got_object_commit_get_author(commit));
8410 if (author0 == NULL)
8411 return got_error_from_errno("strdup");
8412 author = author0;
8413 smallerthan = strchr(author, '<');
8414 if (smallerthan && smallerthan[1] != '\0')
8415 author = smallerthan + 1;
8416 author[strcspn(author, "@>")] = '\0';
8418 err = got_object_commit_get_logmsg(&logmsg0, commit);
8419 if (err)
8420 goto done;
8421 logmsg = logmsg0;
8422 while (*logmsg == '\n')
8423 logmsg++;
8424 newline = strchr(logmsg, '\n');
8425 if (newline)
8426 *newline = '\0';
8428 if (asprintf(brief_str, "%s %s %s",
8429 datebuf, author, logmsg) == -1)
8430 err = got_error_from_errno("asprintf");
8431 done:
8432 free(author0);
8433 free(logmsg0);
8434 return err;
8437 static const struct got_error *
8438 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8439 struct got_repository *repo)
8441 const struct got_error *err;
8442 char *id_str;
8444 err = got_object_id_str(&id_str, id);
8445 if (err)
8446 return err;
8448 err = got_ref_delete(ref, repo);
8449 if (err)
8450 goto done;
8452 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8453 done:
8454 free(id_str);
8455 return err;
8458 static const struct got_error *
8459 print_backup_ref(const char *branch_name, const char *new_id_str,
8460 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8461 struct got_reflist_object_id_map *refs_idmap,
8462 struct got_repository *repo)
8464 const struct got_error *err = NULL;
8465 struct got_reflist_head *refs;
8466 char *refs_str = NULL;
8467 struct got_object_id *new_commit_id = NULL;
8468 struct got_commit_object *new_commit = NULL;
8469 char *new_commit_brief_str = NULL;
8470 struct got_object_id *yca_id = NULL;
8471 struct got_commit_object *yca_commit = NULL;
8472 char *yca_id_str = NULL, *yca_brief_str = NULL;
8473 char *custom_refs_str;
8475 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8476 return got_error_from_errno("asprintf");
8478 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8479 0, 0, refs_idmap, custom_refs_str);
8480 if (err)
8481 goto done;
8483 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8484 if (err)
8485 goto done;
8487 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8488 if (refs) {
8489 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8490 if (err)
8491 goto done;
8494 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8495 if (err)
8496 goto done;
8498 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8499 if (err)
8500 goto done;
8502 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8503 old_commit_id, new_commit_id, repo, check_cancelled, NULL);
8504 if (err)
8505 goto done;
8507 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8508 refs_str ? " (" : "", refs_str ? refs_str : "",
8509 refs_str ? ")" : "", new_commit_brief_str);
8510 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8511 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8512 free(refs_str);
8513 refs_str = NULL;
8515 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8516 if (err)
8517 goto done;
8519 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8520 if (err)
8521 goto done;
8523 err = got_object_id_str(&yca_id_str, yca_id);
8524 if (err)
8525 goto done;
8527 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8528 if (refs) {
8529 err = build_refs_str(&refs_str, refs, yca_id, repo);
8530 if (err)
8531 goto done;
8533 printf("history forked at %s%s%s%s\n %s\n",
8534 yca_id_str,
8535 refs_str ? " (" : "", refs_str ? refs_str : "",
8536 refs_str ? ")" : "", yca_brief_str);
8538 done:
8539 free(custom_refs_str);
8540 free(new_commit_id);
8541 free(refs_str);
8542 free(yca_id);
8543 free(yca_id_str);
8544 free(yca_brief_str);
8545 if (new_commit)
8546 got_object_commit_close(new_commit);
8547 if (yca_commit)
8548 got_object_commit_close(yca_commit);
8550 return NULL;
8553 static const struct got_error *
8554 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8555 int delete, struct got_repository *repo)
8557 const struct got_error *err;
8558 struct got_reflist_head refs, backup_refs;
8559 struct got_reflist_entry *re;
8560 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8561 struct got_object_id *old_commit_id = NULL;
8562 char *branch_name = NULL;
8563 struct got_commit_object *old_commit = NULL;
8564 struct got_reflist_object_id_map *refs_idmap = NULL;
8565 int wanted_branch_found = 0;
8567 TAILQ_INIT(&refs);
8568 TAILQ_INIT(&backup_refs);
8570 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8571 if (err)
8572 return err;
8574 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8575 if (err)
8576 goto done;
8578 if (wanted_branch_name) {
8579 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8580 wanted_branch_name += 11;
8583 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8584 got_ref_cmp_by_commit_timestamp_descending, repo);
8585 if (err)
8586 goto done;
8588 TAILQ_FOREACH(re, &backup_refs, entry) {
8589 const char *refname = got_ref_get_name(re->ref);
8590 char *slash;
8592 err = check_cancelled(NULL);
8593 if (err)
8594 break;
8596 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8597 if (err)
8598 break;
8600 err = got_object_open_as_commit(&old_commit, repo,
8601 old_commit_id);
8602 if (err)
8603 break;
8605 if (strncmp(backup_ref_prefix, refname,
8606 backup_ref_prefix_len) == 0)
8607 refname += backup_ref_prefix_len;
8609 while (refname[0] == '/')
8610 refname++;
8612 branch_name = strdup(refname);
8613 if (branch_name == NULL) {
8614 err = got_error_from_errno("strdup");
8615 break;
8617 slash = strrchr(branch_name, '/');
8618 if (slash) {
8619 *slash = '\0';
8620 refname += strlen(branch_name) + 1;
8623 if (wanted_branch_name == NULL ||
8624 strcmp(wanted_branch_name, branch_name) == 0) {
8625 wanted_branch_found = 1;
8626 if (delete) {
8627 err = delete_backup_ref(re->ref,
8628 old_commit_id, repo);
8629 } else {
8630 err = print_backup_ref(branch_name, refname,
8631 old_commit_id, old_commit, refs_idmap,
8632 repo);
8634 if (err)
8635 break;
8638 free(old_commit_id);
8639 old_commit_id = NULL;
8640 free(branch_name);
8641 branch_name = NULL;
8642 got_object_commit_close(old_commit);
8643 old_commit = NULL;
8646 if (wanted_branch_name && !wanted_branch_found) {
8647 err = got_error_fmt(GOT_ERR_NOT_REF,
8648 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8650 done:
8651 if (refs_idmap)
8652 got_reflist_object_id_map_free(refs_idmap);
8653 got_ref_list_free(&refs);
8654 got_ref_list_free(&backup_refs);
8655 free(old_commit_id);
8656 free(branch_name);
8657 if (old_commit)
8658 got_object_commit_close(old_commit);
8659 return err;
8662 static const struct got_error *
8663 cmd_rebase(int argc, char *argv[])
8665 const struct got_error *error = NULL;
8666 struct got_worktree *worktree = NULL;
8667 struct got_repository *repo = NULL;
8668 struct got_fileindex *fileindex = NULL;
8669 char *cwd = NULL;
8670 struct got_reference *branch = NULL;
8671 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8672 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8673 struct got_object_id *resume_commit_id = NULL;
8674 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8675 struct got_commit_object *commit = NULL;
8676 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8677 int histedit_in_progress = 0, create_backup = 1, list_backups = 0;
8678 int delete_backups = 0;
8679 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
8680 struct got_object_id_queue commits;
8681 struct got_pathlist_head merged_paths;
8682 const struct got_object_id_queue *parent_ids;
8683 struct got_object_qid *qid, *pid;
8685 STAILQ_INIT(&commits);
8686 TAILQ_INIT(&merged_paths);
8688 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8689 switch (ch) {
8690 case 'a':
8691 abort_rebase = 1;
8692 break;
8693 case 'c':
8694 continue_rebase = 1;
8695 break;
8696 case 'l':
8697 list_backups = 1;
8698 break;
8699 case 'X':
8700 delete_backups = 1;
8701 break;
8702 default:
8703 usage_rebase();
8704 /* NOTREACHED */
8708 argc -= optind;
8709 argv += optind;
8711 #ifndef PROFILE
8712 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8713 "unveil", NULL) == -1)
8714 err(1, "pledge");
8715 #endif
8716 if (list_backups) {
8717 if (abort_rebase)
8718 option_conflict('l', 'a');
8719 if (continue_rebase)
8720 option_conflict('l', 'c');
8721 if (delete_backups)
8722 option_conflict('l', 'X');
8723 if (argc != 0 && argc != 1)
8724 usage_rebase();
8725 } else if (delete_backups) {
8726 if (abort_rebase)
8727 option_conflict('X', 'a');
8728 if (continue_rebase)
8729 option_conflict('X', 'c');
8730 if (list_backups)
8731 option_conflict('l', 'X');
8732 if (argc != 0 && argc != 1)
8733 usage_rebase();
8734 } else {
8735 if (abort_rebase && continue_rebase)
8736 usage_rebase();
8737 else if (abort_rebase || continue_rebase) {
8738 if (argc != 0)
8739 usage_rebase();
8740 } else if (argc != 1)
8741 usage_rebase();
8744 cwd = getcwd(NULL, 0);
8745 if (cwd == NULL) {
8746 error = got_error_from_errno("getcwd");
8747 goto done;
8749 error = got_worktree_open(&worktree, cwd);
8750 if (error) {
8751 if (list_backups || delete_backups) {
8752 if (error->code != GOT_ERR_NOT_WORKTREE)
8753 goto done;
8754 } else {
8755 if (error->code == GOT_ERR_NOT_WORKTREE)
8756 error = wrap_not_worktree_error(error,
8757 "rebase", cwd);
8758 goto done;
8762 error = got_repo_open(&repo,
8763 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
8764 if (error != NULL)
8765 goto done;
8767 error = apply_unveil(got_repo_get_path(repo), 0,
8768 worktree ? got_worktree_get_root_path(worktree) : NULL);
8769 if (error)
8770 goto done;
8772 if (list_backups || delete_backups) {
8773 error = process_backup_refs(
8774 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
8775 argc == 1 ? argv[0] : NULL, delete_backups, repo);
8776 goto done; /* nothing else to do */
8779 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8780 worktree);
8781 if (error)
8782 goto done;
8783 if (histedit_in_progress) {
8784 error = got_error(GOT_ERR_HISTEDIT_BUSY);
8785 goto done;
8788 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8789 if (error)
8790 goto done;
8792 if (abort_rebase) {
8793 struct got_update_progress_arg upa;
8794 if (!rebase_in_progress) {
8795 error = got_error(GOT_ERR_NOT_REBASING);
8796 goto done;
8798 error = got_worktree_rebase_continue(&resume_commit_id,
8799 &new_base_branch, &tmp_branch, &branch, &fileindex,
8800 worktree, repo);
8801 if (error)
8802 goto done;
8803 printf("Switching work tree to %s\n",
8804 got_ref_get_symref_target(new_base_branch));
8805 memset(&upa, 0, sizeof(upa));
8806 error = got_worktree_rebase_abort(worktree, fileindex, repo,
8807 new_base_branch, update_progress, &upa);
8808 if (error)
8809 goto done;
8810 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
8811 print_update_progress_stats(&upa);
8812 goto done; /* nothing else to do */
8815 if (continue_rebase) {
8816 if (!rebase_in_progress) {
8817 error = got_error(GOT_ERR_NOT_REBASING);
8818 goto done;
8820 error = got_worktree_rebase_continue(&resume_commit_id,
8821 &new_base_branch, &tmp_branch, &branch, &fileindex,
8822 worktree, repo);
8823 if (error)
8824 goto done;
8826 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
8827 resume_commit_id, repo);
8828 if (error)
8829 goto done;
8831 yca_id = got_object_id_dup(resume_commit_id);
8832 if (yca_id == NULL) {
8833 error = got_error_from_errno("got_object_id_dup");
8834 goto done;
8836 } else {
8837 error = got_ref_open(&branch, repo, argv[0], 0);
8838 if (error != NULL)
8839 goto done;
8842 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
8843 if (error)
8844 goto done;
8846 if (!continue_rebase) {
8847 struct got_object_id *base_commit_id;
8849 base_commit_id = got_worktree_get_base_commit_id(worktree);
8850 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8851 base_commit_id, branch_head_commit_id, repo,
8852 check_cancelled, NULL);
8853 if (error)
8854 goto done;
8855 if (yca_id == NULL) {
8856 error = got_error_msg(GOT_ERR_ANCESTRY,
8857 "specified branch shares no common ancestry "
8858 "with work tree's branch");
8859 goto done;
8862 error = check_same_branch(base_commit_id, branch, yca_id, repo);
8863 if (error) {
8864 if (error->code != GOT_ERR_ANCESTRY)
8865 goto done;
8866 error = NULL;
8867 } else {
8868 static char msg[128];
8869 snprintf(msg, sizeof(msg),
8870 "%s is already based on %s",
8871 got_ref_get_name(branch),
8872 got_worktree_get_head_ref_name(worktree));
8873 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
8874 goto done;
8876 error = got_worktree_rebase_prepare(&new_base_branch,
8877 &tmp_branch, &fileindex, worktree, branch, repo);
8878 if (error)
8879 goto done;
8882 commit_id = branch_head_commit_id;
8883 error = got_object_open_as_commit(&commit, repo, commit_id);
8884 if (error)
8885 goto done;
8887 parent_ids = got_object_commit_get_parent_ids(commit);
8888 pid = STAILQ_FIRST(parent_ids);
8889 if (pid == NULL) {
8890 if (!continue_rebase) {
8891 struct got_update_progress_arg upa;
8892 memset(&upa, 0, sizeof(upa));
8893 error = got_worktree_rebase_abort(worktree, fileindex,
8894 repo, new_base_branch, update_progress, &upa);
8895 if (error)
8896 goto done;
8897 printf("Rebase of %s aborted\n",
8898 got_ref_get_name(branch));
8899 print_update_progress_stats(&upa);
8902 error = got_error(GOT_ERR_EMPTY_REBASE);
8903 goto done;
8905 error = collect_commits(&commits, commit_id, pid->id,
8906 yca_id, got_worktree_get_path_prefix(worktree),
8907 GOT_ERR_REBASE_PATH, repo);
8908 got_object_commit_close(commit);
8909 commit = NULL;
8910 if (error)
8911 goto done;
8913 if (STAILQ_EMPTY(&commits)) {
8914 if (continue_rebase) {
8915 error = rebase_complete(worktree, fileindex,
8916 branch, new_base_branch, tmp_branch, repo,
8917 create_backup);
8918 goto done;
8919 } else {
8920 /* Fast-forward the reference of the branch. */
8921 struct got_object_id *new_head_commit_id;
8922 char *id_str;
8923 error = got_ref_resolve(&new_head_commit_id, repo,
8924 new_base_branch);
8925 if (error)
8926 goto done;
8927 error = got_object_id_str(&id_str, new_head_commit_id);
8928 printf("Forwarding %s to commit %s\n",
8929 got_ref_get_name(branch), id_str);
8930 free(id_str);
8931 error = got_ref_change_ref(branch,
8932 new_head_commit_id);
8933 if (error)
8934 goto done;
8935 /* No backup needed since objects did not change. */
8936 create_backup = 0;
8940 pid = NULL;
8941 STAILQ_FOREACH(qid, &commits, entry) {
8942 struct got_update_progress_arg upa;
8944 commit_id = qid->id;
8945 parent_id = pid ? pid->id : yca_id;
8946 pid = qid;
8948 memset(&upa, 0, sizeof(upa));
8949 error = got_worktree_rebase_merge_files(&merged_paths,
8950 worktree, fileindex, parent_id, commit_id, repo,
8951 update_progress, &upa, check_cancelled, NULL);
8952 if (error)
8953 goto done;
8955 print_update_progress_stats(&upa);
8956 if (upa.conflicts > 0)
8957 rebase_status = GOT_STATUS_CONFLICT;
8959 if (rebase_status == GOT_STATUS_CONFLICT) {
8960 error = show_rebase_merge_conflict(qid->id, repo);
8961 if (error)
8962 goto done;
8963 got_worktree_rebase_pathlist_free(&merged_paths);
8964 break;
8967 error = rebase_commit(&merged_paths, worktree, fileindex,
8968 tmp_branch, commit_id, repo);
8969 got_worktree_rebase_pathlist_free(&merged_paths);
8970 if (error)
8971 goto done;
8974 if (rebase_status == GOT_STATUS_CONFLICT) {
8975 error = got_worktree_rebase_postpone(worktree, fileindex);
8976 if (error)
8977 goto done;
8978 error = got_error_msg(GOT_ERR_CONFLICTS,
8979 "conflicts must be resolved before rebasing can continue");
8980 } else
8981 error = rebase_complete(worktree, fileindex, branch,
8982 new_base_branch, tmp_branch, repo, create_backup);
8983 done:
8984 got_object_id_queue_free(&commits);
8985 free(branch_head_commit_id);
8986 free(resume_commit_id);
8987 free(yca_id);
8988 if (commit)
8989 got_object_commit_close(commit);
8990 if (branch)
8991 got_ref_close(branch);
8992 if (new_base_branch)
8993 got_ref_close(new_base_branch);
8994 if (tmp_branch)
8995 got_ref_close(tmp_branch);
8996 if (worktree)
8997 got_worktree_close(worktree);
8998 if (repo) {
8999 const struct got_error *close_err = got_repo_close(repo);
9000 if (error == NULL)
9001 error = close_err;
9003 return error;
9006 __dead static void
9007 usage_histedit(void)
9009 fprintf(stderr, "usage: %s histedit [-a] [-c] [-f] "
9010 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9011 getprogname());
9012 exit(1);
9015 #define GOT_HISTEDIT_PICK 'p'
9016 #define GOT_HISTEDIT_EDIT 'e'
9017 #define GOT_HISTEDIT_FOLD 'f'
9018 #define GOT_HISTEDIT_DROP 'd'
9019 #define GOT_HISTEDIT_MESG 'm'
9021 static struct got_histedit_cmd {
9022 unsigned char code;
9023 const char *name;
9024 const char *desc;
9025 } got_histedit_cmds[] = {
9026 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9027 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9028 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9029 "be used" },
9030 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9031 { GOT_HISTEDIT_MESG, "mesg",
9032 "single-line log message for commit above (open editor if empty)" },
9035 struct got_histedit_list_entry {
9036 TAILQ_ENTRY(got_histedit_list_entry) entry;
9037 struct got_object_id *commit_id;
9038 const struct got_histedit_cmd *cmd;
9039 char *logmsg;
9041 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9043 static const struct got_error *
9044 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9045 FILE *f, struct got_repository *repo)
9047 const struct got_error *err = NULL;
9048 char *logmsg = NULL, *id_str = NULL;
9049 struct got_commit_object *commit = NULL;
9050 int n;
9052 err = got_object_open_as_commit(&commit, repo, commit_id);
9053 if (err)
9054 goto done;
9056 err = get_short_logmsg(&logmsg, 34, commit);
9057 if (err)
9058 goto done;
9060 err = got_object_id_str(&id_str, commit_id);
9061 if (err)
9062 goto done;
9064 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9065 if (n < 0)
9066 err = got_ferror(f, GOT_ERR_IO);
9067 done:
9068 if (commit)
9069 got_object_commit_close(commit);
9070 free(id_str);
9071 free(logmsg);
9072 return err;
9075 static const struct got_error *
9076 histedit_write_commit_list(struct got_object_id_queue *commits,
9077 FILE *f, int edit_logmsg_only, int fold_only, struct got_repository *repo)
9079 const struct got_error *err = NULL;
9080 struct got_object_qid *qid;
9081 const char *histedit_cmd = NULL;
9083 if (STAILQ_EMPTY(commits))
9084 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9086 STAILQ_FOREACH(qid, commits, entry) {
9087 histedit_cmd = got_histedit_cmds[0].name;
9088 if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9089 histedit_cmd = "fold";
9090 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9091 if (err)
9092 break;
9093 if (edit_logmsg_only) {
9094 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9095 if (n < 0) {
9096 err = got_ferror(f, GOT_ERR_IO);
9097 break;
9102 return err;
9105 static const struct got_error *
9106 write_cmd_list(FILE *f, const char *branch_name,
9107 struct got_object_id_queue *commits)
9109 const struct got_error *err = NULL;
9110 size_t i;
9111 int n;
9112 char *id_str;
9113 struct got_object_qid *qid;
9115 qid = STAILQ_FIRST(commits);
9116 err = got_object_id_str(&id_str, qid->id);
9117 if (err)
9118 return err;
9120 n = fprintf(f,
9121 "# Editing the history of branch '%s' starting at\n"
9122 "# commit %s\n"
9123 "# Commits will be processed in order from top to "
9124 "bottom of this file.\n", branch_name, id_str);
9125 if (n < 0) {
9126 err = got_ferror(f, GOT_ERR_IO);
9127 goto done;
9130 n = fprintf(f, "# Available histedit commands:\n");
9131 if (n < 0) {
9132 err = got_ferror(f, GOT_ERR_IO);
9133 goto done;
9136 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9137 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9138 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9139 cmd->desc);
9140 if (n < 0) {
9141 err = got_ferror(f, GOT_ERR_IO);
9142 break;
9145 done:
9146 free(id_str);
9147 return err;
9150 static const struct got_error *
9151 histedit_syntax_error(int lineno)
9153 static char msg[42];
9154 int ret;
9156 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9157 lineno);
9158 if (ret == -1 || ret >= sizeof(msg))
9159 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9161 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9164 static const struct got_error *
9165 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9166 char *logmsg, struct got_repository *repo)
9168 const struct got_error *err;
9169 struct got_commit_object *folded_commit = NULL;
9170 char *id_str, *folded_logmsg = NULL;
9172 err = got_object_id_str(&id_str, hle->commit_id);
9173 if (err)
9174 return err;
9176 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9177 if (err)
9178 goto done;
9180 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9181 if (err)
9182 goto done;
9183 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9184 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9185 folded_logmsg) == -1) {
9186 err = got_error_from_errno("asprintf");
9188 done:
9189 if (folded_commit)
9190 got_object_commit_close(folded_commit);
9191 free(id_str);
9192 free(folded_logmsg);
9193 return err;
9196 static struct got_histedit_list_entry *
9197 get_folded_commits(struct got_histedit_list_entry *hle)
9199 struct got_histedit_list_entry *prev, *folded = NULL;
9201 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9202 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9203 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9204 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9205 folded = prev;
9206 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9209 return folded;
9212 static const struct got_error *
9213 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9214 struct got_repository *repo)
9216 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9217 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9218 const struct got_error *err = NULL;
9219 struct got_commit_object *commit = NULL;
9220 int logmsg_len;
9221 int fd;
9222 struct got_histedit_list_entry *folded = NULL;
9224 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9225 if (err)
9226 return err;
9228 folded = get_folded_commits(hle);
9229 if (folded) {
9230 while (folded != hle) {
9231 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9232 folded = TAILQ_NEXT(folded, entry);
9233 continue;
9235 err = append_folded_commit_msg(&new_msg, folded,
9236 logmsg, repo);
9237 if (err)
9238 goto done;
9239 free(logmsg);
9240 logmsg = new_msg;
9241 folded = TAILQ_NEXT(folded, entry);
9245 err = got_object_id_str(&id_str, hle->commit_id);
9246 if (err)
9247 goto done;
9248 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9249 if (err)
9250 goto done;
9251 logmsg_len = asprintf(&new_msg,
9252 "%s\n# original log message of commit %s: %s",
9253 logmsg ? logmsg : "", id_str, orig_logmsg);
9254 if (logmsg_len == -1) {
9255 err = got_error_from_errno("asprintf");
9256 goto done;
9258 free(logmsg);
9259 logmsg = new_msg;
9261 err = got_object_id_str(&id_str, hle->commit_id);
9262 if (err)
9263 goto done;
9265 err = got_opentemp_named_fd(&logmsg_path, &fd,
9266 GOT_TMPDIR_STR "/got-logmsg");
9267 if (err)
9268 goto done;
9270 write(fd, logmsg, logmsg_len);
9271 close(fd);
9273 err = get_editor(&editor);
9274 if (err)
9275 goto done;
9277 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9278 logmsg_len, 0);
9279 if (err) {
9280 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9281 goto done;
9282 err = NULL;
9283 hle->logmsg = strdup(new_msg);
9284 if (hle->logmsg == NULL)
9285 err = got_error_from_errno("strdup");
9287 done:
9288 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9289 err = got_error_from_errno2("unlink", logmsg_path);
9290 free(logmsg_path);
9291 free(logmsg);
9292 free(orig_logmsg);
9293 free(editor);
9294 if (commit)
9295 got_object_commit_close(commit);
9296 return err;
9299 static const struct got_error *
9300 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9301 FILE *f, struct got_repository *repo)
9303 const struct got_error *err = NULL;
9304 char *line = NULL, *p, *end;
9305 size_t i, size;
9306 ssize_t len;
9307 int lineno = 0;
9308 const struct got_histedit_cmd *cmd;
9309 struct got_object_id *commit_id = NULL;
9310 struct got_histedit_list_entry *hle = NULL;
9312 for (;;) {
9313 len = getline(&line, &size, f);
9314 if (len == -1) {
9315 const struct got_error *getline_err;
9316 if (feof(f))
9317 break;
9318 getline_err = got_error_from_errno("getline");
9319 err = got_ferror(f, getline_err->code);
9320 break;
9322 lineno++;
9323 p = line;
9324 while (isspace((unsigned char)p[0]))
9325 p++;
9326 if (p[0] == '#' || p[0] == '\0') {
9327 free(line);
9328 line = NULL;
9329 continue;
9331 cmd = NULL;
9332 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9333 cmd = &got_histedit_cmds[i];
9334 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9335 isspace((unsigned char)p[strlen(cmd->name)])) {
9336 p += strlen(cmd->name);
9337 break;
9339 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9340 p++;
9341 break;
9344 if (i == nitems(got_histedit_cmds)) {
9345 err = histedit_syntax_error(lineno);
9346 break;
9348 while (isspace((unsigned char)p[0]))
9349 p++;
9350 if (cmd->code == GOT_HISTEDIT_MESG) {
9351 if (hle == NULL || hle->logmsg != NULL) {
9352 err = got_error(GOT_ERR_HISTEDIT_CMD);
9353 break;
9355 if (p[0] == '\0') {
9356 err = histedit_edit_logmsg(hle, repo);
9357 if (err)
9358 break;
9359 } else {
9360 hle->logmsg = strdup(p);
9361 if (hle->logmsg == NULL) {
9362 err = got_error_from_errno("strdup");
9363 break;
9366 free(line);
9367 line = NULL;
9368 continue;
9369 } else {
9370 end = p;
9371 while (end[0] && !isspace((unsigned char)end[0]))
9372 end++;
9373 *end = '\0';
9375 err = got_object_resolve_id_str(&commit_id, repo, p);
9376 if (err) {
9377 /* override error code */
9378 err = histedit_syntax_error(lineno);
9379 break;
9382 hle = malloc(sizeof(*hle));
9383 if (hle == NULL) {
9384 err = got_error_from_errno("malloc");
9385 break;
9387 hle->cmd = cmd;
9388 hle->commit_id = commit_id;
9389 hle->logmsg = NULL;
9390 commit_id = NULL;
9391 free(line);
9392 line = NULL;
9393 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9396 free(line);
9397 free(commit_id);
9398 return err;
9401 static const struct got_error *
9402 histedit_check_script(struct got_histedit_list *histedit_cmds,
9403 struct got_object_id_queue *commits, struct got_repository *repo)
9405 const struct got_error *err = NULL;
9406 struct got_object_qid *qid;
9407 struct got_histedit_list_entry *hle;
9408 static char msg[92];
9409 char *id_str;
9411 if (TAILQ_EMPTY(histedit_cmds))
9412 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9413 "histedit script contains no commands");
9414 if (STAILQ_EMPTY(commits))
9415 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9417 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9418 struct got_histedit_list_entry *hle2;
9419 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9420 if (hle == hle2)
9421 continue;
9422 if (got_object_id_cmp(hle->commit_id,
9423 hle2->commit_id) != 0)
9424 continue;
9425 err = got_object_id_str(&id_str, hle->commit_id);
9426 if (err)
9427 return err;
9428 snprintf(msg, sizeof(msg), "commit %s is listed "
9429 "more than once in histedit script", id_str);
9430 free(id_str);
9431 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9435 STAILQ_FOREACH(qid, commits, entry) {
9436 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9437 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9438 break;
9440 if (hle == NULL) {
9441 err = got_object_id_str(&id_str, qid->id);
9442 if (err)
9443 return err;
9444 snprintf(msg, sizeof(msg),
9445 "commit %s missing from histedit script", id_str);
9446 free(id_str);
9447 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9451 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9452 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9453 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9454 "last commit in histedit script cannot be folded");
9456 return NULL;
9459 static const struct got_error *
9460 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9461 const char *path, struct got_object_id_queue *commits,
9462 struct got_repository *repo)
9464 const struct got_error *err = NULL;
9465 char *editor;
9466 FILE *f = NULL;
9468 err = get_editor(&editor);
9469 if (err)
9470 return err;
9472 if (spawn_editor(editor, path) == -1) {
9473 err = got_error_from_errno("failed spawning editor");
9474 goto done;
9477 f = fopen(path, "r");
9478 if (f == NULL) {
9479 err = got_error_from_errno("fopen");
9480 goto done;
9482 err = histedit_parse_list(histedit_cmds, f, repo);
9483 if (err)
9484 goto done;
9486 err = histedit_check_script(histedit_cmds, commits, repo);
9487 done:
9488 if (f && fclose(f) == EOF && err == NULL)
9489 err = got_error_from_errno("fclose");
9490 free(editor);
9491 return err;
9494 static const struct got_error *
9495 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9496 struct got_object_id_queue *, const char *, const char *,
9497 struct got_repository *);
9499 static const struct got_error *
9500 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9501 struct got_object_id_queue *commits, const char *branch_name,
9502 int edit_logmsg_only, int fold_only, struct got_repository *repo)
9504 const struct got_error *err;
9505 FILE *f = NULL;
9506 char *path = NULL;
9508 err = got_opentemp_named(&path, &f, "got-histedit");
9509 if (err)
9510 return err;
9512 err = write_cmd_list(f, branch_name, commits);
9513 if (err)
9514 goto done;
9516 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9517 fold_only, repo);
9518 if (err)
9519 goto done;
9521 if (edit_logmsg_only || fold_only) {
9522 rewind(f);
9523 err = histedit_parse_list(histedit_cmds, f, repo);
9524 } else {
9525 if (fclose(f) == EOF) {
9526 err = got_error_from_errno("fclose");
9527 goto done;
9529 f = NULL;
9530 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9531 if (err) {
9532 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9533 err->code != GOT_ERR_HISTEDIT_CMD)
9534 goto done;
9535 err = histedit_edit_list_retry(histedit_cmds, err,
9536 commits, path, branch_name, repo);
9539 done:
9540 if (f && fclose(f) == EOF && err == NULL)
9541 err = got_error_from_errno("fclose");
9542 if (path && unlink(path) != 0 && err == NULL)
9543 err = got_error_from_errno2("unlink", path);
9544 free(path);
9545 return err;
9548 static const struct got_error *
9549 histedit_save_list(struct got_histedit_list *histedit_cmds,
9550 struct got_worktree *worktree, struct got_repository *repo)
9552 const struct got_error *err = NULL;
9553 char *path = NULL;
9554 FILE *f = NULL;
9555 struct got_histedit_list_entry *hle;
9556 struct got_commit_object *commit = NULL;
9558 err = got_worktree_get_histedit_script_path(&path, worktree);
9559 if (err)
9560 return err;
9562 f = fopen(path, "w");
9563 if (f == NULL) {
9564 err = got_error_from_errno2("fopen", path);
9565 goto done;
9567 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9568 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9569 repo);
9570 if (err)
9571 break;
9573 if (hle->logmsg) {
9574 int n = fprintf(f, "%c %s\n",
9575 GOT_HISTEDIT_MESG, hle->logmsg);
9576 if (n < 0) {
9577 err = got_ferror(f, GOT_ERR_IO);
9578 break;
9582 done:
9583 if (f && fclose(f) == EOF && err == NULL)
9584 err = got_error_from_errno("fclose");
9585 free(path);
9586 if (commit)
9587 got_object_commit_close(commit);
9588 return err;
9591 void
9592 histedit_free_list(struct got_histedit_list *histedit_cmds)
9594 struct got_histedit_list_entry *hle;
9596 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9597 TAILQ_REMOVE(histedit_cmds, hle, entry);
9598 free(hle);
9602 static const struct got_error *
9603 histedit_load_list(struct got_histedit_list *histedit_cmds,
9604 const char *path, struct got_repository *repo)
9606 const struct got_error *err = NULL;
9607 FILE *f = NULL;
9609 f = fopen(path, "r");
9610 if (f == NULL) {
9611 err = got_error_from_errno2("fopen", path);
9612 goto done;
9615 err = histedit_parse_list(histedit_cmds, f, repo);
9616 done:
9617 if (f && fclose(f) == EOF && err == NULL)
9618 err = got_error_from_errno("fclose");
9619 return err;
9622 static const struct got_error *
9623 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9624 const struct got_error *edit_err, struct got_object_id_queue *commits,
9625 const char *path, const char *branch_name, struct got_repository *repo)
9627 const struct got_error *err = NULL, *prev_err = edit_err;
9628 int resp = ' ';
9630 while (resp != 'c' && resp != 'r' && resp != 'a') {
9631 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9632 "or (a)bort: ", getprogname(), prev_err->msg);
9633 resp = getchar();
9634 if (resp == '\n')
9635 resp = getchar();
9636 if (resp == 'c') {
9637 histedit_free_list(histedit_cmds);
9638 err = histedit_run_editor(histedit_cmds, path, commits,
9639 repo);
9640 if (err) {
9641 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9642 err->code != GOT_ERR_HISTEDIT_CMD)
9643 break;
9644 prev_err = err;
9645 resp = ' ';
9646 continue;
9648 break;
9649 } else if (resp == 'r') {
9650 histedit_free_list(histedit_cmds);
9651 err = histedit_edit_script(histedit_cmds,
9652 commits, branch_name, 0, 0, repo);
9653 if (err) {
9654 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9655 err->code != GOT_ERR_HISTEDIT_CMD)
9656 break;
9657 prev_err = err;
9658 resp = ' ';
9659 continue;
9661 break;
9662 } else if (resp == 'a') {
9663 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9664 break;
9665 } else
9666 printf("invalid response '%c'\n", resp);
9669 return err;
9672 static const struct got_error *
9673 histedit_complete(struct got_worktree *worktree,
9674 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9675 struct got_reference *branch, struct got_repository *repo)
9677 printf("Switching work tree to %s\n",
9678 got_ref_get_symref_target(branch));
9679 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9680 branch, repo);
9683 static const struct got_error *
9684 show_histedit_progress(struct got_commit_object *commit,
9685 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9687 const struct got_error *err;
9688 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9690 err = got_object_id_str(&old_id_str, hle->commit_id);
9691 if (err)
9692 goto done;
9694 if (new_id) {
9695 err = got_object_id_str(&new_id_str, new_id);
9696 if (err)
9697 goto done;
9700 old_id_str[12] = '\0';
9701 if (new_id_str)
9702 new_id_str[12] = '\0';
9704 if (hle->logmsg) {
9705 logmsg = strdup(hle->logmsg);
9706 if (logmsg == NULL) {
9707 err = got_error_from_errno("strdup");
9708 goto done;
9710 trim_logmsg(logmsg, 42);
9711 } else {
9712 err = get_short_logmsg(&logmsg, 42, commit);
9713 if (err)
9714 goto done;
9717 switch (hle->cmd->code) {
9718 case GOT_HISTEDIT_PICK:
9719 case GOT_HISTEDIT_EDIT:
9720 printf("%s -> %s: %s\n", old_id_str,
9721 new_id_str ? new_id_str : "no-op change", logmsg);
9722 break;
9723 case GOT_HISTEDIT_DROP:
9724 case GOT_HISTEDIT_FOLD:
9725 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
9726 logmsg);
9727 break;
9728 default:
9729 break;
9731 done:
9732 free(old_id_str);
9733 free(new_id_str);
9734 return err;
9737 static const struct got_error *
9738 histedit_commit(struct got_pathlist_head *merged_paths,
9739 struct got_worktree *worktree, struct got_fileindex *fileindex,
9740 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
9741 struct got_repository *repo)
9743 const struct got_error *err;
9744 struct got_commit_object *commit;
9745 struct got_object_id *new_commit_id;
9747 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
9748 && hle->logmsg == NULL) {
9749 err = histedit_edit_logmsg(hle, repo);
9750 if (err)
9751 return err;
9754 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9755 if (err)
9756 return err;
9758 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
9759 worktree, fileindex, tmp_branch, commit, hle->commit_id,
9760 hle->logmsg, repo);
9761 if (err) {
9762 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
9763 goto done;
9764 err = show_histedit_progress(commit, hle, NULL);
9765 } else {
9766 err = show_histedit_progress(commit, hle, new_commit_id);
9767 free(new_commit_id);
9769 done:
9770 got_object_commit_close(commit);
9771 return err;
9774 static const struct got_error *
9775 histedit_skip_commit(struct got_histedit_list_entry *hle,
9776 struct got_worktree *worktree, struct got_repository *repo)
9778 const struct got_error *error;
9779 struct got_commit_object *commit;
9781 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
9782 repo);
9783 if (error)
9784 return error;
9786 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
9787 if (error)
9788 return error;
9790 error = show_histedit_progress(commit, hle, NULL);
9791 got_object_commit_close(commit);
9792 return error;
9795 static const struct got_error *
9796 check_local_changes(void *arg, unsigned char status,
9797 unsigned char staged_status, const char *path,
9798 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
9799 struct got_object_id *commit_id, int dirfd, const char *de_name)
9801 int *have_local_changes = arg;
9803 switch (status) {
9804 case GOT_STATUS_ADD:
9805 case GOT_STATUS_DELETE:
9806 case GOT_STATUS_MODIFY:
9807 case GOT_STATUS_CONFLICT:
9808 *have_local_changes = 1;
9809 return got_error(GOT_ERR_CANCELLED);
9810 default:
9811 break;
9814 switch (staged_status) {
9815 case GOT_STATUS_ADD:
9816 case GOT_STATUS_DELETE:
9817 case GOT_STATUS_MODIFY:
9818 *have_local_changes = 1;
9819 return got_error(GOT_ERR_CANCELLED);
9820 default:
9821 break;
9824 return NULL;
9827 static const struct got_error *
9828 cmd_histedit(int argc, char *argv[])
9830 const struct got_error *error = NULL;
9831 struct got_worktree *worktree = NULL;
9832 struct got_fileindex *fileindex = NULL;
9833 struct got_repository *repo = NULL;
9834 char *cwd = NULL;
9835 struct got_reference *branch = NULL;
9836 struct got_reference *tmp_branch = NULL;
9837 struct got_object_id *resume_commit_id = NULL;
9838 struct got_object_id *base_commit_id = NULL;
9839 struct got_object_id *head_commit_id = NULL;
9840 struct got_commit_object *commit = NULL;
9841 int ch, rebase_in_progress = 0;
9842 struct got_update_progress_arg upa;
9843 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
9844 int edit_logmsg_only = 0, fold_only = 0;
9845 int list_backups = 0, delete_backups = 0;
9846 const char *edit_script_path = NULL;
9847 unsigned char rebase_status = GOT_STATUS_NO_CHANGE;
9848 struct got_object_id_queue commits;
9849 struct got_pathlist_head merged_paths;
9850 const struct got_object_id_queue *parent_ids;
9851 struct got_object_qid *pid;
9852 struct got_histedit_list histedit_cmds;
9853 struct got_histedit_list_entry *hle;
9855 STAILQ_INIT(&commits);
9856 TAILQ_INIT(&histedit_cmds);
9857 TAILQ_INIT(&merged_paths);
9858 memset(&upa, 0, sizeof(upa));
9860 while ((ch = getopt(argc, argv, "acfF:mlX")) != -1) {
9861 switch (ch) {
9862 case 'a':
9863 abort_edit = 1;
9864 break;
9865 case 'c':
9866 continue_edit = 1;
9867 break;
9868 case 'f':
9869 fold_only = 1;
9870 break;
9871 case 'F':
9872 edit_script_path = optarg;
9873 break;
9874 case 'm':
9875 edit_logmsg_only = 1;
9876 break;
9877 case 'l':
9878 list_backups = 1;
9879 break;
9880 case 'X':
9881 delete_backups = 1;
9882 break;
9883 default:
9884 usage_histedit();
9885 /* NOTREACHED */
9889 argc -= optind;
9890 argv += optind;
9892 #ifndef PROFILE
9893 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9894 "unveil", NULL) == -1)
9895 err(1, "pledge");
9896 #endif
9897 if (abort_edit && continue_edit)
9898 option_conflict('a', 'c');
9899 if (edit_script_path && edit_logmsg_only)
9900 option_conflict('F', 'm');
9901 if (abort_edit && edit_logmsg_only)
9902 option_conflict('a', 'm');
9903 if (continue_edit && edit_logmsg_only)
9904 option_conflict('c', 'm');
9905 if (abort_edit && fold_only)
9906 option_conflict('a', 'f');
9907 if (continue_edit && fold_only)
9908 option_conflict('c', 'f');
9909 if (fold_only && edit_logmsg_only)
9910 option_conflict('f', 'm');
9911 if (edit_script_path && fold_only)
9912 option_conflict('F', 'f');
9913 if (list_backups) {
9914 if (abort_edit)
9915 option_conflict('l', 'a');
9916 if (continue_edit)
9917 option_conflict('l', 'c');
9918 if (edit_script_path)
9919 option_conflict('l', 'F');
9920 if (edit_logmsg_only)
9921 option_conflict('l', 'm');
9922 if (fold_only)
9923 option_conflict('l', 'f');
9924 if (delete_backups)
9925 option_conflict('l', 'X');
9926 if (argc != 0 && argc != 1)
9927 usage_histedit();
9928 } else if (delete_backups) {
9929 if (abort_edit)
9930 option_conflict('X', 'a');
9931 if (continue_edit)
9932 option_conflict('X', 'c');
9933 if (edit_script_path)
9934 option_conflict('X', 'F');
9935 if (edit_logmsg_only)
9936 option_conflict('X', 'm');
9937 if (fold_only)
9938 option_conflict('X', 'f');
9939 if (list_backups)
9940 option_conflict('X', 'l');
9941 if (argc != 0 && argc != 1)
9942 usage_histedit();
9943 } else if (argc != 0)
9944 usage_histedit();
9947 * This command cannot apply unveil(2) in all cases because the
9948 * user may choose to run an editor to edit the histedit script
9949 * and to edit individual commit log messages.
9950 * unveil(2) traverses exec(2); if an editor is used we have to
9951 * apply unveil after edit script and log messages have been written.
9952 * XXX TODO: Make use of unveil(2) where possible.
9955 cwd = getcwd(NULL, 0);
9956 if (cwd == NULL) {
9957 error = got_error_from_errno("getcwd");
9958 goto done;
9960 error = got_worktree_open(&worktree, cwd);
9961 if (error) {
9962 if (list_backups || delete_backups) {
9963 if (error->code != GOT_ERR_NOT_WORKTREE)
9964 goto done;
9965 } else {
9966 if (error->code == GOT_ERR_NOT_WORKTREE)
9967 error = wrap_not_worktree_error(error,
9968 "histedit", cwd);
9969 goto done;
9973 if (list_backups || delete_backups) {
9974 error = got_repo_open(&repo,
9975 worktree ? got_worktree_get_repo_path(worktree) : cwd,
9976 NULL);
9977 if (error != NULL)
9978 goto done;
9979 error = apply_unveil(got_repo_get_path(repo), 0,
9980 worktree ? got_worktree_get_root_path(worktree) : NULL);
9981 if (error)
9982 goto done;
9983 error = process_backup_refs(
9984 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
9985 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9986 goto done; /* nothing else to do */
9989 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9990 NULL);
9991 if (error != NULL)
9992 goto done;
9994 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9995 if (error)
9996 goto done;
9997 if (rebase_in_progress) {
9998 error = got_error(GOT_ERR_REBASING);
9999 goto done;
10002 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10003 if (error)
10004 goto done;
10006 if (edit_in_progress && edit_logmsg_only) {
10007 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10008 "histedit operation is in progress in this "
10009 "work tree and must be continued or aborted "
10010 "before the -m option can be used");
10011 goto done;
10013 if (edit_in_progress && fold_only) {
10014 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10015 "histedit operation is in progress in this "
10016 "work tree and must be continued or aborted "
10017 "before the -f option can be used");
10018 goto done;
10021 if (edit_in_progress && abort_edit) {
10022 error = got_worktree_histedit_continue(&resume_commit_id,
10023 &tmp_branch, &branch, &base_commit_id, &fileindex,
10024 worktree, repo);
10025 if (error)
10026 goto done;
10027 printf("Switching work tree to %s\n",
10028 got_ref_get_symref_target(branch));
10029 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10030 branch, base_commit_id, update_progress, &upa);
10031 if (error)
10032 goto done;
10033 printf("Histedit of %s aborted\n",
10034 got_ref_get_symref_target(branch));
10035 print_update_progress_stats(&upa);
10036 goto done; /* nothing else to do */
10037 } else if (abort_edit) {
10038 error = got_error(GOT_ERR_NOT_HISTEDIT);
10039 goto done;
10042 if (continue_edit) {
10043 char *path;
10045 if (!edit_in_progress) {
10046 error = got_error(GOT_ERR_NOT_HISTEDIT);
10047 goto done;
10050 error = got_worktree_get_histedit_script_path(&path, worktree);
10051 if (error)
10052 goto done;
10054 error = histedit_load_list(&histedit_cmds, path, repo);
10055 free(path);
10056 if (error)
10057 goto done;
10059 error = got_worktree_histedit_continue(&resume_commit_id,
10060 &tmp_branch, &branch, &base_commit_id, &fileindex,
10061 worktree, repo);
10062 if (error)
10063 goto done;
10065 error = got_ref_resolve(&head_commit_id, repo, branch);
10066 if (error)
10067 goto done;
10069 error = got_object_open_as_commit(&commit, repo,
10070 head_commit_id);
10071 if (error)
10072 goto done;
10073 parent_ids = got_object_commit_get_parent_ids(commit);
10074 pid = STAILQ_FIRST(parent_ids);
10075 if (pid == NULL) {
10076 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10077 goto done;
10079 error = collect_commits(&commits, head_commit_id, pid->id,
10080 base_commit_id, got_worktree_get_path_prefix(worktree),
10081 GOT_ERR_HISTEDIT_PATH, repo);
10082 got_object_commit_close(commit);
10083 commit = NULL;
10084 if (error)
10085 goto done;
10086 } else {
10087 if (edit_in_progress) {
10088 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10089 goto done;
10092 error = got_ref_open(&branch, repo,
10093 got_worktree_get_head_ref_name(worktree), 0);
10094 if (error != NULL)
10095 goto done;
10097 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10098 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10099 "will not edit commit history of a branch outside "
10100 "the \"refs/heads/\" reference namespace");
10101 goto done;
10104 error = got_ref_resolve(&head_commit_id, repo, branch);
10105 got_ref_close(branch);
10106 branch = NULL;
10107 if (error)
10108 goto done;
10110 error = got_object_open_as_commit(&commit, repo,
10111 head_commit_id);
10112 if (error)
10113 goto done;
10114 parent_ids = got_object_commit_get_parent_ids(commit);
10115 pid = STAILQ_FIRST(parent_ids);
10116 if (pid == NULL) {
10117 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10118 goto done;
10120 error = collect_commits(&commits, head_commit_id, pid->id,
10121 got_worktree_get_base_commit_id(worktree),
10122 got_worktree_get_path_prefix(worktree),
10123 GOT_ERR_HISTEDIT_PATH, repo);
10124 got_object_commit_close(commit);
10125 commit = NULL;
10126 if (error)
10127 goto done;
10129 if (STAILQ_EMPTY(&commits)) {
10130 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10131 goto done;
10134 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10135 &base_commit_id, &fileindex, worktree, repo);
10136 if (error)
10137 goto done;
10139 if (edit_script_path) {
10140 error = histedit_load_list(&histedit_cmds,
10141 edit_script_path, repo);
10142 if (error) {
10143 got_worktree_histedit_abort(worktree, fileindex,
10144 repo, branch, base_commit_id,
10145 update_progress, &upa);
10146 print_update_progress_stats(&upa);
10147 goto done;
10149 } else {
10150 const char *branch_name;
10151 branch_name = got_ref_get_symref_target(branch);
10152 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10153 branch_name += 11;
10154 error = histedit_edit_script(&histedit_cmds, &commits,
10155 branch_name, edit_logmsg_only, fold_only, repo);
10156 if (error) {
10157 got_worktree_histedit_abort(worktree, fileindex,
10158 repo, branch, base_commit_id,
10159 update_progress, &upa);
10160 print_update_progress_stats(&upa);
10161 goto done;
10166 error = histedit_save_list(&histedit_cmds, worktree,
10167 repo);
10168 if (error) {
10169 got_worktree_histedit_abort(worktree, fileindex,
10170 repo, branch, base_commit_id,
10171 update_progress, &upa);
10172 print_update_progress_stats(&upa);
10173 goto done;
10178 error = histedit_check_script(&histedit_cmds, &commits, repo);
10179 if (error)
10180 goto done;
10182 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10183 if (resume_commit_id) {
10184 if (got_object_id_cmp(hle->commit_id,
10185 resume_commit_id) != 0)
10186 continue;
10188 resume_commit_id = NULL;
10189 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10190 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10191 error = histedit_skip_commit(hle, worktree,
10192 repo);
10193 if (error)
10194 goto done;
10195 } else {
10196 struct got_pathlist_head paths;
10197 int have_changes = 0;
10199 TAILQ_INIT(&paths);
10200 error = got_pathlist_append(&paths, "", NULL);
10201 if (error)
10202 goto done;
10203 error = got_worktree_status(worktree, &paths,
10204 repo, 0, check_local_changes, &have_changes,
10205 check_cancelled, NULL);
10206 got_pathlist_free(&paths);
10207 if (error) {
10208 if (error->code != GOT_ERR_CANCELLED)
10209 goto done;
10210 if (sigint_received || sigpipe_received)
10211 goto done;
10213 if (have_changes) {
10214 error = histedit_commit(NULL, worktree,
10215 fileindex, tmp_branch, hle, repo);
10216 if (error)
10217 goto done;
10218 } else {
10219 error = got_object_open_as_commit(
10220 &commit, repo, hle->commit_id);
10221 if (error)
10222 goto done;
10223 error = show_histedit_progress(commit,
10224 hle, NULL);
10225 got_object_commit_close(commit);
10226 commit = NULL;
10227 if (error)
10228 goto done;
10231 continue;
10234 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10235 error = histedit_skip_commit(hle, worktree, repo);
10236 if (error)
10237 goto done;
10238 continue;
10241 error = got_object_open_as_commit(&commit, repo,
10242 hle->commit_id);
10243 if (error)
10244 goto done;
10245 parent_ids = got_object_commit_get_parent_ids(commit);
10246 pid = STAILQ_FIRST(parent_ids);
10248 error = got_worktree_histedit_merge_files(&merged_paths,
10249 worktree, fileindex, pid->id, hle->commit_id, repo,
10250 update_progress, &upa, check_cancelled, NULL);
10251 if (error)
10252 goto done;
10253 got_object_commit_close(commit);
10254 commit = NULL;
10256 print_update_progress_stats(&upa);
10257 if (upa.conflicts > 0)
10258 rebase_status = GOT_STATUS_CONFLICT;
10260 if (rebase_status == GOT_STATUS_CONFLICT) {
10261 error = show_rebase_merge_conflict(hle->commit_id,
10262 repo);
10263 if (error)
10264 goto done;
10265 got_worktree_rebase_pathlist_free(&merged_paths);
10266 break;
10269 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10270 char *id_str;
10271 error = got_object_id_str(&id_str, hle->commit_id);
10272 if (error)
10273 goto done;
10274 printf("Stopping histedit for amending commit %s\n",
10275 id_str);
10276 free(id_str);
10277 got_worktree_rebase_pathlist_free(&merged_paths);
10278 error = got_worktree_histedit_postpone(worktree,
10279 fileindex);
10280 goto done;
10283 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10284 error = histedit_skip_commit(hle, worktree, repo);
10285 if (error)
10286 goto done;
10287 continue;
10290 error = histedit_commit(&merged_paths, worktree, fileindex,
10291 tmp_branch, hle, repo);
10292 got_worktree_rebase_pathlist_free(&merged_paths);
10293 if (error)
10294 goto done;
10297 if (rebase_status == GOT_STATUS_CONFLICT) {
10298 error = got_worktree_histedit_postpone(worktree, fileindex);
10299 if (error)
10300 goto done;
10301 error = got_error_msg(GOT_ERR_CONFLICTS,
10302 "conflicts must be resolved before histedit can continue");
10303 } else
10304 error = histedit_complete(worktree, fileindex, tmp_branch,
10305 branch, repo);
10306 done:
10307 got_object_id_queue_free(&commits);
10308 histedit_free_list(&histedit_cmds);
10309 free(head_commit_id);
10310 free(base_commit_id);
10311 free(resume_commit_id);
10312 if (commit)
10313 got_object_commit_close(commit);
10314 if (branch)
10315 got_ref_close(branch);
10316 if (tmp_branch)
10317 got_ref_close(tmp_branch);
10318 if (worktree)
10319 got_worktree_close(worktree);
10320 if (repo) {
10321 const struct got_error *close_err = got_repo_close(repo);
10322 if (error == NULL)
10323 error = close_err;
10325 return error;
10328 __dead static void
10329 usage_integrate(void)
10331 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10332 exit(1);
10335 static const struct got_error *
10336 cmd_integrate(int argc, char *argv[])
10338 const struct got_error *error = NULL;
10339 struct got_repository *repo = NULL;
10340 struct got_worktree *worktree = NULL;
10341 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10342 const char *branch_arg = NULL;
10343 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10344 struct got_fileindex *fileindex = NULL;
10345 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10346 int ch;
10347 struct got_update_progress_arg upa;
10349 while ((ch = getopt(argc, argv, "")) != -1) {
10350 switch (ch) {
10351 default:
10352 usage_integrate();
10353 /* NOTREACHED */
10357 argc -= optind;
10358 argv += optind;
10360 if (argc != 1)
10361 usage_integrate();
10362 branch_arg = argv[0];
10363 #ifndef PROFILE
10364 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10365 "unveil", NULL) == -1)
10366 err(1, "pledge");
10367 #endif
10368 cwd = getcwd(NULL, 0);
10369 if (cwd == NULL) {
10370 error = got_error_from_errno("getcwd");
10371 goto done;
10374 error = got_worktree_open(&worktree, cwd);
10375 if (error) {
10376 if (error->code == GOT_ERR_NOT_WORKTREE)
10377 error = wrap_not_worktree_error(error, "integrate",
10378 cwd);
10379 goto done;
10382 error = check_rebase_or_histedit_in_progress(worktree);
10383 if (error)
10384 goto done;
10386 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10387 NULL);
10388 if (error != NULL)
10389 goto done;
10391 error = apply_unveil(got_repo_get_path(repo), 0,
10392 got_worktree_get_root_path(worktree));
10393 if (error)
10394 goto done;
10396 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10397 error = got_error_from_errno("asprintf");
10398 goto done;
10401 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10402 &base_branch_ref, worktree, refname, repo);
10403 if (error)
10404 goto done;
10406 refname = strdup(got_ref_get_name(branch_ref));
10407 if (refname == NULL) {
10408 error = got_error_from_errno("strdup");
10409 got_worktree_integrate_abort(worktree, fileindex, repo,
10410 branch_ref, base_branch_ref);
10411 goto done;
10413 base_refname = strdup(got_ref_get_name(base_branch_ref));
10414 if (base_refname == NULL) {
10415 error = got_error_from_errno("strdup");
10416 got_worktree_integrate_abort(worktree, fileindex, repo,
10417 branch_ref, base_branch_ref);
10418 goto done;
10421 error = got_ref_resolve(&commit_id, repo, branch_ref);
10422 if (error)
10423 goto done;
10425 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10426 if (error)
10427 goto done;
10429 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10430 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10431 "specified branch has already been integrated");
10432 got_worktree_integrate_abort(worktree, fileindex, repo,
10433 branch_ref, base_branch_ref);
10434 goto done;
10437 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10438 if (error) {
10439 if (error->code == GOT_ERR_ANCESTRY)
10440 error = got_error(GOT_ERR_REBASE_REQUIRED);
10441 got_worktree_integrate_abort(worktree, fileindex, repo,
10442 branch_ref, base_branch_ref);
10443 goto done;
10446 memset(&upa, 0, sizeof(upa));
10447 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10448 branch_ref, base_branch_ref, update_progress, &upa,
10449 check_cancelled, NULL);
10450 if (error)
10451 goto done;
10453 printf("Integrated %s into %s\n", refname, base_refname);
10454 print_update_progress_stats(&upa);
10455 done:
10456 if (repo) {
10457 const struct got_error *close_err = got_repo_close(repo);
10458 if (error == NULL)
10459 error = close_err;
10461 if (worktree)
10462 got_worktree_close(worktree);
10463 free(cwd);
10464 free(base_commit_id);
10465 free(commit_id);
10466 free(refname);
10467 free(base_refname);
10468 return error;
10471 __dead static void
10472 usage_stage(void)
10474 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
10475 "[-S] [file-path ...]\n",
10476 getprogname());
10477 exit(1);
10480 static const struct got_error *
10481 print_stage(void *arg, unsigned char status, unsigned char staged_status,
10482 const char *path, struct got_object_id *blob_id,
10483 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
10484 int dirfd, const char *de_name)
10486 const struct got_error *err = NULL;
10487 char *id_str = NULL;
10489 if (staged_status != GOT_STATUS_ADD &&
10490 staged_status != GOT_STATUS_MODIFY &&
10491 staged_status != GOT_STATUS_DELETE)
10492 return NULL;
10494 if (staged_status == GOT_STATUS_ADD ||
10495 staged_status == GOT_STATUS_MODIFY)
10496 err = got_object_id_str(&id_str, staged_blob_id);
10497 else
10498 err = got_object_id_str(&id_str, blob_id);
10499 if (err)
10500 return err;
10502 printf("%s %c %s\n", id_str, staged_status, path);
10503 free(id_str);
10504 return NULL;
10507 static const struct got_error *
10508 cmd_stage(int argc, char *argv[])
10510 const struct got_error *error = NULL;
10511 struct got_repository *repo = NULL;
10512 struct got_worktree *worktree = NULL;
10513 char *cwd = NULL;
10514 struct got_pathlist_head paths;
10515 struct got_pathlist_entry *pe;
10516 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
10517 FILE *patch_script_file = NULL;
10518 const char *patch_script_path = NULL;
10519 struct choose_patch_arg cpa;
10521 TAILQ_INIT(&paths);
10523 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
10524 switch (ch) {
10525 case 'l':
10526 list_stage = 1;
10527 break;
10528 case 'p':
10529 pflag = 1;
10530 break;
10531 case 'F':
10532 patch_script_path = optarg;
10533 break;
10534 case 'S':
10535 allow_bad_symlinks = 1;
10536 break;
10537 default:
10538 usage_stage();
10539 /* NOTREACHED */
10543 argc -= optind;
10544 argv += optind;
10546 #ifndef PROFILE
10547 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10548 "unveil", NULL) == -1)
10549 err(1, "pledge");
10550 #endif
10551 if (list_stage && (pflag || patch_script_path))
10552 errx(1, "-l option cannot be used with other options");
10553 if (patch_script_path && !pflag)
10554 errx(1, "-F option can only be used together with -p option");
10556 cwd = getcwd(NULL, 0);
10557 if (cwd == NULL) {
10558 error = got_error_from_errno("getcwd");
10559 goto done;
10562 error = got_worktree_open(&worktree, cwd);
10563 if (error) {
10564 if (error->code == GOT_ERR_NOT_WORKTREE)
10565 error = wrap_not_worktree_error(error, "stage", cwd);
10566 goto done;
10569 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10570 NULL);
10571 if (error != NULL)
10572 goto done;
10574 if (patch_script_path) {
10575 patch_script_file = fopen(patch_script_path, "r");
10576 if (patch_script_file == NULL) {
10577 error = got_error_from_errno2("fopen",
10578 patch_script_path);
10579 goto done;
10582 error = apply_unveil(got_repo_get_path(repo), 0,
10583 got_worktree_get_root_path(worktree));
10584 if (error)
10585 goto done;
10587 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10588 if (error)
10589 goto done;
10591 if (list_stage)
10592 error = got_worktree_status(worktree, &paths, repo, 0,
10593 print_stage, NULL, check_cancelled, NULL);
10594 else {
10595 cpa.patch_script_file = patch_script_file;
10596 cpa.action = "stage";
10597 error = got_worktree_stage(worktree, &paths,
10598 pflag ? NULL : print_status, NULL,
10599 pflag ? choose_patch : NULL, &cpa,
10600 allow_bad_symlinks, repo);
10602 done:
10603 if (patch_script_file && fclose(patch_script_file) == EOF &&
10604 error == NULL)
10605 error = got_error_from_errno2("fclose", patch_script_path);
10606 if (repo) {
10607 const struct got_error *close_err = got_repo_close(repo);
10608 if (error == NULL)
10609 error = close_err;
10611 if (worktree)
10612 got_worktree_close(worktree);
10613 TAILQ_FOREACH(pe, &paths, entry)
10614 free((char *)pe->path);
10615 got_pathlist_free(&paths);
10616 free(cwd);
10617 return error;
10620 __dead static void
10621 usage_unstage(void)
10623 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
10624 "[file-path ...]\n",
10625 getprogname());
10626 exit(1);
10630 static const struct got_error *
10631 cmd_unstage(int argc, char *argv[])
10633 const struct got_error *error = NULL;
10634 struct got_repository *repo = NULL;
10635 struct got_worktree *worktree = NULL;
10636 char *cwd = NULL;
10637 struct got_pathlist_head paths;
10638 struct got_pathlist_entry *pe;
10639 int ch, pflag = 0;
10640 struct got_update_progress_arg upa;
10641 FILE *patch_script_file = NULL;
10642 const char *patch_script_path = NULL;
10643 struct choose_patch_arg cpa;
10645 TAILQ_INIT(&paths);
10647 while ((ch = getopt(argc, argv, "pF:")) != -1) {
10648 switch (ch) {
10649 case 'p':
10650 pflag = 1;
10651 break;
10652 case 'F':
10653 patch_script_path = optarg;
10654 break;
10655 default:
10656 usage_unstage();
10657 /* NOTREACHED */
10661 argc -= optind;
10662 argv += optind;
10664 #ifndef PROFILE
10665 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10666 "unveil", NULL) == -1)
10667 err(1, "pledge");
10668 #endif
10669 if (patch_script_path && !pflag)
10670 errx(1, "-F option can only be used together with -p option");
10672 cwd = getcwd(NULL, 0);
10673 if (cwd == NULL) {
10674 error = got_error_from_errno("getcwd");
10675 goto done;
10678 error = got_worktree_open(&worktree, cwd);
10679 if (error) {
10680 if (error->code == GOT_ERR_NOT_WORKTREE)
10681 error = wrap_not_worktree_error(error, "unstage", cwd);
10682 goto done;
10685 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10686 NULL);
10687 if (error != NULL)
10688 goto done;
10690 if (patch_script_path) {
10691 patch_script_file = fopen(patch_script_path, "r");
10692 if (patch_script_file == NULL) {
10693 error = got_error_from_errno2("fopen",
10694 patch_script_path);
10695 goto done;
10699 error = apply_unveil(got_repo_get_path(repo), 0,
10700 got_worktree_get_root_path(worktree));
10701 if (error)
10702 goto done;
10704 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
10705 if (error)
10706 goto done;
10708 cpa.patch_script_file = patch_script_file;
10709 cpa.action = "unstage";
10710 memset(&upa, 0, sizeof(upa));
10711 error = got_worktree_unstage(worktree, &paths, update_progress,
10712 &upa, pflag ? choose_patch : NULL, &cpa, repo);
10713 if (!error)
10714 print_update_progress_stats(&upa);
10715 done:
10716 if (patch_script_file && fclose(patch_script_file) == EOF &&
10717 error == NULL)
10718 error = got_error_from_errno2("fclose", patch_script_path);
10719 if (repo) {
10720 const struct got_error *close_err = got_repo_close(repo);
10721 if (error == NULL)
10722 error = close_err;
10724 if (worktree)
10725 got_worktree_close(worktree);
10726 TAILQ_FOREACH(pe, &paths, entry)
10727 free((char *)pe->path);
10728 got_pathlist_free(&paths);
10729 free(cwd);
10730 return error;
10733 __dead static void
10734 usage_cat(void)
10736 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
10737 "arg1 [arg2 ...]\n", getprogname());
10738 exit(1);
10741 static const struct got_error *
10742 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10744 const struct got_error *err;
10745 struct got_blob_object *blob;
10747 err = got_object_open_as_blob(&blob, repo, id, 8192);
10748 if (err)
10749 return err;
10751 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
10752 got_object_blob_close(blob);
10753 return err;
10756 static const struct got_error *
10757 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10759 const struct got_error *err;
10760 struct got_tree_object *tree;
10761 int nentries, i;
10763 err = got_object_open_as_tree(&tree, repo, id);
10764 if (err)
10765 return err;
10767 nentries = got_object_tree_get_nentries(tree);
10768 for (i = 0; i < nentries; i++) {
10769 struct got_tree_entry *te;
10770 char *id_str;
10771 if (sigint_received || sigpipe_received)
10772 break;
10773 te = got_object_tree_get_entry(tree, i);
10774 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
10775 if (err)
10776 break;
10777 fprintf(outfile, "%s %.7o %s\n", id_str,
10778 got_tree_entry_get_mode(te),
10779 got_tree_entry_get_name(te));
10780 free(id_str);
10783 got_object_tree_close(tree);
10784 return err;
10787 static const struct got_error *
10788 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10790 const struct got_error *err;
10791 struct got_commit_object *commit;
10792 const struct got_object_id_queue *parent_ids;
10793 struct got_object_qid *pid;
10794 char *id_str = NULL;
10795 const char *logmsg = NULL;
10797 err = got_object_open_as_commit(&commit, repo, id);
10798 if (err)
10799 return err;
10801 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
10802 if (err)
10803 goto done;
10805 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
10806 parent_ids = got_object_commit_get_parent_ids(commit);
10807 fprintf(outfile, "numparents %d\n",
10808 got_object_commit_get_nparents(commit));
10809 STAILQ_FOREACH(pid, parent_ids, entry) {
10810 char *pid_str;
10811 err = got_object_id_str(&pid_str, pid->id);
10812 if (err)
10813 goto done;
10814 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
10815 free(pid_str);
10817 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
10818 got_object_commit_get_author(commit),
10819 (long long)got_object_commit_get_author_time(commit));
10821 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
10822 got_object_commit_get_author(commit),
10823 (long long)got_object_commit_get_committer_time(commit));
10825 logmsg = got_object_commit_get_logmsg_raw(commit);
10826 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
10827 fprintf(outfile, "%s", logmsg);
10828 done:
10829 free(id_str);
10830 got_object_commit_close(commit);
10831 return err;
10834 static const struct got_error *
10835 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
10837 const struct got_error *err;
10838 struct got_tag_object *tag;
10839 char *id_str = NULL;
10840 const char *tagmsg = NULL;
10842 err = got_object_open_as_tag(&tag, repo, id);
10843 if (err)
10844 return err;
10846 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
10847 if (err)
10848 goto done;
10850 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
10852 switch (got_object_tag_get_object_type(tag)) {
10853 case GOT_OBJ_TYPE_BLOB:
10854 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10855 GOT_OBJ_LABEL_BLOB);
10856 break;
10857 case GOT_OBJ_TYPE_TREE:
10858 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10859 GOT_OBJ_LABEL_TREE);
10860 break;
10861 case GOT_OBJ_TYPE_COMMIT:
10862 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10863 GOT_OBJ_LABEL_COMMIT);
10864 break;
10865 case GOT_OBJ_TYPE_TAG:
10866 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
10867 GOT_OBJ_LABEL_TAG);
10868 break;
10869 default:
10870 break;
10873 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
10874 got_object_tag_get_name(tag));
10876 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
10877 got_object_tag_get_tagger(tag),
10878 (long long)got_object_tag_get_tagger_time(tag));
10880 tagmsg = got_object_tag_get_message(tag);
10881 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
10882 fprintf(outfile, "%s", tagmsg);
10883 done:
10884 free(id_str);
10885 got_object_tag_close(tag);
10886 return err;
10889 static const struct got_error *
10890 cmd_cat(int argc, char *argv[])
10892 const struct got_error *error;
10893 struct got_repository *repo = NULL;
10894 struct got_worktree *worktree = NULL;
10895 char *cwd = NULL, *repo_path = NULL, *label = NULL;
10896 const char *commit_id_str = NULL;
10897 struct got_object_id *id = NULL, *commit_id = NULL;
10898 int ch, obj_type, i, force_path = 0;
10899 struct got_reflist_head refs;
10901 TAILQ_INIT(&refs);
10903 #ifndef PROFILE
10904 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
10905 NULL) == -1)
10906 err(1, "pledge");
10907 #endif
10909 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
10910 switch (ch) {
10911 case 'c':
10912 commit_id_str = optarg;
10913 break;
10914 case 'r':
10915 repo_path = realpath(optarg, NULL);
10916 if (repo_path == NULL)
10917 return got_error_from_errno2("realpath",
10918 optarg);
10919 got_path_strip_trailing_slashes(repo_path);
10920 break;
10921 case 'P':
10922 force_path = 1;
10923 break;
10924 default:
10925 usage_cat();
10926 /* NOTREACHED */
10930 argc -= optind;
10931 argv += optind;
10933 cwd = getcwd(NULL, 0);
10934 if (cwd == NULL) {
10935 error = got_error_from_errno("getcwd");
10936 goto done;
10938 error = got_worktree_open(&worktree, cwd);
10939 if (error && error->code != GOT_ERR_NOT_WORKTREE)
10940 goto done;
10941 if (worktree) {
10942 if (repo_path == NULL) {
10943 repo_path = strdup(
10944 got_worktree_get_repo_path(worktree));
10945 if (repo_path == NULL) {
10946 error = got_error_from_errno("strdup");
10947 goto done;
10952 if (repo_path == NULL) {
10953 repo_path = getcwd(NULL, 0);
10954 if (repo_path == NULL)
10955 return got_error_from_errno("getcwd");
10958 error = got_repo_open(&repo, repo_path, NULL);
10959 free(repo_path);
10960 if (error != NULL)
10961 goto done;
10963 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
10964 if (error)
10965 goto done;
10967 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10968 if (error)
10969 goto done;
10971 if (commit_id_str == NULL)
10972 commit_id_str = GOT_REF_HEAD;
10973 error = got_repo_match_object_id(&commit_id, NULL,
10974 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
10975 if (error)
10976 goto done;
10978 for (i = 0; i < argc; i++) {
10979 if (force_path) {
10980 error = got_object_id_by_path(&id, repo, commit_id,
10981 argv[i]);
10982 if (error)
10983 break;
10984 } else {
10985 error = got_repo_match_object_id(&id, &label, argv[i],
10986 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
10987 repo);
10988 if (error) {
10989 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
10990 error->code != GOT_ERR_NOT_REF)
10991 break;
10992 error = got_object_id_by_path(&id, repo,
10993 commit_id, argv[i]);
10994 if (error)
10995 break;
10999 error = got_object_get_type(&obj_type, repo, id);
11000 if (error)
11001 break;
11003 switch (obj_type) {
11004 case GOT_OBJ_TYPE_BLOB:
11005 error = cat_blob(id, repo, stdout);
11006 break;
11007 case GOT_OBJ_TYPE_TREE:
11008 error = cat_tree(id, repo, stdout);
11009 break;
11010 case GOT_OBJ_TYPE_COMMIT:
11011 error = cat_commit(id, repo, stdout);
11012 break;
11013 case GOT_OBJ_TYPE_TAG:
11014 error = cat_tag(id, repo, stdout);
11015 break;
11016 default:
11017 error = got_error(GOT_ERR_OBJ_TYPE);
11018 break;
11020 if (error)
11021 break;
11022 free(label);
11023 label = NULL;
11024 free(id);
11025 id = NULL;
11027 done:
11028 free(label);
11029 free(id);
11030 free(commit_id);
11031 if (worktree)
11032 got_worktree_close(worktree);
11033 if (repo) {
11034 const struct got_error *close_err = got_repo_close(repo);
11035 if (error == NULL)
11036 error = close_err;
11038 got_ref_list_free(&refs);
11039 return error;
11042 __dead static void
11043 usage_info(void)
11045 fprintf(stderr, "usage: %s info [path ...]\n",
11046 getprogname());
11047 exit(1);
11050 static const struct got_error *
11051 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11052 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11053 struct got_object_id *commit_id)
11055 const struct got_error *err = NULL;
11056 char *id_str = NULL;
11057 char datebuf[128];
11058 struct tm mytm, *tm;
11059 struct got_pathlist_head *paths = arg;
11060 struct got_pathlist_entry *pe;
11063 * Clear error indication from any of the path arguments which
11064 * would cause this file index entry to be displayed.
11066 TAILQ_FOREACH(pe, paths, entry) {
11067 if (got_path_cmp(path, pe->path, strlen(path),
11068 pe->path_len) == 0 ||
11069 got_path_is_child(path, pe->path, pe->path_len))
11070 pe->data = NULL; /* no error */
11073 printf(GOT_COMMIT_SEP_STR);
11074 if (S_ISLNK(mode))
11075 printf("symlink: %s\n", path);
11076 else if (S_ISREG(mode)) {
11077 printf("file: %s\n", path);
11078 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11079 } else if (S_ISDIR(mode))
11080 printf("directory: %s\n", path);
11081 else
11082 printf("something: %s\n", path);
11084 tm = localtime_r(&mtime, &mytm);
11085 if (tm == NULL)
11086 return NULL;
11087 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11088 return got_error(GOT_ERR_NO_SPACE);
11089 printf("timestamp: %s\n", datebuf);
11091 if (blob_id) {
11092 err = got_object_id_str(&id_str, blob_id);
11093 if (err)
11094 return err;
11095 printf("based on blob: %s\n", id_str);
11096 free(id_str);
11099 if (staged_blob_id) {
11100 err = got_object_id_str(&id_str, staged_blob_id);
11101 if (err)
11102 return err;
11103 printf("based on staged blob: %s\n", id_str);
11104 free(id_str);
11107 if (commit_id) {
11108 err = got_object_id_str(&id_str, commit_id);
11109 if (err)
11110 return err;
11111 printf("based on commit: %s\n", id_str);
11112 free(id_str);
11115 return NULL;
11118 static const struct got_error *
11119 cmd_info(int argc, char *argv[])
11121 const struct got_error *error = NULL;
11122 struct got_worktree *worktree = NULL;
11123 char *cwd = NULL, *id_str = NULL;
11124 struct got_pathlist_head paths;
11125 struct got_pathlist_entry *pe;
11126 char *uuidstr = NULL;
11127 int ch, show_files = 0;
11129 TAILQ_INIT(&paths);
11131 while ((ch = getopt(argc, argv, "")) != -1) {
11132 switch (ch) {
11133 default:
11134 usage_info();
11135 /* NOTREACHED */
11139 argc -= optind;
11140 argv += optind;
11142 #ifndef PROFILE
11143 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11144 NULL) == -1)
11145 err(1, "pledge");
11146 #endif
11147 cwd = getcwd(NULL, 0);
11148 if (cwd == NULL) {
11149 error = got_error_from_errno("getcwd");
11150 goto done;
11153 error = got_worktree_open(&worktree, cwd);
11154 if (error) {
11155 if (error->code == GOT_ERR_NOT_WORKTREE)
11156 error = wrap_not_worktree_error(error, "info", cwd);
11157 goto done;
11160 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11161 if (error)
11162 goto done;
11164 if (argc >= 1) {
11165 error = get_worktree_paths_from_argv(&paths, argc, argv,
11166 worktree);
11167 if (error)
11168 goto done;
11169 show_files = 1;
11172 error = got_object_id_str(&id_str,
11173 got_worktree_get_base_commit_id(worktree));
11174 if (error)
11175 goto done;
11177 error = got_worktree_get_uuid(&uuidstr, worktree);
11178 if (error)
11179 goto done;
11181 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11182 printf("work tree base commit: %s\n", id_str);
11183 printf("work tree path prefix: %s\n",
11184 got_worktree_get_path_prefix(worktree));
11185 printf("work tree branch reference: %s\n",
11186 got_worktree_get_head_ref_name(worktree));
11187 printf("work tree UUID: %s\n", uuidstr);
11188 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11190 if (show_files) {
11191 struct got_pathlist_entry *pe;
11192 TAILQ_FOREACH(pe, &paths, entry) {
11193 if (pe->path_len == 0)
11194 continue;
11196 * Assume this path will fail. This will be corrected
11197 * in print_path_info() in case the path does suceeed.
11199 pe->data = (void *)got_error_path(pe->path,
11200 GOT_ERR_BAD_PATH);
11202 error = got_worktree_path_info(worktree, &paths,
11203 print_path_info, &paths, check_cancelled, NULL);
11204 if (error)
11205 goto done;
11206 TAILQ_FOREACH(pe, &paths, entry) {
11207 if (pe->data != NULL) {
11208 error = pe->data; /* bad path */
11209 break;
11213 done:
11214 TAILQ_FOREACH(pe, &paths, entry)
11215 free((char *)pe->path);
11216 got_pathlist_free(&paths);
11217 free(cwd);
11218 free(id_str);
11219 free(uuidstr);
11220 return error;