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"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 int
408 spawn_editor(const char *editor, const char *file)
410 pid_t pid;
411 sig_t sighup, sigint, sigquit;
412 int st = -1;
414 sighup = signal(SIGHUP, SIG_IGN);
415 sigint = signal(SIGINT, SIG_IGN);
416 sigquit = signal(SIGQUIT, SIG_IGN);
418 switch (pid = fork()) {
419 case -1:
420 goto doneediting;
421 case 0:
422 execl(editor, editor, file, (char *)NULL);
423 _exit(127);
426 while (waitpid(pid, &st, 0) == -1)
427 if (errno != EINTR)
428 break;
430 doneediting:
431 (void)signal(SIGHUP, sighup);
432 (void)signal(SIGINT, sigint);
433 (void)signal(SIGQUIT, sigquit);
435 if (!WIFEXITED(st)) {
436 errno = EINTR;
437 return -1;
440 return WEXITSTATUS(st);
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 char *line = NULL;
450 size_t linesize = 0;
451 ssize_t linelen;
452 struct stat st, st2;
453 FILE *fp = NULL;
454 size_t len, logmsg_len;
455 char *initial_content_stripped = NULL, *buf = NULL, *s;
457 *logmsg = NULL;
459 if (stat(logmsg_path, &st) == -1)
460 return got_error_from_errno2("stat", logmsg_path);
462 if (spawn_editor(editor, logmsg_path) == -1)
463 return got_error_from_errno("failed spawning editor");
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification &&
469 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 /*
474 * Set up a stripped version of the initial content without comments
475 * and blank lines. We need this in order to check if the message
476 * has in fact been edited.
477 */
478 initial_content_stripped = malloc(initial_content_len + 1);
479 if (initial_content_stripped == NULL)
480 return got_error_from_errno("malloc");
481 initial_content_stripped[0] = '\0';
483 buf = strdup(initial_content);
484 if (buf == NULL) {
485 err = got_error_from_errno("strdup");
486 goto done;
488 s = buf;
489 len = 0;
490 while ((line = strsep(&s, "\n")) != NULL) {
491 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
492 continue; /* remove comments and leading empty lines */
493 len = strlcat(initial_content_stripped, line,
494 initial_content_len + 1);
495 if (len >= initial_content_len + 1) {
496 err = got_error(GOT_ERR_NO_SPACE);
497 goto done;
500 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
501 initial_content_stripped[len - 1] = '\0';
502 len--;
505 logmsg_len = st2.st_size;
506 *logmsg = malloc(logmsg_len + 1);
507 if (*logmsg == NULL)
508 return got_error_from_errno("malloc");
509 (*logmsg)[0] = '\0';
511 fp = fopen(logmsg_path, "re");
512 if (fp == NULL) {
513 err = got_error_from_errno("fopen");
514 goto done;
517 len = 0;
518 while ((linelen = getline(&line, &linesize, fp)) != -1) {
519 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
520 continue; /* remove comments and leading empty lines */
521 len = strlcat(*logmsg, line, logmsg_len + 1);
522 if (len >= logmsg_len + 1) {
523 err = got_error(GOT_ERR_NO_SPACE);
524 goto done;
527 free(line);
528 if (ferror(fp)) {
529 err = got_ferror(fp, GOT_ERR_IO);
530 goto done;
532 while (len > 0 && (*logmsg)[len - 1] == '\n') {
533 (*logmsg)[len - 1] = '\0';
534 len--;
537 if (len == 0) {
538 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
539 "commit message cannot be empty, aborting");
540 goto done;
542 if (require_modification &&
543 strcmp(*logmsg, initial_content_stripped) == 0)
544 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
545 "no changes made to commit message, aborting");
546 done:
547 free(initial_content_stripped);
548 free(buf);
549 if (fp && fclose(fp) == EOF && err == NULL)
550 err = got_error_from_errno("fclose");
551 if (err) {
552 free(*logmsg);
553 *logmsg = NULL;
555 return err;
558 static const struct got_error *
559 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
560 const char *path_dir, const char *branch_name)
562 char *initial_content = NULL;
563 const struct got_error *err = NULL;
564 int initial_content_len;
565 int fd = -1;
567 initial_content_len = asprintf(&initial_content,
568 "\n# %s to be imported to branch %s\n", path_dir,
569 branch_name);
570 if (initial_content_len == -1)
571 return got_error_from_errno("asprintf");
573 err = got_opentemp_named_fd(logmsg_path, &fd,
574 GOT_TMPDIR_STR "/got-importmsg");
575 if (err)
576 goto done;
578 if (write(fd, initial_content, initial_content_len) == -1) {
579 err = got_error_from_errno2("write", *logmsg_path);
580 goto done;
583 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
584 initial_content_len, 1);
585 done:
586 if (fd != -1 && close(fd) == -1 && err == NULL)
587 err = got_error_from_errno2("close", *logmsg_path);
588 free(initial_content);
589 if (err) {
590 free(*logmsg_path);
591 *logmsg_path = NULL;
593 return err;
596 static const struct got_error *
597 import_progress(void *arg, const char *path)
599 printf("A %s\n", path);
600 return NULL;
603 static int
604 valid_author(const char *author)
606 /*
607 * Really dumb email address check; we're only doing this to
608 * avoid git's object parser breaking on commits we create.
609 */
610 while (*author && *author != '<')
611 author++;
612 if (*author != '<')
613 return 0;
614 while (*author && *author != '@')
615 author++;
616 if (*author != '@')
617 return 0;
618 while (*author && *author != '>')
619 author++;
620 return *author == '>';
623 static const struct got_error *
624 get_author(char **author, struct got_repository *repo,
625 struct got_worktree *worktree)
627 const struct got_error *err = NULL;
628 const char *got_author = NULL, *name, *email;
629 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
631 *author = NULL;
633 if (worktree)
634 worktree_conf = got_worktree_get_gotconfig(worktree);
635 repo_conf = got_repo_get_gotconfig(repo);
637 /*
638 * Priority of potential author information sources, from most
639 * significant to least significant:
640 * 1) work tree's .got/got.conf file
641 * 2) repository's got.conf file
642 * 3) repository's git config file
643 * 4) environment variables
644 * 5) global git config files (in user's home directory or /etc)
645 */
647 if (worktree_conf)
648 got_author = got_gotconfig_get_author(worktree_conf);
649 if (got_author == NULL)
650 got_author = got_gotconfig_get_author(repo_conf);
651 if (got_author == NULL) {
652 name = got_repo_get_gitconfig_author_name(repo);
653 email = got_repo_get_gitconfig_author_email(repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email) == -1)
656 return got_error_from_errno("asprintf");
657 return NULL;
660 got_author = getenv("GOT_AUTHOR");
661 if (got_author == NULL) {
662 name = got_repo_get_global_gitconfig_author_name(repo);
663 email = got_repo_get_global_gitconfig_author_email(
664 repo);
665 if (name && email) {
666 if (asprintf(author, "%s <%s>", name, email)
667 == -1)
668 return got_error_from_errno("asprintf");
669 return NULL;
671 /* TODO: Look up user in password database? */
672 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
676 *author = strdup(got_author);
677 if (*author == NULL)
678 return got_error_from_errno("strdup");
680 if (!valid_author(*author)) {
681 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
682 free(*author);
683 *author = NULL;
685 return err;
688 static const struct got_error *
689 get_gitconfig_path(char **gitconfig_path)
691 const char *homedir = getenv("HOME");
693 *gitconfig_path = NULL;
694 if (homedir) {
695 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
696 return got_error_from_errno("asprintf");
699 return NULL;
702 static const struct got_error *
703 cmd_import(int argc, char *argv[])
705 const struct got_error *error = NULL;
706 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
707 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
708 const char *branch_name = "main";
709 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
710 struct got_repository *repo = NULL;
711 struct got_reference *branch_ref = NULL, *head_ref = NULL;
712 struct got_object_id *new_commit_id = NULL;
713 int ch;
714 struct got_pathlist_head ignores;
715 struct got_pathlist_entry *pe;
716 int preserve_logmsg = 0;
718 TAILQ_INIT(&ignores);
720 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
721 switch (ch) {
722 case 'b':
723 branch_name = optarg;
724 break;
725 case 'm':
726 logmsg = strdup(optarg);
727 if (logmsg == NULL) {
728 error = got_error_from_errno("strdup");
729 goto done;
731 break;
732 case 'r':
733 repo_path = realpath(optarg, NULL);
734 if (repo_path == NULL) {
735 error = got_error_from_errno2("realpath",
736 optarg);
737 goto done;
739 break;
740 case 'I':
741 if (optarg[0] == '\0')
742 break;
743 error = got_pathlist_insert(&pe, &ignores, optarg,
744 NULL);
745 if (error)
746 goto done;
747 break;
748 default:
749 usage_import();
750 /* NOTREACHED */
754 argc -= optind;
755 argv += optind;
757 #ifndef PROFILE
758 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
759 "unveil",
760 NULL) == -1)
761 err(1, "pledge");
762 #endif
763 if (argc != 1)
764 usage_import();
766 if (repo_path == NULL) {
767 repo_path = getcwd(NULL, 0);
768 if (repo_path == NULL)
769 return got_error_from_errno("getcwd");
771 got_path_strip_trailing_slashes(repo_path);
772 error = get_gitconfig_path(&gitconfig_path);
773 if (error)
774 goto done;
775 error = got_repo_open(&repo, repo_path, gitconfig_path);
776 if (error)
777 goto done;
779 error = get_author(&author, repo, NULL);
780 if (error)
781 return error;
783 /*
784 * Don't let the user create a branch name with a leading '-'.
785 * While technically a valid reference name, this case is usually
786 * an unintended typo.
787 */
788 if (branch_name[0] == '-')
789 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
791 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
792 error = got_error_from_errno("asprintf");
793 goto done;
796 error = got_ref_open(&branch_ref, repo, refname, 0);
797 if (error) {
798 if (error->code != GOT_ERR_NOT_REF)
799 goto done;
800 } else {
801 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
802 "import target branch already exists");
803 goto done;
806 path_dir = realpath(argv[0], NULL);
807 if (path_dir == NULL) {
808 error = got_error_from_errno2("realpath", argv[0]);
809 goto done;
811 got_path_strip_trailing_slashes(path_dir);
813 /*
814 * unveil(2) traverses exec(2); if an editor is used we have
815 * to apply unveil after the log message has been written.
816 */
817 if (logmsg == NULL || strlen(logmsg) == 0) {
818 error = get_editor(&editor);
819 if (error)
820 goto done;
821 free(logmsg);
822 error = collect_import_msg(&logmsg, &logmsg_path, editor,
823 path_dir, refname);
824 if (error) {
825 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
826 logmsg_path != NULL)
827 preserve_logmsg = 1;
828 goto done;
832 if (unveil(path_dir, "r") != 0) {
833 error = got_error_from_errno2("unveil", path_dir);
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_repo_import(&new_commit_id, path_dir, logmsg,
847 author, &ignores, repo, import_progress, NULL);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_write(branch_ref, repo);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_object_id_str(&id_str, new_commit_id);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
876 if (error) {
877 if (error->code != GOT_ERR_NOT_REF) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
884 branch_ref);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
891 error = got_ref_write(head_ref, repo);
892 if (error) {
893 if (logmsg_path)
894 preserve_logmsg = 1;
895 goto done;
899 printf("Created branch %s with commit %s\n",
900 got_ref_get_name(branch_ref), id_str);
901 done:
902 if (preserve_logmsg) {
903 fprintf(stderr, "%s: log message preserved in %s\n",
904 getprogname(), logmsg_path);
905 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
906 error = got_error_from_errno2("unlink", logmsg_path);
907 free(logmsg);
908 free(logmsg_path);
909 free(repo_path);
910 free(editor);
911 free(refname);
912 free(new_commit_id);
913 free(id_str);
914 free(author);
915 free(gitconfig_path);
916 if (branch_ref)
917 got_ref_close(branch_ref);
918 if (head_ref)
919 got_ref_close(head_ref);
920 return error;
923 __dead static void
924 usage_clone(void)
926 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
927 "[-R reference] repository-url [directory]\n", getprogname());
928 exit(1);
931 struct got_fetch_progress_arg {
932 char last_scaled_size[FMT_SCALED_STRSIZE];
933 int last_p_indexed;
934 int last_p_resolved;
935 int verbosity;
937 struct got_repository *repo;
939 int create_configs;
940 int configs_created;
941 struct {
942 struct got_pathlist_head *symrefs;
943 struct got_pathlist_head *wanted_branches;
944 struct got_pathlist_head *wanted_refs;
945 const char *proto;
946 const char *host;
947 const char *port;
948 const char *remote_repo_path;
949 const char *git_url;
950 int fetch_all_branches;
951 int mirror_references;
952 } config_info;
953 };
955 /* XXX forward declaration */
956 static const struct got_error *
957 create_config_files(const char *proto, const char *host, const char *port,
958 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
959 int mirror_references, struct got_pathlist_head *symrefs,
960 struct got_pathlist_head *wanted_branches,
961 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
963 static const struct got_error *
964 fetch_progress(void *arg, const char *message, off_t packfile_size,
965 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
967 const struct got_error *err = NULL;
968 struct got_fetch_progress_arg *a = arg;
969 char scaled_size[FMT_SCALED_STRSIZE];
970 int p_indexed, p_resolved;
971 int print_size = 0, print_indexed = 0, print_resolved = 0;
973 /*
974 * In order to allow a failed clone to be resumed with 'got fetch'
975 * we try to create configuration files as soon as possible.
976 * Once the server has sent information about its default branch
977 * we have all required information.
978 */
979 if (a->create_configs && !a->configs_created &&
980 !TAILQ_EMPTY(a->config_info.symrefs)) {
981 err = create_config_files(a->config_info.proto,
982 a->config_info.host, a->config_info.port,
983 a->config_info.remote_repo_path,
984 a->config_info.git_url,
985 a->config_info.fetch_all_branches,
986 a->config_info.mirror_references,
987 a->config_info.symrefs,
988 a->config_info.wanted_branches,
989 a->config_info.wanted_refs, a->repo);
990 if (err)
991 return err;
992 a->configs_created = 1;
995 if (a->verbosity < 0)
996 return NULL;
998 if (message && message[0] != '\0') {
999 printf("\rserver: %s", message);
1000 fflush(stdout);
1001 return NULL;
1004 if (packfile_size > 0 || nobj_indexed > 0) {
1005 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1006 (a->last_scaled_size[0] == '\0' ||
1007 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1008 print_size = 1;
1009 if (strlcpy(a->last_scaled_size, scaled_size,
1010 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1011 return got_error(GOT_ERR_NO_SPACE);
1013 if (nobj_indexed > 0) {
1014 p_indexed = (nobj_indexed * 100) / nobj_total;
1015 if (p_indexed != a->last_p_indexed) {
1016 a->last_p_indexed = p_indexed;
1017 print_indexed = 1;
1018 print_size = 1;
1021 if (nobj_resolved > 0) {
1022 p_resolved = (nobj_resolved * 100) /
1023 (nobj_total - nobj_loose);
1024 if (p_resolved != a->last_p_resolved) {
1025 a->last_p_resolved = p_resolved;
1026 print_resolved = 1;
1027 print_indexed = 1;
1028 print_size = 1;
1033 if (print_size || print_indexed || print_resolved)
1034 printf("\r");
1035 if (print_size)
1036 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1037 if (print_indexed)
1038 printf("; indexing %d%%", p_indexed);
1039 if (print_resolved)
1040 printf("; resolving deltas %d%%", p_resolved);
1041 if (print_size || print_indexed || print_resolved)
1042 fflush(stdout);
1044 return NULL;
1047 static const struct got_error *
1048 create_symref(const char *refname, struct got_reference *target_ref,
1049 int verbosity, struct got_repository *repo)
1051 const struct got_error *err;
1052 struct got_reference *head_symref;
1054 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1055 if (err)
1056 return err;
1058 err = got_ref_write(head_symref, repo);
1059 if (err == NULL && verbosity > 0) {
1060 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1061 got_ref_get_name(target_ref));
1063 got_ref_close(head_symref);
1064 return err;
1067 static const struct got_error *
1068 list_remote_refs(struct got_pathlist_head *symrefs,
1069 struct got_pathlist_head *refs)
1071 const struct got_error *err;
1072 struct got_pathlist_entry *pe;
1074 TAILQ_FOREACH(pe, symrefs, entry) {
1075 const char *refname = pe->path;
1076 const char *targetref = pe->data;
1078 printf("%s: %s\n", refname, targetref);
1081 TAILQ_FOREACH(pe, refs, entry) {
1082 const char *refname = pe->path;
1083 struct got_object_id *id = pe->data;
1084 char *id_str;
1086 err = got_object_id_str(&id_str, id);
1087 if (err)
1088 return err;
1089 printf("%s: %s\n", refname, id_str);
1090 free(id_str);
1093 return NULL;
1096 static const struct got_error *
1097 create_ref(const char *refname, struct got_object_id *id,
1098 int verbosity, struct got_repository *repo)
1100 const struct got_error *err = NULL;
1101 struct got_reference *ref;
1102 char *id_str;
1104 err = got_object_id_str(&id_str, id);
1105 if (err)
1106 return err;
1108 err = got_ref_alloc(&ref, refname, id);
1109 if (err)
1110 goto done;
1112 err = got_ref_write(ref, repo);
1113 got_ref_close(ref);
1115 if (err == NULL && verbosity >= 0)
1116 printf("Created reference %s: %s\n", refname, id_str);
1117 done:
1118 free(id_str);
1119 return err;
1122 static int
1123 match_wanted_ref(const char *refname, const char *wanted_ref)
1125 if (strncmp(refname, "refs/", 5) != 0)
1126 return 0;
1127 refname += 5;
1130 * Prevent fetching of references that won't make any
1131 * sense outside of the remote repository's context.
1133 if (strncmp(refname, "got/", 4) == 0)
1134 return 0;
1135 if (strncmp(refname, "remotes/", 8) == 0)
1136 return 0;
1138 if (strncmp(wanted_ref, "refs/", 5) == 0)
1139 wanted_ref += 5;
1141 /* Allow prefix match. */
1142 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1143 return 1;
1145 /* Allow exact match. */
1146 return (strcmp(refname, wanted_ref) == 0);
1149 static int
1150 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1152 struct got_pathlist_entry *pe;
1154 TAILQ_FOREACH(pe, wanted_refs, entry) {
1155 if (match_wanted_ref(refname, pe->path))
1156 return 1;
1159 return 0;
1162 static const struct got_error *
1163 create_wanted_ref(const char *refname, struct got_object_id *id,
1164 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1166 const struct got_error *err;
1167 char *remote_refname;
1169 if (strncmp("refs/", refname, 5) == 0)
1170 refname += 5;
1172 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1173 remote_repo_name, refname) == -1)
1174 return got_error_from_errno("asprintf");
1176 err = create_ref(remote_refname, id, verbosity, repo);
1177 free(remote_refname);
1178 return err;
1181 static const struct got_error *
1182 create_gotconfig(const char *proto, const char *host, const char *port,
1183 const char *remote_repo_path, const char *default_branch,
1184 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1185 struct got_pathlist_head *wanted_refs, int mirror_references,
1186 struct got_repository *repo)
1188 const struct got_error *err = NULL;
1189 char *gotconfig_path = NULL;
1190 char *gotconfig = NULL;
1191 FILE *gotconfig_file = NULL;
1192 const char *branchname = NULL;
1193 char *branches = NULL, *refs = NULL;
1194 ssize_t n;
1196 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1197 struct got_pathlist_entry *pe;
1198 TAILQ_FOREACH(pe, wanted_branches, entry) {
1199 char *s;
1200 branchname = pe->path;
1201 if (strncmp(branchname, "refs/heads/", 11) == 0)
1202 branchname += 11;
1203 if (asprintf(&s, "%s\"%s\" ",
1204 branches ? branches : "", branchname) == -1) {
1205 err = got_error_from_errno("asprintf");
1206 goto done;
1208 free(branches);
1209 branches = s;
1211 } else if (!fetch_all_branches && default_branch) {
1212 branchname = default_branch;
1213 if (strncmp(branchname, "refs/heads/", 11) == 0)
1214 branchname += 11;
1215 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1220 if (!TAILQ_EMPTY(wanted_refs)) {
1221 struct got_pathlist_entry *pe;
1222 TAILQ_FOREACH(pe, wanted_refs, entry) {
1223 char *s;
1224 const char *refname = pe->path;
1225 if (strncmp(refname, "refs/", 5) == 0)
1226 branchname += 5;
1227 if (asprintf(&s, "%s\"%s\" ",
1228 refs ? refs : "", refname) == -1) {
1229 err = got_error_from_errno("asprintf");
1230 goto done;
1232 free(refs);
1233 refs = s;
1237 /* Create got.conf(5). */
1238 gotconfig_path = got_repo_get_path_gotconfig(repo);
1239 if (gotconfig_path == NULL) {
1240 err = got_error_from_errno("got_repo_get_path_gotconfig");
1241 goto done;
1243 gotconfig_file = fopen(gotconfig_path, "ae");
1244 if (gotconfig_file == NULL) {
1245 err = got_error_from_errno2("fopen", gotconfig_path);
1246 goto done;
1248 if (asprintf(&gotconfig,
1249 "remote \"%s\" {\n"
1250 "\tserver %s\n"
1251 "\tprotocol %s\n"
1252 "%s%s%s"
1253 "\trepository \"%s\"\n"
1254 "%s%s%s"
1255 "%s%s%s"
1256 "%s"
1257 "%s"
1258 "}\n",
1259 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1260 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1261 remote_repo_path, branches ? "\tbranch { " : "",
1262 branches ? branches : "", branches ? "}\n" : "",
1263 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1264 mirror_references ? "\tmirror-references yes\n" : "",
1265 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1269 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1270 if (n != strlen(gotconfig)) {
1271 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1272 goto done;
1275 done:
1276 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1277 err = got_error_from_errno2("fclose", gotconfig_path);
1278 free(gotconfig_path);
1279 free(branches);
1280 return err;
1283 static const struct got_error *
1284 create_gitconfig(const char *git_url, const char *default_branch,
1285 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1286 struct got_pathlist_head *wanted_refs, int mirror_references,
1287 struct got_repository *repo)
1289 const struct got_error *err = NULL;
1290 char *gitconfig_path = NULL;
1291 char *gitconfig = NULL;
1292 FILE *gitconfig_file = NULL;
1293 char *branches = NULL, *refs = NULL;
1294 const char *branchname;
1295 ssize_t n;
1297 /* Create a config file Git can understand. */
1298 gitconfig_path = got_repo_get_path_gitconfig(repo);
1299 if (gitconfig_path == NULL) {
1300 err = got_error_from_errno("got_repo_get_path_gitconfig");
1301 goto done;
1303 gitconfig_file = fopen(gitconfig_path, "ae");
1304 if (gitconfig_file == NULL) {
1305 err = got_error_from_errno2("fopen", gitconfig_path);
1306 goto done;
1308 if (fetch_all_branches) {
1309 if (mirror_references) {
1310 if (asprintf(&branches,
1311 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 } else if (asprintf(&branches,
1316 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1317 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1318 err = got_error_from_errno("asprintf");
1319 goto done;
1321 } else if (!TAILQ_EMPTY(wanted_branches)) {
1322 struct got_pathlist_entry *pe;
1323 TAILQ_FOREACH(pe, wanted_branches, entry) {
1324 char *s;
1325 branchname = pe->path;
1326 if (strncmp(branchname, "refs/heads/", 11) == 0)
1327 branchname += 11;
1328 if (mirror_references) {
1329 if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1331 branches ? branches : "",
1332 branchname, branchname) == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 } else if (asprintf(&s,
1337 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1338 branches ? branches : "",
1339 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1340 branchname) == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 free(branches);
1345 branches = s;
1347 } else {
1349 * If the server specified a default branch, use just that one.
1350 * Otherwise fall back to fetching all branches on next fetch.
1352 if (default_branch) {
1353 branchname = default_branch;
1354 if (strncmp(branchname, "refs/heads/", 11) == 0)
1355 branchname += 11;
1356 } else
1357 branchname = "*"; /* fall back to all branches */
1358 if (mirror_references) {
1359 if (asprintf(&branches,
1360 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1361 branchname, branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1365 } else if (asprintf(&branches,
1366 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1367 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1368 branchname) == -1) {
1369 err = got_error_from_errno("asprintf");
1370 goto done;
1373 if (!TAILQ_EMPTY(wanted_refs)) {
1374 struct got_pathlist_entry *pe;
1375 TAILQ_FOREACH(pe, wanted_refs, entry) {
1376 char *s;
1377 const char *refname = pe->path;
1378 if (strncmp(refname, "refs/", 5) == 0)
1379 refname += 5;
1380 if (mirror_references) {
1381 if (asprintf(&s,
1382 "%s\tfetch = refs/%s:refs/%s\n",
1383 refs ? refs : "", refname, refname) == -1) {
1384 err = got_error_from_errno("asprintf");
1385 goto done;
1387 } else if (asprintf(&s,
1388 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1389 refs ? refs : "",
1390 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1391 refname) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 free(refs);
1396 refs = s;
1400 if (asprintf(&gitconfig,
1401 "[remote \"%s\"]\n"
1402 "\turl = %s\n"
1403 "%s"
1404 "%s"
1405 "\tfetch = refs/tags/*:refs/tags/*\n",
1406 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1407 refs ? refs : "") == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1412 if (n != strlen(gitconfig)) {
1413 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1414 goto done;
1416 done:
1417 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1418 err = got_error_from_errno2("fclose", gitconfig_path);
1419 free(gitconfig_path);
1420 free(branches);
1421 return err;
1424 static const struct got_error *
1425 create_config_files(const char *proto, const char *host, const char *port,
1426 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1427 int mirror_references, struct got_pathlist_head *symrefs,
1428 struct got_pathlist_head *wanted_branches,
1429 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1431 const struct got_error *err = NULL;
1432 const char *default_branch = NULL;
1433 struct got_pathlist_entry *pe;
1436 * If we asked for a set of wanted branches then use the first
1437 * one of those.
1439 if (!TAILQ_EMPTY(wanted_branches)) {
1440 pe = TAILQ_FIRST(wanted_branches);
1441 default_branch = pe->path;
1442 } else {
1443 /* First HEAD ref listed by server is the default branch. */
1444 TAILQ_FOREACH(pe, symrefs, entry) {
1445 const char *refname = pe->path;
1446 const char *target = pe->data;
1448 if (strcmp(refname, GOT_REF_HEAD) != 0)
1449 continue;
1451 default_branch = target;
1452 break;
1456 /* Create got.conf(5). */
1457 err = create_gotconfig(proto, host, port, remote_repo_path,
1458 default_branch, fetch_all_branches, wanted_branches,
1459 wanted_refs, mirror_references, repo);
1460 if (err)
1461 return err;
1463 /* Create a config file Git can understand. */
1464 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1465 wanted_branches, wanted_refs, mirror_references, repo);
1468 static const struct got_error *
1469 cmd_clone(int argc, char *argv[])
1471 const struct got_error *error = NULL;
1472 const char *uri, *dirname;
1473 char *proto, *host, *port, *repo_name, *server_path;
1474 char *default_destdir = NULL, *id_str = NULL;
1475 const char *repo_path;
1476 struct got_repository *repo = NULL;
1477 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1478 struct got_pathlist_entry *pe;
1479 struct got_object_id *pack_hash = NULL;
1480 int ch, fetchfd = -1, fetchstatus;
1481 pid_t fetchpid = -1;
1482 struct got_fetch_progress_arg fpa;
1483 char *git_url = NULL;
1484 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1485 int list_refs_only = 0;
1487 TAILQ_INIT(&refs);
1488 TAILQ_INIT(&symrefs);
1489 TAILQ_INIT(&wanted_branches);
1490 TAILQ_INIT(&wanted_refs);
1492 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1493 switch (ch) {
1494 case 'a':
1495 fetch_all_branches = 1;
1496 break;
1497 case 'b':
1498 error = got_pathlist_append(&wanted_branches,
1499 optarg, NULL);
1500 if (error)
1501 return error;
1502 break;
1503 case 'l':
1504 list_refs_only = 1;
1505 break;
1506 case 'm':
1507 mirror_references = 1;
1508 break;
1509 case 'v':
1510 if (verbosity < 0)
1511 verbosity = 0;
1512 else if (verbosity < 3)
1513 verbosity++;
1514 break;
1515 case 'q':
1516 verbosity = -1;
1517 break;
1518 case 'R':
1519 error = got_pathlist_append(&wanted_refs,
1520 optarg, NULL);
1521 if (error)
1522 return error;
1523 break;
1524 default:
1525 usage_clone();
1526 break;
1529 argc -= optind;
1530 argv += optind;
1532 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1533 option_conflict('a', 'b');
1534 if (list_refs_only) {
1535 if (!TAILQ_EMPTY(&wanted_branches))
1536 option_conflict('l', 'b');
1537 if (fetch_all_branches)
1538 option_conflict('l', 'a');
1539 if (mirror_references)
1540 option_conflict('l', 'm');
1541 if (!TAILQ_EMPTY(&wanted_refs))
1542 option_conflict('l', 'R');
1545 uri = argv[0];
1547 if (argc == 1)
1548 dirname = NULL;
1549 else if (argc == 2)
1550 dirname = argv[1];
1551 else
1552 usage_clone();
1554 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1555 &repo_name, uri);
1556 if (error)
1557 goto done;
1559 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1560 host, port ? ":" : "", port ? port : "",
1561 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1562 error = got_error_from_errno("asprintf");
1563 goto done;
1566 if (strcmp(proto, "git") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd dns inet unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "git+ssh") == 0 ||
1573 strcmp(proto, "ssh") == 0) {
1574 #ifndef PROFILE
1575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1576 "sendfd unveil", NULL) == -1)
1577 err(1, "pledge");
1578 #endif
1579 } else if (strcmp(proto, "http") == 0 ||
1580 strcmp(proto, "git+http") == 0) {
1581 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1582 goto done;
1583 } else {
1584 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1585 goto done;
1587 if (dirname == NULL) {
1588 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1589 error = got_error_from_errno("asprintf");
1590 goto done;
1592 repo_path = default_destdir;
1593 } else
1594 repo_path = dirname;
1596 if (!list_refs_only) {
1597 error = got_path_mkdir(repo_path);
1598 if (error &&
1599 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1600 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1601 goto done;
1602 if (!got_path_dir_is_empty(repo_path)) {
1603 error = got_error_path(repo_path,
1604 GOT_ERR_DIR_NOT_EMPTY);
1605 goto done;
1609 error = got_dial_apply_unveil(proto);
1610 if (error)
1611 goto done;
1613 error = apply_unveil(repo_path, 0, NULL);
1614 if (error)
1615 goto done;
1617 if (verbosity >= 0)
1618 printf("Connecting to %s%s%s\n", host,
1619 port ? ":" : "", port ? port : "");
1621 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1622 server_path, verbosity);
1623 if (error)
1624 goto done;
1626 if (!list_refs_only) {
1627 error = got_repo_init(repo_path);
1628 if (error)
1629 goto done;
1630 error = got_repo_open(&repo, repo_path, NULL);
1631 if (error)
1632 goto done;
1635 fpa.last_scaled_size[0] = '\0';
1636 fpa.last_p_indexed = -1;
1637 fpa.last_p_resolved = -1;
1638 fpa.verbosity = verbosity;
1639 fpa.create_configs = 1;
1640 fpa.configs_created = 0;
1641 fpa.repo = repo;
1642 fpa.config_info.symrefs = &symrefs;
1643 fpa.config_info.wanted_branches = &wanted_branches;
1644 fpa.config_info.wanted_refs = &wanted_refs;
1645 fpa.config_info.proto = proto;
1646 fpa.config_info.host = host;
1647 fpa.config_info.port = port;
1648 fpa.config_info.remote_repo_path = server_path;
1649 fpa.config_info.git_url = git_url;
1650 fpa.config_info.fetch_all_branches = fetch_all_branches;
1651 fpa.config_info.mirror_references = mirror_references;
1652 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1653 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1654 fetch_all_branches, &wanted_branches, &wanted_refs,
1655 list_refs_only, verbosity, fetchfd, repo,
1656 fetch_progress, &fpa);
1657 if (error)
1658 goto done;
1660 if (list_refs_only) {
1661 error = list_remote_refs(&symrefs, &refs);
1662 goto done;
1665 if (pack_hash == NULL) {
1666 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1667 "server sent an empty pack file");
1668 goto done;
1670 error = got_object_id_str(&id_str, pack_hash);
1671 if (error)
1672 goto done;
1673 if (verbosity >= 0)
1674 printf("\nFetched %s.pack\n", id_str);
1675 free(id_str);
1677 /* Set up references provided with the pack file. */
1678 TAILQ_FOREACH(pe, &refs, entry) {
1679 const char *refname = pe->path;
1680 struct got_object_id *id = pe->data;
1681 char *remote_refname;
1683 if (is_wanted_ref(&wanted_refs, refname) &&
1684 !mirror_references) {
1685 error = create_wanted_ref(refname, id,
1686 GOT_FETCH_DEFAULT_REMOTE_NAME,
1687 verbosity - 1, repo);
1688 if (error)
1689 goto done;
1690 continue;
1693 error = create_ref(refname, id, verbosity - 1, repo);
1694 if (error)
1695 goto done;
1697 if (mirror_references)
1698 continue;
1700 if (strncmp("refs/heads/", refname, 11) != 0)
1701 continue;
1703 if (asprintf(&remote_refname,
1704 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1705 refname + 11) == -1) {
1706 error = got_error_from_errno("asprintf");
1707 goto done;
1709 error = create_ref(remote_refname, id, verbosity - 1, repo);
1710 free(remote_refname);
1711 if (error)
1712 goto done;
1715 /* Set the HEAD reference if the server provided one. */
1716 TAILQ_FOREACH(pe, &symrefs, entry) {
1717 struct got_reference *target_ref;
1718 const char *refname = pe->path;
1719 const char *target = pe->data;
1720 char *remote_refname = NULL, *remote_target = NULL;
1722 if (strcmp(refname, GOT_REF_HEAD) != 0)
1723 continue;
1725 error = got_ref_open(&target_ref, repo, target, 0);
1726 if (error) {
1727 if (error->code == GOT_ERR_NOT_REF) {
1728 error = NULL;
1729 continue;
1731 goto done;
1734 error = create_symref(refname, target_ref, verbosity, repo);
1735 got_ref_close(target_ref);
1736 if (error)
1737 goto done;
1739 if (mirror_references)
1740 continue;
1742 if (strncmp("refs/heads/", target, 11) != 0)
1743 continue;
1745 if (asprintf(&remote_refname,
1746 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1747 refname) == -1) {
1748 error = got_error_from_errno("asprintf");
1749 goto done;
1751 if (asprintf(&remote_target,
1752 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1753 target + 11) == -1) {
1754 error = got_error_from_errno("asprintf");
1755 free(remote_refname);
1756 goto done;
1758 error = got_ref_open(&target_ref, repo, remote_target, 0);
1759 if (error) {
1760 free(remote_refname);
1761 free(remote_target);
1762 if (error->code == GOT_ERR_NOT_REF) {
1763 error = NULL;
1764 continue;
1766 goto done;
1768 error = create_symref(remote_refname, target_ref,
1769 verbosity - 1, repo);
1770 free(remote_refname);
1771 free(remote_target);
1772 got_ref_close(target_ref);
1773 if (error)
1774 goto done;
1776 if (pe == NULL) {
1778 * We failed to set the HEAD reference. If we asked for
1779 * a set of wanted branches use the first of one of those
1780 * which could be fetched instead.
1782 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1783 const char *target = pe->path;
1784 struct got_reference *target_ref;
1786 error = got_ref_open(&target_ref, repo, target, 0);
1787 if (error) {
1788 if (error->code == GOT_ERR_NOT_REF) {
1789 error = NULL;
1790 continue;
1792 goto done;
1795 error = create_symref(GOT_REF_HEAD, target_ref,
1796 verbosity, repo);
1797 got_ref_close(target_ref);
1798 if (error)
1799 goto done;
1800 break;
1804 if (verbosity >= 0)
1805 printf("Created %s repository '%s'\n",
1806 mirror_references ? "mirrored" : "cloned", repo_path);
1807 done:
1808 if (fetchpid > 0) {
1809 if (kill(fetchpid, SIGTERM) == -1)
1810 error = got_error_from_errno("kill");
1811 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1812 error = got_error_from_errno("waitpid");
1814 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1815 error = got_error_from_errno("close");
1816 if (repo) {
1817 const struct got_error *close_err = got_repo_close(repo);
1818 if (error == NULL)
1819 error = close_err;
1821 TAILQ_FOREACH(pe, &refs, entry) {
1822 free((void *)pe->path);
1823 free(pe->data);
1825 got_pathlist_free(&refs);
1826 TAILQ_FOREACH(pe, &symrefs, entry) {
1827 free((void *)pe->path);
1828 free(pe->data);
1830 got_pathlist_free(&symrefs);
1831 got_pathlist_free(&wanted_branches);
1832 got_pathlist_free(&wanted_refs);
1833 free(pack_hash);
1834 free(proto);
1835 free(host);
1836 free(port);
1837 free(server_path);
1838 free(repo_name);
1839 free(default_destdir);
1840 free(git_url);
1841 return error;
1844 static const struct got_error *
1845 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1846 int replace_tags, int verbosity, struct got_repository *repo)
1848 const struct got_error *err = NULL;
1849 char *new_id_str = NULL;
1850 struct got_object_id *old_id = NULL;
1852 err = got_object_id_str(&new_id_str, new_id);
1853 if (err)
1854 goto done;
1856 if (!replace_tags &&
1857 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1858 err = got_ref_resolve(&old_id, repo, ref);
1859 if (err)
1860 goto done;
1861 if (got_object_id_cmp(old_id, new_id) == 0)
1862 goto done;
1863 if (verbosity >= 0) {
1864 printf("Rejecting update of existing tag %s: %s\n",
1865 got_ref_get_name(ref), new_id_str);
1867 goto done;
1870 if (got_ref_is_symbolic(ref)) {
1871 if (verbosity >= 0) {
1872 printf("Replacing reference %s: %s\n",
1873 got_ref_get_name(ref),
1874 got_ref_get_symref_target(ref));
1876 err = got_ref_change_symref_to_ref(ref, new_id);
1877 if (err)
1878 goto done;
1879 err = got_ref_write(ref, repo);
1880 if (err)
1881 goto done;
1882 } else {
1883 err = got_ref_resolve(&old_id, repo, ref);
1884 if (err)
1885 goto done;
1886 if (got_object_id_cmp(old_id, new_id) == 0)
1887 goto done;
1889 err = got_ref_change_ref(ref, new_id);
1890 if (err)
1891 goto done;
1892 err = got_ref_write(ref, repo);
1893 if (err)
1894 goto done;
1897 if (verbosity >= 0)
1898 printf("Updated %s: %s\n", got_ref_get_name(ref),
1899 new_id_str);
1900 done:
1901 free(old_id);
1902 free(new_id_str);
1903 return err;
1906 static const struct got_error *
1907 update_symref(const char *refname, struct got_reference *target_ref,
1908 int verbosity, struct got_repository *repo)
1910 const struct got_error *err = NULL, *unlock_err;
1911 struct got_reference *symref;
1912 int symref_is_locked = 0;
1914 err = got_ref_open(&symref, repo, refname, 1);
1915 if (err) {
1916 if (err->code != GOT_ERR_NOT_REF)
1917 return err;
1918 err = got_ref_alloc_symref(&symref, refname, target_ref);
1919 if (err)
1920 goto done;
1922 err = got_ref_write(symref, repo);
1923 if (err)
1924 goto done;
1926 if (verbosity >= 0)
1927 printf("Created reference %s: %s\n",
1928 got_ref_get_name(symref),
1929 got_ref_get_symref_target(symref));
1930 } else {
1931 symref_is_locked = 1;
1933 if (strcmp(got_ref_get_symref_target(symref),
1934 got_ref_get_name(target_ref)) == 0)
1935 goto done;
1937 err = got_ref_change_symref(symref,
1938 got_ref_get_name(target_ref));
1939 if (err)
1940 goto done;
1942 err = got_ref_write(symref, repo);
1943 if (err)
1944 goto done;
1946 if (verbosity >= 0)
1947 printf("Updated %s: %s\n", got_ref_get_name(symref),
1948 got_ref_get_symref_target(symref));
1951 done:
1952 if (symref_is_locked) {
1953 unlock_err = got_ref_unlock(symref);
1954 if (unlock_err && err == NULL)
1955 err = unlock_err;
1957 got_ref_close(symref);
1958 return err;
1961 __dead static void
1962 usage_fetch(void)
1964 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1965 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1966 "[remote-repository-name]\n",
1967 getprogname());
1968 exit(1);
1971 static const struct got_error *
1972 delete_missing_ref(struct got_reference *ref,
1973 int verbosity, struct got_repository *repo)
1975 const struct got_error *err = NULL;
1976 struct got_object_id *id = NULL;
1977 char *id_str = NULL;
1979 if (got_ref_is_symbolic(ref)) {
1980 err = got_ref_delete(ref, repo);
1981 if (err)
1982 return err;
1983 if (verbosity >= 0) {
1984 printf("Deleted %s: %s\n",
1985 got_ref_get_name(ref),
1986 got_ref_get_symref_target(ref));
1988 } else {
1989 err = got_ref_resolve(&id, repo, ref);
1990 if (err)
1991 return err;
1992 err = got_object_id_str(&id_str, id);
1993 if (err)
1994 goto done;
1996 err = got_ref_delete(ref, repo);
1997 if (err)
1998 goto done;
1999 if (verbosity >= 0) {
2000 printf("Deleted %s: %s\n",
2001 got_ref_get_name(ref), id_str);
2004 done:
2005 free(id);
2006 free(id_str);
2007 return NULL;
2010 static const struct got_error *
2011 delete_missing_refs(struct got_pathlist_head *their_refs,
2012 struct got_pathlist_head *their_symrefs,
2013 const struct got_remote_repo *remote,
2014 int verbosity, struct got_repository *repo)
2016 const struct got_error *err = NULL, *unlock_err;
2017 struct got_reflist_head my_refs;
2018 struct got_reflist_entry *re;
2019 struct got_pathlist_entry *pe;
2020 char *remote_namespace = NULL;
2021 char *local_refname = NULL;
2023 TAILQ_INIT(&my_refs);
2025 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2026 == -1)
2027 return got_error_from_errno("asprintf");
2029 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2030 if (err)
2031 goto done;
2033 TAILQ_FOREACH(re, &my_refs, entry) {
2034 const char *refname = got_ref_get_name(re->ref);
2035 const char *their_refname;
2037 if (remote->mirror_references) {
2038 their_refname = refname;
2039 } else {
2040 if (strncmp(refname, remote_namespace,
2041 strlen(remote_namespace)) == 0) {
2042 if (strcmp(refname + strlen(remote_namespace),
2043 GOT_REF_HEAD) == 0)
2044 continue;
2045 if (asprintf(&local_refname, "refs/heads/%s",
2046 refname + strlen(remote_namespace)) == -1) {
2047 err = got_error_from_errno("asprintf");
2048 goto done;
2050 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2051 continue;
2053 their_refname = local_refname;
2056 TAILQ_FOREACH(pe, their_refs, entry) {
2057 if (strcmp(their_refname, pe->path) == 0)
2058 break;
2060 if (pe != NULL)
2061 continue;
2063 TAILQ_FOREACH(pe, their_symrefs, entry) {
2064 if (strcmp(their_refname, pe->path) == 0)
2065 break;
2067 if (pe != NULL)
2068 continue;
2070 err = delete_missing_ref(re->ref, verbosity, repo);
2071 if (err)
2072 break;
2074 if (local_refname) {
2075 struct got_reference *ref;
2076 err = got_ref_open(&ref, repo, local_refname, 1);
2077 if (err) {
2078 if (err->code != GOT_ERR_NOT_REF)
2079 break;
2080 free(local_refname);
2081 local_refname = NULL;
2082 continue;
2084 err = delete_missing_ref(ref, verbosity, repo);
2085 if (err)
2086 break;
2087 unlock_err = got_ref_unlock(ref);
2088 got_ref_close(ref);
2089 if (unlock_err && err == NULL) {
2090 err = unlock_err;
2091 break;
2094 free(local_refname);
2095 local_refname = NULL;
2098 done:
2099 free(remote_namespace);
2100 free(local_refname);
2101 return err;
2104 static const struct got_error *
2105 update_wanted_ref(const char *refname, struct got_object_id *id,
2106 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2108 const struct got_error *err, *unlock_err;
2109 char *remote_refname;
2110 struct got_reference *ref;
2112 if (strncmp("refs/", refname, 5) == 0)
2113 refname += 5;
2115 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2116 remote_repo_name, refname) == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_open(&ref, repo, remote_refname, 1);
2120 if (err) {
2121 if (err->code != GOT_ERR_NOT_REF)
2122 goto done;
2123 err = create_ref(remote_refname, id, verbosity, repo);
2124 } else {
2125 err = update_ref(ref, id, 0, verbosity, repo);
2126 unlock_err = got_ref_unlock(ref);
2127 if (unlock_err && err == NULL)
2128 err = unlock_err;
2129 got_ref_close(ref);
2131 done:
2132 free(remote_refname);
2133 return err;
2136 static const struct got_error *
2137 delete_ref(struct got_repository *repo, struct got_reference *ref)
2139 const struct got_error *err = NULL;
2140 struct got_object_id *id = NULL;
2141 char *id_str = NULL;
2142 const char *target;
2144 if (got_ref_is_symbolic(ref)) {
2145 target = got_ref_get_symref_target(ref);
2146 } else {
2147 err = got_ref_resolve(&id, repo, ref);
2148 if (err)
2149 goto done;
2150 err = got_object_id_str(&id_str, id);
2151 if (err)
2152 goto done;
2153 target = id_str;
2156 err = got_ref_delete(ref, repo);
2157 if (err)
2158 goto done;
2160 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2161 done:
2162 free(id);
2163 free(id_str);
2164 return err;
2167 static const struct got_error *
2168 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2170 const struct got_error *err = NULL;
2171 struct got_reflist_head refs;
2172 struct got_reflist_entry *re;
2173 char *prefix;
2175 TAILQ_INIT(&refs);
2177 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2178 err = got_error_from_errno("asprintf");
2179 goto done;
2181 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2182 if (err)
2183 goto done;
2185 TAILQ_FOREACH(re, &refs, entry)
2186 delete_ref(repo, re->ref);
2187 done:
2188 got_ref_list_free(&refs);
2189 return err;
2192 static const struct got_error *
2193 cmd_fetch(int argc, char *argv[])
2195 const struct got_error *error = NULL, *unlock_err;
2196 char *cwd = NULL, *repo_path = NULL;
2197 const char *remote_name;
2198 char *proto = NULL, *host = NULL, *port = NULL;
2199 char *repo_name = NULL, *server_path = NULL;
2200 const struct got_remote_repo *remotes, *remote = NULL;
2201 int nremotes;
2202 char *id_str = NULL;
2203 struct got_repository *repo = NULL;
2204 struct got_worktree *worktree = NULL;
2205 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2206 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2207 struct got_pathlist_entry *pe;
2208 struct got_object_id *pack_hash = NULL;
2209 int i, ch, fetchfd = -1, fetchstatus;
2210 pid_t fetchpid = -1;
2211 struct got_fetch_progress_arg fpa;
2212 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2213 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2215 TAILQ_INIT(&refs);
2216 TAILQ_INIT(&symrefs);
2217 TAILQ_INIT(&wanted_branches);
2218 TAILQ_INIT(&wanted_refs);
2220 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2221 switch (ch) {
2222 case 'a':
2223 fetch_all_branches = 1;
2224 break;
2225 case 'b':
2226 error = got_pathlist_append(&wanted_branches,
2227 optarg, NULL);
2228 if (error)
2229 return error;
2230 break;
2231 case 'd':
2232 delete_refs = 1;
2233 break;
2234 case 'l':
2235 list_refs_only = 1;
2236 break;
2237 case 'r':
2238 repo_path = realpath(optarg, NULL);
2239 if (repo_path == NULL)
2240 return got_error_from_errno2("realpath",
2241 optarg);
2242 got_path_strip_trailing_slashes(repo_path);
2243 break;
2244 case 't':
2245 replace_tags = 1;
2246 break;
2247 case 'v':
2248 if (verbosity < 0)
2249 verbosity = 0;
2250 else if (verbosity < 3)
2251 verbosity++;
2252 break;
2253 case 'q':
2254 verbosity = -1;
2255 break;
2256 case 'R':
2257 error = got_pathlist_append(&wanted_refs,
2258 optarg, NULL);
2259 if (error)
2260 return error;
2261 break;
2262 case 'X':
2263 delete_remote = 1;
2264 break;
2265 default:
2266 usage_fetch();
2267 break;
2270 argc -= optind;
2271 argv += optind;
2273 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2274 option_conflict('a', 'b');
2275 if (list_refs_only) {
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('l', 'b');
2278 if (fetch_all_branches)
2279 option_conflict('l', 'a');
2280 if (delete_refs)
2281 option_conflict('l', 'd');
2282 if (delete_remote)
2283 option_conflict('l', 'X');
2285 if (delete_remote) {
2286 if (fetch_all_branches)
2287 option_conflict('X', 'a');
2288 if (!TAILQ_EMPTY(&wanted_branches))
2289 option_conflict('X', 'b');
2290 if (delete_refs)
2291 option_conflict('X', 'd');
2292 if (replace_tags)
2293 option_conflict('X', 't');
2294 if (!TAILQ_EMPTY(&wanted_refs))
2295 option_conflict('X', 'R');
2298 if (argc == 0) {
2299 if (delete_remote)
2300 errx(1, "-X option requires a remote name");
2301 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2302 } else if (argc == 1)
2303 remote_name = argv[0];
2304 else
2305 usage_fetch();
2307 cwd = getcwd(NULL, 0);
2308 if (cwd == NULL) {
2309 error = got_error_from_errno("getcwd");
2310 goto done;
2313 if (repo_path == NULL) {
2314 error = got_worktree_open(&worktree, cwd);
2315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2316 goto done;
2317 else
2318 error = NULL;
2319 if (worktree) {
2320 repo_path =
2321 strdup(got_worktree_get_repo_path(worktree));
2322 if (repo_path == NULL)
2323 error = got_error_from_errno("strdup");
2324 if (error)
2325 goto done;
2326 } else {
2327 repo_path = strdup(cwd);
2328 if (repo_path == NULL) {
2329 error = got_error_from_errno("strdup");
2330 goto done;
2335 error = got_repo_open(&repo, repo_path, NULL);
2336 if (error)
2337 goto done;
2339 if (delete_remote) {
2340 error = delete_refs_for_remote(repo, remote_name);
2341 goto done; /* nothing else to do */
2344 if (worktree) {
2345 worktree_conf = got_worktree_get_gotconfig(worktree);
2346 if (worktree_conf) {
2347 got_gotconfig_get_remotes(&nremotes, &remotes,
2348 worktree_conf);
2349 for (i = 0; i < nremotes; i++) {
2350 if (strcmp(remotes[i].name, remote_name) == 0) {
2351 remote = &remotes[i];
2352 break;
2357 if (remote == NULL) {
2358 repo_conf = got_repo_get_gotconfig(repo);
2359 if (repo_conf) {
2360 got_gotconfig_get_remotes(&nremotes, &remotes,
2361 repo_conf);
2362 for (i = 0; i < nremotes; i++) {
2363 if (strcmp(remotes[i].name, remote_name) == 0) {
2364 remote = &remotes[i];
2365 break;
2370 if (remote == NULL) {
2371 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2372 for (i = 0; i < nremotes; i++) {
2373 if (strcmp(remotes[i].name, remote_name) == 0) {
2374 remote = &remotes[i];
2375 break;
2379 if (remote == NULL) {
2380 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2381 goto done;
2384 if (TAILQ_EMPTY(&wanted_branches)) {
2385 if (!fetch_all_branches)
2386 fetch_all_branches = remote->fetch_all_branches;
2387 for (i = 0; i < remote->nfetch_branches; i++) {
2388 got_pathlist_append(&wanted_branches,
2389 remote->fetch_branches[i], NULL);
2392 if (TAILQ_EMPTY(&wanted_refs)) {
2393 for (i = 0; i < remote->nfetch_refs; i++) {
2394 got_pathlist_append(&wanted_refs,
2395 remote->fetch_refs[i], NULL);
2399 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2400 &repo_name, remote->fetch_url);
2401 if (error)
2402 goto done;
2404 if (strcmp(proto, "git") == 0) {
2405 #ifndef PROFILE
2406 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2407 "sendfd dns inet unveil", NULL) == -1)
2408 err(1, "pledge");
2409 #endif
2410 } else if (strcmp(proto, "git+ssh") == 0 ||
2411 strcmp(proto, "ssh") == 0) {
2412 #ifndef PROFILE
2413 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2414 "sendfd unveil", NULL) == -1)
2415 err(1, "pledge");
2416 #endif
2417 } else if (strcmp(proto, "http") == 0 ||
2418 strcmp(proto, "git+http") == 0) {
2419 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2420 goto done;
2421 } else {
2422 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2423 goto done;
2426 error = got_dial_apply_unveil(proto);
2427 if (error)
2428 goto done;
2430 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2431 if (error)
2432 goto done;
2434 if (verbosity >= 0)
2435 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2436 port ? ":" : "", port ? port : "");
2438 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2439 server_path, verbosity);
2440 if (error)
2441 goto done;
2443 fpa.last_scaled_size[0] = '\0';
2444 fpa.last_p_indexed = -1;
2445 fpa.last_p_resolved = -1;
2446 fpa.verbosity = verbosity;
2447 fpa.repo = repo;
2448 fpa.create_configs = 0;
2449 fpa.configs_created = 0;
2450 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2451 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2452 remote->mirror_references, fetch_all_branches, &wanted_branches,
2453 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2454 fetch_progress, &fpa);
2455 if (error)
2456 goto done;
2458 if (list_refs_only) {
2459 error = list_remote_refs(&symrefs, &refs);
2460 goto done;
2463 if (pack_hash == NULL) {
2464 if (verbosity >= 0)
2465 printf("Already up-to-date\n");
2466 } else if (verbosity >= 0) {
2467 error = got_object_id_str(&id_str, pack_hash);
2468 if (error)
2469 goto done;
2470 printf("\nFetched %s.pack\n", id_str);
2471 free(id_str);
2472 id_str = NULL;
2475 /* Update references provided with the pack file. */
2476 TAILQ_FOREACH(pe, &refs, entry) {
2477 const char *refname = pe->path;
2478 struct got_object_id *id = pe->data;
2479 struct got_reference *ref;
2480 char *remote_refname;
2482 if (is_wanted_ref(&wanted_refs, refname) &&
2483 !remote->mirror_references) {
2484 error = update_wanted_ref(refname, id,
2485 remote->name, verbosity, repo);
2486 if (error)
2487 goto done;
2488 continue;
2491 if (remote->mirror_references ||
2492 strncmp("refs/tags/", refname, 10) == 0) {
2493 error = got_ref_open(&ref, repo, refname, 1);
2494 if (error) {
2495 if (error->code != GOT_ERR_NOT_REF)
2496 goto done;
2497 error = create_ref(refname, id, verbosity,
2498 repo);
2499 if (error)
2500 goto done;
2501 } else {
2502 error = update_ref(ref, id, replace_tags,
2503 verbosity, repo);
2504 unlock_err = got_ref_unlock(ref);
2505 if (unlock_err && error == NULL)
2506 error = unlock_err;
2507 got_ref_close(ref);
2508 if (error)
2509 goto done;
2511 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2512 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2513 remote_name, refname + 11) == -1) {
2514 error = got_error_from_errno("asprintf");
2515 goto done;
2518 error = got_ref_open(&ref, repo, remote_refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(remote_refname, id,
2523 verbosity, repo);
2524 if (error)
2525 goto done;
2526 } else {
2527 error = update_ref(ref, id, replace_tags,
2528 verbosity, repo);
2529 unlock_err = got_ref_unlock(ref);
2530 if (unlock_err && error == NULL)
2531 error = unlock_err;
2532 got_ref_close(ref);
2533 if (error)
2534 goto done;
2537 /* Also create a local branch if none exists yet. */
2538 error = got_ref_open(&ref, repo, refname, 1);
2539 if (error) {
2540 if (error->code != GOT_ERR_NOT_REF)
2541 goto done;
2542 error = create_ref(refname, id, verbosity,
2543 repo);
2544 if (error)
2545 goto done;
2546 } else {
2547 unlock_err = got_ref_unlock(ref);
2548 if (unlock_err && error == NULL)
2549 error = unlock_err;
2550 got_ref_close(ref);
2554 if (delete_refs) {
2555 error = delete_missing_refs(&refs, &symrefs, remote,
2556 verbosity, repo);
2557 if (error)
2558 goto done;
2561 if (!remote->mirror_references) {
2562 /* Update remote HEAD reference if the server provided one. */
2563 TAILQ_FOREACH(pe, &symrefs, entry) {
2564 struct got_reference *target_ref;
2565 const char *refname = pe->path;
2566 const char *target = pe->data;
2567 char *remote_refname = NULL, *remote_target = NULL;
2569 if (strcmp(refname, GOT_REF_HEAD) != 0)
2570 continue;
2572 if (strncmp("refs/heads/", target, 11) != 0)
2573 continue;
2575 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2576 remote->name, refname) == -1) {
2577 error = got_error_from_errno("asprintf");
2578 goto done;
2580 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2581 remote->name, target + 11) == -1) {
2582 error = got_error_from_errno("asprintf");
2583 free(remote_refname);
2584 goto done;
2587 error = got_ref_open(&target_ref, repo, remote_target,
2588 0);
2589 if (error) {
2590 free(remote_refname);
2591 free(remote_target);
2592 if (error->code == GOT_ERR_NOT_REF) {
2593 error = NULL;
2594 continue;
2596 goto done;
2598 error = update_symref(remote_refname, target_ref,
2599 verbosity, repo);
2600 free(remote_refname);
2601 free(remote_target);
2602 got_ref_close(target_ref);
2603 if (error)
2604 goto done;
2607 done:
2608 if (fetchpid > 0) {
2609 if (kill(fetchpid, SIGTERM) == -1)
2610 error = got_error_from_errno("kill");
2611 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2612 error = got_error_from_errno("waitpid");
2614 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2615 error = got_error_from_errno("close");
2616 if (repo) {
2617 const struct got_error *close_err = got_repo_close(repo);
2618 if (error == NULL)
2619 error = close_err;
2621 if (worktree)
2622 got_worktree_close(worktree);
2623 TAILQ_FOREACH(pe, &refs, entry) {
2624 free((void *)pe->path);
2625 free(pe->data);
2627 got_pathlist_free(&refs);
2628 TAILQ_FOREACH(pe, &symrefs, entry) {
2629 free((void *)pe->path);
2630 free(pe->data);
2632 got_pathlist_free(&symrefs);
2633 got_pathlist_free(&wanted_branches);
2634 got_pathlist_free(&wanted_refs);
2635 free(id_str);
2636 free(cwd);
2637 free(repo_path);
2638 free(pack_hash);
2639 free(proto);
2640 free(host);
2641 free(port);
2642 free(server_path);
2643 free(repo_name);
2644 return error;
2648 __dead static void
2649 usage_checkout(void)
2651 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2652 "[-p prefix] [-q] repository-path [worktree-path]\n",
2653 getprogname());
2654 exit(1);
2657 static void
2658 show_worktree_base_ref_warning(void)
2660 fprintf(stderr, "%s: warning: could not create a reference "
2661 "to the work tree's base commit; the commit could be "
2662 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2663 "repository writable and running 'got update' will prevent this\n",
2664 getprogname());
2667 struct got_checkout_progress_arg {
2668 const char *worktree_path;
2669 int had_base_commit_ref_error;
2670 int verbosity;
2673 static const struct got_error *
2674 checkout_progress(void *arg, unsigned char status, const char *path)
2676 struct got_checkout_progress_arg *a = arg;
2678 /* Base commit bump happens silently. */
2679 if (status == GOT_STATUS_BUMP_BASE)
2680 return NULL;
2682 if (status == GOT_STATUS_BASE_REF_ERR) {
2683 a->had_base_commit_ref_error = 1;
2684 return NULL;
2687 while (path[0] == '/')
2688 path++;
2690 if (a->verbosity >= 0)
2691 printf("%c %s/%s\n", status, a->worktree_path, path);
2693 return NULL;
2696 static const struct got_error *
2697 check_cancelled(void *arg)
2699 if (sigint_received || sigpipe_received)
2700 return got_error(GOT_ERR_CANCELLED);
2701 return NULL;
2704 static const struct got_error *
2705 check_linear_ancestry(struct got_object_id *commit_id,
2706 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2707 struct got_repository *repo)
2709 const struct got_error *err = NULL;
2710 struct got_object_id *yca_id;
2712 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2713 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2714 if (err)
2715 return err;
2717 if (yca_id == NULL)
2718 return got_error(GOT_ERR_ANCESTRY);
2721 * Require a straight line of history between the target commit
2722 * and the work tree's base commit.
2724 * Non-linear situations such as this require a rebase:
2726 * (commit) D F (base_commit)
2727 * \ /
2728 * C E
2729 * \ /
2730 * B (yca)
2731 * |
2732 * A
2734 * 'got update' only handles linear cases:
2735 * Update forwards in time: A (base/yca) - B - C - D (commit)
2736 * Update backwards in time: D (base) - C - B - A (commit/yca)
2738 if (allow_forwards_in_time_only) {
2739 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2740 return got_error(GOT_ERR_ANCESTRY);
2741 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2742 got_object_id_cmp(base_commit_id, yca_id) != 0)
2743 return got_error(GOT_ERR_ANCESTRY);
2745 free(yca_id);
2746 return NULL;
2749 static const struct got_error *
2750 check_same_branch(struct got_object_id *commit_id,
2751 struct got_reference *head_ref, struct got_object_id *yca_id,
2752 struct got_repository *repo)
2754 const struct got_error *err = NULL;
2755 struct got_commit_graph *graph = NULL;
2756 struct got_object_id *head_commit_id = NULL;
2757 int is_same_branch = 0;
2759 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2760 if (err)
2761 goto done;
2763 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2764 is_same_branch = 1;
2765 goto done;
2767 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2768 is_same_branch = 1;
2769 goto done;
2772 err = got_commit_graph_open(&graph, "/", 1);
2773 if (err)
2774 goto done;
2776 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2777 check_cancelled, NULL);
2778 if (err)
2779 goto done;
2781 for (;;) {
2782 struct got_object_id *id;
2783 err = got_commit_graph_iter_next(&id, graph, repo,
2784 check_cancelled, NULL);
2785 if (err) {
2786 if (err->code == GOT_ERR_ITER_COMPLETED)
2787 err = NULL;
2788 break;
2791 if (id) {
2792 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2793 break;
2794 if (got_object_id_cmp(id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 break;
2800 done:
2801 if (graph)
2802 got_commit_graph_close(graph);
2803 free(head_commit_id);
2804 if (!err && !is_same_branch)
2805 err = got_error(GOT_ERR_ANCESTRY);
2806 return err;
2809 static const struct got_error *
2810 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2812 static char msg[512];
2813 const char *branch_name;
2815 if (got_ref_is_symbolic(ref))
2816 branch_name = got_ref_get_symref_target(ref);
2817 else
2818 branch_name = got_ref_get_name(ref);
2820 if (strncmp("refs/heads/", branch_name, 11) == 0)
2821 branch_name += 11;
2823 snprintf(msg, sizeof(msg),
2824 "target commit is not contained in branch '%s'; "
2825 "the branch to use must be specified with -b; "
2826 "if necessary a new branch can be created for "
2827 "this commit with 'got branch -c %s BRANCH_NAME'",
2828 branch_name, commit_id_str);
2830 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2833 static const struct got_error *
2834 cmd_checkout(int argc, char *argv[])
2836 const struct got_error *error = NULL;
2837 struct got_repository *repo = NULL;
2838 struct got_reference *head_ref = NULL, *ref = NULL;
2839 struct got_worktree *worktree = NULL;
2840 char *repo_path = NULL;
2841 char *worktree_path = NULL;
2842 const char *path_prefix = "";
2843 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2844 char *commit_id_str = NULL;
2845 struct got_object_id *commit_id = NULL;
2846 char *cwd = NULL;
2847 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2848 struct got_pathlist_head paths;
2849 struct got_checkout_progress_arg cpa;
2851 TAILQ_INIT(&paths);
2853 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2854 switch (ch) {
2855 case 'b':
2856 branch_name = optarg;
2857 break;
2858 case 'c':
2859 commit_id_str = strdup(optarg);
2860 if (commit_id_str == NULL)
2861 return got_error_from_errno("strdup");
2862 break;
2863 case 'E':
2864 allow_nonempty = 1;
2865 break;
2866 case 'p':
2867 path_prefix = optarg;
2868 break;
2869 case 'q':
2870 verbosity = -1;
2871 break;
2872 default:
2873 usage_checkout();
2874 /* NOTREACHED */
2878 argc -= optind;
2879 argv += optind;
2881 #ifndef PROFILE
2882 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2883 "unveil", NULL) == -1)
2884 err(1, "pledge");
2885 #endif
2886 if (argc == 1) {
2887 char *base, *dotgit;
2888 const char *path;
2889 repo_path = realpath(argv[0], NULL);
2890 if (repo_path == NULL)
2891 return got_error_from_errno2("realpath", argv[0]);
2892 cwd = getcwd(NULL, 0);
2893 if (cwd == NULL) {
2894 error = got_error_from_errno("getcwd");
2895 goto done;
2897 if (path_prefix[0])
2898 path = path_prefix;
2899 else
2900 path = repo_path;
2901 error = got_path_basename(&base, path);
2902 if (error)
2903 goto done;
2904 dotgit = strstr(base, ".git");
2905 if (dotgit)
2906 *dotgit = '\0';
2907 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2908 error = got_error_from_errno("asprintf");
2909 free(base);
2910 goto done;
2912 free(base);
2913 } else if (argc == 2) {
2914 repo_path = realpath(argv[0], NULL);
2915 if (repo_path == NULL) {
2916 error = got_error_from_errno2("realpath", argv[0]);
2917 goto done;
2919 worktree_path = realpath(argv[1], NULL);
2920 if (worktree_path == NULL) {
2921 if (errno != ENOENT) {
2922 error = got_error_from_errno2("realpath",
2923 argv[1]);
2924 goto done;
2926 worktree_path = strdup(argv[1]);
2927 if (worktree_path == NULL) {
2928 error = got_error_from_errno("strdup");
2929 goto done;
2932 } else
2933 usage_checkout();
2935 got_path_strip_trailing_slashes(repo_path);
2936 got_path_strip_trailing_slashes(worktree_path);
2938 error = got_repo_open(&repo, repo_path, NULL);
2939 if (error != NULL)
2940 goto done;
2942 /* Pre-create work tree path for unveil(2) */
2943 error = got_path_mkdir(worktree_path);
2944 if (error) {
2945 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2946 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2947 goto done;
2948 if (!allow_nonempty &&
2949 !got_path_dir_is_empty(worktree_path)) {
2950 error = got_error_path(worktree_path,
2951 GOT_ERR_DIR_NOT_EMPTY);
2952 goto done;
2956 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2957 if (error)
2958 goto done;
2960 error = got_ref_open(&head_ref, repo, branch_name, 0);
2961 if (error != NULL)
2962 goto done;
2964 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2965 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2966 goto done;
2968 error = got_worktree_open(&worktree, worktree_path);
2969 if (error != NULL)
2970 goto done;
2972 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2973 path_prefix);
2974 if (error != NULL)
2975 goto done;
2976 if (!same_path_prefix) {
2977 error = got_error(GOT_ERR_PATH_PREFIX);
2978 goto done;
2981 if (commit_id_str) {
2982 struct got_reflist_head refs;
2983 TAILQ_INIT(&refs);
2984 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2985 NULL);
2986 if (error)
2987 goto done;
2988 error = got_repo_match_object_id(&commit_id, NULL,
2989 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2990 got_ref_list_free(&refs);
2991 if (error)
2992 goto done;
2993 error = check_linear_ancestry(commit_id,
2994 got_worktree_get_base_commit_id(worktree), 0, repo);
2995 if (error != NULL) {
2996 free(commit_id);
2997 if (error->code == GOT_ERR_ANCESTRY) {
2998 error = checkout_ancestry_error(
2999 head_ref, commit_id_str);
3001 goto done;
3003 error = check_same_branch(commit_id, head_ref, NULL, repo);
3004 if (error) {
3005 if (error->code == GOT_ERR_ANCESTRY) {
3006 error = checkout_ancestry_error(
3007 head_ref, commit_id_str);
3009 goto done;
3011 error = got_worktree_set_base_commit_id(worktree, repo,
3012 commit_id);
3013 if (error)
3014 goto done;
3015 /* Expand potentially abbreviated commit ID string. */
3016 free(commit_id_str);
3017 error = got_object_id_str(&commit_id_str, commit_id);
3018 if (error)
3019 goto done;
3020 } else {
3021 commit_id = got_object_id_dup(
3022 got_worktree_get_base_commit_id(worktree));
3023 if (commit_id == NULL) {
3024 error = got_error_from_errno("got_object_id_dup");
3025 goto done;
3027 error = got_object_id_str(&commit_id_str, commit_id);
3028 if (error)
3029 goto done;
3032 error = got_pathlist_append(&paths, "", NULL);
3033 if (error)
3034 goto done;
3035 cpa.worktree_path = worktree_path;
3036 cpa.had_base_commit_ref_error = 0;
3037 cpa.verbosity = verbosity;
3038 error = got_worktree_checkout_files(worktree, &paths, repo,
3039 checkout_progress, &cpa, check_cancelled, NULL);
3040 if (error != NULL)
3041 goto done;
3043 if (got_ref_is_symbolic(head_ref)) {
3044 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3045 if (error)
3046 goto done;
3047 refname = got_ref_get_name(ref);
3048 } else
3049 refname = got_ref_get_name(head_ref);
3050 printf("Checked out %s: %s\n", refname, commit_id_str);
3051 printf("Now shut up and hack\n");
3052 if (cpa.had_base_commit_ref_error)
3053 show_worktree_base_ref_warning();
3054 done:
3055 if (head_ref)
3056 got_ref_close(head_ref);
3057 if (ref)
3058 got_ref_close(ref);
3059 got_pathlist_free(&paths);
3060 free(commit_id_str);
3061 free(commit_id);
3062 free(repo_path);
3063 free(worktree_path);
3064 free(cwd);
3065 return error;
3068 struct got_update_progress_arg {
3069 int did_something;
3070 int conflicts;
3071 int obstructed;
3072 int not_updated;
3073 int missing;
3074 int not_deleted;
3075 int unversioned;
3076 int verbosity;
3079 void
3080 print_update_progress_stats(struct got_update_progress_arg *upa)
3082 if (!upa->did_something)
3083 return;
3085 if (upa->conflicts > 0)
3086 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3087 if (upa->obstructed > 0)
3088 printf("File paths obstructed by a non-regular file: %d\n",
3089 upa->obstructed);
3090 if (upa->not_updated > 0)
3091 printf("Files not updated because of existing merge "
3092 "conflicts: %d\n", upa->not_updated);
3096 * The meaning of some status codes differs between merge-style operations and
3097 * update operations. For example, the ! status code means "file was missing"
3098 * if changes were merged into the work tree, and "missing file was restored"
3099 * if the work tree was updated. This function should be used by any operation
3100 * which merges changes into the work tree without updating the work tree.
3102 void
3103 print_merge_progress_stats(struct got_update_progress_arg *upa)
3105 if (!upa->did_something)
3106 return;
3108 if (upa->conflicts > 0)
3109 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3110 if (upa->obstructed > 0)
3111 printf("File paths obstructed by a non-regular file: %d\n",
3112 upa->obstructed);
3113 if (upa->missing > 0)
3114 printf("Files which had incoming changes but could not be "
3115 "found in the work tree: %d\n", upa->missing);
3116 if (upa->not_deleted > 0)
3117 printf("Files not deleted due to differences in deleted "
3118 "content: %d\n", upa->not_deleted);
3119 if (upa->unversioned > 0)
3120 printf("Files not merged because an unversioned file was "
3121 "found in the work tree: %d\n", upa->unversioned);
3124 __dead static void
3125 usage_update(void)
3127 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3128 "[path ...]\n",
3129 getprogname());
3130 exit(1);
3133 static const struct got_error *
3134 update_progress(void *arg, unsigned char status, const char *path)
3136 struct got_update_progress_arg *upa = arg;
3138 if (status == GOT_STATUS_EXISTS ||
3139 status == GOT_STATUS_BASE_REF_ERR)
3140 return NULL;
3142 upa->did_something = 1;
3144 /* Base commit bump happens silently. */
3145 if (status == GOT_STATUS_BUMP_BASE)
3146 return NULL;
3148 if (status == GOT_STATUS_CONFLICT)
3149 upa->conflicts++;
3150 if (status == GOT_STATUS_OBSTRUCTED)
3151 upa->obstructed++;
3152 if (status == GOT_STATUS_CANNOT_UPDATE)
3153 upa->not_updated++;
3154 if (status == GOT_STATUS_MISSING)
3155 upa->missing++;
3156 if (status == GOT_STATUS_CANNOT_DELETE)
3157 upa->not_deleted++;
3158 if (status == GOT_STATUS_UNVERSIONED)
3159 upa->unversioned++;
3161 while (path[0] == '/')
3162 path++;
3163 if (upa->verbosity >= 0)
3164 printf("%c %s\n", status, path);
3166 return NULL;
3169 static const struct got_error *
3170 switch_head_ref(struct got_reference *head_ref,
3171 struct got_object_id *commit_id, struct got_worktree *worktree,
3172 struct got_repository *repo)
3174 const struct got_error *err = NULL;
3175 char *base_id_str;
3176 int ref_has_moved = 0;
3178 /* Trivial case: switching between two different references. */
3179 if (strcmp(got_ref_get_name(head_ref),
3180 got_worktree_get_head_ref_name(worktree)) != 0) {
3181 printf("Switching work tree from %s to %s\n",
3182 got_worktree_get_head_ref_name(worktree),
3183 got_ref_get_name(head_ref));
3184 return got_worktree_set_head_ref(worktree, head_ref);
3187 err = check_linear_ancestry(commit_id,
3188 got_worktree_get_base_commit_id(worktree), 0, repo);
3189 if (err) {
3190 if (err->code != GOT_ERR_ANCESTRY)
3191 return err;
3192 ref_has_moved = 1;
3194 if (!ref_has_moved)
3195 return NULL;
3197 /* Switching to a rebased branch with the same reference name. */
3198 err = got_object_id_str(&base_id_str,
3199 got_worktree_get_base_commit_id(worktree));
3200 if (err)
3201 return err;
3202 printf("Reference %s now points at a different branch\n",
3203 got_worktree_get_head_ref_name(worktree));
3204 printf("Switching work tree from %s to %s\n", base_id_str,
3205 got_worktree_get_head_ref_name(worktree));
3206 return NULL;
3209 static const struct got_error *
3210 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3212 const struct got_error *err;
3213 int in_progress;
3215 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3216 if (err)
3217 return err;
3218 if (in_progress)
3219 return got_error(GOT_ERR_REBASING);
3221 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3222 if (err)
3223 return err;
3224 if (in_progress)
3225 return got_error(GOT_ERR_HISTEDIT_BUSY);
3227 return NULL;
3230 static const struct got_error *
3231 check_merge_in_progress(struct got_worktree *worktree,
3232 struct got_repository *repo)
3234 const struct got_error *err;
3235 int in_progress;
3237 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3238 if (err)
3239 return err;
3240 if (in_progress)
3241 return got_error(GOT_ERR_MERGE_BUSY);
3243 return NULL;
3246 static const struct got_error *
3247 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3248 char *argv[], struct got_worktree *worktree)
3250 const struct got_error *err = NULL;
3251 char *path;
3252 struct got_pathlist_entry *new;
3253 int i;
3255 if (argc == 0) {
3256 path = strdup("");
3257 if (path == NULL)
3258 return got_error_from_errno("strdup");
3259 return got_pathlist_append(paths, path, NULL);
3262 for (i = 0; i < argc; i++) {
3263 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3264 if (err)
3265 break;
3266 err = got_pathlist_insert(&new, paths, path, NULL);
3267 if (err || new == NULL /* duplicate */) {
3268 free(path);
3269 if (err)
3270 break;
3274 return err;
3277 static const struct got_error *
3278 wrap_not_worktree_error(const struct got_error *orig_err,
3279 const char *cmdname, const char *path)
3281 const struct got_error *err;
3282 struct got_repository *repo;
3283 static char msg[512];
3285 err = got_repo_open(&repo, path, NULL);
3286 if (err)
3287 return orig_err;
3289 snprintf(msg, sizeof(msg),
3290 "'got %s' needs a work tree in addition to a git repository\n"
3291 "Work trees can be checked out from this Git repository with "
3292 "'got checkout'.\n"
3293 "The got(1) manual page contains more information.", cmdname);
3294 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3295 got_repo_close(repo);
3296 return err;
3299 static const struct got_error *
3300 cmd_update(int argc, char *argv[])
3302 const struct got_error *error = NULL;
3303 struct got_repository *repo = NULL;
3304 struct got_worktree *worktree = NULL;
3305 char *worktree_path = NULL;
3306 struct got_object_id *commit_id = NULL;
3307 char *commit_id_str = NULL;
3308 const char *branch_name = NULL;
3309 struct got_reference *head_ref = NULL;
3310 struct got_pathlist_head paths;
3311 struct got_pathlist_entry *pe;
3312 int ch, verbosity = 0;
3313 struct got_update_progress_arg upa;
3315 TAILQ_INIT(&paths);
3317 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3318 switch (ch) {
3319 case 'b':
3320 branch_name = optarg;
3321 break;
3322 case 'c':
3323 commit_id_str = strdup(optarg);
3324 if (commit_id_str == NULL)
3325 return got_error_from_errno("strdup");
3326 break;
3327 case 'q':
3328 verbosity = -1;
3329 break;
3330 default:
3331 usage_update();
3332 /* NOTREACHED */
3336 argc -= optind;
3337 argv += optind;
3339 #ifndef PROFILE
3340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3341 "unveil", NULL) == -1)
3342 err(1, "pledge");
3343 #endif
3344 worktree_path = getcwd(NULL, 0);
3345 if (worktree_path == NULL) {
3346 error = got_error_from_errno("getcwd");
3347 goto done;
3349 error = got_worktree_open(&worktree, worktree_path);
3350 if (error) {
3351 if (error->code == GOT_ERR_NOT_WORKTREE)
3352 error = wrap_not_worktree_error(error, "update",
3353 worktree_path);
3354 goto done;
3357 error = check_rebase_or_histedit_in_progress(worktree);
3358 if (error)
3359 goto done;
3361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3362 NULL);
3363 if (error != NULL)
3364 goto done;
3366 error = apply_unveil(got_repo_get_path(repo), 0,
3367 got_worktree_get_root_path(worktree));
3368 if (error)
3369 goto done;
3371 error = check_merge_in_progress(worktree, repo);
3372 if (error)
3373 goto done;
3375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3376 if (error)
3377 goto done;
3379 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3380 got_worktree_get_head_ref_name(worktree), 0);
3381 if (error != NULL)
3382 goto done;
3383 if (commit_id_str == NULL) {
3384 error = got_ref_resolve(&commit_id, repo, head_ref);
3385 if (error != NULL)
3386 goto done;
3387 error = got_object_id_str(&commit_id_str, commit_id);
3388 if (error != NULL)
3389 goto done;
3390 } else {
3391 struct got_reflist_head refs;
3392 TAILQ_INIT(&refs);
3393 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3394 NULL);
3395 if (error)
3396 goto done;
3397 error = got_repo_match_object_id(&commit_id, NULL,
3398 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3399 got_ref_list_free(&refs);
3400 free(commit_id_str);
3401 commit_id_str = NULL;
3402 if (error)
3403 goto done;
3404 error = got_object_id_str(&commit_id_str, commit_id);
3405 if (error)
3406 goto done;
3409 if (branch_name) {
3410 struct got_object_id *head_commit_id;
3411 TAILQ_FOREACH(pe, &paths, entry) {
3412 if (pe->path_len == 0)
3413 continue;
3414 error = got_error_msg(GOT_ERR_BAD_PATH,
3415 "switching between branches requires that "
3416 "the entire work tree gets updated");
3417 goto done;
3419 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3420 if (error)
3421 goto done;
3422 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3423 repo);
3424 free(head_commit_id);
3425 if (error != NULL)
3426 goto done;
3427 error = check_same_branch(commit_id, head_ref, NULL, repo);
3428 if (error)
3429 goto done;
3430 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3431 if (error)
3432 goto done;
3433 } else {
3434 error = check_linear_ancestry(commit_id,
3435 got_worktree_get_base_commit_id(worktree), 0, repo);
3436 if (error != NULL) {
3437 if (error->code == GOT_ERR_ANCESTRY)
3438 error = got_error(GOT_ERR_BRANCH_MOVED);
3439 goto done;
3441 error = check_same_branch(commit_id, head_ref, NULL, repo);
3442 if (error)
3443 goto done;
3446 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3447 commit_id) != 0) {
3448 error = got_worktree_set_base_commit_id(worktree, repo,
3449 commit_id);
3450 if (error)
3451 goto done;
3454 memset(&upa, 0, sizeof(upa));
3455 upa.verbosity = verbosity;
3456 error = got_worktree_checkout_files(worktree, &paths, repo,
3457 update_progress, &upa, check_cancelled, NULL);
3458 if (error != NULL)
3459 goto done;
3461 if (upa.did_something) {
3462 printf("Updated to %s: %s\n",
3463 got_worktree_get_head_ref_name(worktree), commit_id_str);
3464 } else
3465 printf("Already up-to-date\n");
3466 print_update_progress_stats(&upa);
3467 done:
3468 free(worktree_path);
3469 TAILQ_FOREACH(pe, &paths, entry)
3470 free((char *)pe->path);
3471 got_pathlist_free(&paths);
3472 free(commit_id);
3473 free(commit_id_str);
3474 return error;
3477 static const struct got_error *
3478 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3479 const char *path, int diff_context, int ignore_whitespace,
3480 int force_text_diff, struct got_repository *repo)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3485 if (blob_id1) {
3486 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3487 if (err)
3488 goto done;
3491 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3492 if (err)
3493 goto done;
3495 while (path[0] == '/')
3496 path++;
3497 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3498 diff_context, ignore_whitespace, force_text_diff, stdout);
3499 done:
3500 if (blob1)
3501 got_object_blob_close(blob1);
3502 got_object_blob_close(blob2);
3503 return err;
3506 static const struct got_error *
3507 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3508 const char *path, int diff_context, int ignore_whitespace,
3509 int force_text_diff, struct got_repository *repo)
3511 const struct got_error *err = NULL;
3512 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3513 struct got_diff_blob_output_unidiff_arg arg;
3515 if (tree_id1) {
3516 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3517 if (err)
3518 goto done;
3521 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3522 if (err)
3523 goto done;
3525 arg.diff_context = diff_context;
3526 arg.ignore_whitespace = ignore_whitespace;
3527 arg.force_text_diff = force_text_diff;
3528 arg.outfile = stdout;
3529 arg.line_offsets = NULL;
3530 arg.nlines = 0;
3531 while (path[0] == '/')
3532 path++;
3533 err = got_diff_tree(tree1, tree2, path, path, repo,
3534 got_diff_blob_output_unidiff, &arg, 1);
3535 done:
3536 if (tree1)
3537 got_object_tree_close(tree1);
3538 if (tree2)
3539 got_object_tree_close(tree2);
3540 return err;
3543 static const struct got_error *
3544 get_changed_paths(struct got_pathlist_head *paths,
3545 struct got_commit_object *commit, struct got_repository *repo)
3547 const struct got_error *err = NULL;
3548 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3549 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3550 struct got_object_qid *qid;
3552 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3553 if (qid != NULL) {
3554 struct got_commit_object *pcommit;
3555 err = got_object_open_as_commit(&pcommit, repo,
3556 qid->id);
3557 if (err)
3558 return err;
3560 tree_id1 = got_object_id_dup(
3561 got_object_commit_get_tree_id(pcommit));
3562 if (tree_id1 == NULL) {
3563 got_object_commit_close(pcommit);
3564 return got_error_from_errno("got_object_id_dup");
3566 got_object_commit_close(pcommit);
3570 if (tree_id1) {
3571 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3572 if (err)
3573 goto done;
3576 tree_id2 = got_object_commit_get_tree_id(commit);
3577 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3578 if (err)
3579 goto done;
3581 err = got_diff_tree(tree1, tree2, "", "", repo,
3582 got_diff_tree_collect_changed_paths, paths, 0);
3583 done:
3584 if (tree1)
3585 got_object_tree_close(tree1);
3586 if (tree2)
3587 got_object_tree_close(tree2);
3588 free(tree_id1);
3589 return err;
3592 static const struct got_error *
3593 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3594 const char *path, int diff_context, struct got_repository *repo)
3596 const struct got_error *err = NULL;
3597 struct got_commit_object *pcommit = NULL;
3598 char *id_str1 = NULL, *id_str2 = NULL;
3599 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3600 struct got_object_qid *qid;
3602 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3603 if (qid != NULL) {
3604 err = got_object_open_as_commit(&pcommit, repo,
3605 qid->id);
3606 if (err)
3607 return err;
3610 if (path && path[0] != '\0') {
3611 int obj_type;
3612 err = got_object_id_by_path(&obj_id2, repo, id, path);
3613 if (err)
3614 goto done;
3615 err = got_object_id_str(&id_str2, obj_id2);
3616 if (err) {
3617 free(obj_id2);
3618 goto done;
3620 if (pcommit) {
3621 err = got_object_id_by_path(&obj_id1, repo,
3622 qid->id, path);
3623 if (err) {
3624 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3625 free(obj_id2);
3626 goto done;
3628 } else {
3629 err = got_object_id_str(&id_str1, obj_id1);
3630 if (err) {
3631 free(obj_id2);
3632 goto done;
3636 err = got_object_get_type(&obj_type, repo, obj_id2);
3637 if (err) {
3638 free(obj_id2);
3639 goto done;
3641 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3642 switch (obj_type) {
3643 case GOT_OBJ_TYPE_BLOB:
3644 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3645 0, 0, repo);
3646 break;
3647 case GOT_OBJ_TYPE_TREE:
3648 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3649 0, 0, repo);
3650 break;
3651 default:
3652 err = got_error(GOT_ERR_OBJ_TYPE);
3653 break;
3655 free(obj_id1);
3656 free(obj_id2);
3657 } else {
3658 obj_id2 = got_object_commit_get_tree_id(commit);
3659 err = got_object_id_str(&id_str2, obj_id2);
3660 if (err)
3661 goto done;
3662 if (pcommit) {
3663 obj_id1 = got_object_commit_get_tree_id(pcommit);
3664 err = got_object_id_str(&id_str1, obj_id1);
3665 if (err)
3666 goto done;
3668 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3669 id_str2);
3670 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3671 repo);
3673 done:
3674 free(id_str1);
3675 free(id_str2);
3676 if (pcommit)
3677 got_object_commit_close(pcommit);
3678 return err;
3681 static char *
3682 get_datestr(time_t *time, char *datebuf)
3684 struct tm mytm, *tm;
3685 char *p, *s;
3687 tm = gmtime_r(time, &mytm);
3688 if (tm == NULL)
3689 return NULL;
3690 s = asctime_r(tm, datebuf);
3691 if (s == NULL)
3692 return NULL;
3693 p = strchr(s, '\n');
3694 if (p)
3695 *p = '\0';
3696 return s;
3699 static const struct got_error *
3700 match_logmsg(int *have_match, struct got_object_id *id,
3701 struct got_commit_object *commit, regex_t *regex)
3703 const struct got_error *err = NULL;
3704 regmatch_t regmatch;
3705 char *id_str = NULL, *logmsg = NULL;
3707 *have_match = 0;
3709 err = got_object_id_str(&id_str, id);
3710 if (err)
3711 return err;
3713 err = got_object_commit_get_logmsg(&logmsg, commit);
3714 if (err)
3715 goto done;
3717 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3718 *have_match = 1;
3719 done:
3720 free(id_str);
3721 free(logmsg);
3722 return err;
3725 static void
3726 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3727 regex_t *regex)
3729 regmatch_t regmatch;
3730 struct got_pathlist_entry *pe;
3732 *have_match = 0;
3734 TAILQ_FOREACH(pe, changed_paths, entry) {
3735 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3736 *have_match = 1;
3737 break;
3742 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3744 static const struct got_error*
3745 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3746 struct got_object_id *id, struct got_repository *repo)
3748 static const struct got_error *err = NULL;
3749 struct got_reflist_entry *re;
3750 char *s;
3751 const char *name;
3753 *refs_str = NULL;
3755 TAILQ_FOREACH(re, refs, entry) {
3756 struct got_tag_object *tag = NULL;
3757 struct got_object_id *ref_id;
3758 int cmp;
3760 name = got_ref_get_name(re->ref);
3761 if (strcmp(name, GOT_REF_HEAD) == 0)
3762 continue;
3763 if (strncmp(name, "refs/", 5) == 0)
3764 name += 5;
3765 if (strncmp(name, "got/", 4) == 0)
3766 continue;
3767 if (strncmp(name, "heads/", 6) == 0)
3768 name += 6;
3769 if (strncmp(name, "remotes/", 8) == 0) {
3770 name += 8;
3771 s = strstr(name, "/" GOT_REF_HEAD);
3772 if (s != NULL && s[strlen(s)] == '\0')
3773 continue;
3775 err = got_ref_resolve(&ref_id, repo, re->ref);
3776 if (err)
3777 break;
3778 if (strncmp(name, "tags/", 5) == 0) {
3779 err = got_object_open_as_tag(&tag, repo, ref_id);
3780 if (err) {
3781 if (err->code != GOT_ERR_OBJ_TYPE) {
3782 free(ref_id);
3783 break;
3785 /* Ref points at something other than a tag. */
3786 err = NULL;
3787 tag = NULL;
3790 cmp = got_object_id_cmp(tag ?
3791 got_object_tag_get_object_id(tag) : ref_id, id);
3792 free(ref_id);
3793 if (tag)
3794 got_object_tag_close(tag);
3795 if (cmp != 0)
3796 continue;
3797 s = *refs_str;
3798 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3799 s ? ", " : "", name) == -1) {
3800 err = got_error_from_errno("asprintf");
3801 free(s);
3802 *refs_str = NULL;
3803 break;
3805 free(s);
3808 return err;
3811 static const struct got_error *
3812 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3813 struct got_repository *repo, const char *path,
3814 struct got_pathlist_head *changed_paths, int show_patch,
3815 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3816 const char *custom_refs_str)
3818 const struct got_error *err = NULL;
3819 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3820 char datebuf[26];
3821 time_t committer_time;
3822 const char *author, *committer;
3823 char *refs_str = NULL;
3825 err = got_object_id_str(&id_str, id);
3826 if (err)
3827 return err;
3829 if (custom_refs_str == NULL) {
3830 struct got_reflist_head *refs;
3831 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3832 if (refs) {
3833 err = build_refs_str(&refs_str, refs, id, repo);
3834 if (err)
3835 goto done;
3839 printf(GOT_COMMIT_SEP_STR);
3840 if (custom_refs_str)
3841 printf("commit %s (%s)\n", id_str, custom_refs_str);
3842 else
3843 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3844 refs_str ? refs_str : "", refs_str ? ")" : "");
3845 free(id_str);
3846 id_str = NULL;
3847 free(refs_str);
3848 refs_str = NULL;
3849 printf("from: %s\n", got_object_commit_get_author(commit));
3850 committer_time = got_object_commit_get_committer_time(commit);
3851 datestr = get_datestr(&committer_time, datebuf);
3852 if (datestr)
3853 printf("date: %s UTC\n", datestr);
3854 author = got_object_commit_get_author(commit);
3855 committer = got_object_commit_get_committer(commit);
3856 if (strcmp(author, committer) != 0)
3857 printf("via: %s\n", committer);
3858 if (got_object_commit_get_nparents(commit) > 1) {
3859 const struct got_object_id_queue *parent_ids;
3860 struct got_object_qid *qid;
3861 int n = 1;
3862 parent_ids = got_object_commit_get_parent_ids(commit);
3863 STAILQ_FOREACH(qid, parent_ids, entry) {
3864 err = got_object_id_str(&id_str, qid->id);
3865 if (err)
3866 goto done;
3867 printf("parent %d: %s\n", n++, id_str);
3868 free(id_str);
3869 id_str = NULL;
3873 err = got_object_commit_get_logmsg(&logmsg0, commit);
3874 if (err)
3875 goto done;
3877 logmsg = logmsg0;
3878 do {
3879 line = strsep(&logmsg, "\n");
3880 if (line)
3881 printf(" %s\n", line);
3882 } while (line);
3883 free(logmsg0);
3885 if (changed_paths) {
3886 struct got_pathlist_entry *pe;
3887 TAILQ_FOREACH(pe, changed_paths, entry) {
3888 struct got_diff_changed_path *cp = pe->data;
3889 printf(" %c %s\n", cp->status, pe->path);
3891 printf("\n");
3893 if (show_patch) {
3894 err = print_patch(commit, id, path, diff_context, repo);
3895 if (err == 0)
3896 printf("\n");
3899 if (fflush(stdout) != 0 && err == NULL)
3900 err = got_error_from_errno("fflush");
3901 done:
3902 free(id_str);
3903 free(refs_str);
3904 return err;
3907 static const struct got_error *
3908 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3909 struct got_repository *repo, const char *path, int show_changed_paths,
3910 int show_patch, const char *search_pattern, int diff_context, int limit,
3911 int log_branches, int reverse_display_order,
3912 struct got_reflist_object_id_map *refs_idmap)
3914 const struct got_error *err;
3915 struct got_commit_graph *graph;
3916 regex_t regex;
3917 int have_match;
3918 struct got_object_id_queue reversed_commits;
3919 struct got_object_qid *qid;
3920 struct got_commit_object *commit;
3921 struct got_pathlist_head changed_paths;
3922 struct got_pathlist_entry *pe;
3924 STAILQ_INIT(&reversed_commits);
3925 TAILQ_INIT(&changed_paths);
3927 if (search_pattern && regcomp(&regex, search_pattern,
3928 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3929 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3931 err = got_commit_graph_open(&graph, path, !log_branches);
3932 if (err)
3933 return err;
3934 err = got_commit_graph_iter_start(graph, root_id, repo,
3935 check_cancelled, NULL);
3936 if (err)
3937 goto done;
3938 for (;;) {
3939 struct got_object_id *id;
3941 if (sigint_received || sigpipe_received)
3942 break;
3944 err = got_commit_graph_iter_next(&id, graph, repo,
3945 check_cancelled, NULL);
3946 if (err) {
3947 if (err->code == GOT_ERR_ITER_COMPLETED)
3948 err = NULL;
3949 break;
3951 if (id == NULL)
3952 break;
3954 err = got_object_open_as_commit(&commit, repo, id);
3955 if (err)
3956 break;
3958 if (show_changed_paths && !reverse_display_order) {
3959 err = get_changed_paths(&changed_paths, commit, repo);
3960 if (err)
3961 break;
3964 if (search_pattern) {
3965 err = match_logmsg(&have_match, id, commit, &regex);
3966 if (err) {
3967 got_object_commit_close(commit);
3968 break;
3970 if (have_match == 0 && show_changed_paths)
3971 match_changed_paths(&have_match,
3972 &changed_paths, &regex);
3973 if (have_match == 0) {
3974 got_object_commit_close(commit);
3975 TAILQ_FOREACH(pe, &changed_paths, entry) {
3976 free((char *)pe->path);
3977 free(pe->data);
3979 got_pathlist_free(&changed_paths);
3980 continue;
3984 if (reverse_display_order) {
3985 err = got_object_qid_alloc(&qid, id);
3986 if (err)
3987 break;
3988 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3989 got_object_commit_close(commit);
3990 } else {
3991 err = print_commit(commit, id, repo, path,
3992 show_changed_paths ? &changed_paths : NULL,
3993 show_patch, diff_context, refs_idmap, NULL);
3994 got_object_commit_close(commit);
3995 if (err)
3996 break;
3998 if ((limit && --limit == 0) ||
3999 (end_id && got_object_id_cmp(id, end_id) == 0))
4000 break;
4002 TAILQ_FOREACH(pe, &changed_paths, entry) {
4003 free((char *)pe->path);
4004 free(pe->data);
4006 got_pathlist_free(&changed_paths);
4008 if (reverse_display_order) {
4009 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4010 err = got_object_open_as_commit(&commit, repo, qid->id);
4011 if (err)
4012 break;
4013 if (show_changed_paths) {
4014 err = get_changed_paths(&changed_paths,
4015 commit, repo);
4016 if (err)
4017 break;
4019 err = print_commit(commit, qid->id, repo, path,
4020 show_changed_paths ? &changed_paths : NULL,
4021 show_patch, diff_context, refs_idmap, NULL);
4022 got_object_commit_close(commit);
4023 if (err)
4024 break;
4025 TAILQ_FOREACH(pe, &changed_paths, entry) {
4026 free((char *)pe->path);
4027 free(pe->data);
4029 got_pathlist_free(&changed_paths);
4032 done:
4033 while (!STAILQ_EMPTY(&reversed_commits)) {
4034 qid = STAILQ_FIRST(&reversed_commits);
4035 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4036 got_object_qid_free(qid);
4038 TAILQ_FOREACH(pe, &changed_paths, entry) {
4039 free((char *)pe->path);
4040 free(pe->data);
4042 got_pathlist_free(&changed_paths);
4043 if (search_pattern)
4044 regfree(&regex);
4045 got_commit_graph_close(graph);
4046 return err;
4049 __dead static void
4050 usage_log(void)
4052 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4053 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4054 "[-R] [path]\n", getprogname());
4055 exit(1);
4058 static int
4059 get_default_log_limit(void)
4061 const char *got_default_log_limit;
4062 long long n;
4063 const char *errstr;
4065 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4066 if (got_default_log_limit == NULL)
4067 return 0;
4068 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4069 if (errstr != NULL)
4070 return 0;
4071 return n;
4074 static const struct got_error *
4075 cmd_log(int argc, char *argv[])
4077 const struct got_error *error;
4078 struct got_repository *repo = NULL;
4079 struct got_worktree *worktree = NULL;
4080 struct got_object_id *start_id = NULL, *end_id = NULL;
4081 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4082 const char *start_commit = NULL, *end_commit = NULL;
4083 const char *search_pattern = NULL;
4084 int diff_context = -1, ch;
4085 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4086 int reverse_display_order = 0;
4087 const char *errstr;
4088 struct got_reflist_head refs;
4089 struct got_reflist_object_id_map *refs_idmap = NULL;
4091 TAILQ_INIT(&refs);
4093 #ifndef PROFILE
4094 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4095 NULL)
4096 == -1)
4097 err(1, "pledge");
4098 #endif
4100 limit = get_default_log_limit();
4102 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4103 switch (ch) {
4104 case 'p':
4105 show_patch = 1;
4106 break;
4107 case 'P':
4108 show_changed_paths = 1;
4109 break;
4110 case 'c':
4111 start_commit = optarg;
4112 break;
4113 case 'C':
4114 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4115 &errstr);
4116 if (errstr != NULL)
4117 errx(1, "number of context lines is %s: %s",
4118 errstr, optarg);
4119 break;
4120 case 'l':
4121 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4122 if (errstr != NULL)
4123 errx(1, "number of commits is %s: %s",
4124 errstr, optarg);
4125 break;
4126 case 'b':
4127 log_branches = 1;
4128 break;
4129 case 'r':
4130 repo_path = realpath(optarg, NULL);
4131 if (repo_path == NULL)
4132 return got_error_from_errno2("realpath",
4133 optarg);
4134 got_path_strip_trailing_slashes(repo_path);
4135 break;
4136 case 'R':
4137 reverse_display_order = 1;
4138 break;
4139 case 's':
4140 search_pattern = optarg;
4141 break;
4142 case 'x':
4143 end_commit = optarg;
4144 break;
4145 default:
4146 usage_log();
4147 /* NOTREACHED */
4151 argc -= optind;
4152 argv += optind;
4154 if (diff_context == -1)
4155 diff_context = 3;
4156 else if (!show_patch)
4157 errx(1, "-C requires -p");
4159 cwd = getcwd(NULL, 0);
4160 if (cwd == NULL) {
4161 error = got_error_from_errno("getcwd");
4162 goto done;
4165 if (repo_path == NULL) {
4166 error = got_worktree_open(&worktree, cwd);
4167 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4168 goto done;
4169 error = NULL;
4172 if (argc == 1) {
4173 if (worktree) {
4174 error = got_worktree_resolve_path(&path, worktree,
4175 argv[0]);
4176 if (error)
4177 goto done;
4178 } else {
4179 path = strdup(argv[0]);
4180 if (path == NULL) {
4181 error = got_error_from_errno("strdup");
4182 goto done;
4185 } else if (argc != 0)
4186 usage_log();
4188 if (repo_path == NULL) {
4189 repo_path = worktree ?
4190 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4192 if (repo_path == NULL) {
4193 error = got_error_from_errno("strdup");
4194 goto done;
4197 error = got_repo_open(&repo, repo_path, NULL);
4198 if (error != NULL)
4199 goto done;
4201 error = apply_unveil(got_repo_get_path(repo), 1,
4202 worktree ? got_worktree_get_root_path(worktree) : NULL);
4203 if (error)
4204 goto done;
4206 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4207 if (error)
4208 goto done;
4210 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4211 if (error)
4212 goto done;
4214 if (start_commit == NULL) {
4215 struct got_reference *head_ref;
4216 struct got_commit_object *commit = NULL;
4217 error = got_ref_open(&head_ref, repo,
4218 worktree ? got_worktree_get_head_ref_name(worktree)
4219 : GOT_REF_HEAD, 0);
4220 if (error != NULL)
4221 goto done;
4222 error = got_ref_resolve(&start_id, repo, head_ref);
4223 got_ref_close(head_ref);
4224 if (error != NULL)
4225 goto done;
4226 error = got_object_open_as_commit(&commit, repo,
4227 start_id);
4228 if (error != NULL)
4229 goto done;
4230 got_object_commit_close(commit);
4231 } else {
4232 error = got_repo_match_object_id(&start_id, NULL,
4233 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4234 if (error != NULL)
4235 goto done;
4237 if (end_commit != NULL) {
4238 error = got_repo_match_object_id(&end_id, NULL,
4239 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4240 if (error != NULL)
4241 goto done;
4244 if (worktree) {
4246 * If a path was specified on the command line it was resolved
4247 * to a path in the work tree above. Prepend the work tree's
4248 * path prefix to obtain the corresponding in-repository path.
4250 if (path) {
4251 const char *prefix;
4252 prefix = got_worktree_get_path_prefix(worktree);
4253 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4254 (path[0] != '\0') ? "/" : "", path) == -1) {
4255 error = got_error_from_errno("asprintf");
4256 goto done;
4259 } else
4260 error = got_repo_map_path(&in_repo_path, repo,
4261 path ? path : "");
4262 if (error != NULL)
4263 goto done;
4264 if (in_repo_path) {
4265 free(path);
4266 path = in_repo_path;
4269 error = print_commits(start_id, end_id, repo, path ? path : "",
4270 show_changed_paths, show_patch, search_pattern, diff_context,
4271 limit, log_branches, reverse_display_order, refs_idmap);
4272 done:
4273 free(path);
4274 free(repo_path);
4275 free(cwd);
4276 if (worktree)
4277 got_worktree_close(worktree);
4278 if (repo) {
4279 const struct got_error *close_err = got_repo_close(repo);
4280 if (error == NULL)
4281 error = close_err;
4283 if (refs_idmap)
4284 got_reflist_object_id_map_free(refs_idmap);
4285 got_ref_list_free(&refs);
4286 return error;
4289 __dead static void
4290 usage_diff(void)
4292 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4293 "[-r repository-path] [-s] [-w] [-P] "
4294 "[object1 object2 | path ...]\n", getprogname());
4295 exit(1);
4298 struct print_diff_arg {
4299 struct got_repository *repo;
4300 struct got_worktree *worktree;
4301 int diff_context;
4302 const char *id_str;
4303 int header_shown;
4304 int diff_staged;
4305 int ignore_whitespace;
4306 int force_text_diff;
4310 * Create a file which contains the target path of a symlink so we can feed
4311 * it as content to the diff engine.
4313 static const struct got_error *
4314 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4315 const char *abspath)
4317 const struct got_error *err = NULL;
4318 char target_path[PATH_MAX];
4319 ssize_t target_len, outlen;
4321 *fd = -1;
4323 if (dirfd != -1) {
4324 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4325 if (target_len == -1)
4326 return got_error_from_errno2("readlinkat", abspath);
4327 } else {
4328 target_len = readlink(abspath, target_path, PATH_MAX);
4329 if (target_len == -1)
4330 return got_error_from_errno2("readlink", abspath);
4333 *fd = got_opentempfd();
4334 if (*fd == -1)
4335 return got_error_from_errno("got_opentempfd");
4337 outlen = write(*fd, target_path, target_len);
4338 if (outlen == -1) {
4339 err = got_error_from_errno("got_opentempfd");
4340 goto done;
4343 if (lseek(*fd, 0, SEEK_SET) == -1) {
4344 err = got_error_from_errno2("lseek", abspath);
4345 goto done;
4347 done:
4348 if (err) {
4349 close(*fd);
4350 *fd = -1;
4352 return err;
4355 static const struct got_error *
4356 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4357 const char *path, struct got_object_id *blob_id,
4358 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4359 int dirfd, const char *de_name)
4361 struct print_diff_arg *a = arg;
4362 const struct got_error *err = NULL;
4363 struct got_blob_object *blob1 = NULL;
4364 int fd = -1;
4365 FILE *f2 = NULL;
4366 char *abspath = NULL, *label1 = NULL;
4367 struct stat sb;
4369 if (a->diff_staged) {
4370 if (staged_status != GOT_STATUS_MODIFY &&
4371 staged_status != GOT_STATUS_ADD &&
4372 staged_status != GOT_STATUS_DELETE)
4373 return NULL;
4374 } else {
4375 if (staged_status == GOT_STATUS_DELETE)
4376 return NULL;
4377 if (status == GOT_STATUS_NONEXISTENT)
4378 return got_error_set_errno(ENOENT, path);
4379 if (status != GOT_STATUS_MODIFY &&
4380 status != GOT_STATUS_ADD &&
4381 status != GOT_STATUS_DELETE &&
4382 status != GOT_STATUS_CONFLICT)
4383 return NULL;
4386 if (!a->header_shown) {
4387 printf("diff %s %s%s\n", a->id_str,
4388 got_worktree_get_root_path(a->worktree),
4389 a->diff_staged ? " (staged changes)" : "");
4390 a->header_shown = 1;
4393 if (a->diff_staged) {
4394 const char *label1 = NULL, *label2 = NULL;
4395 switch (staged_status) {
4396 case GOT_STATUS_MODIFY:
4397 label1 = path;
4398 label2 = path;
4399 break;
4400 case GOT_STATUS_ADD:
4401 label2 = path;
4402 break;
4403 case GOT_STATUS_DELETE:
4404 label1 = path;
4405 break;
4406 default:
4407 return got_error(GOT_ERR_FILE_STATUS);
4409 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4410 staged_blob_id, label1, label2, a->diff_context,
4411 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4414 if (staged_status == GOT_STATUS_ADD ||
4415 staged_status == GOT_STATUS_MODIFY) {
4416 char *id_str;
4417 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4418 8192);
4419 if (err)
4420 goto done;
4421 err = got_object_id_str(&id_str, staged_blob_id);
4422 if (err)
4423 goto done;
4424 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4425 err = got_error_from_errno("asprintf");
4426 free(id_str);
4427 goto done;
4429 free(id_str);
4430 } else if (status != GOT_STATUS_ADD) {
4431 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4432 if (err)
4433 goto done;
4436 if (status != GOT_STATUS_DELETE) {
4437 if (asprintf(&abspath, "%s/%s",
4438 got_worktree_get_root_path(a->worktree), path) == -1) {
4439 err = got_error_from_errno("asprintf");
4440 goto done;
4443 if (dirfd != -1) {
4444 fd = openat(dirfd, de_name,
4445 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4446 if (fd == -1) {
4447 if (!got_err_open_nofollow_on_symlink()) {
4448 err = got_error_from_errno2("openat",
4449 abspath);
4450 goto done;
4452 err = get_symlink_target_file(&fd, dirfd,
4453 de_name, abspath);
4454 if (err)
4455 goto done;
4457 } else {
4458 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4459 if (fd == -1) {
4460 if (!got_err_open_nofollow_on_symlink()) {
4461 err = got_error_from_errno2("open",
4462 abspath);
4463 goto done;
4465 err = get_symlink_target_file(&fd, dirfd,
4466 de_name, abspath);
4467 if (err)
4468 goto done;
4471 if (fstat(fd, &sb) == -1) {
4472 err = got_error_from_errno2("fstat", abspath);
4473 goto done;
4475 f2 = fdopen(fd, "r");
4476 if (f2 == NULL) {
4477 err = got_error_from_errno2("fdopen", abspath);
4478 goto done;
4480 fd = -1;
4481 } else
4482 sb.st_size = 0;
4484 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4485 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4486 done:
4487 if (blob1)
4488 got_object_blob_close(blob1);
4489 if (f2 && fclose(f2) == EOF && err == NULL)
4490 err = got_error_from_errno("fclose");
4491 if (fd != -1 && close(fd) == -1 && err == NULL)
4492 err = got_error_from_errno("close");
4493 free(abspath);
4494 return err;
4497 static const struct got_error *
4498 cmd_diff(int argc, char *argv[])
4500 const struct got_error *error;
4501 struct got_repository *repo = NULL;
4502 struct got_worktree *worktree = NULL;
4503 char *cwd = NULL, *repo_path = NULL;
4504 const char *commit_args[2] = { NULL, NULL };
4505 int ncommit_args = 0;
4506 struct got_object_id *ids[2] = { NULL, NULL };
4507 char *labels[2] = { NULL, NULL };
4508 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4509 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4510 int force_text_diff = 0, force_path = 0, rflag = 0;
4511 const char *errstr;
4512 struct got_reflist_head refs;
4513 struct got_pathlist_head paths;
4514 struct got_pathlist_entry *pe;
4516 TAILQ_INIT(&refs);
4517 TAILQ_INIT(&paths);
4519 #ifndef PROFILE
4520 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4521 NULL) == -1)
4522 err(1, "pledge");
4523 #endif
4525 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4526 switch (ch) {
4527 case 'a':
4528 force_text_diff = 1;
4529 break;
4530 case 'c':
4531 if (ncommit_args >= 2)
4532 errx(1, "too many -c options used");
4533 commit_args[ncommit_args++] = optarg;
4534 break;
4535 case 'C':
4536 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4537 &errstr);
4538 if (errstr != NULL)
4539 errx(1, "number of context lines is %s: %s",
4540 errstr, optarg);
4541 break;
4542 case 'r':
4543 repo_path = realpath(optarg, NULL);
4544 if (repo_path == NULL)
4545 return got_error_from_errno2("realpath",
4546 optarg);
4547 got_path_strip_trailing_slashes(repo_path);
4548 rflag = 1;
4549 break;
4550 case 's':
4551 diff_staged = 1;
4552 break;
4553 case 'w':
4554 ignore_whitespace = 1;
4555 break;
4556 case 'P':
4557 force_path = 1;
4558 break;
4559 default:
4560 usage_diff();
4561 /* NOTREACHED */
4565 argc -= optind;
4566 argv += optind;
4568 cwd = getcwd(NULL, 0);
4569 if (cwd == NULL) {
4570 error = got_error_from_errno("getcwd");
4571 goto done;
4574 if (repo_path == NULL) {
4575 error = got_worktree_open(&worktree, cwd);
4576 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4577 goto done;
4578 else
4579 error = NULL;
4580 if (worktree) {
4581 repo_path =
4582 strdup(got_worktree_get_repo_path(worktree));
4583 if (repo_path == NULL) {
4584 error = got_error_from_errno("strdup");
4585 goto done;
4587 } else {
4588 repo_path = strdup(cwd);
4589 if (repo_path == NULL) {
4590 error = got_error_from_errno("strdup");
4591 goto done;
4596 error = got_repo_open(&repo, repo_path, NULL);
4597 free(repo_path);
4598 if (error != NULL)
4599 goto done;
4601 if (rflag || worktree == NULL || ncommit_args > 0) {
4602 if (force_path) {
4603 error = got_error_msg(GOT_ERR_NOT_IMPL,
4604 "-P option can only be used when diffing "
4605 "a work tree");
4606 goto done;
4608 if (diff_staged) {
4609 error = got_error_msg(GOT_ERR_NOT_IMPL,
4610 "-s option can only be used when diffing "
4611 "a work tree");
4612 goto done;
4616 error = apply_unveil(got_repo_get_path(repo), 1,
4617 worktree ? got_worktree_get_root_path(worktree) : NULL);
4618 if (error)
4619 goto done;
4621 if ((!force_path && argc == 2) || ncommit_args > 0) {
4622 int obj_type = (ncommit_args > 0 ?
4623 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4624 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4625 NULL);
4626 if (error)
4627 goto done;
4628 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4629 const char *arg;
4630 if (ncommit_args > 0)
4631 arg = commit_args[i];
4632 else
4633 arg = argv[i];
4634 error = got_repo_match_object_id(&ids[i], &labels[i],
4635 arg, obj_type, &refs, repo);
4636 if (error) {
4637 if (error->code != GOT_ERR_NOT_REF &&
4638 error->code != GOT_ERR_NO_OBJ)
4639 goto done;
4640 if (ncommit_args > 0)
4641 goto done;
4642 error = NULL;
4643 break;
4648 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4649 struct print_diff_arg arg;
4650 char *id_str;
4652 if (worktree == NULL) {
4653 if (argc == 2 && ids[0] == NULL) {
4654 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4655 goto done;
4656 } else if (argc == 2 && ids[1] == NULL) {
4657 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4658 goto done;
4659 } else if (argc > 0) {
4660 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4661 "%s", "specified paths cannot be resolved");
4662 goto done;
4663 } else {
4664 error = got_error(GOT_ERR_NOT_WORKTREE);
4665 goto done;
4669 error = get_worktree_paths_from_argv(&paths, argc, argv,
4670 worktree);
4671 if (error)
4672 goto done;
4674 error = got_object_id_str(&id_str,
4675 got_worktree_get_base_commit_id(worktree));
4676 if (error)
4677 goto done;
4678 arg.repo = repo;
4679 arg.worktree = worktree;
4680 arg.diff_context = diff_context;
4681 arg.id_str = id_str;
4682 arg.header_shown = 0;
4683 arg.diff_staged = diff_staged;
4684 arg.ignore_whitespace = ignore_whitespace;
4685 arg.force_text_diff = force_text_diff;
4687 error = got_worktree_status(worktree, &paths, repo, 0,
4688 print_diff, &arg, check_cancelled, NULL);
4689 free(id_str);
4690 goto done;
4693 if (ncommit_args == 1) {
4694 struct got_commit_object *commit;
4695 error = got_object_open_as_commit(&commit, repo, ids[0]);
4696 if (error)
4697 goto done;
4699 labels[1] = labels[0];
4700 ids[1] = ids[0];
4701 if (got_object_commit_get_nparents(commit) > 0) {
4702 const struct got_object_id_queue *pids;
4703 struct got_object_qid *pid;
4704 pids = got_object_commit_get_parent_ids(commit);
4705 pid = STAILQ_FIRST(pids);
4706 ids[0] = got_object_id_dup(pid->id);
4707 if (ids[0] == NULL) {
4708 error = got_error_from_errno(
4709 "got_object_id_dup");
4710 got_object_commit_close(commit);
4711 goto done;
4713 error = got_object_id_str(&labels[0], ids[0]);
4714 if (error) {
4715 got_object_commit_close(commit);
4716 goto done;
4718 } else {
4719 ids[0] = NULL;
4720 labels[0] = strdup("/dev/null");
4721 if (labels[0] == NULL) {
4722 error = got_error_from_errno("strdup");
4723 got_object_commit_close(commit);
4724 goto done;
4728 got_object_commit_close(commit);
4731 if (ncommit_args == 0 && argc > 2) {
4732 error = got_error_msg(GOT_ERR_BAD_PATH,
4733 "path arguments cannot be used when diffing two objects");
4734 goto done;
4737 if (ids[0]) {
4738 error = got_object_get_type(&type1, repo, ids[0]);
4739 if (error)
4740 goto done;
4743 error = got_object_get_type(&type2, repo, ids[1]);
4744 if (error)
4745 goto done;
4746 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4747 error = got_error(GOT_ERR_OBJ_TYPE);
4748 goto done;
4750 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4751 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4752 "path arguments cannot be used when diffing blobs");
4753 goto done;
4756 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4757 char *in_repo_path;
4758 struct got_pathlist_entry *new;
4759 if (worktree) {
4760 const char *prefix;
4761 char *p;
4762 error = got_worktree_resolve_path(&p, worktree,
4763 argv[i]);
4764 if (error)
4765 goto done;
4766 prefix = got_worktree_get_path_prefix(worktree);
4767 while (prefix[0] == '/')
4768 prefix++;
4769 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4770 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4771 p) == -1) {
4772 error = got_error_from_errno("asprintf");
4773 free(p);
4774 goto done;
4776 free(p);
4777 } else {
4778 char *mapped_path, *s;
4779 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4780 if (error)
4781 goto done;
4782 s = mapped_path;
4783 while (s[0] == '/')
4784 s++;
4785 in_repo_path = strdup(s);
4786 if (in_repo_path == NULL) {
4787 error = got_error_from_errno("asprintf");
4788 free(mapped_path);
4789 goto done;
4791 free(mapped_path);
4794 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4795 if (error || new == NULL /* duplicate */)
4796 free(in_repo_path);
4797 if (error)
4798 goto done;
4801 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4802 case GOT_OBJ_TYPE_BLOB:
4803 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4804 NULL, NULL, diff_context, ignore_whitespace,
4805 force_text_diff, repo, stdout);
4806 break;
4807 case GOT_OBJ_TYPE_TREE:
4808 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4809 &paths, "", "", diff_context, ignore_whitespace,
4810 force_text_diff, repo, stdout);
4811 break;
4812 case GOT_OBJ_TYPE_COMMIT:
4813 printf("diff %s %s\n", labels[0], labels[1]);
4814 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4815 &paths, diff_context, ignore_whitespace, force_text_diff,
4816 repo, stdout);
4817 break;
4818 default:
4819 error = got_error(GOT_ERR_OBJ_TYPE);
4821 done:
4822 free(labels[0]);
4823 free(labels[1]);
4824 free(ids[0]);
4825 free(ids[1]);
4826 if (worktree)
4827 got_worktree_close(worktree);
4828 if (repo) {
4829 const struct got_error *close_err = got_repo_close(repo);
4830 if (error == NULL)
4831 error = close_err;
4833 TAILQ_FOREACH(pe, &paths, entry)
4834 free((char *)pe->path);
4835 got_pathlist_free(&paths);
4836 got_ref_list_free(&refs);
4837 return error;
4840 __dead static void
4841 usage_blame(void)
4843 fprintf(stderr,
4844 "usage: %s blame [-c commit] [-r repository-path] path\n",
4845 getprogname());
4846 exit(1);
4849 struct blame_line {
4850 int annotated;
4851 char *id_str;
4852 char *committer;
4853 char datebuf[11]; /* YYYY-MM-DD + NUL */
4856 struct blame_cb_args {
4857 struct blame_line *lines;
4858 int nlines;
4859 int nlines_prec;
4860 int lineno_cur;
4861 off_t *line_offsets;
4862 FILE *f;
4863 struct got_repository *repo;
4866 static const struct got_error *
4867 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4869 const struct got_error *err = NULL;
4870 struct blame_cb_args *a = arg;
4871 struct blame_line *bline;
4872 char *line = NULL;
4873 size_t linesize = 0;
4874 struct got_commit_object *commit = NULL;
4875 off_t offset;
4876 struct tm tm;
4877 time_t committer_time;
4879 if (nlines != a->nlines ||
4880 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4881 return got_error(GOT_ERR_RANGE);
4883 if (sigint_received)
4884 return got_error(GOT_ERR_ITER_COMPLETED);
4886 if (lineno == -1)
4887 return NULL; /* no change in this commit */
4889 /* Annotate this line. */
4890 bline = &a->lines[lineno - 1];
4891 if (bline->annotated)
4892 return NULL;
4893 err = got_object_id_str(&bline->id_str, id);
4894 if (err)
4895 return err;
4897 err = got_object_open_as_commit(&commit, a->repo, id);
4898 if (err)
4899 goto done;
4901 bline->committer = strdup(got_object_commit_get_committer(commit));
4902 if (bline->committer == NULL) {
4903 err = got_error_from_errno("strdup");
4904 goto done;
4907 committer_time = got_object_commit_get_committer_time(commit);
4908 if (gmtime_r(&committer_time, &tm) == NULL)
4909 return got_error_from_errno("gmtime_r");
4910 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4911 &tm) == 0) {
4912 err = got_error(GOT_ERR_NO_SPACE);
4913 goto done;
4915 bline->annotated = 1;
4917 /* Print lines annotated so far. */
4918 bline = &a->lines[a->lineno_cur - 1];
4919 if (!bline->annotated)
4920 goto done;
4922 offset = a->line_offsets[a->lineno_cur - 1];
4923 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4924 err = got_error_from_errno("fseeko");
4925 goto done;
4928 while (bline->annotated) {
4929 char *smallerthan, *at, *nl, *committer;
4930 size_t len;
4932 if (getline(&line, &linesize, a->f) == -1) {
4933 if (ferror(a->f))
4934 err = got_error_from_errno("getline");
4935 break;
4938 committer = bline->committer;
4939 smallerthan = strchr(committer, '<');
4940 if (smallerthan && smallerthan[1] != '\0')
4941 committer = smallerthan + 1;
4942 at = strchr(committer, '@');
4943 if (at)
4944 *at = '\0';
4945 len = strlen(committer);
4946 if (len >= 9)
4947 committer[8] = '\0';
4949 nl = strchr(line, '\n');
4950 if (nl)
4951 *nl = '\0';
4952 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4953 bline->id_str, bline->datebuf, committer, line);
4955 a->lineno_cur++;
4956 bline = &a->lines[a->lineno_cur - 1];
4958 done:
4959 if (commit)
4960 got_object_commit_close(commit);
4961 free(line);
4962 return err;
4965 static const struct got_error *
4966 cmd_blame(int argc, char *argv[])
4968 const struct got_error *error;
4969 struct got_repository *repo = NULL;
4970 struct got_worktree *worktree = NULL;
4971 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4972 char *link_target = NULL;
4973 struct got_object_id *obj_id = NULL;
4974 struct got_object_id *commit_id = NULL;
4975 struct got_blob_object *blob = NULL;
4976 char *commit_id_str = NULL;
4977 struct blame_cb_args bca;
4978 int ch, obj_type, i;
4979 off_t filesize;
4981 memset(&bca, 0, sizeof(bca));
4983 #ifndef PROFILE
4984 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4985 NULL) == -1)
4986 err(1, "pledge");
4987 #endif
4989 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4990 switch (ch) {
4991 case 'c':
4992 commit_id_str = optarg;
4993 break;
4994 case 'r':
4995 repo_path = realpath(optarg, NULL);
4996 if (repo_path == NULL)
4997 return got_error_from_errno2("realpath",
4998 optarg);
4999 got_path_strip_trailing_slashes(repo_path);
5000 break;
5001 default:
5002 usage_blame();
5003 /* NOTREACHED */
5007 argc -= optind;
5008 argv += optind;
5010 if (argc == 1)
5011 path = argv[0];
5012 else
5013 usage_blame();
5015 cwd = getcwd(NULL, 0);
5016 if (cwd == NULL) {
5017 error = got_error_from_errno("getcwd");
5018 goto done;
5020 if (repo_path == NULL) {
5021 error = got_worktree_open(&worktree, cwd);
5022 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5023 goto done;
5024 else
5025 error = NULL;
5026 if (worktree) {
5027 repo_path =
5028 strdup(got_worktree_get_repo_path(worktree));
5029 if (repo_path == NULL) {
5030 error = got_error_from_errno("strdup");
5031 if (error)
5032 goto done;
5034 } else {
5035 repo_path = strdup(cwd);
5036 if (repo_path == NULL) {
5037 error = got_error_from_errno("strdup");
5038 goto done;
5043 error = got_repo_open(&repo, repo_path, NULL);
5044 if (error != NULL)
5045 goto done;
5047 if (worktree) {
5048 const char *prefix = got_worktree_get_path_prefix(worktree);
5049 char *p;
5051 error = got_worktree_resolve_path(&p, worktree, path);
5052 if (error)
5053 goto done;
5054 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5055 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5056 p) == -1) {
5057 error = got_error_from_errno("asprintf");
5058 free(p);
5059 goto done;
5061 free(p);
5062 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5063 } else {
5064 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5065 if (error)
5066 goto done;
5067 error = got_repo_map_path(&in_repo_path, repo, path);
5069 if (error)
5070 goto done;
5072 if (commit_id_str == NULL) {
5073 struct got_reference *head_ref;
5074 error = got_ref_open(&head_ref, repo, worktree ?
5075 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5076 if (error != NULL)
5077 goto done;
5078 error = got_ref_resolve(&commit_id, repo, head_ref);
5079 got_ref_close(head_ref);
5080 if (error != NULL)
5081 goto done;
5082 } else {
5083 struct got_reflist_head refs;
5084 TAILQ_INIT(&refs);
5085 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5086 NULL);
5087 if (error)
5088 goto done;
5089 error = got_repo_match_object_id(&commit_id, NULL,
5090 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5091 got_ref_list_free(&refs);
5092 if (error)
5093 goto done;
5096 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5097 commit_id, repo);
5098 if (error)
5099 goto done;
5101 error = got_object_id_by_path(&obj_id, repo, commit_id,
5102 link_target ? link_target : in_repo_path);
5103 if (error)
5104 goto done;
5106 error = got_object_get_type(&obj_type, repo, obj_id);
5107 if (error)
5108 goto done;
5110 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5111 error = got_error_path(link_target ? link_target : in_repo_path,
5112 GOT_ERR_OBJ_TYPE);
5113 goto done;
5116 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5117 if (error)
5118 goto done;
5119 bca.f = got_opentemp();
5120 if (bca.f == NULL) {
5121 error = got_error_from_errno("got_opentemp");
5122 goto done;
5124 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5125 &bca.line_offsets, bca.f, blob);
5126 if (error || bca.nlines == 0)
5127 goto done;
5129 /* Don't include \n at EOF in the blame line count. */
5130 if (bca.line_offsets[bca.nlines - 1] == filesize)
5131 bca.nlines--;
5133 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5134 if (bca.lines == NULL) {
5135 error = got_error_from_errno("calloc");
5136 goto done;
5138 bca.lineno_cur = 1;
5139 bca.nlines_prec = 0;
5140 i = bca.nlines;
5141 while (i > 0) {
5142 i /= 10;
5143 bca.nlines_prec++;
5145 bca.repo = repo;
5147 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5148 repo, blame_cb, &bca, check_cancelled, NULL);
5149 done:
5150 free(in_repo_path);
5151 free(link_target);
5152 free(repo_path);
5153 free(cwd);
5154 free(commit_id);
5155 free(obj_id);
5156 if (blob)
5157 got_object_blob_close(blob);
5158 if (worktree)
5159 got_worktree_close(worktree);
5160 if (repo) {
5161 const struct got_error *close_err = got_repo_close(repo);
5162 if (error == NULL)
5163 error = close_err;
5165 if (bca.lines) {
5166 for (i = 0; i < bca.nlines; i++) {
5167 struct blame_line *bline = &bca.lines[i];
5168 free(bline->id_str);
5169 free(bline->committer);
5171 free(bca.lines);
5173 free(bca.line_offsets);
5174 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5175 error = got_error_from_errno("fclose");
5176 return error;
5179 __dead static void
5180 usage_tree(void)
5182 fprintf(stderr,
5183 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5184 getprogname());
5185 exit(1);
5188 static const struct got_error *
5189 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5190 const char *root_path, struct got_repository *repo)
5192 const struct got_error *err = NULL;
5193 int is_root_path = (strcmp(path, root_path) == 0);
5194 const char *modestr = "";
5195 mode_t mode = got_tree_entry_get_mode(te);
5196 char *link_target = NULL;
5198 path += strlen(root_path);
5199 while (path[0] == '/')
5200 path++;
5202 if (got_object_tree_entry_is_submodule(te))
5203 modestr = "$";
5204 else if (S_ISLNK(mode)) {
5205 int i;
5207 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5208 if (err)
5209 return err;
5210 for (i = 0; i < strlen(link_target); i++) {
5211 if (!isprint((unsigned char)link_target[i]))
5212 link_target[i] = '?';
5215 modestr = "@";
5217 else if (S_ISDIR(mode))
5218 modestr = "/";
5219 else if (mode & S_IXUSR)
5220 modestr = "*";
5222 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5223 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5224 link_target ? " -> ": "", link_target ? link_target : "");
5226 free(link_target);
5227 return NULL;
5230 static const struct got_error *
5231 print_tree(const char *path, struct got_object_id *commit_id,
5232 int show_ids, int recurse, const char *root_path,
5233 struct got_repository *repo)
5235 const struct got_error *err = NULL;
5236 struct got_object_id *tree_id = NULL;
5237 struct got_tree_object *tree = NULL;
5238 int nentries, i;
5240 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5241 if (err)
5242 goto done;
5244 err = got_object_open_as_tree(&tree, repo, tree_id);
5245 if (err)
5246 goto done;
5247 nentries = got_object_tree_get_nentries(tree);
5248 for (i = 0; i < nentries; i++) {
5249 struct got_tree_entry *te;
5250 char *id = NULL;
5252 if (sigint_received || sigpipe_received)
5253 break;
5255 te = got_object_tree_get_entry(tree, i);
5256 if (show_ids) {
5257 char *id_str;
5258 err = got_object_id_str(&id_str,
5259 got_tree_entry_get_id(te));
5260 if (err)
5261 goto done;
5262 if (asprintf(&id, "%s ", id_str) == -1) {
5263 err = got_error_from_errno("asprintf");
5264 free(id_str);
5265 goto done;
5267 free(id_str);
5269 err = print_entry(te, id, path, root_path, repo);
5270 free(id);
5271 if (err)
5272 goto done;
5274 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5275 char *child_path;
5276 if (asprintf(&child_path, "%s%s%s", path,
5277 path[0] == '/' && path[1] == '\0' ? "" : "/",
5278 got_tree_entry_get_name(te)) == -1) {
5279 err = got_error_from_errno("asprintf");
5280 goto done;
5282 err = print_tree(child_path, commit_id, show_ids, 1,
5283 root_path, repo);
5284 free(child_path);
5285 if (err)
5286 goto done;
5289 done:
5290 if (tree)
5291 got_object_tree_close(tree);
5292 free(tree_id);
5293 return err;
5296 static const struct got_error *
5297 cmd_tree(int argc, char *argv[])
5299 const struct got_error *error;
5300 struct got_repository *repo = NULL;
5301 struct got_worktree *worktree = NULL;
5302 const char *path, *refname = NULL;
5303 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5304 struct got_object_id *commit_id = NULL;
5305 char *commit_id_str = NULL;
5306 int show_ids = 0, recurse = 0;
5307 int ch;
5309 #ifndef PROFILE
5310 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5311 NULL) == -1)
5312 err(1, "pledge");
5313 #endif
5315 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5316 switch (ch) {
5317 case 'c':
5318 commit_id_str = optarg;
5319 break;
5320 case 'r':
5321 repo_path = realpath(optarg, NULL);
5322 if (repo_path == NULL)
5323 return got_error_from_errno2("realpath",
5324 optarg);
5325 got_path_strip_trailing_slashes(repo_path);
5326 break;
5327 case 'i':
5328 show_ids = 1;
5329 break;
5330 case 'R':
5331 recurse = 1;
5332 break;
5333 default:
5334 usage_tree();
5335 /* NOTREACHED */
5339 argc -= optind;
5340 argv += optind;
5342 if (argc == 1)
5343 path = argv[0];
5344 else if (argc > 1)
5345 usage_tree();
5346 else
5347 path = NULL;
5349 cwd = getcwd(NULL, 0);
5350 if (cwd == NULL) {
5351 error = got_error_from_errno("getcwd");
5352 goto done;
5354 if (repo_path == NULL) {
5355 error = got_worktree_open(&worktree, cwd);
5356 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5357 goto done;
5358 else
5359 error = NULL;
5360 if (worktree) {
5361 repo_path =
5362 strdup(got_worktree_get_repo_path(worktree));
5363 if (repo_path == NULL)
5364 error = got_error_from_errno("strdup");
5365 if (error)
5366 goto done;
5367 } else {
5368 repo_path = strdup(cwd);
5369 if (repo_path == NULL) {
5370 error = got_error_from_errno("strdup");
5371 goto done;
5376 error = got_repo_open(&repo, repo_path, NULL);
5377 if (error != NULL)
5378 goto done;
5380 if (worktree) {
5381 const char *prefix = got_worktree_get_path_prefix(worktree);
5382 char *p;
5384 if (path == NULL)
5385 path = "";
5386 error = got_worktree_resolve_path(&p, worktree, path);
5387 if (error)
5388 goto done;
5389 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5390 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5391 p) == -1) {
5392 error = got_error_from_errno("asprintf");
5393 free(p);
5394 goto done;
5396 free(p);
5397 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5398 if (error)
5399 goto done;
5400 } else {
5401 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5402 if (error)
5403 goto done;
5404 if (path == NULL)
5405 path = "/";
5406 error = got_repo_map_path(&in_repo_path, repo, path);
5407 if (error != NULL)
5408 goto done;
5411 if (commit_id_str == NULL) {
5412 struct got_reference *head_ref;
5413 if (worktree)
5414 refname = got_worktree_get_head_ref_name(worktree);
5415 else
5416 refname = GOT_REF_HEAD;
5417 error = got_ref_open(&head_ref, repo, refname, 0);
5418 if (error != NULL)
5419 goto done;
5420 error = got_ref_resolve(&commit_id, repo, head_ref);
5421 got_ref_close(head_ref);
5422 if (error != NULL)
5423 goto done;
5424 } else {
5425 struct got_reflist_head refs;
5426 TAILQ_INIT(&refs);
5427 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5428 NULL);
5429 if (error)
5430 goto done;
5431 error = got_repo_match_object_id(&commit_id, NULL,
5432 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5433 got_ref_list_free(&refs);
5434 if (error)
5435 goto done;
5438 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5439 in_repo_path, repo);
5440 done:
5441 free(in_repo_path);
5442 free(repo_path);
5443 free(cwd);
5444 free(commit_id);
5445 if (worktree)
5446 got_worktree_close(worktree);
5447 if (repo) {
5448 const struct got_error *close_err = got_repo_close(repo);
5449 if (error == NULL)
5450 error = close_err;
5452 return error;
5455 __dead static void
5456 usage_status(void)
5458 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5459 "[-S status-codes] [path ...]\n", getprogname());
5460 exit(1);
5463 struct got_status_arg {
5464 char *status_codes;
5465 int suppress;
5468 static const struct got_error *
5469 print_status(void *arg, unsigned char status, unsigned char staged_status,
5470 const char *path, struct got_object_id *blob_id,
5471 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5472 int dirfd, const char *de_name)
5474 struct got_status_arg *st = arg;
5476 if (status == staged_status && (status == GOT_STATUS_DELETE))
5477 status = GOT_STATUS_NO_CHANGE;
5478 if (st != NULL && st->status_codes) {
5479 size_t ncodes = strlen(st->status_codes);
5480 int i, j = 0;
5482 for (i = 0; i < ncodes ; i++) {
5483 if (st->suppress) {
5484 if (status == st->status_codes[i] ||
5485 staged_status == st->status_codes[i]) {
5486 j++;
5487 continue;
5489 } else {
5490 if (status == st->status_codes[i] ||
5491 staged_status == st->status_codes[i])
5492 break;
5496 if (st->suppress && j == 0)
5497 goto print;
5499 if (i == ncodes)
5500 return NULL;
5502 print:
5503 printf("%c%c %s\n", status, staged_status, path);
5504 return NULL;
5507 static const struct got_error *
5508 cmd_status(int argc, char *argv[])
5510 const struct got_error *error = NULL;
5511 struct got_repository *repo = NULL;
5512 struct got_worktree *worktree = NULL;
5513 struct got_status_arg st;
5514 char *cwd = NULL;
5515 struct got_pathlist_head paths;
5516 struct got_pathlist_entry *pe;
5517 int ch, i, no_ignores = 0;
5519 TAILQ_INIT(&paths);
5521 memset(&st, 0, sizeof(st));
5522 st.status_codes = NULL;
5523 st.suppress = 0;
5525 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5526 switch (ch) {
5527 case 'I':
5528 no_ignores = 1;
5529 break;
5530 case 'S':
5531 if (st.status_codes != NULL && st.suppress == 0)
5532 option_conflict('S', 's');
5533 st.suppress = 1;
5534 /* fallthrough */
5535 case 's':
5536 for (i = 0; i < strlen(optarg); i++) {
5537 switch (optarg[i]) {
5538 case GOT_STATUS_MODIFY:
5539 case GOT_STATUS_ADD:
5540 case GOT_STATUS_DELETE:
5541 case GOT_STATUS_CONFLICT:
5542 case GOT_STATUS_MISSING:
5543 case GOT_STATUS_OBSTRUCTED:
5544 case GOT_STATUS_UNVERSIONED:
5545 case GOT_STATUS_MODE_CHANGE:
5546 case GOT_STATUS_NONEXISTENT:
5547 break;
5548 default:
5549 errx(1, "invalid status code '%c'",
5550 optarg[i]);
5553 if (ch == 's' && st.suppress)
5554 option_conflict('s', 'S');
5555 st.status_codes = optarg;
5556 break;
5557 default:
5558 usage_status();
5559 /* NOTREACHED */
5563 argc -= optind;
5564 argv += optind;
5566 #ifndef PROFILE
5567 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5568 NULL) == -1)
5569 err(1, "pledge");
5570 #endif
5571 cwd = getcwd(NULL, 0);
5572 if (cwd == NULL) {
5573 error = got_error_from_errno("getcwd");
5574 goto done;
5577 error = got_worktree_open(&worktree, cwd);
5578 if (error) {
5579 if (error->code == GOT_ERR_NOT_WORKTREE)
5580 error = wrap_not_worktree_error(error, "status", cwd);
5581 goto done;
5584 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5585 NULL);
5586 if (error != NULL)
5587 goto done;
5589 error = apply_unveil(got_repo_get_path(repo), 1,
5590 got_worktree_get_root_path(worktree));
5591 if (error)
5592 goto done;
5594 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5595 if (error)
5596 goto done;
5598 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5599 print_status, &st, check_cancelled, NULL);
5600 done:
5601 TAILQ_FOREACH(pe, &paths, entry)
5602 free((char *)pe->path);
5603 got_pathlist_free(&paths);
5604 free(cwd);
5605 return error;
5608 __dead static void
5609 usage_ref(void)
5611 fprintf(stderr,
5612 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5613 "[-s reference] [-d] [name]\n",
5614 getprogname());
5615 exit(1);
5618 static const struct got_error *
5619 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5621 static const struct got_error *err = NULL;
5622 struct got_reflist_head refs;
5623 struct got_reflist_entry *re;
5625 TAILQ_INIT(&refs);
5626 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5627 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5628 repo);
5629 if (err)
5630 return err;
5632 TAILQ_FOREACH(re, &refs, entry) {
5633 char *refstr;
5634 refstr = got_ref_to_str(re->ref);
5635 if (refstr == NULL)
5636 return got_error_from_errno("got_ref_to_str");
5637 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5638 free(refstr);
5641 got_ref_list_free(&refs);
5642 return NULL;
5645 static const struct got_error *
5646 delete_ref_by_name(struct got_repository *repo, const char *refname)
5648 const struct got_error *err;
5649 struct got_reference *ref;
5651 err = got_ref_open(&ref, repo, refname, 0);
5652 if (err)
5653 return err;
5655 err = delete_ref(repo, ref);
5656 got_ref_close(ref);
5657 return err;
5660 static const struct got_error *
5661 add_ref(struct got_repository *repo, const char *refname, const char *target)
5663 const struct got_error *err = NULL;
5664 struct got_object_id *id = NULL;
5665 struct got_reference *ref = NULL;
5666 struct got_reflist_head refs;
5669 * Don't let the user create a reference name with a leading '-'.
5670 * While technically a valid reference name, this case is usually
5671 * an unintended typo.
5673 if (refname[0] == '-')
5674 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5676 TAILQ_INIT(&refs);
5677 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5678 if (err)
5679 goto done;
5680 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5681 &refs, repo);
5682 got_ref_list_free(&refs);
5683 if (err)
5684 goto done;
5686 err = got_ref_alloc(&ref, refname, id);
5687 if (err)
5688 goto done;
5690 err = got_ref_write(ref, repo);
5691 done:
5692 if (ref)
5693 got_ref_close(ref);
5694 free(id);
5695 return err;
5698 static const struct got_error *
5699 add_symref(struct got_repository *repo, const char *refname, const char *target)
5701 const struct got_error *err = NULL;
5702 struct got_reference *ref = NULL;
5703 struct got_reference *target_ref = NULL;
5706 * Don't let the user create a reference name with a leading '-'.
5707 * While technically a valid reference name, this case is usually
5708 * an unintended typo.
5710 if (refname[0] == '-')
5711 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5713 err = got_ref_open(&target_ref, repo, target, 0);
5714 if (err)
5715 return err;
5717 err = got_ref_alloc_symref(&ref, refname, target_ref);
5718 if (err)
5719 goto done;
5721 err = got_ref_write(ref, repo);
5722 done:
5723 if (target_ref)
5724 got_ref_close(target_ref);
5725 if (ref)
5726 got_ref_close(ref);
5727 return err;
5730 static const struct got_error *
5731 cmd_ref(int argc, char *argv[])
5733 const struct got_error *error = NULL;
5734 struct got_repository *repo = NULL;
5735 struct got_worktree *worktree = NULL;
5736 char *cwd = NULL, *repo_path = NULL;
5737 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5738 const char *obj_arg = NULL, *symref_target= NULL;
5739 char *refname = NULL;
5741 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5742 switch (ch) {
5743 case 'c':
5744 obj_arg = optarg;
5745 break;
5746 case 'd':
5747 do_delete = 1;
5748 break;
5749 case 'r':
5750 repo_path = realpath(optarg, NULL);
5751 if (repo_path == NULL)
5752 return got_error_from_errno2("realpath",
5753 optarg);
5754 got_path_strip_trailing_slashes(repo_path);
5755 break;
5756 case 'l':
5757 do_list = 1;
5758 break;
5759 case 's':
5760 symref_target = optarg;
5761 break;
5762 case 't':
5763 sort_by_time = 1;
5764 break;
5765 default:
5766 usage_ref();
5767 /* NOTREACHED */
5771 if (obj_arg && do_list)
5772 option_conflict('c', 'l');
5773 if (obj_arg && do_delete)
5774 option_conflict('c', 'd');
5775 if (obj_arg && symref_target)
5776 option_conflict('c', 's');
5777 if (symref_target && do_delete)
5778 option_conflict('s', 'd');
5779 if (symref_target && do_list)
5780 option_conflict('s', 'l');
5781 if (do_delete && do_list)
5782 option_conflict('d', 'l');
5783 if (sort_by_time && !do_list)
5784 errx(1, "-t option requires -l option");
5786 argc -= optind;
5787 argv += optind;
5789 if (do_list) {
5790 if (argc != 0 && argc != 1)
5791 usage_ref();
5792 if (argc == 1) {
5793 refname = strdup(argv[0]);
5794 if (refname == NULL) {
5795 error = got_error_from_errno("strdup");
5796 goto done;
5799 } else {
5800 if (argc != 1)
5801 usage_ref();
5802 refname = strdup(argv[0]);
5803 if (refname == NULL) {
5804 error = got_error_from_errno("strdup");
5805 goto done;
5809 if (refname)
5810 got_path_strip_trailing_slashes(refname);
5812 #ifndef PROFILE
5813 if (do_list) {
5814 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5815 NULL) == -1)
5816 err(1, "pledge");
5817 } else {
5818 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5819 "sendfd unveil", NULL) == -1)
5820 err(1, "pledge");
5822 #endif
5823 cwd = getcwd(NULL, 0);
5824 if (cwd == NULL) {
5825 error = got_error_from_errno("getcwd");
5826 goto done;
5829 if (repo_path == NULL) {
5830 error = got_worktree_open(&worktree, cwd);
5831 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5832 goto done;
5833 else
5834 error = NULL;
5835 if (worktree) {
5836 repo_path =
5837 strdup(got_worktree_get_repo_path(worktree));
5838 if (repo_path == NULL)
5839 error = got_error_from_errno("strdup");
5840 if (error)
5841 goto done;
5842 } else {
5843 repo_path = strdup(cwd);
5844 if (repo_path == NULL) {
5845 error = got_error_from_errno("strdup");
5846 goto done;
5851 error = got_repo_open(&repo, repo_path, NULL);
5852 if (error != NULL)
5853 goto done;
5855 error = apply_unveil(got_repo_get_path(repo), do_list,
5856 worktree ? got_worktree_get_root_path(worktree) : NULL);
5857 if (error)
5858 goto done;
5860 if (do_list)
5861 error = list_refs(repo, refname, sort_by_time);
5862 else if (do_delete)
5863 error = delete_ref_by_name(repo, refname);
5864 else if (symref_target)
5865 error = add_symref(repo, refname, symref_target);
5866 else {
5867 if (obj_arg == NULL)
5868 usage_ref();
5869 error = add_ref(repo, refname, obj_arg);
5871 done:
5872 free(refname);
5873 if (repo) {
5874 const struct got_error *close_err = got_repo_close(repo);
5875 if (error == NULL)
5876 error = close_err;
5878 if (worktree)
5879 got_worktree_close(worktree);
5880 free(cwd);
5881 free(repo_path);
5882 return error;
5885 __dead static void
5886 usage_branch(void)
5888 fprintf(stderr,
5889 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5890 "[-n] [name]\n", getprogname());
5891 exit(1);
5894 static const struct got_error *
5895 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5896 struct got_reference *ref)
5898 const struct got_error *err = NULL;
5899 const char *refname, *marker = " ";
5900 char *refstr;
5902 refname = got_ref_get_name(ref);
5903 if (worktree && strcmp(refname,
5904 got_worktree_get_head_ref_name(worktree)) == 0) {
5905 struct got_object_id *id = NULL;
5907 err = got_ref_resolve(&id, repo, ref);
5908 if (err)
5909 return err;
5910 if (got_object_id_cmp(id,
5911 got_worktree_get_base_commit_id(worktree)) == 0)
5912 marker = "* ";
5913 else
5914 marker = "~ ";
5915 free(id);
5918 if (strncmp(refname, "refs/heads/", 11) == 0)
5919 refname += 11;
5920 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5921 refname += 18;
5922 if (strncmp(refname, "refs/remotes/", 13) == 0)
5923 refname += 13;
5925 refstr = got_ref_to_str(ref);
5926 if (refstr == NULL)
5927 return got_error_from_errno("got_ref_to_str");
5929 printf("%s%s: %s\n", marker, refname, refstr);
5930 free(refstr);
5931 return NULL;
5934 static const struct got_error *
5935 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5937 const char *refname;
5939 if (worktree == NULL)
5940 return got_error(GOT_ERR_NOT_WORKTREE);
5942 refname = got_worktree_get_head_ref_name(worktree);
5944 if (strncmp(refname, "refs/heads/", 11) == 0)
5945 refname += 11;
5946 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5947 refname += 18;
5949 printf("%s\n", refname);
5951 return NULL;
5954 static const struct got_error *
5955 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5956 int sort_by_time)
5958 static const struct got_error *err = NULL;
5959 struct got_reflist_head refs;
5960 struct got_reflist_entry *re;
5961 struct got_reference *temp_ref = NULL;
5962 int rebase_in_progress, histedit_in_progress;
5964 TAILQ_INIT(&refs);
5966 if (worktree) {
5967 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5968 worktree);
5969 if (err)
5970 return err;
5972 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5973 worktree);
5974 if (err)
5975 return err;
5977 if (rebase_in_progress || histedit_in_progress) {
5978 err = got_ref_open(&temp_ref, repo,
5979 got_worktree_get_head_ref_name(worktree), 0);
5980 if (err)
5981 return err;
5982 list_branch(repo, worktree, temp_ref);
5983 got_ref_close(temp_ref);
5987 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
5988 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5989 repo);
5990 if (err)
5991 return err;
5993 TAILQ_FOREACH(re, &refs, entry)
5994 list_branch(repo, worktree, re->ref);
5996 got_ref_list_free(&refs);
5998 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
5999 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6000 repo);
6001 if (err)
6002 return err;
6004 TAILQ_FOREACH(re, &refs, entry)
6005 list_branch(repo, worktree, re->ref);
6007 got_ref_list_free(&refs);
6009 return NULL;
6012 static const struct got_error *
6013 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6014 const char *branch_name)
6016 const struct got_error *err = NULL;
6017 struct got_reference *ref = NULL;
6018 char *refname, *remote_refname = NULL;
6020 if (strncmp(branch_name, "refs/", 5) == 0)
6021 branch_name += 5;
6022 if (strncmp(branch_name, "heads/", 6) == 0)
6023 branch_name += 6;
6024 else if (strncmp(branch_name, "remotes/", 8) == 0)
6025 branch_name += 8;
6027 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6028 return got_error_from_errno("asprintf");
6030 if (asprintf(&remote_refname, "refs/remotes/%s",
6031 branch_name) == -1) {
6032 err = got_error_from_errno("asprintf");
6033 goto done;
6036 err = got_ref_open(&ref, repo, refname, 0);
6037 if (err) {
6038 const struct got_error *err2;
6039 if (err->code != GOT_ERR_NOT_REF)
6040 goto done;
6042 * Keep 'err' intact such that if neither branch exists
6043 * we report "refs/heads" rather than "refs/remotes" in
6044 * our error message.
6046 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6047 if (err2)
6048 goto done;
6049 err = NULL;
6052 if (worktree &&
6053 strcmp(got_worktree_get_head_ref_name(worktree),
6054 got_ref_get_name(ref)) == 0) {
6055 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6056 "will not delete this work tree's current branch");
6057 goto done;
6060 err = delete_ref(repo, ref);
6061 done:
6062 if (ref)
6063 got_ref_close(ref);
6064 free(refname);
6065 free(remote_refname);
6066 return err;
6069 static const struct got_error *
6070 add_branch(struct got_repository *repo, const char *branch_name,
6071 struct got_object_id *base_commit_id)
6073 const struct got_error *err = NULL;
6074 struct got_reference *ref = NULL;
6075 char *base_refname = NULL, *refname = NULL;
6078 * Don't let the user create a branch name with a leading '-'.
6079 * While technically a valid reference name, this case is usually
6080 * an unintended typo.
6082 if (branch_name[0] == '-')
6083 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6085 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6086 branch_name += 11;
6088 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6089 err = got_error_from_errno("asprintf");
6090 goto done;
6093 err = got_ref_open(&ref, repo, refname, 0);
6094 if (err == NULL) {
6095 err = got_error(GOT_ERR_BRANCH_EXISTS);
6096 goto done;
6097 } else if (err->code != GOT_ERR_NOT_REF)
6098 goto done;
6100 err = got_ref_alloc(&ref, refname, base_commit_id);
6101 if (err)
6102 goto done;
6104 err = got_ref_write(ref, repo);
6105 done:
6106 if (ref)
6107 got_ref_close(ref);
6108 free(base_refname);
6109 free(refname);
6110 return err;
6113 static const struct got_error *
6114 cmd_branch(int argc, char *argv[])
6116 const struct got_error *error = NULL;
6117 struct got_repository *repo = NULL;
6118 struct got_worktree *worktree = NULL;
6119 char *cwd = NULL, *repo_path = NULL;
6120 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6121 const char *delref = NULL, *commit_id_arg = NULL;
6122 struct got_reference *ref = NULL;
6123 struct got_pathlist_head paths;
6124 struct got_pathlist_entry *pe;
6125 struct got_object_id *commit_id = NULL;
6126 char *commit_id_str = NULL;
6128 TAILQ_INIT(&paths);
6130 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6131 switch (ch) {
6132 case 'c':
6133 commit_id_arg = optarg;
6134 break;
6135 case 'd':
6136 delref = optarg;
6137 break;
6138 case 'r':
6139 repo_path = realpath(optarg, NULL);
6140 if (repo_path == NULL)
6141 return got_error_from_errno2("realpath",
6142 optarg);
6143 got_path_strip_trailing_slashes(repo_path);
6144 break;
6145 case 'l':
6146 do_list = 1;
6147 break;
6148 case 'n':
6149 do_update = 0;
6150 break;
6151 case 't':
6152 sort_by_time = 1;
6153 break;
6154 default:
6155 usage_branch();
6156 /* NOTREACHED */
6160 if (do_list && delref)
6161 option_conflict('l', 'd');
6162 if (sort_by_time && !do_list)
6163 errx(1, "-t option requires -l option");
6165 argc -= optind;
6166 argv += optind;
6168 if (!do_list && !delref && argc == 0)
6169 do_show = 1;
6171 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6172 errx(1, "-c option can only be used when creating a branch");
6174 if (do_list || delref) {
6175 if (argc > 0)
6176 usage_branch();
6177 } else if (!do_show && argc != 1)
6178 usage_branch();
6180 #ifndef PROFILE
6181 if (do_list || do_show) {
6182 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6183 NULL) == -1)
6184 err(1, "pledge");
6185 } else {
6186 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6187 "sendfd unveil", NULL) == -1)
6188 err(1, "pledge");
6190 #endif
6191 cwd = getcwd(NULL, 0);
6192 if (cwd == NULL) {
6193 error = got_error_from_errno("getcwd");
6194 goto done;
6197 if (repo_path == NULL) {
6198 error = got_worktree_open(&worktree, cwd);
6199 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6200 goto done;
6201 else
6202 error = NULL;
6203 if (worktree) {
6204 repo_path =
6205 strdup(got_worktree_get_repo_path(worktree));
6206 if (repo_path == NULL)
6207 error = got_error_from_errno("strdup");
6208 if (error)
6209 goto done;
6210 } else {
6211 repo_path = strdup(cwd);
6212 if (repo_path == NULL) {
6213 error = got_error_from_errno("strdup");
6214 goto done;
6219 error = got_repo_open(&repo, repo_path, NULL);
6220 if (error != NULL)
6221 goto done;
6223 error = apply_unveil(got_repo_get_path(repo), do_list,
6224 worktree ? got_worktree_get_root_path(worktree) : NULL);
6225 if (error)
6226 goto done;
6228 if (do_show)
6229 error = show_current_branch(repo, worktree);
6230 else if (do_list)
6231 error = list_branches(repo, worktree, sort_by_time);
6232 else if (delref)
6233 error = delete_branch(repo, worktree, delref);
6234 else {
6235 struct got_reflist_head refs;
6236 TAILQ_INIT(&refs);
6237 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6238 NULL);
6239 if (error)
6240 goto done;
6241 if (commit_id_arg == NULL)
6242 commit_id_arg = worktree ?
6243 got_worktree_get_head_ref_name(worktree) :
6244 GOT_REF_HEAD;
6245 error = got_repo_match_object_id(&commit_id, NULL,
6246 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6247 got_ref_list_free(&refs);
6248 if (error)
6249 goto done;
6250 error = add_branch(repo, argv[0], commit_id);
6251 if (error)
6252 goto done;
6253 if (worktree && do_update) {
6254 struct got_update_progress_arg upa;
6255 char *branch_refname = NULL;
6257 error = got_object_id_str(&commit_id_str, commit_id);
6258 if (error)
6259 goto done;
6260 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6261 worktree);
6262 if (error)
6263 goto done;
6264 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6265 == -1) {
6266 error = got_error_from_errno("asprintf");
6267 goto done;
6269 error = got_ref_open(&ref, repo, branch_refname, 0);
6270 free(branch_refname);
6271 if (error)
6272 goto done;
6273 error = switch_head_ref(ref, commit_id, worktree,
6274 repo);
6275 if (error)
6276 goto done;
6277 error = got_worktree_set_base_commit_id(worktree, repo,
6278 commit_id);
6279 if (error)
6280 goto done;
6281 memset(&upa, 0, sizeof(upa));
6282 error = got_worktree_checkout_files(worktree, &paths,
6283 repo, update_progress, &upa, check_cancelled,
6284 NULL);
6285 if (error)
6286 goto done;
6287 if (upa.did_something) {
6288 printf("Updated to %s: %s\n",
6289 got_worktree_get_head_ref_name(worktree),
6290 commit_id_str);
6292 print_update_progress_stats(&upa);
6295 done:
6296 if (ref)
6297 got_ref_close(ref);
6298 if (repo) {
6299 const struct got_error *close_err = got_repo_close(repo);
6300 if (error == NULL)
6301 error = close_err;
6303 if (worktree)
6304 got_worktree_close(worktree);
6305 free(cwd);
6306 free(repo_path);
6307 free(commit_id);
6308 free(commit_id_str);
6309 TAILQ_FOREACH(pe, &paths, entry)
6310 free((char *)pe->path);
6311 got_pathlist_free(&paths);
6312 return error;
6316 __dead static void
6317 usage_tag(void)
6319 fprintf(stderr,
6320 "usage: %s tag [-c commit] [-r repository] [-l] "
6321 "[-m message] name\n", getprogname());
6322 exit(1);
6325 #if 0
6326 static const struct got_error *
6327 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6329 const struct got_error *err = NULL;
6330 struct got_reflist_entry *re, *se, *new;
6331 struct got_object_id *re_id, *se_id;
6332 struct got_tag_object *re_tag, *se_tag;
6333 time_t re_time, se_time;
6335 STAILQ_FOREACH(re, tags, entry) {
6336 se = STAILQ_FIRST(sorted);
6337 if (se == NULL) {
6338 err = got_reflist_entry_dup(&new, re);
6339 if (err)
6340 return err;
6341 STAILQ_INSERT_HEAD(sorted, new, entry);
6342 continue;
6343 } else {
6344 err = got_ref_resolve(&re_id, repo, re->ref);
6345 if (err)
6346 break;
6347 err = got_object_open_as_tag(&re_tag, repo, re_id);
6348 free(re_id);
6349 if (err)
6350 break;
6351 re_time = got_object_tag_get_tagger_time(re_tag);
6352 got_object_tag_close(re_tag);
6355 while (se) {
6356 err = got_ref_resolve(&se_id, repo, re->ref);
6357 if (err)
6358 break;
6359 err = got_object_open_as_tag(&se_tag, repo, se_id);
6360 free(se_id);
6361 if (err)
6362 break;
6363 se_time = got_object_tag_get_tagger_time(se_tag);
6364 got_object_tag_close(se_tag);
6366 if (se_time > re_time) {
6367 err = got_reflist_entry_dup(&new, re);
6368 if (err)
6369 return err;
6370 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6371 break;
6373 se = STAILQ_NEXT(se, entry);
6374 continue;
6377 done:
6378 return err;
6380 #endif
6382 static const struct got_error *
6383 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6385 static const struct got_error *err = NULL;
6386 struct got_reflist_head refs;
6387 struct got_reflist_entry *re;
6389 TAILQ_INIT(&refs);
6391 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6392 if (err)
6393 return err;
6395 TAILQ_FOREACH(re, &refs, entry) {
6396 const char *refname;
6397 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6398 char datebuf[26];
6399 const char *tagger;
6400 time_t tagger_time;
6401 struct got_object_id *id;
6402 struct got_tag_object *tag;
6403 struct got_commit_object *commit = NULL;
6405 refname = got_ref_get_name(re->ref);
6406 if (strncmp(refname, "refs/tags/", 10) != 0)
6407 continue;
6408 refname += 10;
6409 refstr = got_ref_to_str(re->ref);
6410 if (refstr == NULL) {
6411 err = got_error_from_errno("got_ref_to_str");
6412 break;
6414 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6415 free(refstr);
6417 err = got_ref_resolve(&id, repo, re->ref);
6418 if (err)
6419 break;
6420 err = got_object_open_as_tag(&tag, repo, id);
6421 if (err) {
6422 if (err->code != GOT_ERR_OBJ_TYPE) {
6423 free(id);
6424 break;
6426 /* "lightweight" tag */
6427 err = got_object_open_as_commit(&commit, repo, id);
6428 if (err) {
6429 free(id);
6430 break;
6432 tagger = got_object_commit_get_committer(commit);
6433 tagger_time =
6434 got_object_commit_get_committer_time(commit);
6435 err = got_object_id_str(&id_str, id);
6436 free(id);
6437 if (err)
6438 break;
6439 } else {
6440 free(id);
6441 tagger = got_object_tag_get_tagger(tag);
6442 tagger_time = got_object_tag_get_tagger_time(tag);
6443 err = got_object_id_str(&id_str,
6444 got_object_tag_get_object_id(tag));
6445 if (err)
6446 break;
6448 printf("from: %s\n", tagger);
6449 datestr = get_datestr(&tagger_time, datebuf);
6450 if (datestr)
6451 printf("date: %s UTC\n", datestr);
6452 if (commit)
6453 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6454 else {
6455 switch (got_object_tag_get_object_type(tag)) {
6456 case GOT_OBJ_TYPE_BLOB:
6457 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6458 id_str);
6459 break;
6460 case GOT_OBJ_TYPE_TREE:
6461 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6462 id_str);
6463 break;
6464 case GOT_OBJ_TYPE_COMMIT:
6465 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6466 id_str);
6467 break;
6468 case GOT_OBJ_TYPE_TAG:
6469 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6470 id_str);
6471 break;
6472 default:
6473 break;
6476 free(id_str);
6477 if (commit) {
6478 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6479 if (err)
6480 break;
6481 got_object_commit_close(commit);
6482 } else {
6483 tagmsg0 = strdup(got_object_tag_get_message(tag));
6484 got_object_tag_close(tag);
6485 if (tagmsg0 == NULL) {
6486 err = got_error_from_errno("strdup");
6487 break;
6491 tagmsg = tagmsg0;
6492 do {
6493 line = strsep(&tagmsg, "\n");
6494 if (line)
6495 printf(" %s\n", line);
6496 } while (line);
6497 free(tagmsg0);
6500 got_ref_list_free(&refs);
6501 return NULL;
6504 static const struct got_error *
6505 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6506 const char *tag_name, const char *repo_path)
6508 const struct got_error *err = NULL;
6509 char *template = NULL, *initial_content = NULL;
6510 char *editor = NULL;
6511 int initial_content_len;
6512 int fd = -1;
6514 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6515 err = got_error_from_errno("asprintf");
6516 goto done;
6519 initial_content_len = asprintf(&initial_content,
6520 "\n# tagging commit %s as %s\n",
6521 commit_id_str, tag_name);
6522 if (initial_content_len == -1) {
6523 err = got_error_from_errno("asprintf");
6524 goto done;
6527 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6528 if (err)
6529 goto done;
6531 if (write(fd, initial_content, initial_content_len) == -1) {
6532 err = got_error_from_errno2("write", *tagmsg_path);
6533 goto done;
6536 err = get_editor(&editor);
6537 if (err)
6538 goto done;
6539 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6540 initial_content_len, 1);
6541 done:
6542 free(initial_content);
6543 free(template);
6544 free(editor);
6546 if (fd != -1 && close(fd) == -1 && err == NULL)
6547 err = got_error_from_errno2("close", *tagmsg_path);
6549 /* Editor is done; we can now apply unveil(2) */
6550 if (err == NULL)
6551 err = apply_unveil(repo_path, 0, NULL);
6552 if (err) {
6553 free(*tagmsg);
6554 *tagmsg = NULL;
6556 return err;
6559 static const struct got_error *
6560 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6561 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6563 const struct got_error *err = NULL;
6564 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6565 char *label = NULL, *commit_id_str = NULL;
6566 struct got_reference *ref = NULL;
6567 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6568 char *tagmsg_path = NULL, *tag_id_str = NULL;
6569 int preserve_tagmsg = 0;
6570 struct got_reflist_head refs;
6572 TAILQ_INIT(&refs);
6575 * Don't let the user create a tag name with a leading '-'.
6576 * While technically a valid reference name, this case is usually
6577 * an unintended typo.
6579 if (tag_name[0] == '-')
6580 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6582 err = get_author(&tagger, repo, worktree);
6583 if (err)
6584 return err;
6586 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6587 if (err)
6588 goto done;
6590 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6591 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6592 if (err)
6593 goto done;
6595 err = got_object_id_str(&commit_id_str, commit_id);
6596 if (err)
6597 goto done;
6599 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6600 refname = strdup(tag_name);
6601 if (refname == NULL) {
6602 err = got_error_from_errno("strdup");
6603 goto done;
6605 tag_name += 10;
6606 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6607 err = got_error_from_errno("asprintf");
6608 goto done;
6611 err = got_ref_open(&ref, repo, refname, 0);
6612 if (err == NULL) {
6613 err = got_error(GOT_ERR_TAG_EXISTS);
6614 goto done;
6615 } else if (err->code != GOT_ERR_NOT_REF)
6616 goto done;
6618 if (tagmsg_arg == NULL) {
6619 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6620 tag_name, got_repo_get_path(repo));
6621 if (err) {
6622 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6623 tagmsg_path != NULL)
6624 preserve_tagmsg = 1;
6625 goto done;
6629 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6630 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6631 if (err) {
6632 if (tagmsg_path)
6633 preserve_tagmsg = 1;
6634 goto done;
6637 err = got_ref_alloc(&ref, refname, tag_id);
6638 if (err) {
6639 if (tagmsg_path)
6640 preserve_tagmsg = 1;
6641 goto done;
6644 err = got_ref_write(ref, repo);
6645 if (err) {
6646 if (tagmsg_path)
6647 preserve_tagmsg = 1;
6648 goto done;
6651 err = got_object_id_str(&tag_id_str, tag_id);
6652 if (err) {
6653 if (tagmsg_path)
6654 preserve_tagmsg = 1;
6655 goto done;
6657 printf("Created tag %s\n", tag_id_str);
6658 done:
6659 if (preserve_tagmsg) {
6660 fprintf(stderr, "%s: tag message preserved in %s\n",
6661 getprogname(), tagmsg_path);
6662 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6663 err = got_error_from_errno2("unlink", tagmsg_path);
6664 free(tag_id_str);
6665 if (ref)
6666 got_ref_close(ref);
6667 free(commit_id);
6668 free(commit_id_str);
6669 free(refname);
6670 free(tagmsg);
6671 free(tagmsg_path);
6672 free(tagger);
6673 got_ref_list_free(&refs);
6674 return err;
6677 static const struct got_error *
6678 cmd_tag(int argc, char *argv[])
6680 const struct got_error *error = NULL;
6681 struct got_repository *repo = NULL;
6682 struct got_worktree *worktree = NULL;
6683 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6684 char *gitconfig_path = NULL;
6685 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6686 int ch, do_list = 0;
6688 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6689 switch (ch) {
6690 case 'c':
6691 commit_id_arg = optarg;
6692 break;
6693 case 'm':
6694 tagmsg = optarg;
6695 break;
6696 case 'r':
6697 repo_path = realpath(optarg, NULL);
6698 if (repo_path == NULL)
6699 return got_error_from_errno2("realpath",
6700 optarg);
6701 got_path_strip_trailing_slashes(repo_path);
6702 break;
6703 case 'l':
6704 do_list = 1;
6705 break;
6706 default:
6707 usage_tag();
6708 /* NOTREACHED */
6712 argc -= optind;
6713 argv += optind;
6715 if (do_list) {
6716 if (commit_id_arg != NULL)
6717 errx(1,
6718 "-c option can only be used when creating a tag");
6719 if (tagmsg)
6720 option_conflict('l', 'm');
6721 if (argc > 0)
6722 usage_tag();
6723 } else if (argc != 1)
6724 usage_tag();
6726 tag_name = argv[0];
6728 #ifndef PROFILE
6729 if (do_list) {
6730 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6731 NULL) == -1)
6732 err(1, "pledge");
6733 } else {
6734 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6735 "sendfd unveil", NULL) == -1)
6736 err(1, "pledge");
6738 #endif
6739 cwd = getcwd(NULL, 0);
6740 if (cwd == NULL) {
6741 error = got_error_from_errno("getcwd");
6742 goto done;
6745 if (repo_path == NULL) {
6746 error = got_worktree_open(&worktree, cwd);
6747 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6748 goto done;
6749 else
6750 error = NULL;
6751 if (worktree) {
6752 repo_path =
6753 strdup(got_worktree_get_repo_path(worktree));
6754 if (repo_path == NULL)
6755 error = got_error_from_errno("strdup");
6756 if (error)
6757 goto done;
6758 } else {
6759 repo_path = strdup(cwd);
6760 if (repo_path == NULL) {
6761 error = got_error_from_errno("strdup");
6762 goto done;
6767 if (do_list) {
6768 error = got_repo_open(&repo, repo_path, NULL);
6769 if (error != NULL)
6770 goto done;
6771 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6772 if (error)
6773 goto done;
6774 error = list_tags(repo, worktree);
6775 } else {
6776 error = get_gitconfig_path(&gitconfig_path);
6777 if (error)
6778 goto done;
6779 error = got_repo_open(&repo, repo_path, gitconfig_path);
6780 if (error != NULL)
6781 goto done;
6783 if (tagmsg) {
6784 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6785 if (error)
6786 goto done;
6789 if (commit_id_arg == NULL) {
6790 struct got_reference *head_ref;
6791 struct got_object_id *commit_id;
6792 error = got_ref_open(&head_ref, repo,
6793 worktree ? got_worktree_get_head_ref_name(worktree)
6794 : GOT_REF_HEAD, 0);
6795 if (error)
6796 goto done;
6797 error = got_ref_resolve(&commit_id, repo, head_ref);
6798 got_ref_close(head_ref);
6799 if (error)
6800 goto done;
6801 error = got_object_id_str(&commit_id_str, commit_id);
6802 free(commit_id);
6803 if (error)
6804 goto done;
6807 error = add_tag(repo, worktree, tag_name,
6808 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6810 done:
6811 if (repo) {
6812 const struct got_error *close_err = got_repo_close(repo);
6813 if (error == NULL)
6814 error = close_err;
6816 if (worktree)
6817 got_worktree_close(worktree);
6818 free(cwd);
6819 free(repo_path);
6820 free(gitconfig_path);
6821 free(commit_id_str);
6822 return error;
6825 __dead static void
6826 usage_add(void)
6828 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6829 getprogname());
6830 exit(1);
6833 static const struct got_error *
6834 add_progress(void *arg, unsigned char status, const char *path)
6836 while (path[0] == '/')
6837 path++;
6838 printf("%c %s\n", status, path);
6839 return NULL;
6842 static const struct got_error *
6843 cmd_add(int argc, char *argv[])
6845 const struct got_error *error = NULL;
6846 struct got_repository *repo = NULL;
6847 struct got_worktree *worktree = NULL;
6848 char *cwd = NULL;
6849 struct got_pathlist_head paths;
6850 struct got_pathlist_entry *pe;
6851 int ch, can_recurse = 0, no_ignores = 0;
6853 TAILQ_INIT(&paths);
6855 while ((ch = getopt(argc, argv, "IR")) != -1) {
6856 switch (ch) {
6857 case 'I':
6858 no_ignores = 1;
6859 break;
6860 case 'R':
6861 can_recurse = 1;
6862 break;
6863 default:
6864 usage_add();
6865 /* NOTREACHED */
6869 argc -= optind;
6870 argv += optind;
6872 #ifndef PROFILE
6873 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6874 NULL) == -1)
6875 err(1, "pledge");
6876 #endif
6877 if (argc < 1)
6878 usage_add();
6880 cwd = getcwd(NULL, 0);
6881 if (cwd == NULL) {
6882 error = got_error_from_errno("getcwd");
6883 goto done;
6886 error = got_worktree_open(&worktree, cwd);
6887 if (error) {
6888 if (error->code == GOT_ERR_NOT_WORKTREE)
6889 error = wrap_not_worktree_error(error, "add", cwd);
6890 goto done;
6893 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6894 NULL);
6895 if (error != NULL)
6896 goto done;
6898 error = apply_unveil(got_repo_get_path(repo), 1,
6899 got_worktree_get_root_path(worktree));
6900 if (error)
6901 goto done;
6903 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6904 if (error)
6905 goto done;
6907 if (!can_recurse) {
6908 char *ondisk_path;
6909 struct stat sb;
6910 TAILQ_FOREACH(pe, &paths, entry) {
6911 if (asprintf(&ondisk_path, "%s/%s",
6912 got_worktree_get_root_path(worktree),
6913 pe->path) == -1) {
6914 error = got_error_from_errno("asprintf");
6915 goto done;
6917 if (lstat(ondisk_path, &sb) == -1) {
6918 if (errno == ENOENT) {
6919 free(ondisk_path);
6920 continue;
6922 error = got_error_from_errno2("lstat",
6923 ondisk_path);
6924 free(ondisk_path);
6925 goto done;
6927 free(ondisk_path);
6928 if (S_ISDIR(sb.st_mode)) {
6929 error = got_error_msg(GOT_ERR_BAD_PATH,
6930 "adding directories requires -R option");
6931 goto done;
6936 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6937 NULL, repo, no_ignores);
6938 done:
6939 if (repo) {
6940 const struct got_error *close_err = got_repo_close(repo);
6941 if (error == NULL)
6942 error = close_err;
6944 if (worktree)
6945 got_worktree_close(worktree);
6946 TAILQ_FOREACH(pe, &paths, entry)
6947 free((char *)pe->path);
6948 got_pathlist_free(&paths);
6949 free(cwd);
6950 return error;
6953 __dead static void
6954 usage_remove(void)
6956 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6957 "path ...\n", getprogname());
6958 exit(1);
6961 static const struct got_error *
6962 print_remove_status(void *arg, unsigned char status,
6963 unsigned char staged_status, const char *path)
6965 while (path[0] == '/')
6966 path++;
6967 if (status == GOT_STATUS_NONEXISTENT)
6968 return NULL;
6969 if (status == staged_status && (status == GOT_STATUS_DELETE))
6970 status = GOT_STATUS_NO_CHANGE;
6971 printf("%c%c %s\n", status, staged_status, path);
6972 return NULL;
6975 static const struct got_error *
6976 cmd_remove(int argc, char *argv[])
6978 const struct got_error *error = NULL;
6979 struct got_worktree *worktree = NULL;
6980 struct got_repository *repo = NULL;
6981 const char *status_codes = NULL;
6982 char *cwd = NULL;
6983 struct got_pathlist_head paths;
6984 struct got_pathlist_entry *pe;
6985 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6986 int ignore_missing_paths = 0;
6988 TAILQ_INIT(&paths);
6990 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6991 switch (ch) {
6992 case 'f':
6993 delete_local_mods = 1;
6994 ignore_missing_paths = 1;
6995 break;
6996 case 'k':
6997 keep_on_disk = 1;
6998 break;
6999 case 'R':
7000 can_recurse = 1;
7001 break;
7002 case 's':
7003 for (i = 0; i < strlen(optarg); i++) {
7004 switch (optarg[i]) {
7005 case GOT_STATUS_MODIFY:
7006 delete_local_mods = 1;
7007 break;
7008 case GOT_STATUS_MISSING:
7009 ignore_missing_paths = 1;
7010 break;
7011 default:
7012 errx(1, "invalid status code '%c'",
7013 optarg[i]);
7016 status_codes = optarg;
7017 break;
7018 default:
7019 usage_remove();
7020 /* NOTREACHED */
7024 argc -= optind;
7025 argv += optind;
7027 #ifndef PROFILE
7028 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7029 NULL) == -1)
7030 err(1, "pledge");
7031 #endif
7032 if (argc < 1)
7033 usage_remove();
7035 cwd = getcwd(NULL, 0);
7036 if (cwd == NULL) {
7037 error = got_error_from_errno("getcwd");
7038 goto done;
7040 error = got_worktree_open(&worktree, cwd);
7041 if (error) {
7042 if (error->code == GOT_ERR_NOT_WORKTREE)
7043 error = wrap_not_worktree_error(error, "remove", cwd);
7044 goto done;
7047 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7048 NULL);
7049 if (error)
7050 goto done;
7052 error = apply_unveil(got_repo_get_path(repo), 1,
7053 got_worktree_get_root_path(worktree));
7054 if (error)
7055 goto done;
7057 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7058 if (error)
7059 goto done;
7061 if (!can_recurse) {
7062 char *ondisk_path;
7063 struct stat sb;
7064 TAILQ_FOREACH(pe, &paths, entry) {
7065 if (asprintf(&ondisk_path, "%s/%s",
7066 got_worktree_get_root_path(worktree),
7067 pe->path) == -1) {
7068 error = got_error_from_errno("asprintf");
7069 goto done;
7071 if (lstat(ondisk_path, &sb) == -1) {
7072 if (errno == ENOENT) {
7073 free(ondisk_path);
7074 continue;
7076 error = got_error_from_errno2("lstat",
7077 ondisk_path);
7078 free(ondisk_path);
7079 goto done;
7081 free(ondisk_path);
7082 if (S_ISDIR(sb.st_mode)) {
7083 error = got_error_msg(GOT_ERR_BAD_PATH,
7084 "removing directories requires -R option");
7085 goto done;
7090 error = got_worktree_schedule_delete(worktree, &paths,
7091 delete_local_mods, status_codes, print_remove_status, NULL,
7092 repo, keep_on_disk, ignore_missing_paths);
7093 done:
7094 if (repo) {
7095 const struct got_error *close_err = got_repo_close(repo);
7096 if (error == NULL)
7097 error = close_err;
7099 if (worktree)
7100 got_worktree_close(worktree);
7101 TAILQ_FOREACH(pe, &paths, entry)
7102 free((char *)pe->path);
7103 got_pathlist_free(&paths);
7104 free(cwd);
7105 return error;
7108 __dead static void
7109 usage_patch(void)
7111 fprintf(stderr, "usage: %s patch [patchfile]\n",
7112 getprogname());
7113 exit(1);
7116 static const struct got_error *
7117 patch_from_stdin(int *patchfd)
7119 const struct got_error *err = NULL;
7120 ssize_t r;
7121 char *path, buf[BUFSIZ];
7122 sig_t sighup, sigint, sigquit;
7124 err = got_opentemp_named_fd(&path, patchfd,
7125 GOT_TMPDIR_STR "/got-patch");
7126 if (err)
7127 return err;
7128 unlink(path);
7129 free(path);
7131 sighup = signal(SIGHUP, SIG_DFL);
7132 sigint = signal(SIGINT, SIG_DFL);
7133 sigquit = signal(SIGQUIT, SIG_DFL);
7135 for (;;) {
7136 r = read(0, buf, sizeof(buf));
7137 if (r == -1) {
7138 err = got_error_from_errno("read");
7139 break;
7141 if (r == 0)
7142 break;
7143 if (write(*patchfd, buf, r) == -1) {
7144 err = got_error_from_errno("write");
7145 break;
7149 signal(SIGHUP, sighup);
7150 signal(SIGINT, sigint);
7151 signal(SIGQUIT, sigquit);
7153 if (err != NULL)
7154 close(*patchfd);
7155 return NULL;
7158 static const struct got_error *
7159 cmd_patch(int argc, char *argv[])
7161 const struct got_error *error = NULL, *close_error = NULL;
7162 struct got_worktree *worktree = NULL;
7163 struct got_repository *repo = NULL;
7164 char *cwd = NULL;
7165 int ch;
7166 int patchfd;
7168 while ((ch = getopt(argc, argv, "")) != -1) {
7169 switch (ch) {
7170 default:
7171 usage_patch();
7172 /* NOTREACHED */
7176 argc -= optind;
7177 argv += optind;
7179 if (argc == 0) {
7180 error = patch_from_stdin(&patchfd);
7181 if (error)
7182 return error;
7183 } else if (argc == 1) {
7184 patchfd = open(argv[0], O_RDONLY);
7185 if (patchfd == -1) {
7186 error = got_error_from_errno2("open", argv[0]);
7187 return error;
7189 } else
7190 usage_patch();
7192 if ((cwd = getcwd(NULL, 0)) == NULL) {
7193 error = got_error_from_errno("getcwd");
7194 goto done;
7197 error = got_worktree_open(&worktree, cwd);
7198 if (error != NULL)
7199 goto done;
7201 const char *repo_path = got_worktree_get_repo_path(worktree);
7202 error = got_repo_open(&repo, repo_path, NULL);
7203 if (error != NULL)
7204 goto done;
7206 error = apply_unveil(got_repo_get_path(repo), 0,
7207 worktree ? got_worktree_get_root_path(worktree) : NULL);
7208 if (error != NULL)
7209 goto done;
7211 #ifndef PROFILE
7212 if (pledge("stdio rpath wpath cpath proc exec sendfd flock",
7213 NULL) == -1)
7214 err(1, "pledge");
7215 #endif
7217 error = got_patch(patchfd, worktree, repo, &print_remove_status,
7218 NULL, &add_progress, NULL);
7220 done:
7221 if (repo) {
7222 close_error = got_repo_close(repo);
7223 if (error == NULL)
7224 error = close_error;
7226 if (worktree != NULL) {
7227 close_error = got_worktree_close(worktree);
7228 if (error == NULL)
7229 error = close_error;
7231 free(cwd);
7232 return error;
7235 __dead static void
7236 usage_revert(void)
7238 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7239 "path ...\n", getprogname());
7240 exit(1);
7243 static const struct got_error *
7244 revert_progress(void *arg, unsigned char status, const char *path)
7246 if (status == GOT_STATUS_UNVERSIONED)
7247 return NULL;
7249 while (path[0] == '/')
7250 path++;
7251 printf("%c %s\n", status, path);
7252 return NULL;
7255 struct choose_patch_arg {
7256 FILE *patch_script_file;
7257 const char *action;
7260 static const struct got_error *
7261 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7262 int nchanges, const char *action)
7264 char *line = NULL;
7265 size_t linesize = 0;
7266 ssize_t linelen;
7268 switch (status) {
7269 case GOT_STATUS_ADD:
7270 printf("A %s\n%s this addition? [y/n] ", path, action);
7271 break;
7272 case GOT_STATUS_DELETE:
7273 printf("D %s\n%s this deletion? [y/n] ", path, action);
7274 break;
7275 case GOT_STATUS_MODIFY:
7276 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7277 return got_error_from_errno("fseek");
7278 printf(GOT_COMMIT_SEP_STR);
7279 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7280 printf("%s", line);
7281 if (ferror(patch_file))
7282 return got_error_from_errno("getline");
7283 printf(GOT_COMMIT_SEP_STR);
7284 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7285 path, n, nchanges, action);
7286 break;
7287 default:
7288 return got_error_path(path, GOT_ERR_FILE_STATUS);
7291 return NULL;
7294 static const struct got_error *
7295 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7296 FILE *patch_file, int n, int nchanges)
7298 const struct got_error *err = NULL;
7299 char *line = NULL;
7300 size_t linesize = 0;
7301 ssize_t linelen;
7302 int resp = ' ';
7303 struct choose_patch_arg *a = arg;
7305 *choice = GOT_PATCH_CHOICE_NONE;
7307 if (a->patch_script_file) {
7308 char *nl;
7309 err = show_change(status, path, patch_file, n, nchanges,
7310 a->action);
7311 if (err)
7312 return err;
7313 linelen = getline(&line, &linesize, a->patch_script_file);
7314 if (linelen == -1) {
7315 if (ferror(a->patch_script_file))
7316 return got_error_from_errno("getline");
7317 return NULL;
7319 nl = strchr(line, '\n');
7320 if (nl)
7321 *nl = '\0';
7322 if (strcmp(line, "y") == 0) {
7323 *choice = GOT_PATCH_CHOICE_YES;
7324 printf("y\n");
7325 } else if (strcmp(line, "n") == 0) {
7326 *choice = GOT_PATCH_CHOICE_NO;
7327 printf("n\n");
7328 } else if (strcmp(line, "q") == 0 &&
7329 status == GOT_STATUS_MODIFY) {
7330 *choice = GOT_PATCH_CHOICE_QUIT;
7331 printf("q\n");
7332 } else
7333 printf("invalid response '%s'\n", line);
7334 free(line);
7335 return NULL;
7338 while (resp != 'y' && resp != 'n' && resp != 'q') {
7339 err = show_change(status, path, patch_file, n, nchanges,
7340 a->action);
7341 if (err)
7342 return err;
7343 resp = getchar();
7344 if (resp == '\n')
7345 resp = getchar();
7346 if (status == GOT_STATUS_MODIFY) {
7347 if (resp != 'y' && resp != 'n' && resp != 'q') {
7348 printf("invalid response '%c'\n", resp);
7349 resp = ' ';
7351 } else if (resp != 'y' && resp != 'n') {
7352 printf("invalid response '%c'\n", resp);
7353 resp = ' ';
7357 if (resp == 'y')
7358 *choice = GOT_PATCH_CHOICE_YES;
7359 else if (resp == 'n')
7360 *choice = GOT_PATCH_CHOICE_NO;
7361 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7362 *choice = GOT_PATCH_CHOICE_QUIT;
7364 return NULL;
7367 static const struct got_error *
7368 cmd_revert(int argc, char *argv[])
7370 const struct got_error *error = NULL;
7371 struct got_worktree *worktree = NULL;
7372 struct got_repository *repo = NULL;
7373 char *cwd = NULL, *path = NULL;
7374 struct got_pathlist_head paths;
7375 struct got_pathlist_entry *pe;
7376 int ch, can_recurse = 0, pflag = 0;
7377 FILE *patch_script_file = NULL;
7378 const char *patch_script_path = NULL;
7379 struct choose_patch_arg cpa;
7381 TAILQ_INIT(&paths);
7383 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7384 switch (ch) {
7385 case 'p':
7386 pflag = 1;
7387 break;
7388 case 'F':
7389 patch_script_path = optarg;
7390 break;
7391 case 'R':
7392 can_recurse = 1;
7393 break;
7394 default:
7395 usage_revert();
7396 /* NOTREACHED */
7400 argc -= optind;
7401 argv += optind;
7403 #ifndef PROFILE
7404 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7405 "unveil", NULL) == -1)
7406 err(1, "pledge");
7407 #endif
7408 if (argc < 1)
7409 usage_revert();
7410 if (patch_script_path && !pflag)
7411 errx(1, "-F option can only be used together with -p option");
7413 cwd = getcwd(NULL, 0);
7414 if (cwd == NULL) {
7415 error = got_error_from_errno("getcwd");
7416 goto done;
7418 error = got_worktree_open(&worktree, cwd);
7419 if (error) {
7420 if (error->code == GOT_ERR_NOT_WORKTREE)
7421 error = wrap_not_worktree_error(error, "revert", cwd);
7422 goto done;
7425 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7426 NULL);
7427 if (error != NULL)
7428 goto done;
7430 if (patch_script_path) {
7431 patch_script_file = fopen(patch_script_path, "re");
7432 if (patch_script_file == NULL) {
7433 error = got_error_from_errno2("fopen",
7434 patch_script_path);
7435 goto done;
7438 error = apply_unveil(got_repo_get_path(repo), 1,
7439 got_worktree_get_root_path(worktree));
7440 if (error)
7441 goto done;
7443 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7444 if (error)
7445 goto done;
7447 if (!can_recurse) {
7448 char *ondisk_path;
7449 struct stat sb;
7450 TAILQ_FOREACH(pe, &paths, entry) {
7451 if (asprintf(&ondisk_path, "%s/%s",
7452 got_worktree_get_root_path(worktree),
7453 pe->path) == -1) {
7454 error = got_error_from_errno("asprintf");
7455 goto done;
7457 if (lstat(ondisk_path, &sb) == -1) {
7458 if (errno == ENOENT) {
7459 free(ondisk_path);
7460 continue;
7462 error = got_error_from_errno2("lstat",
7463 ondisk_path);
7464 free(ondisk_path);
7465 goto done;
7467 free(ondisk_path);
7468 if (S_ISDIR(sb.st_mode)) {
7469 error = got_error_msg(GOT_ERR_BAD_PATH,
7470 "reverting directories requires -R option");
7471 goto done;
7476 cpa.patch_script_file = patch_script_file;
7477 cpa.action = "revert";
7478 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7479 pflag ? choose_patch : NULL, &cpa, repo);
7480 done:
7481 if (patch_script_file && fclose(patch_script_file) == EOF &&
7482 error == NULL)
7483 error = got_error_from_errno2("fclose", patch_script_path);
7484 if (repo) {
7485 const struct got_error *close_err = got_repo_close(repo);
7486 if (error == NULL)
7487 error = close_err;
7489 if (worktree)
7490 got_worktree_close(worktree);
7491 free(path);
7492 free(cwd);
7493 return error;
7496 __dead static void
7497 usage_commit(void)
7499 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7500 "[path ...]\n", getprogname());
7501 exit(1);
7504 struct collect_commit_logmsg_arg {
7505 const char *cmdline_log;
7506 const char *prepared_log;
7507 int non_interactive;
7508 const char *editor;
7509 const char *worktree_path;
7510 const char *branch_name;
7511 const char *repo_path;
7512 char *logmsg_path;
7516 static const struct got_error *
7517 read_prepared_logmsg(char **logmsg, const char *path)
7519 const struct got_error *err = NULL;
7520 FILE *f = NULL;
7521 struct stat sb;
7522 size_t r;
7524 *logmsg = NULL;
7525 memset(&sb, 0, sizeof(sb));
7527 f = fopen(path, "re");
7528 if (f == NULL)
7529 return got_error_from_errno2("fopen", path);
7531 if (fstat(fileno(f), &sb) == -1) {
7532 err = got_error_from_errno2("fstat", path);
7533 goto done;
7535 if (sb.st_size == 0) {
7536 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7537 goto done;
7540 *logmsg = malloc(sb.st_size + 1);
7541 if (*logmsg == NULL) {
7542 err = got_error_from_errno("malloc");
7543 goto done;
7546 r = fread(*logmsg, 1, sb.st_size, f);
7547 if (r != sb.st_size) {
7548 if (ferror(f))
7549 err = got_error_from_errno2("fread", path);
7550 else
7551 err = got_error(GOT_ERR_IO);
7552 goto done;
7554 (*logmsg)[sb.st_size] = '\0';
7555 done:
7556 if (fclose(f) == EOF && err == NULL)
7557 err = got_error_from_errno2("fclose", path);
7558 if (err) {
7559 free(*logmsg);
7560 *logmsg = NULL;
7562 return err;
7566 static const struct got_error *
7567 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7568 void *arg)
7570 char *initial_content = NULL;
7571 struct got_pathlist_entry *pe;
7572 const struct got_error *err = NULL;
7573 char *template = NULL;
7574 struct collect_commit_logmsg_arg *a = arg;
7575 int initial_content_len;
7576 int fd = -1;
7577 size_t len;
7579 /* if a message was specified on the command line, just use it */
7580 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7581 len = strlen(a->cmdline_log) + 1;
7582 *logmsg = malloc(len + 1);
7583 if (*logmsg == NULL)
7584 return got_error_from_errno("malloc");
7585 strlcpy(*logmsg, a->cmdline_log, len);
7586 return NULL;
7587 } else if (a->prepared_log != NULL && a->non_interactive)
7588 return read_prepared_logmsg(logmsg, a->prepared_log);
7590 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7591 return got_error_from_errno("asprintf");
7593 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7594 if (err)
7595 goto done;
7597 if (a->prepared_log) {
7598 char *msg;
7599 err = read_prepared_logmsg(&msg, a->prepared_log);
7600 if (err)
7601 goto done;
7602 if (write(fd, msg, strlen(msg)) == -1) {
7603 err = got_error_from_errno2("write", a->logmsg_path);
7604 free(msg);
7605 goto done;
7607 free(msg);
7610 initial_content_len = asprintf(&initial_content,
7611 "\n# changes to be committed on branch %s:\n",
7612 a->branch_name);
7613 if (initial_content_len == -1) {
7614 err = got_error_from_errno("asprintf");
7615 goto done;
7618 if (write(fd, initial_content, initial_content_len) == -1) {
7619 err = got_error_from_errno2("write", a->logmsg_path);
7620 goto done;
7623 TAILQ_FOREACH(pe, commitable_paths, entry) {
7624 struct got_commitable *ct = pe->data;
7625 dprintf(fd, "# %c %s\n",
7626 got_commitable_get_status(ct),
7627 got_commitable_get_path(ct));
7630 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7631 initial_content_len, a->prepared_log ? 0 : 1);
7632 done:
7633 free(initial_content);
7634 free(template);
7636 if (fd != -1 && close(fd) == -1 && err == NULL)
7637 err = got_error_from_errno2("close", a->logmsg_path);
7639 /* Editor is done; we can now apply unveil(2) */
7640 if (err == NULL)
7641 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7642 if (err) {
7643 free(*logmsg);
7644 *logmsg = NULL;
7646 return err;
7649 static const struct got_error *
7650 cmd_commit(int argc, char *argv[])
7652 const struct got_error *error = NULL;
7653 struct got_worktree *worktree = NULL;
7654 struct got_repository *repo = NULL;
7655 char *cwd = NULL, *id_str = NULL;
7656 struct got_object_id *id = NULL;
7657 const char *logmsg = NULL;
7658 char *prepared_logmsg = NULL;
7659 struct collect_commit_logmsg_arg cl_arg;
7660 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7661 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7662 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7663 struct got_pathlist_head paths;
7665 TAILQ_INIT(&paths);
7666 cl_arg.logmsg_path = NULL;
7668 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7669 switch (ch) {
7670 case 'F':
7671 if (logmsg != NULL)
7672 option_conflict('F', 'm');
7673 prepared_logmsg = realpath(optarg, NULL);
7674 if (prepared_logmsg == NULL)
7675 return got_error_from_errno2("realpath",
7676 optarg);
7677 break;
7678 case 'm':
7679 if (prepared_logmsg)
7680 option_conflict('m', 'F');
7681 logmsg = optarg;
7682 break;
7683 case 'N':
7684 non_interactive = 1;
7685 break;
7686 case 'S':
7687 allow_bad_symlinks = 1;
7688 break;
7689 default:
7690 usage_commit();
7691 /* NOTREACHED */
7695 argc -= optind;
7696 argv += optind;
7698 #ifndef PROFILE
7699 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7700 "unveil", NULL) == -1)
7701 err(1, "pledge");
7702 #endif
7703 cwd = getcwd(NULL, 0);
7704 if (cwd == NULL) {
7705 error = got_error_from_errno("getcwd");
7706 goto done;
7708 error = got_worktree_open(&worktree, cwd);
7709 if (error) {
7710 if (error->code == GOT_ERR_NOT_WORKTREE)
7711 error = wrap_not_worktree_error(error, "commit", cwd);
7712 goto done;
7715 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7716 if (error)
7717 goto done;
7718 if (rebase_in_progress) {
7719 error = got_error(GOT_ERR_REBASING);
7720 goto done;
7723 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7724 worktree);
7725 if (error)
7726 goto done;
7728 error = get_gitconfig_path(&gitconfig_path);
7729 if (error)
7730 goto done;
7731 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7732 gitconfig_path);
7733 if (error != NULL)
7734 goto done;
7736 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7737 if (error)
7738 goto done;
7739 if (merge_in_progress) {
7740 error = got_error(GOT_ERR_MERGE_BUSY);
7741 goto done;
7744 error = get_author(&author, repo, worktree);
7745 if (error)
7746 return error;
7749 * unveil(2) traverses exec(2); if an editor is used we have
7750 * to apply unveil after the log message has been written.
7752 if (logmsg == NULL || strlen(logmsg) == 0)
7753 error = get_editor(&editor);
7754 else
7755 error = apply_unveil(got_repo_get_path(repo), 0,
7756 got_worktree_get_root_path(worktree));
7757 if (error)
7758 goto done;
7760 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7761 if (error)
7762 goto done;
7764 cl_arg.editor = editor;
7765 cl_arg.cmdline_log = logmsg;
7766 cl_arg.prepared_log = prepared_logmsg;
7767 cl_arg.non_interactive = non_interactive;
7768 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7769 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7770 if (!histedit_in_progress) {
7771 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7772 error = got_error(GOT_ERR_COMMIT_BRANCH);
7773 goto done;
7775 cl_arg.branch_name += 11;
7777 cl_arg.repo_path = got_repo_get_path(repo);
7778 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7779 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7780 print_status, NULL, repo);
7781 if (error) {
7782 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7783 cl_arg.logmsg_path != NULL)
7784 preserve_logmsg = 1;
7785 goto done;
7788 error = got_object_id_str(&id_str, id);
7789 if (error)
7790 goto done;
7791 printf("Created commit %s\n", id_str);
7792 done:
7793 if (preserve_logmsg) {
7794 fprintf(stderr, "%s: log message preserved in %s\n",
7795 getprogname(), cl_arg.logmsg_path);
7796 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7797 error == NULL)
7798 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7799 free(cl_arg.logmsg_path);
7800 if (repo) {
7801 const struct got_error *close_err = got_repo_close(repo);
7802 if (error == NULL)
7803 error = close_err;
7805 if (worktree)
7806 got_worktree_close(worktree);
7807 free(cwd);
7808 free(id_str);
7809 free(gitconfig_path);
7810 free(editor);
7811 free(author);
7812 free(prepared_logmsg);
7813 return error;
7816 __dead static void
7817 usage_send(void)
7819 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7820 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7821 "[remote-repository]\n", getprogname());
7822 exit(1);
7825 struct got_send_progress_arg {
7826 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7827 int verbosity;
7828 int last_ncommits;
7829 int last_nobj_total;
7830 int last_p_deltify;
7831 int last_p_written;
7832 int last_p_sent;
7833 int printed_something;
7834 int sent_something;
7835 struct got_pathlist_head *delete_branches;
7838 static const struct got_error *
7839 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7840 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7841 int success)
7843 struct got_send_progress_arg *a = arg;
7844 char scaled_packsize[FMT_SCALED_STRSIZE];
7845 char scaled_sent[FMT_SCALED_STRSIZE];
7846 int p_deltify = 0, p_written = 0, p_sent = 0;
7847 int print_searching = 0, print_total = 0;
7848 int print_deltify = 0, print_written = 0, print_sent = 0;
7850 if (a->verbosity < 0)
7851 return NULL;
7853 if (refname) {
7854 const char *status = success ? "accepted" : "rejected";
7856 if (success) {
7857 struct got_pathlist_entry *pe;
7858 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7859 const char *branchname = pe->path;
7860 if (got_path_cmp(branchname, refname,
7861 strlen(branchname), strlen(refname)) == 0) {
7862 status = "deleted";
7863 a->sent_something = 1;
7864 break;
7869 if (a->printed_something)
7870 putchar('\n');
7871 printf("Server has %s %s", status, refname);
7872 a->printed_something = 1;
7873 return NULL;
7876 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7877 return got_error_from_errno("fmt_scaled");
7878 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7879 return got_error_from_errno("fmt_scaled");
7881 if (a->last_ncommits != ncommits) {
7882 print_searching = 1;
7883 a->last_ncommits = ncommits;
7886 if (a->last_nobj_total != nobj_total) {
7887 print_searching = 1;
7888 print_total = 1;
7889 a->last_nobj_total = nobj_total;
7892 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7893 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7894 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7895 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7896 return got_error(GOT_ERR_NO_SPACE);
7899 if (nobj_deltify > 0 || nobj_written > 0) {
7900 if (nobj_deltify > 0) {
7901 p_deltify = (nobj_deltify * 100) / nobj_total;
7902 if (p_deltify != a->last_p_deltify) {
7903 a->last_p_deltify = p_deltify;
7904 print_searching = 1;
7905 print_total = 1;
7906 print_deltify = 1;
7909 if (nobj_written > 0) {
7910 p_written = (nobj_written * 100) / nobj_total;
7911 if (p_written != a->last_p_written) {
7912 a->last_p_written = p_written;
7913 print_searching = 1;
7914 print_total = 1;
7915 print_deltify = 1;
7916 print_written = 1;
7921 if (bytes_sent > 0) {
7922 p_sent = (bytes_sent * 100) / packfile_size;
7923 if (p_sent != a->last_p_sent) {
7924 a->last_p_sent = p_sent;
7925 print_searching = 1;
7926 print_total = 1;
7927 print_deltify = 1;
7928 print_written = 1;
7929 print_sent = 1;
7931 a->sent_something = 1;
7934 if (print_searching || print_total || print_deltify || print_written ||
7935 print_sent)
7936 printf("\r");
7937 if (print_searching)
7938 printf("packing %d reference%s", ncommits,
7939 ncommits == 1 ? "" : "s");
7940 if (print_total)
7941 printf("; %d object%s", nobj_total,
7942 nobj_total == 1 ? "" : "s");
7943 if (print_deltify)
7944 printf("; deltify: %d%%", p_deltify);
7945 if (print_sent)
7946 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
7947 scaled_packsize, p_sent);
7948 else if (print_written)
7949 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
7950 scaled_packsize, p_written);
7951 if (print_searching || print_total || print_deltify ||
7952 print_written || print_sent) {
7953 a->printed_something = 1;
7954 fflush(stdout);
7956 return NULL;
7959 static const struct got_error *
7960 cmd_send(int argc, char *argv[])
7962 const struct got_error *error = NULL;
7963 char *cwd = NULL, *repo_path = NULL;
7964 const char *remote_name;
7965 char *proto = NULL, *host = NULL, *port = NULL;
7966 char *repo_name = NULL, *server_path = NULL;
7967 const struct got_remote_repo *remotes, *remote = NULL;
7968 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7969 struct got_repository *repo = NULL;
7970 struct got_worktree *worktree = NULL;
7971 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7972 struct got_pathlist_head branches;
7973 struct got_pathlist_head tags;
7974 struct got_reflist_head all_branches;
7975 struct got_reflist_head all_tags;
7976 struct got_pathlist_head delete_args;
7977 struct got_pathlist_head delete_branches;
7978 struct got_reflist_entry *re;
7979 struct got_pathlist_entry *pe;
7980 int i, ch, sendfd = -1, sendstatus;
7981 pid_t sendpid = -1;
7982 struct got_send_progress_arg spa;
7983 int verbosity = 0, overwrite_refs = 0;
7984 int send_all_branches = 0, send_all_tags = 0;
7985 struct got_reference *ref = NULL;
7987 TAILQ_INIT(&branches);
7988 TAILQ_INIT(&tags);
7989 TAILQ_INIT(&all_branches);
7990 TAILQ_INIT(&all_tags);
7991 TAILQ_INIT(&delete_args);
7992 TAILQ_INIT(&delete_branches);
7994 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7995 switch (ch) {
7996 case 'a':
7997 send_all_branches = 1;
7998 break;
7999 case 'b':
8000 error = got_pathlist_append(&branches, optarg, NULL);
8001 if (error)
8002 return error;
8003 nbranches++;
8004 break;
8005 case 'd':
8006 error = got_pathlist_append(&delete_args, optarg, NULL);
8007 if (error)
8008 return error;
8009 break;
8010 case 'f':
8011 overwrite_refs = 1;
8012 break;
8013 case 'r':
8014 repo_path = realpath(optarg, NULL);
8015 if (repo_path == NULL)
8016 return got_error_from_errno2("realpath",
8017 optarg);
8018 got_path_strip_trailing_slashes(repo_path);
8019 break;
8020 case 't':
8021 error = got_pathlist_append(&tags, optarg, NULL);
8022 if (error)
8023 return error;
8024 ntags++;
8025 break;
8026 case 'T':
8027 send_all_tags = 1;
8028 break;
8029 case 'v':
8030 if (verbosity < 0)
8031 verbosity = 0;
8032 else if (verbosity < 3)
8033 verbosity++;
8034 break;
8035 case 'q':
8036 verbosity = -1;
8037 break;
8038 default:
8039 usage_send();
8040 /* NOTREACHED */
8043 argc -= optind;
8044 argv += optind;
8046 if (send_all_branches && !TAILQ_EMPTY(&branches))
8047 option_conflict('a', 'b');
8048 if (send_all_tags && !TAILQ_EMPTY(&tags))
8049 option_conflict('T', 't');
8052 if (argc == 0)
8053 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8054 else if (argc == 1)
8055 remote_name = argv[0];
8056 else
8057 usage_send();
8059 cwd = getcwd(NULL, 0);
8060 if (cwd == NULL) {
8061 error = got_error_from_errno("getcwd");
8062 goto done;
8065 if (repo_path == NULL) {
8066 error = got_worktree_open(&worktree, cwd);
8067 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8068 goto done;
8069 else
8070 error = NULL;
8071 if (worktree) {
8072 repo_path =
8073 strdup(got_worktree_get_repo_path(worktree));
8074 if (repo_path == NULL)
8075 error = got_error_from_errno("strdup");
8076 if (error)
8077 goto done;
8078 } else {
8079 repo_path = strdup(cwd);
8080 if (repo_path == NULL) {
8081 error = got_error_from_errno("strdup");
8082 goto done;
8087 error = got_repo_open(&repo, repo_path, NULL);
8088 if (error)
8089 goto done;
8091 if (worktree) {
8092 worktree_conf = got_worktree_get_gotconfig(worktree);
8093 if (worktree_conf) {
8094 got_gotconfig_get_remotes(&nremotes, &remotes,
8095 worktree_conf);
8096 for (i = 0; i < nremotes; i++) {
8097 if (strcmp(remotes[i].name, remote_name) == 0) {
8098 remote = &remotes[i];
8099 break;
8104 if (remote == NULL) {
8105 repo_conf = got_repo_get_gotconfig(repo);
8106 if (repo_conf) {
8107 got_gotconfig_get_remotes(&nremotes, &remotes,
8108 repo_conf);
8109 for (i = 0; i < nremotes; i++) {
8110 if (strcmp(remotes[i].name, remote_name) == 0) {
8111 remote = &remotes[i];
8112 break;
8117 if (remote == NULL) {
8118 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8119 for (i = 0; i < nremotes; i++) {
8120 if (strcmp(remotes[i].name, remote_name) == 0) {
8121 remote = &remotes[i];
8122 break;
8126 if (remote == NULL) {
8127 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8128 goto done;
8131 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8132 &repo_name, remote->send_url);
8133 if (error)
8134 goto done;
8136 if (strcmp(proto, "git") == 0) {
8137 #ifndef PROFILE
8138 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8139 "sendfd dns inet unveil", NULL) == -1)
8140 err(1, "pledge");
8141 #endif
8142 } else if (strcmp(proto, "git+ssh") == 0 ||
8143 strcmp(proto, "ssh") == 0) {
8144 #ifndef PROFILE
8145 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8146 "sendfd unveil", NULL) == -1)
8147 err(1, "pledge");
8148 #endif
8149 } else if (strcmp(proto, "http") == 0 ||
8150 strcmp(proto, "git+http") == 0) {
8151 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8152 goto done;
8153 } else {
8154 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8155 goto done;
8158 error = got_dial_apply_unveil(proto);
8159 if (error)
8160 goto done;
8162 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8163 if (error)
8164 goto done;
8166 if (send_all_branches) {
8167 error = got_ref_list(&all_branches, repo, "refs/heads",
8168 got_ref_cmp_by_name, NULL);
8169 if (error)
8170 goto done;
8171 TAILQ_FOREACH(re, &all_branches, entry) {
8172 const char *branchname = got_ref_get_name(re->ref);
8173 error = got_pathlist_append(&branches,
8174 branchname, NULL);
8175 if (error)
8176 goto done;
8177 nbranches++;
8179 } else if (nbranches == 0) {
8180 for (i = 0; i < remote->nsend_branches; i++) {
8181 got_pathlist_append(&branches,
8182 remote->send_branches[i], NULL);
8186 if (send_all_tags) {
8187 error = got_ref_list(&all_tags, repo, "refs/tags",
8188 got_ref_cmp_by_name, NULL);
8189 if (error)
8190 goto done;
8191 TAILQ_FOREACH(re, &all_tags, entry) {
8192 const char *tagname = got_ref_get_name(re->ref);
8193 error = got_pathlist_append(&tags,
8194 tagname, NULL);
8195 if (error)
8196 goto done;
8197 ntags++;
8202 * To prevent accidents only branches in refs/heads/ can be deleted
8203 * with 'got send -d'.
8204 * Deleting anything else requires local repository access or Git.
8206 TAILQ_FOREACH(pe, &delete_args, entry) {
8207 const char *branchname = pe->path;
8208 char *s;
8209 struct got_pathlist_entry *new;
8210 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8211 s = strdup(branchname);
8212 if (s == NULL) {
8213 error = got_error_from_errno("strdup");
8214 goto done;
8216 } else {
8217 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8218 error = got_error_from_errno("asprintf");
8219 goto done;
8222 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8223 if (error || new == NULL /* duplicate */)
8224 free(s);
8225 if (error)
8226 goto done;
8227 ndelete_branches++;
8230 if (nbranches == 0 && ndelete_branches == 0) {
8231 struct got_reference *head_ref;
8232 if (worktree)
8233 error = got_ref_open(&head_ref, repo,
8234 got_worktree_get_head_ref_name(worktree), 0);
8235 else
8236 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8237 if (error)
8238 goto done;
8239 if (got_ref_is_symbolic(head_ref)) {
8240 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8241 got_ref_close(head_ref);
8242 if (error)
8243 goto done;
8244 } else
8245 ref = head_ref;
8246 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8247 NULL);
8248 if (error)
8249 goto done;
8250 nbranches++;
8253 if (verbosity >= 0)
8254 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8255 port ? ":" : "", port ? port : "");
8257 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8258 server_path, verbosity);
8259 if (error)
8260 goto done;
8262 memset(&spa, 0, sizeof(spa));
8263 spa.last_scaled_packsize[0] = '\0';
8264 spa.last_p_deltify = -1;
8265 spa.last_p_written = -1;
8266 spa.verbosity = verbosity;
8267 spa.delete_branches = &delete_branches;
8268 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8269 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8270 check_cancelled, NULL);
8271 if (spa.printed_something)
8272 putchar('\n');
8273 if (error)
8274 goto done;
8275 if (!spa.sent_something && verbosity >= 0)
8276 printf("Already up-to-date\n");
8277 done:
8278 if (sendpid > 0) {
8279 if (kill(sendpid, SIGTERM) == -1)
8280 error = got_error_from_errno("kill");
8281 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8282 error = got_error_from_errno("waitpid");
8284 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8285 error = got_error_from_errno("close");
8286 if (repo) {
8287 const struct got_error *close_err = got_repo_close(repo);
8288 if (error == NULL)
8289 error = close_err;
8291 if (worktree)
8292 got_worktree_close(worktree);
8293 if (ref)
8294 got_ref_close(ref);
8295 got_pathlist_free(&branches);
8296 got_pathlist_free(&tags);
8297 got_ref_list_free(&all_branches);
8298 got_ref_list_free(&all_tags);
8299 got_pathlist_free(&delete_args);
8300 TAILQ_FOREACH(pe, &delete_branches, entry)
8301 free((char *)pe->path);
8302 got_pathlist_free(&delete_branches);
8303 free(cwd);
8304 free(repo_path);
8305 free(proto);
8306 free(host);
8307 free(port);
8308 free(server_path);
8309 free(repo_name);
8310 return error;
8313 __dead static void
8314 usage_cherrypick(void)
8316 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8317 exit(1);
8320 static const struct got_error *
8321 cmd_cherrypick(int argc, char *argv[])
8323 const struct got_error *error = NULL;
8324 struct got_worktree *worktree = NULL;
8325 struct got_repository *repo = NULL;
8326 char *cwd = NULL, *commit_id_str = NULL;
8327 struct got_object_id *commit_id = NULL;
8328 struct got_commit_object *commit = NULL;
8329 struct got_object_qid *pid;
8330 int ch;
8331 struct got_update_progress_arg upa;
8333 while ((ch = getopt(argc, argv, "")) != -1) {
8334 switch (ch) {
8335 default:
8336 usage_cherrypick();
8337 /* NOTREACHED */
8341 argc -= optind;
8342 argv += optind;
8344 #ifndef PROFILE
8345 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8346 "unveil", NULL) == -1)
8347 err(1, "pledge");
8348 #endif
8349 if (argc != 1)
8350 usage_cherrypick();
8352 cwd = getcwd(NULL, 0);
8353 if (cwd == NULL) {
8354 error = got_error_from_errno("getcwd");
8355 goto done;
8357 error = got_worktree_open(&worktree, cwd);
8358 if (error) {
8359 if (error->code == GOT_ERR_NOT_WORKTREE)
8360 error = wrap_not_worktree_error(error, "cherrypick",
8361 cwd);
8362 goto done;
8365 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8366 NULL);
8367 if (error != NULL)
8368 goto done;
8370 error = apply_unveil(got_repo_get_path(repo), 0,
8371 got_worktree_get_root_path(worktree));
8372 if (error)
8373 goto done;
8375 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8376 GOT_OBJ_TYPE_COMMIT, repo);
8377 if (error != NULL) {
8378 struct got_reference *ref;
8379 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8380 goto done;
8381 error = got_ref_open(&ref, repo, argv[0], 0);
8382 if (error != NULL)
8383 goto done;
8384 error = got_ref_resolve(&commit_id, repo, ref);
8385 got_ref_close(ref);
8386 if (error != NULL)
8387 goto done;
8389 error = got_object_id_str(&commit_id_str, commit_id);
8390 if (error)
8391 goto done;
8393 error = got_object_open_as_commit(&commit, repo, commit_id);
8394 if (error)
8395 goto done;
8396 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8397 memset(&upa, 0, sizeof(upa));
8398 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8399 commit_id, repo, update_progress, &upa, check_cancelled,
8400 NULL);
8401 if (error != NULL)
8402 goto done;
8404 if (upa.did_something)
8405 printf("Merged commit %s\n", commit_id_str);
8406 print_merge_progress_stats(&upa);
8407 done:
8408 if (commit)
8409 got_object_commit_close(commit);
8410 free(commit_id_str);
8411 if (worktree)
8412 got_worktree_close(worktree);
8413 if (repo) {
8414 const struct got_error *close_err = got_repo_close(repo);
8415 if (error == NULL)
8416 error = close_err;
8418 return error;
8421 __dead static void
8422 usage_backout(void)
8424 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8425 exit(1);
8428 static const struct got_error *
8429 cmd_backout(int argc, char *argv[])
8431 const struct got_error *error = NULL;
8432 struct got_worktree *worktree = NULL;
8433 struct got_repository *repo = NULL;
8434 char *cwd = NULL, *commit_id_str = NULL;
8435 struct got_object_id *commit_id = NULL;
8436 struct got_commit_object *commit = NULL;
8437 struct got_object_qid *pid;
8438 int ch;
8439 struct got_update_progress_arg upa;
8441 while ((ch = getopt(argc, argv, "")) != -1) {
8442 switch (ch) {
8443 default:
8444 usage_backout();
8445 /* NOTREACHED */
8449 argc -= optind;
8450 argv += optind;
8452 #ifndef PROFILE
8453 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8454 "unveil", NULL) == -1)
8455 err(1, "pledge");
8456 #endif
8457 if (argc != 1)
8458 usage_backout();
8460 cwd = getcwd(NULL, 0);
8461 if (cwd == NULL) {
8462 error = got_error_from_errno("getcwd");
8463 goto done;
8465 error = got_worktree_open(&worktree, cwd);
8466 if (error) {
8467 if (error->code == GOT_ERR_NOT_WORKTREE)
8468 error = wrap_not_worktree_error(error, "backout", cwd);
8469 goto done;
8472 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8473 NULL);
8474 if (error != NULL)
8475 goto done;
8477 error = apply_unveil(got_repo_get_path(repo), 0,
8478 got_worktree_get_root_path(worktree));
8479 if (error)
8480 goto done;
8482 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8483 GOT_OBJ_TYPE_COMMIT, repo);
8484 if (error != NULL) {
8485 struct got_reference *ref;
8486 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8487 goto done;
8488 error = got_ref_open(&ref, repo, argv[0], 0);
8489 if (error != NULL)
8490 goto done;
8491 error = got_ref_resolve(&commit_id, repo, ref);
8492 got_ref_close(ref);
8493 if (error != NULL)
8494 goto done;
8496 error = got_object_id_str(&commit_id_str, commit_id);
8497 if (error)
8498 goto done;
8500 error = got_object_open_as_commit(&commit, repo, commit_id);
8501 if (error)
8502 goto done;
8503 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8504 if (pid == NULL) {
8505 error = got_error(GOT_ERR_ROOT_COMMIT);
8506 goto done;
8509 memset(&upa, 0, sizeof(upa));
8510 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8511 repo, update_progress, &upa, check_cancelled, NULL);
8512 if (error != NULL)
8513 goto done;
8515 if (upa.did_something)
8516 printf("Backed out commit %s\n", commit_id_str);
8517 print_merge_progress_stats(&upa);
8518 done:
8519 if (commit)
8520 got_object_commit_close(commit);
8521 free(commit_id_str);
8522 if (worktree)
8523 got_worktree_close(worktree);
8524 if (repo) {
8525 const struct got_error *close_err = got_repo_close(repo);
8526 if (error == NULL)
8527 error = close_err;
8529 return error;
8532 __dead static void
8533 usage_rebase(void)
8535 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8536 getprogname());
8537 exit(1);
8540 void
8541 trim_logmsg(char *logmsg, int limit)
8543 char *nl;
8544 size_t len;
8546 len = strlen(logmsg);
8547 if (len > limit)
8548 len = limit;
8549 logmsg[len] = '\0';
8550 nl = strchr(logmsg, '\n');
8551 if (nl)
8552 *nl = '\0';
8555 static const struct got_error *
8556 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8558 const struct got_error *err;
8559 char *logmsg0 = NULL;
8560 const char *s;
8562 err = got_object_commit_get_logmsg(&logmsg0, commit);
8563 if (err)
8564 return err;
8566 s = logmsg0;
8567 while (isspace((unsigned char)s[0]))
8568 s++;
8570 *logmsg = strdup(s);
8571 if (*logmsg == NULL) {
8572 err = got_error_from_errno("strdup");
8573 goto done;
8576 trim_logmsg(*logmsg, limit);
8577 done:
8578 free(logmsg0);
8579 return err;
8582 static const struct got_error *
8583 show_rebase_merge_conflict(struct got_object_id *id,
8584 struct got_repository *repo)
8586 const struct got_error *err;
8587 struct got_commit_object *commit = NULL;
8588 char *id_str = NULL, *logmsg = NULL;
8590 err = got_object_open_as_commit(&commit, repo, id);
8591 if (err)
8592 return err;
8594 err = got_object_id_str(&id_str, id);
8595 if (err)
8596 goto done;
8598 id_str[12] = '\0';
8600 err = get_short_logmsg(&logmsg, 42, commit);
8601 if (err)
8602 goto done;
8604 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8605 done:
8606 free(id_str);
8607 got_object_commit_close(commit);
8608 free(logmsg);
8609 return err;
8612 static const struct got_error *
8613 show_rebase_progress(struct got_commit_object *commit,
8614 struct got_object_id *old_id, struct got_object_id *new_id)
8616 const struct got_error *err;
8617 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8619 err = got_object_id_str(&old_id_str, old_id);
8620 if (err)
8621 goto done;
8623 if (new_id) {
8624 err = got_object_id_str(&new_id_str, new_id);
8625 if (err)
8626 goto done;
8629 old_id_str[12] = '\0';
8630 if (new_id_str)
8631 new_id_str[12] = '\0';
8633 err = get_short_logmsg(&logmsg, 42, commit);
8634 if (err)
8635 goto done;
8637 printf("%s -> %s: %s\n", old_id_str,
8638 new_id_str ? new_id_str : "no-op change", logmsg);
8639 done:
8640 free(old_id_str);
8641 free(new_id_str);
8642 free(logmsg);
8643 return err;
8646 static const struct got_error *
8647 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8648 struct got_reference *branch, struct got_reference *new_base_branch,
8649 struct got_reference *tmp_branch, struct got_repository *repo,
8650 int create_backup)
8652 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8653 return got_worktree_rebase_complete(worktree, fileindex,
8654 new_base_branch, tmp_branch, branch, repo, create_backup);
8657 static const struct got_error *
8658 rebase_commit(struct got_pathlist_head *merged_paths,
8659 struct got_worktree *worktree, struct got_fileindex *fileindex,
8660 struct got_reference *tmp_branch,
8661 struct got_object_id *commit_id, struct got_repository *repo)
8663 const struct got_error *error;
8664 struct got_commit_object *commit;
8665 struct got_object_id *new_commit_id;
8667 error = got_object_open_as_commit(&commit, repo, commit_id);
8668 if (error)
8669 return error;
8671 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8672 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8673 if (error) {
8674 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8675 goto done;
8676 error = show_rebase_progress(commit, commit_id, NULL);
8677 } else {
8678 error = show_rebase_progress(commit, commit_id, new_commit_id);
8679 free(new_commit_id);
8681 done:
8682 got_object_commit_close(commit);
8683 return error;
8686 struct check_path_prefix_arg {
8687 const char *path_prefix;
8688 size_t len;
8689 int errcode;
8692 static const struct got_error *
8693 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8694 struct got_blob_object *blob2, struct got_object_id *id1,
8695 struct got_object_id *id2, const char *path1, const char *path2,
8696 mode_t mode1, mode_t mode2, struct got_repository *repo)
8698 struct check_path_prefix_arg *a = arg;
8700 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8701 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8702 return got_error(a->errcode);
8704 return NULL;
8707 static const struct got_error *
8708 check_path_prefix(struct got_object_id *parent_id,
8709 struct got_object_id *commit_id, const char *path_prefix,
8710 int errcode, struct got_repository *repo)
8712 const struct got_error *err;
8713 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8714 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8715 struct check_path_prefix_arg cpp_arg;
8717 if (got_path_is_root_dir(path_prefix))
8718 return NULL;
8720 err = got_object_open_as_commit(&commit, repo, commit_id);
8721 if (err)
8722 goto done;
8724 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8725 if (err)
8726 goto done;
8728 err = got_object_open_as_tree(&tree1, repo,
8729 got_object_commit_get_tree_id(parent_commit));
8730 if (err)
8731 goto done;
8733 err = got_object_open_as_tree(&tree2, repo,
8734 got_object_commit_get_tree_id(commit));
8735 if (err)
8736 goto done;
8738 cpp_arg.path_prefix = path_prefix;
8739 while (cpp_arg.path_prefix[0] == '/')
8740 cpp_arg.path_prefix++;
8741 cpp_arg.len = strlen(cpp_arg.path_prefix);
8742 cpp_arg.errcode = errcode;
8743 err = got_diff_tree(tree1, tree2, "", "", repo,
8744 check_path_prefix_in_diff, &cpp_arg, 0);
8745 done:
8746 if (tree1)
8747 got_object_tree_close(tree1);
8748 if (tree2)
8749 got_object_tree_close(tree2);
8750 if (commit)
8751 got_object_commit_close(commit);
8752 if (parent_commit)
8753 got_object_commit_close(parent_commit);
8754 return err;
8757 static const struct got_error *
8758 collect_commits(struct got_object_id_queue *commits,
8759 struct got_object_id *initial_commit_id,
8760 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8761 const char *path_prefix, int path_prefix_errcode,
8762 struct got_repository *repo)
8764 const struct got_error *err = NULL;
8765 struct got_commit_graph *graph = NULL;
8766 struct got_object_id *parent_id = NULL;
8767 struct got_object_qid *qid;
8768 struct got_object_id *commit_id = initial_commit_id;
8770 err = got_commit_graph_open(&graph, "/", 1);
8771 if (err)
8772 return err;
8774 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8775 check_cancelled, NULL);
8776 if (err)
8777 goto done;
8778 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8779 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8780 check_cancelled, NULL);
8781 if (err) {
8782 if (err->code == GOT_ERR_ITER_COMPLETED) {
8783 err = got_error_msg(GOT_ERR_ANCESTRY,
8784 "ran out of commits to rebase before "
8785 "youngest common ancestor commit has "
8786 "been reached?!?");
8788 goto done;
8789 } else {
8790 err = check_path_prefix(parent_id, commit_id,
8791 path_prefix, path_prefix_errcode, repo);
8792 if (err)
8793 goto done;
8795 err = got_object_qid_alloc(&qid, commit_id);
8796 if (err)
8797 goto done;
8798 STAILQ_INSERT_HEAD(commits, qid, entry);
8799 commit_id = parent_id;
8802 done:
8803 got_commit_graph_close(graph);
8804 return err;
8807 static const struct got_error *
8808 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8810 const struct got_error *err = NULL;
8811 time_t committer_time;
8812 struct tm tm;
8813 char datebuf[11]; /* YYYY-MM-DD + NUL */
8814 char *author0 = NULL, *author, *smallerthan;
8815 char *logmsg0 = NULL, *logmsg, *newline;
8817 committer_time = got_object_commit_get_committer_time(commit);
8818 if (gmtime_r(&committer_time, &tm) == NULL)
8819 return got_error_from_errno("gmtime_r");
8820 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8821 return got_error(GOT_ERR_NO_SPACE);
8823 author0 = strdup(got_object_commit_get_author(commit));
8824 if (author0 == NULL)
8825 return got_error_from_errno("strdup");
8826 author = author0;
8827 smallerthan = strchr(author, '<');
8828 if (smallerthan && smallerthan[1] != '\0')
8829 author = smallerthan + 1;
8830 author[strcspn(author, "@>")] = '\0';
8832 err = got_object_commit_get_logmsg(&logmsg0, commit);
8833 if (err)
8834 goto done;
8835 logmsg = logmsg0;
8836 while (*logmsg == '\n')
8837 logmsg++;
8838 newline = strchr(logmsg, '\n');
8839 if (newline)
8840 *newline = '\0';
8842 if (asprintf(brief_str, "%s %s %s",
8843 datebuf, author, logmsg) == -1)
8844 err = got_error_from_errno("asprintf");
8845 done:
8846 free(author0);
8847 free(logmsg0);
8848 return err;
8851 static const struct got_error *
8852 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8853 struct got_repository *repo)
8855 const struct got_error *err;
8856 char *id_str;
8858 err = got_object_id_str(&id_str, id);
8859 if (err)
8860 return err;
8862 err = got_ref_delete(ref, repo);
8863 if (err)
8864 goto done;
8866 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8867 done:
8868 free(id_str);
8869 return err;
8872 static const struct got_error *
8873 print_backup_ref(const char *branch_name, const char *new_id_str,
8874 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8875 struct got_reflist_object_id_map *refs_idmap,
8876 struct got_repository *repo)
8878 const struct got_error *err = NULL;
8879 struct got_reflist_head *refs;
8880 char *refs_str = NULL;
8881 struct got_object_id *new_commit_id = NULL;
8882 struct got_commit_object *new_commit = NULL;
8883 char *new_commit_brief_str = NULL;
8884 struct got_object_id *yca_id = NULL;
8885 struct got_commit_object *yca_commit = NULL;
8886 char *yca_id_str = NULL, *yca_brief_str = NULL;
8887 char *custom_refs_str;
8889 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8890 return got_error_from_errno("asprintf");
8892 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8893 0, 0, refs_idmap, custom_refs_str);
8894 if (err)
8895 goto done;
8897 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8898 if (err)
8899 goto done;
8901 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8902 if (refs) {
8903 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8904 if (err)
8905 goto done;
8908 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8909 if (err)
8910 goto done;
8912 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8913 if (err)
8914 goto done;
8916 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8917 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8918 if (err)
8919 goto done;
8921 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8922 refs_str ? " (" : "", refs_str ? refs_str : "",
8923 refs_str ? ")" : "", new_commit_brief_str);
8924 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8925 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8926 free(refs_str);
8927 refs_str = NULL;
8929 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8930 if (err)
8931 goto done;
8933 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8934 if (err)
8935 goto done;
8937 err = got_object_id_str(&yca_id_str, yca_id);
8938 if (err)
8939 goto done;
8941 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8942 if (refs) {
8943 err = build_refs_str(&refs_str, refs, yca_id, repo);
8944 if (err)
8945 goto done;
8947 printf("history forked at %s%s%s%s\n %s\n",
8948 yca_id_str,
8949 refs_str ? " (" : "", refs_str ? refs_str : "",
8950 refs_str ? ")" : "", yca_brief_str);
8952 done:
8953 free(custom_refs_str);
8954 free(new_commit_id);
8955 free(refs_str);
8956 free(yca_id);
8957 free(yca_id_str);
8958 free(yca_brief_str);
8959 if (new_commit)
8960 got_object_commit_close(new_commit);
8961 if (yca_commit)
8962 got_object_commit_close(yca_commit);
8964 return NULL;
8967 static const struct got_error *
8968 process_backup_refs(const char *backup_ref_prefix,
8969 const char *wanted_branch_name,
8970 int delete, struct got_repository *repo)
8972 const struct got_error *err;
8973 struct got_reflist_head refs, backup_refs;
8974 struct got_reflist_entry *re;
8975 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8976 struct got_object_id *old_commit_id = NULL;
8977 char *branch_name = NULL;
8978 struct got_commit_object *old_commit = NULL;
8979 struct got_reflist_object_id_map *refs_idmap = NULL;
8980 int wanted_branch_found = 0;
8982 TAILQ_INIT(&refs);
8983 TAILQ_INIT(&backup_refs);
8985 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8986 if (err)
8987 return err;
8989 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8990 if (err)
8991 goto done;
8993 if (wanted_branch_name) {
8994 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8995 wanted_branch_name += 11;
8998 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8999 got_ref_cmp_by_commit_timestamp_descending, repo);
9000 if (err)
9001 goto done;
9003 TAILQ_FOREACH(re, &backup_refs, entry) {
9004 const char *refname = got_ref_get_name(re->ref);
9005 char *slash;
9007 err = check_cancelled(NULL);
9008 if (err)
9009 break;
9011 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9012 if (err)
9013 break;
9015 err = got_object_open_as_commit(&old_commit, repo,
9016 old_commit_id);
9017 if (err)
9018 break;
9020 if (strncmp(backup_ref_prefix, refname,
9021 backup_ref_prefix_len) == 0)
9022 refname += backup_ref_prefix_len;
9024 while (refname[0] == '/')
9025 refname++;
9027 branch_name = strdup(refname);
9028 if (branch_name == NULL) {
9029 err = got_error_from_errno("strdup");
9030 break;
9032 slash = strrchr(branch_name, '/');
9033 if (slash) {
9034 *slash = '\0';
9035 refname += strlen(branch_name) + 1;
9038 if (wanted_branch_name == NULL ||
9039 strcmp(wanted_branch_name, branch_name) == 0) {
9040 wanted_branch_found = 1;
9041 if (delete) {
9042 err = delete_backup_ref(re->ref,
9043 old_commit_id, repo);
9044 } else {
9045 err = print_backup_ref(branch_name, refname,
9046 old_commit_id, old_commit, refs_idmap,
9047 repo);
9049 if (err)
9050 break;
9053 free(old_commit_id);
9054 old_commit_id = NULL;
9055 free(branch_name);
9056 branch_name = NULL;
9057 got_object_commit_close(old_commit);
9058 old_commit = NULL;
9061 if (wanted_branch_name && !wanted_branch_found) {
9062 err = got_error_fmt(GOT_ERR_NOT_REF,
9063 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9065 done:
9066 if (refs_idmap)
9067 got_reflist_object_id_map_free(refs_idmap);
9068 got_ref_list_free(&refs);
9069 got_ref_list_free(&backup_refs);
9070 free(old_commit_id);
9071 free(branch_name);
9072 if (old_commit)
9073 got_object_commit_close(old_commit);
9074 return err;
9077 static const struct got_error *
9078 abort_progress(void *arg, unsigned char status, const char *path)
9081 * Unversioned files should not clutter progress output when
9082 * an operation is aborted.
9084 if (status == GOT_STATUS_UNVERSIONED)
9085 return NULL;
9087 return update_progress(arg, status, path);
9090 static const struct got_error *
9091 cmd_rebase(int argc, char *argv[])
9093 const struct got_error *error = NULL;
9094 struct got_worktree *worktree = NULL;
9095 struct got_repository *repo = NULL;
9096 struct got_fileindex *fileindex = NULL;
9097 char *cwd = NULL;
9098 struct got_reference *branch = NULL;
9099 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9100 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9101 struct got_object_id *resume_commit_id = NULL;
9102 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9103 struct got_commit_object *commit = NULL;
9104 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9105 int histedit_in_progress = 0, merge_in_progress = 0;
9106 int create_backup = 1, list_backups = 0, delete_backups = 0;
9107 struct got_object_id_queue commits;
9108 struct got_pathlist_head merged_paths;
9109 const struct got_object_id_queue *parent_ids;
9110 struct got_object_qid *qid, *pid;
9111 struct got_update_progress_arg upa;
9113 STAILQ_INIT(&commits);
9114 TAILQ_INIT(&merged_paths);
9115 memset(&upa, 0, sizeof(upa));
9117 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9118 switch (ch) {
9119 case 'a':
9120 abort_rebase = 1;
9121 break;
9122 case 'c':
9123 continue_rebase = 1;
9124 break;
9125 case 'l':
9126 list_backups = 1;
9127 break;
9128 case 'X':
9129 delete_backups = 1;
9130 break;
9131 default:
9132 usage_rebase();
9133 /* NOTREACHED */
9137 argc -= optind;
9138 argv += optind;
9140 #ifndef PROFILE
9141 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9142 "unveil", NULL) == -1)
9143 err(1, "pledge");
9144 #endif
9145 if (list_backups) {
9146 if (abort_rebase)
9147 option_conflict('l', 'a');
9148 if (continue_rebase)
9149 option_conflict('l', 'c');
9150 if (delete_backups)
9151 option_conflict('l', 'X');
9152 if (argc != 0 && argc != 1)
9153 usage_rebase();
9154 } else if (delete_backups) {
9155 if (abort_rebase)
9156 option_conflict('X', 'a');
9157 if (continue_rebase)
9158 option_conflict('X', 'c');
9159 if (list_backups)
9160 option_conflict('l', 'X');
9161 if (argc != 0 && argc != 1)
9162 usage_rebase();
9163 } else {
9164 if (abort_rebase && continue_rebase)
9165 usage_rebase();
9166 else if (abort_rebase || continue_rebase) {
9167 if (argc != 0)
9168 usage_rebase();
9169 } else if (argc != 1)
9170 usage_rebase();
9173 cwd = getcwd(NULL, 0);
9174 if (cwd == NULL) {
9175 error = got_error_from_errno("getcwd");
9176 goto done;
9178 error = got_worktree_open(&worktree, cwd);
9179 if (error) {
9180 if (list_backups || delete_backups) {
9181 if (error->code != GOT_ERR_NOT_WORKTREE)
9182 goto done;
9183 } else {
9184 if (error->code == GOT_ERR_NOT_WORKTREE)
9185 error = wrap_not_worktree_error(error,
9186 "rebase", cwd);
9187 goto done;
9191 error = got_repo_open(&repo,
9192 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9193 if (error != NULL)
9194 goto done;
9196 error = apply_unveil(got_repo_get_path(repo), 0,
9197 worktree ? got_worktree_get_root_path(worktree) : NULL);
9198 if (error)
9199 goto done;
9201 if (list_backups || delete_backups) {
9202 error = process_backup_refs(
9203 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9204 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9205 goto done; /* nothing else to do */
9208 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9209 worktree);
9210 if (error)
9211 goto done;
9212 if (histedit_in_progress) {
9213 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9214 goto done;
9217 error = got_worktree_merge_in_progress(&merge_in_progress,
9218 worktree, repo);
9219 if (error)
9220 goto done;
9221 if (merge_in_progress) {
9222 error = got_error(GOT_ERR_MERGE_BUSY);
9223 goto done;
9226 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9227 if (error)
9228 goto done;
9230 if (abort_rebase) {
9231 if (!rebase_in_progress) {
9232 error = got_error(GOT_ERR_NOT_REBASING);
9233 goto done;
9235 error = got_worktree_rebase_continue(&resume_commit_id,
9236 &new_base_branch, &tmp_branch, &branch, &fileindex,
9237 worktree, repo);
9238 if (error)
9239 goto done;
9240 printf("Switching work tree to %s\n",
9241 got_ref_get_symref_target(new_base_branch));
9242 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9243 new_base_branch, abort_progress, &upa);
9244 if (error)
9245 goto done;
9246 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9247 print_merge_progress_stats(&upa);
9248 goto done; /* nothing else to do */
9251 if (continue_rebase) {
9252 if (!rebase_in_progress) {
9253 error = got_error(GOT_ERR_NOT_REBASING);
9254 goto done;
9256 error = got_worktree_rebase_continue(&resume_commit_id,
9257 &new_base_branch, &tmp_branch, &branch, &fileindex,
9258 worktree, repo);
9259 if (error)
9260 goto done;
9262 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9263 resume_commit_id, repo);
9264 if (error)
9265 goto done;
9267 yca_id = got_object_id_dup(resume_commit_id);
9268 if (yca_id == NULL) {
9269 error = got_error_from_errno("got_object_id_dup");
9270 goto done;
9272 } else {
9273 error = got_ref_open(&branch, repo, argv[0], 0);
9274 if (error != NULL)
9275 goto done;
9278 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9279 if (error)
9280 goto done;
9282 if (!continue_rebase) {
9283 struct got_object_id *base_commit_id;
9285 base_commit_id = got_worktree_get_base_commit_id(worktree);
9286 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9287 base_commit_id, branch_head_commit_id, 1, repo,
9288 check_cancelled, NULL);
9289 if (error)
9290 goto done;
9291 if (yca_id == NULL) {
9292 error = got_error_msg(GOT_ERR_ANCESTRY,
9293 "specified branch shares no common ancestry "
9294 "with work tree's branch");
9295 goto done;
9298 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9299 if (error) {
9300 if (error->code != GOT_ERR_ANCESTRY)
9301 goto done;
9302 error = NULL;
9303 } else {
9304 struct got_pathlist_head paths;
9305 printf("%s is already based on %s\n",
9306 got_ref_get_name(branch),
9307 got_worktree_get_head_ref_name(worktree));
9308 error = switch_head_ref(branch, branch_head_commit_id,
9309 worktree, repo);
9310 if (error)
9311 goto done;
9312 error = got_worktree_set_base_commit_id(worktree, repo,
9313 branch_head_commit_id);
9314 if (error)
9315 goto done;
9316 TAILQ_INIT(&paths);
9317 error = got_pathlist_append(&paths, "", NULL);
9318 if (error)
9319 goto done;
9320 error = got_worktree_checkout_files(worktree,
9321 &paths, repo, update_progress, &upa,
9322 check_cancelled, NULL);
9323 got_pathlist_free(&paths);
9324 if (error)
9325 goto done;
9326 if (upa.did_something) {
9327 char *id_str;
9328 error = got_object_id_str(&id_str,
9329 branch_head_commit_id);
9330 if (error)
9331 goto done;
9332 printf("Updated to %s: %s\n",
9333 got_worktree_get_head_ref_name(worktree),
9334 id_str);
9335 free(id_str);
9336 } else
9337 printf("Already up-to-date\n");
9338 print_update_progress_stats(&upa);
9339 goto done;
9341 error = got_worktree_rebase_prepare(&new_base_branch,
9342 &tmp_branch, &fileindex, worktree, branch, repo);
9343 if (error)
9344 goto done;
9347 commit_id = branch_head_commit_id;
9348 error = got_object_open_as_commit(&commit, repo, commit_id);
9349 if (error)
9350 goto done;
9352 parent_ids = got_object_commit_get_parent_ids(commit);
9353 pid = STAILQ_FIRST(parent_ids);
9354 if (pid == NULL) {
9355 if (!continue_rebase) {
9356 error = got_worktree_rebase_abort(worktree, fileindex,
9357 repo, new_base_branch, abort_progress, &upa);
9358 if (error)
9359 goto done;
9360 printf("Rebase of %s aborted\n",
9361 got_ref_get_name(branch));
9362 print_merge_progress_stats(&upa);
9365 error = got_error(GOT_ERR_EMPTY_REBASE);
9366 goto done;
9368 error = collect_commits(&commits, commit_id, pid->id,
9369 yca_id, got_worktree_get_path_prefix(worktree),
9370 GOT_ERR_REBASE_PATH, repo);
9371 got_object_commit_close(commit);
9372 commit = NULL;
9373 if (error)
9374 goto done;
9376 if (STAILQ_EMPTY(&commits)) {
9377 if (continue_rebase) {
9378 error = rebase_complete(worktree, fileindex,
9379 branch, new_base_branch, tmp_branch, repo,
9380 create_backup);
9381 goto done;
9382 } else {
9383 /* Fast-forward the reference of the branch. */
9384 struct got_object_id *new_head_commit_id;
9385 char *id_str;
9386 error = got_ref_resolve(&new_head_commit_id, repo,
9387 new_base_branch);
9388 if (error)
9389 goto done;
9390 error = got_object_id_str(&id_str, new_head_commit_id);
9391 printf("Forwarding %s to commit %s\n",
9392 got_ref_get_name(branch), id_str);
9393 free(id_str);
9394 error = got_ref_change_ref(branch,
9395 new_head_commit_id);
9396 if (error)
9397 goto done;
9398 /* No backup needed since objects did not change. */
9399 create_backup = 0;
9403 pid = NULL;
9404 STAILQ_FOREACH(qid, &commits, entry) {
9406 commit_id = qid->id;
9407 parent_id = pid ? pid->id : yca_id;
9408 pid = qid;
9410 memset(&upa, 0, sizeof(upa));
9411 error = got_worktree_rebase_merge_files(&merged_paths,
9412 worktree, fileindex, parent_id, commit_id, repo,
9413 update_progress, &upa, check_cancelled, NULL);
9414 if (error)
9415 goto done;
9417 print_merge_progress_stats(&upa);
9418 if (upa.conflicts > 0 || upa.missing > 0 ||
9419 upa.not_deleted > 0 || upa.unversioned > 0) {
9420 if (upa.conflicts > 0) {
9421 error = show_rebase_merge_conflict(qid->id,
9422 repo);
9423 if (error)
9424 goto done;
9426 got_worktree_rebase_pathlist_free(&merged_paths);
9427 break;
9430 error = rebase_commit(&merged_paths, worktree, fileindex,
9431 tmp_branch, commit_id, repo);
9432 got_worktree_rebase_pathlist_free(&merged_paths);
9433 if (error)
9434 goto done;
9437 if (upa.conflicts > 0 || upa.missing > 0 ||
9438 upa.not_deleted > 0 || upa.unversioned > 0) {
9439 error = got_worktree_rebase_postpone(worktree, fileindex);
9440 if (error)
9441 goto done;
9442 if (upa.conflicts > 0 && upa.missing == 0 &&
9443 upa.not_deleted == 0 && upa.unversioned == 0) {
9444 error = got_error_msg(GOT_ERR_CONFLICTS,
9445 "conflicts must be resolved before rebasing "
9446 "can continue");
9447 } else if (upa.conflicts > 0) {
9448 error = got_error_msg(GOT_ERR_CONFLICTS,
9449 "conflicts must be resolved before rebasing "
9450 "can continue; changes destined for some "
9451 "files were not yet merged and should be "
9452 "merged manually if required before the "
9453 "rebase operation is continued");
9454 } else {
9455 error = got_error_msg(GOT_ERR_CONFLICTS,
9456 "changes destined for some files were not "
9457 "yet merged and should be merged manually "
9458 "if required before the rebase operation "
9459 "is continued");
9461 } else
9462 error = rebase_complete(worktree, fileindex, branch,
9463 new_base_branch, tmp_branch, repo, create_backup);
9464 done:
9465 got_object_id_queue_free(&commits);
9466 free(branch_head_commit_id);
9467 free(resume_commit_id);
9468 free(yca_id);
9469 if (commit)
9470 got_object_commit_close(commit);
9471 if (branch)
9472 got_ref_close(branch);
9473 if (new_base_branch)
9474 got_ref_close(new_base_branch);
9475 if (tmp_branch)
9476 got_ref_close(tmp_branch);
9477 if (worktree)
9478 got_worktree_close(worktree);
9479 if (repo) {
9480 const struct got_error *close_err = got_repo_close(repo);
9481 if (error == NULL)
9482 error = close_err;
9484 return error;
9487 __dead static void
9488 usage_histedit(void)
9490 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9491 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9492 getprogname());
9493 exit(1);
9496 #define GOT_HISTEDIT_PICK 'p'
9497 #define GOT_HISTEDIT_EDIT 'e'
9498 #define GOT_HISTEDIT_FOLD 'f'
9499 #define GOT_HISTEDIT_DROP 'd'
9500 #define GOT_HISTEDIT_MESG 'm'
9502 static const struct got_histedit_cmd {
9503 unsigned char code;
9504 const char *name;
9505 const char *desc;
9506 } got_histedit_cmds[] = {
9507 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9508 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9509 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9510 "be used" },
9511 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9512 { GOT_HISTEDIT_MESG, "mesg",
9513 "single-line log message for commit above (open editor if empty)" },
9516 struct got_histedit_list_entry {
9517 TAILQ_ENTRY(got_histedit_list_entry) entry;
9518 struct got_object_id *commit_id;
9519 const struct got_histedit_cmd *cmd;
9520 char *logmsg;
9522 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9524 static const struct got_error *
9525 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9526 FILE *f, struct got_repository *repo)
9528 const struct got_error *err = NULL;
9529 char *logmsg = NULL, *id_str = NULL;
9530 struct got_commit_object *commit = NULL;
9531 int n;
9533 err = got_object_open_as_commit(&commit, repo, commit_id);
9534 if (err)
9535 goto done;
9537 err = get_short_logmsg(&logmsg, 34, commit);
9538 if (err)
9539 goto done;
9541 err = got_object_id_str(&id_str, commit_id);
9542 if (err)
9543 goto done;
9545 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9546 if (n < 0)
9547 err = got_ferror(f, GOT_ERR_IO);
9548 done:
9549 if (commit)
9550 got_object_commit_close(commit);
9551 free(id_str);
9552 free(logmsg);
9553 return err;
9556 static const struct got_error *
9557 histedit_write_commit_list(struct got_object_id_queue *commits,
9558 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9559 struct got_repository *repo)
9561 const struct got_error *err = NULL;
9562 struct got_object_qid *qid;
9563 const char *histedit_cmd = NULL;
9565 if (STAILQ_EMPTY(commits))
9566 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9568 STAILQ_FOREACH(qid, commits, entry) {
9569 histedit_cmd = got_histedit_cmds[0].name;
9570 if (edit_only)
9571 histedit_cmd = "edit";
9572 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9573 histedit_cmd = "fold";
9574 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9575 if (err)
9576 break;
9577 if (edit_logmsg_only) {
9578 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9579 if (n < 0) {
9580 err = got_ferror(f, GOT_ERR_IO);
9581 break;
9586 return err;
9589 static const struct got_error *
9590 write_cmd_list(FILE *f, const char *branch_name,
9591 struct got_object_id_queue *commits)
9593 const struct got_error *err = NULL;
9594 size_t i;
9595 int n;
9596 char *id_str;
9597 struct got_object_qid *qid;
9599 qid = STAILQ_FIRST(commits);
9600 err = got_object_id_str(&id_str, qid->id);
9601 if (err)
9602 return err;
9604 n = fprintf(f,
9605 "# Editing the history of branch '%s' starting at\n"
9606 "# commit %s\n"
9607 "# Commits will be processed in order from top to "
9608 "bottom of this file.\n", branch_name, id_str);
9609 if (n < 0) {
9610 err = got_ferror(f, GOT_ERR_IO);
9611 goto done;
9614 n = fprintf(f, "# Available histedit commands:\n");
9615 if (n < 0) {
9616 err = got_ferror(f, GOT_ERR_IO);
9617 goto done;
9620 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9621 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9622 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9623 cmd->desc);
9624 if (n < 0) {
9625 err = got_ferror(f, GOT_ERR_IO);
9626 break;
9629 done:
9630 free(id_str);
9631 return err;
9634 static const struct got_error *
9635 histedit_syntax_error(int lineno)
9637 static char msg[42];
9638 int ret;
9640 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9641 lineno);
9642 if (ret == -1 || ret >= sizeof(msg))
9643 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9645 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9648 static const struct got_error *
9649 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9650 char *logmsg, struct got_repository *repo)
9652 const struct got_error *err;
9653 struct got_commit_object *folded_commit = NULL;
9654 char *id_str, *folded_logmsg = NULL;
9656 err = got_object_id_str(&id_str, hle->commit_id);
9657 if (err)
9658 return err;
9660 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9661 if (err)
9662 goto done;
9664 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9665 if (err)
9666 goto done;
9667 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9668 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9669 folded_logmsg) == -1) {
9670 err = got_error_from_errno("asprintf");
9672 done:
9673 if (folded_commit)
9674 got_object_commit_close(folded_commit);
9675 free(id_str);
9676 free(folded_logmsg);
9677 return err;
9680 static struct got_histedit_list_entry *
9681 get_folded_commits(struct got_histedit_list_entry *hle)
9683 struct got_histedit_list_entry *prev, *folded = NULL;
9685 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9686 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9687 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9688 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9689 folded = prev;
9690 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9693 return folded;
9696 static const struct got_error *
9697 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9698 struct got_repository *repo)
9700 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9701 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9702 const struct got_error *err = NULL;
9703 struct got_commit_object *commit = NULL;
9704 int logmsg_len;
9705 int fd;
9706 struct got_histedit_list_entry *folded = NULL;
9708 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9709 if (err)
9710 return err;
9712 folded = get_folded_commits(hle);
9713 if (folded) {
9714 while (folded != hle) {
9715 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9716 folded = TAILQ_NEXT(folded, entry);
9717 continue;
9719 err = append_folded_commit_msg(&new_msg, folded,
9720 logmsg, repo);
9721 if (err)
9722 goto done;
9723 free(logmsg);
9724 logmsg = new_msg;
9725 folded = TAILQ_NEXT(folded, entry);
9729 err = got_object_id_str(&id_str, hle->commit_id);
9730 if (err)
9731 goto done;
9732 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9733 if (err)
9734 goto done;
9735 logmsg_len = asprintf(&new_msg,
9736 "%s\n# original log message of commit %s: %s",
9737 logmsg ? logmsg : "", id_str, orig_logmsg);
9738 if (logmsg_len == -1) {
9739 err = got_error_from_errno("asprintf");
9740 goto done;
9742 free(logmsg);
9743 logmsg = new_msg;
9745 err = got_object_id_str(&id_str, hle->commit_id);
9746 if (err)
9747 goto done;
9749 err = got_opentemp_named_fd(&logmsg_path, &fd,
9750 GOT_TMPDIR_STR "/got-logmsg");
9751 if (err)
9752 goto done;
9754 write(fd, logmsg, logmsg_len);
9755 close(fd);
9757 err = get_editor(&editor);
9758 if (err)
9759 goto done;
9761 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9762 logmsg_len, 0);
9763 if (err) {
9764 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9765 goto done;
9766 err = NULL;
9767 hle->logmsg = strdup(new_msg);
9768 if (hle->logmsg == NULL)
9769 err = got_error_from_errno("strdup");
9771 done:
9772 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9773 err = got_error_from_errno2("unlink", logmsg_path);
9774 free(logmsg_path);
9775 free(logmsg);
9776 free(orig_logmsg);
9777 free(editor);
9778 if (commit)
9779 got_object_commit_close(commit);
9780 return err;
9783 static const struct got_error *
9784 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9785 FILE *f, struct got_repository *repo)
9787 const struct got_error *err = NULL;
9788 char *line = NULL, *p, *end;
9789 size_t i, size;
9790 ssize_t len;
9791 int lineno = 0;
9792 const struct got_histedit_cmd *cmd;
9793 struct got_object_id *commit_id = NULL;
9794 struct got_histedit_list_entry *hle = NULL;
9796 for (;;) {
9797 len = getline(&line, &size, f);
9798 if (len == -1) {
9799 const struct got_error *getline_err;
9800 if (feof(f))
9801 break;
9802 getline_err = got_error_from_errno("getline");
9803 err = got_ferror(f, getline_err->code);
9804 break;
9806 lineno++;
9807 p = line;
9808 while (isspace((unsigned char)p[0]))
9809 p++;
9810 if (p[0] == '#' || p[0] == '\0') {
9811 free(line);
9812 line = NULL;
9813 continue;
9815 cmd = NULL;
9816 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9817 cmd = &got_histedit_cmds[i];
9818 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9819 isspace((unsigned char)p[strlen(cmd->name)])) {
9820 p += strlen(cmd->name);
9821 break;
9823 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9824 p++;
9825 break;
9828 if (i == nitems(got_histedit_cmds)) {
9829 err = histedit_syntax_error(lineno);
9830 break;
9832 while (isspace((unsigned char)p[0]))
9833 p++;
9834 if (cmd->code == GOT_HISTEDIT_MESG) {
9835 if (hle == NULL || hle->logmsg != NULL) {
9836 err = got_error(GOT_ERR_HISTEDIT_CMD);
9837 break;
9839 if (p[0] == '\0') {
9840 err = histedit_edit_logmsg(hle, repo);
9841 if (err)
9842 break;
9843 } else {
9844 hle->logmsg = strdup(p);
9845 if (hle->logmsg == NULL) {
9846 err = got_error_from_errno("strdup");
9847 break;
9850 free(line);
9851 line = NULL;
9852 continue;
9853 } else {
9854 end = p;
9855 while (end[0] && !isspace((unsigned char)end[0]))
9856 end++;
9857 *end = '\0';
9859 err = got_object_resolve_id_str(&commit_id, repo, p);
9860 if (err) {
9861 /* override error code */
9862 err = histedit_syntax_error(lineno);
9863 break;
9866 hle = malloc(sizeof(*hle));
9867 if (hle == NULL) {
9868 err = got_error_from_errno("malloc");
9869 break;
9871 hle->cmd = cmd;
9872 hle->commit_id = commit_id;
9873 hle->logmsg = NULL;
9874 commit_id = NULL;
9875 free(line);
9876 line = NULL;
9877 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9880 free(line);
9881 free(commit_id);
9882 return err;
9885 static const struct got_error *
9886 histedit_check_script(struct got_histedit_list *histedit_cmds,
9887 struct got_object_id_queue *commits, struct got_repository *repo)
9889 const struct got_error *err = NULL;
9890 struct got_object_qid *qid;
9891 struct got_histedit_list_entry *hle;
9892 static char msg[92];
9893 char *id_str;
9895 if (TAILQ_EMPTY(histedit_cmds))
9896 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9897 "histedit script contains no commands");
9898 if (STAILQ_EMPTY(commits))
9899 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9901 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9902 struct got_histedit_list_entry *hle2;
9903 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9904 if (hle == hle2)
9905 continue;
9906 if (got_object_id_cmp(hle->commit_id,
9907 hle2->commit_id) != 0)
9908 continue;
9909 err = got_object_id_str(&id_str, hle->commit_id);
9910 if (err)
9911 return err;
9912 snprintf(msg, sizeof(msg), "commit %s is listed "
9913 "more than once in histedit script", id_str);
9914 free(id_str);
9915 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9919 STAILQ_FOREACH(qid, commits, entry) {
9920 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9921 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9922 break;
9924 if (hle == NULL) {
9925 err = got_object_id_str(&id_str, qid->id);
9926 if (err)
9927 return err;
9928 snprintf(msg, sizeof(msg),
9929 "commit %s missing from histedit script", id_str);
9930 free(id_str);
9931 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9935 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9936 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9937 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9938 "last commit in histedit script cannot be folded");
9940 return NULL;
9943 static const struct got_error *
9944 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9945 const char *path, struct got_object_id_queue *commits,
9946 struct got_repository *repo)
9948 const struct got_error *err = NULL;
9949 char *editor;
9950 FILE *f = NULL;
9952 err = get_editor(&editor);
9953 if (err)
9954 return err;
9956 if (spawn_editor(editor, path) == -1) {
9957 err = got_error_from_errno("failed spawning editor");
9958 goto done;
9961 f = fopen(path, "re");
9962 if (f == NULL) {
9963 err = got_error_from_errno("fopen");
9964 goto done;
9966 err = histedit_parse_list(histedit_cmds, f, repo);
9967 if (err)
9968 goto done;
9970 err = histedit_check_script(histedit_cmds, commits, repo);
9971 done:
9972 if (f && fclose(f) == EOF && err == NULL)
9973 err = got_error_from_errno("fclose");
9974 free(editor);
9975 return err;
9978 static const struct got_error *
9979 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9980 struct got_object_id_queue *, const char *, const char *,
9981 struct got_repository *);
9983 static const struct got_error *
9984 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9985 struct got_object_id_queue *commits, const char *branch_name,
9986 int edit_logmsg_only, int fold_only, int edit_only,
9987 struct got_repository *repo)
9989 const struct got_error *err;
9990 FILE *f = NULL;
9991 char *path = NULL;
9993 err = got_opentemp_named(&path, &f, "got-histedit");
9994 if (err)
9995 return err;
9997 err = write_cmd_list(f, branch_name, commits);
9998 if (err)
9999 goto done;
10001 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10002 fold_only, edit_only, repo);
10003 if (err)
10004 goto done;
10006 if (edit_logmsg_only || fold_only || edit_only) {
10007 rewind(f);
10008 err = histedit_parse_list(histedit_cmds, f, repo);
10009 } else {
10010 if (fclose(f) == EOF) {
10011 err = got_error_from_errno("fclose");
10012 goto done;
10014 f = NULL;
10015 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10016 if (err) {
10017 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10018 err->code != GOT_ERR_HISTEDIT_CMD)
10019 goto done;
10020 err = histedit_edit_list_retry(histedit_cmds, err,
10021 commits, path, branch_name, repo);
10024 done:
10025 if (f && fclose(f) == EOF && err == NULL)
10026 err = got_error_from_errno("fclose");
10027 if (path && unlink(path) != 0 && err == NULL)
10028 err = got_error_from_errno2("unlink", path);
10029 free(path);
10030 return err;
10033 static const struct got_error *
10034 histedit_save_list(struct got_histedit_list *histedit_cmds,
10035 struct got_worktree *worktree, struct got_repository *repo)
10037 const struct got_error *err = NULL;
10038 char *path = NULL;
10039 FILE *f = NULL;
10040 struct got_histedit_list_entry *hle;
10041 struct got_commit_object *commit = NULL;
10043 err = got_worktree_get_histedit_script_path(&path, worktree);
10044 if (err)
10045 return err;
10047 f = fopen(path, "we");
10048 if (f == NULL) {
10049 err = got_error_from_errno2("fopen", path);
10050 goto done;
10052 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10053 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10054 repo);
10055 if (err)
10056 break;
10058 if (hle->logmsg) {
10059 int n = fprintf(f, "%c %s\n",
10060 GOT_HISTEDIT_MESG, hle->logmsg);
10061 if (n < 0) {
10062 err = got_ferror(f, GOT_ERR_IO);
10063 break;
10067 done:
10068 if (f && fclose(f) == EOF && err == NULL)
10069 err = got_error_from_errno("fclose");
10070 free(path);
10071 if (commit)
10072 got_object_commit_close(commit);
10073 return err;
10076 void
10077 histedit_free_list(struct got_histedit_list *histedit_cmds)
10079 struct got_histedit_list_entry *hle;
10081 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10082 TAILQ_REMOVE(histedit_cmds, hle, entry);
10083 free(hle);
10087 static const struct got_error *
10088 histedit_load_list(struct got_histedit_list *histedit_cmds,
10089 const char *path, struct got_repository *repo)
10091 const struct got_error *err = NULL;
10092 FILE *f = NULL;
10094 f = fopen(path, "re");
10095 if (f == NULL) {
10096 err = got_error_from_errno2("fopen", path);
10097 goto done;
10100 err = histedit_parse_list(histedit_cmds, f, repo);
10101 done:
10102 if (f && fclose(f) == EOF && err == NULL)
10103 err = got_error_from_errno("fclose");
10104 return err;
10107 static const struct got_error *
10108 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10109 const struct got_error *edit_err, struct got_object_id_queue *commits,
10110 const char *path, const char *branch_name, struct got_repository *repo)
10112 const struct got_error *err = NULL, *prev_err = edit_err;
10113 int resp = ' ';
10115 while (resp != 'c' && resp != 'r' && resp != 'a') {
10116 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10117 "or (a)bort: ", getprogname(), prev_err->msg);
10118 resp = getchar();
10119 if (resp == '\n')
10120 resp = getchar();
10121 if (resp == 'c') {
10122 histedit_free_list(histedit_cmds);
10123 err = histedit_run_editor(histedit_cmds, path, commits,
10124 repo);
10125 if (err) {
10126 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10127 err->code != GOT_ERR_HISTEDIT_CMD)
10128 break;
10129 prev_err = err;
10130 resp = ' ';
10131 continue;
10133 break;
10134 } else if (resp == 'r') {
10135 histedit_free_list(histedit_cmds);
10136 err = histedit_edit_script(histedit_cmds,
10137 commits, branch_name, 0, 0, 0, repo);
10138 if (err) {
10139 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10140 err->code != GOT_ERR_HISTEDIT_CMD)
10141 break;
10142 prev_err = err;
10143 resp = ' ';
10144 continue;
10146 break;
10147 } else if (resp == 'a') {
10148 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10149 break;
10150 } else
10151 printf("invalid response '%c'\n", resp);
10154 return err;
10157 static const struct got_error *
10158 histedit_complete(struct got_worktree *worktree,
10159 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10160 struct got_reference *branch, struct got_repository *repo)
10162 printf("Switching work tree to %s\n",
10163 got_ref_get_symref_target(branch));
10164 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10165 branch, repo);
10168 static const struct got_error *
10169 show_histedit_progress(struct got_commit_object *commit,
10170 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10172 const struct got_error *err;
10173 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10175 err = got_object_id_str(&old_id_str, hle->commit_id);
10176 if (err)
10177 goto done;
10179 if (new_id) {
10180 err = got_object_id_str(&new_id_str, new_id);
10181 if (err)
10182 goto done;
10185 old_id_str[12] = '\0';
10186 if (new_id_str)
10187 new_id_str[12] = '\0';
10189 if (hle->logmsg) {
10190 logmsg = strdup(hle->logmsg);
10191 if (logmsg == NULL) {
10192 err = got_error_from_errno("strdup");
10193 goto done;
10195 trim_logmsg(logmsg, 42);
10196 } else {
10197 err = get_short_logmsg(&logmsg, 42, commit);
10198 if (err)
10199 goto done;
10202 switch (hle->cmd->code) {
10203 case GOT_HISTEDIT_PICK:
10204 case GOT_HISTEDIT_EDIT:
10205 printf("%s -> %s: %s\n", old_id_str,
10206 new_id_str ? new_id_str : "no-op change", logmsg);
10207 break;
10208 case GOT_HISTEDIT_DROP:
10209 case GOT_HISTEDIT_FOLD:
10210 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10211 logmsg);
10212 break;
10213 default:
10214 break;
10216 done:
10217 free(old_id_str);
10218 free(new_id_str);
10219 return err;
10222 static const struct got_error *
10223 histedit_commit(struct got_pathlist_head *merged_paths,
10224 struct got_worktree *worktree, struct got_fileindex *fileindex,
10225 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10226 struct got_repository *repo)
10228 const struct got_error *err;
10229 struct got_commit_object *commit;
10230 struct got_object_id *new_commit_id;
10232 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10233 && hle->logmsg == NULL) {
10234 err = histedit_edit_logmsg(hle, repo);
10235 if (err)
10236 return err;
10239 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10240 if (err)
10241 return err;
10243 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10244 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10245 hle->logmsg, repo);
10246 if (err) {
10247 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10248 goto done;
10249 err = show_histedit_progress(commit, hle, NULL);
10250 } else {
10251 err = show_histedit_progress(commit, hle, new_commit_id);
10252 free(new_commit_id);
10254 done:
10255 got_object_commit_close(commit);
10256 return err;
10259 static const struct got_error *
10260 histedit_skip_commit(struct got_histedit_list_entry *hle,
10261 struct got_worktree *worktree, struct got_repository *repo)
10263 const struct got_error *error;
10264 struct got_commit_object *commit;
10266 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10267 repo);
10268 if (error)
10269 return error;
10271 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10272 if (error)
10273 return error;
10275 error = show_histedit_progress(commit, hle, NULL);
10276 got_object_commit_close(commit);
10277 return error;
10280 static const struct got_error *
10281 check_local_changes(void *arg, unsigned char status,
10282 unsigned char staged_status, const char *path,
10283 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10284 struct got_object_id *commit_id, int dirfd, const char *de_name)
10286 int *have_local_changes = arg;
10288 switch (status) {
10289 case GOT_STATUS_ADD:
10290 case GOT_STATUS_DELETE:
10291 case GOT_STATUS_MODIFY:
10292 case GOT_STATUS_CONFLICT:
10293 *have_local_changes = 1;
10294 return got_error(GOT_ERR_CANCELLED);
10295 default:
10296 break;
10299 switch (staged_status) {
10300 case GOT_STATUS_ADD:
10301 case GOT_STATUS_DELETE:
10302 case GOT_STATUS_MODIFY:
10303 *have_local_changes = 1;
10304 return got_error(GOT_ERR_CANCELLED);
10305 default:
10306 break;
10309 return NULL;
10312 static const struct got_error *
10313 cmd_histedit(int argc, char *argv[])
10315 const struct got_error *error = NULL;
10316 struct got_worktree *worktree = NULL;
10317 struct got_fileindex *fileindex = NULL;
10318 struct got_repository *repo = NULL;
10319 char *cwd = NULL;
10320 struct got_reference *branch = NULL;
10321 struct got_reference *tmp_branch = NULL;
10322 struct got_object_id *resume_commit_id = NULL;
10323 struct got_object_id *base_commit_id = NULL;
10324 struct got_object_id *head_commit_id = NULL;
10325 struct got_commit_object *commit = NULL;
10326 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10327 struct got_update_progress_arg upa;
10328 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10329 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10330 int list_backups = 0, delete_backups = 0;
10331 const char *edit_script_path = NULL;
10332 struct got_object_id_queue commits;
10333 struct got_pathlist_head merged_paths;
10334 const struct got_object_id_queue *parent_ids;
10335 struct got_object_qid *pid;
10336 struct got_histedit_list histedit_cmds;
10337 struct got_histedit_list_entry *hle;
10339 STAILQ_INIT(&commits);
10340 TAILQ_INIT(&histedit_cmds);
10341 TAILQ_INIT(&merged_paths);
10342 memset(&upa, 0, sizeof(upa));
10344 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10345 switch (ch) {
10346 case 'a':
10347 abort_edit = 1;
10348 break;
10349 case 'c':
10350 continue_edit = 1;
10351 break;
10352 case 'e':
10353 edit_only = 1;
10354 break;
10355 case 'f':
10356 fold_only = 1;
10357 break;
10358 case 'F':
10359 edit_script_path = optarg;
10360 break;
10361 case 'm':
10362 edit_logmsg_only = 1;
10363 break;
10364 case 'l':
10365 list_backups = 1;
10366 break;
10367 case 'X':
10368 delete_backups = 1;
10369 break;
10370 default:
10371 usage_histedit();
10372 /* NOTREACHED */
10376 argc -= optind;
10377 argv += optind;
10379 #ifndef PROFILE
10380 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10381 "unveil", NULL) == -1)
10382 err(1, "pledge");
10383 #endif
10384 if (abort_edit && continue_edit)
10385 option_conflict('a', 'c');
10386 if (edit_script_path && edit_logmsg_only)
10387 option_conflict('F', 'm');
10388 if (abort_edit && edit_logmsg_only)
10389 option_conflict('a', 'm');
10390 if (continue_edit && edit_logmsg_only)
10391 option_conflict('c', 'm');
10392 if (abort_edit && fold_only)
10393 option_conflict('a', 'f');
10394 if (continue_edit && fold_only)
10395 option_conflict('c', 'f');
10396 if (fold_only && edit_logmsg_only)
10397 option_conflict('f', 'm');
10398 if (edit_script_path && fold_only)
10399 option_conflict('F', 'f');
10400 if (abort_edit && edit_only)
10401 option_conflict('a', 'e');
10402 if (continue_edit && edit_only)
10403 option_conflict('c', 'e');
10404 if (edit_only && edit_logmsg_only)
10405 option_conflict('e', 'm');
10406 if (edit_script_path && edit_only)
10407 option_conflict('F', 'e');
10408 if (list_backups) {
10409 if (abort_edit)
10410 option_conflict('l', 'a');
10411 if (continue_edit)
10412 option_conflict('l', 'c');
10413 if (edit_script_path)
10414 option_conflict('l', 'F');
10415 if (edit_logmsg_only)
10416 option_conflict('l', 'm');
10417 if (fold_only)
10418 option_conflict('l', 'f');
10419 if (edit_only)
10420 option_conflict('l', 'e');
10421 if (delete_backups)
10422 option_conflict('l', 'X');
10423 if (argc != 0 && argc != 1)
10424 usage_histedit();
10425 } else if (delete_backups) {
10426 if (abort_edit)
10427 option_conflict('X', 'a');
10428 if (continue_edit)
10429 option_conflict('X', 'c');
10430 if (edit_script_path)
10431 option_conflict('X', 'F');
10432 if (edit_logmsg_only)
10433 option_conflict('X', 'm');
10434 if (fold_only)
10435 option_conflict('X', 'f');
10436 if (edit_only)
10437 option_conflict('X', 'e');
10438 if (list_backups)
10439 option_conflict('X', 'l');
10440 if (argc != 0 && argc != 1)
10441 usage_histedit();
10442 } else if (argc != 0)
10443 usage_histedit();
10446 * This command cannot apply unveil(2) in all cases because the
10447 * user may choose to run an editor to edit the histedit script
10448 * and to edit individual commit log messages.
10449 * unveil(2) traverses exec(2); if an editor is used we have to
10450 * apply unveil after edit script and log messages have been written.
10451 * XXX TODO: Make use of unveil(2) where possible.
10454 cwd = getcwd(NULL, 0);
10455 if (cwd == NULL) {
10456 error = got_error_from_errno("getcwd");
10457 goto done;
10459 error = got_worktree_open(&worktree, cwd);
10460 if (error) {
10461 if (list_backups || delete_backups) {
10462 if (error->code != GOT_ERR_NOT_WORKTREE)
10463 goto done;
10464 } else {
10465 if (error->code == GOT_ERR_NOT_WORKTREE)
10466 error = wrap_not_worktree_error(error,
10467 "histedit", cwd);
10468 goto done;
10472 if (list_backups || delete_backups) {
10473 error = got_repo_open(&repo,
10474 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10475 NULL);
10476 if (error != NULL)
10477 goto done;
10478 error = apply_unveil(got_repo_get_path(repo), 0,
10479 worktree ? got_worktree_get_root_path(worktree) : NULL);
10480 if (error)
10481 goto done;
10482 error = process_backup_refs(
10483 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10484 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10485 goto done; /* nothing else to do */
10488 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10489 NULL);
10490 if (error != NULL)
10491 goto done;
10493 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10494 if (error)
10495 goto done;
10496 if (rebase_in_progress) {
10497 error = got_error(GOT_ERR_REBASING);
10498 goto done;
10501 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10502 repo);
10503 if (error)
10504 goto done;
10505 if (merge_in_progress) {
10506 error = got_error(GOT_ERR_MERGE_BUSY);
10507 goto done;
10510 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10511 if (error)
10512 goto done;
10514 if (edit_in_progress && edit_logmsg_only) {
10515 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10516 "histedit operation is in progress in this "
10517 "work tree and must be continued or aborted "
10518 "before the -m option can be used");
10519 goto done;
10521 if (edit_in_progress && fold_only) {
10522 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10523 "histedit operation is in progress in this "
10524 "work tree and must be continued or aborted "
10525 "before the -f option can be used");
10526 goto done;
10528 if (edit_in_progress && edit_only) {
10529 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10530 "histedit operation is in progress in this "
10531 "work tree and must be continued or aborted "
10532 "before the -e option can be used");
10533 goto done;
10536 if (edit_in_progress && abort_edit) {
10537 error = got_worktree_histedit_continue(&resume_commit_id,
10538 &tmp_branch, &branch, &base_commit_id, &fileindex,
10539 worktree, repo);
10540 if (error)
10541 goto done;
10542 printf("Switching work tree to %s\n",
10543 got_ref_get_symref_target(branch));
10544 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10545 branch, base_commit_id, abort_progress, &upa);
10546 if (error)
10547 goto done;
10548 printf("Histedit of %s aborted\n",
10549 got_ref_get_symref_target(branch));
10550 print_merge_progress_stats(&upa);
10551 goto done; /* nothing else to do */
10552 } else if (abort_edit) {
10553 error = got_error(GOT_ERR_NOT_HISTEDIT);
10554 goto done;
10557 if (continue_edit) {
10558 char *path;
10560 if (!edit_in_progress) {
10561 error = got_error(GOT_ERR_NOT_HISTEDIT);
10562 goto done;
10565 error = got_worktree_get_histedit_script_path(&path, worktree);
10566 if (error)
10567 goto done;
10569 error = histedit_load_list(&histedit_cmds, path, repo);
10570 free(path);
10571 if (error)
10572 goto done;
10574 error = got_worktree_histedit_continue(&resume_commit_id,
10575 &tmp_branch, &branch, &base_commit_id, &fileindex,
10576 worktree, repo);
10577 if (error)
10578 goto done;
10580 error = got_ref_resolve(&head_commit_id, repo, branch);
10581 if (error)
10582 goto done;
10584 error = got_object_open_as_commit(&commit, repo,
10585 head_commit_id);
10586 if (error)
10587 goto done;
10588 parent_ids = got_object_commit_get_parent_ids(commit);
10589 pid = STAILQ_FIRST(parent_ids);
10590 if (pid == NULL) {
10591 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10592 goto done;
10594 error = collect_commits(&commits, head_commit_id, pid->id,
10595 base_commit_id, got_worktree_get_path_prefix(worktree),
10596 GOT_ERR_HISTEDIT_PATH, repo);
10597 got_object_commit_close(commit);
10598 commit = NULL;
10599 if (error)
10600 goto done;
10601 } else {
10602 if (edit_in_progress) {
10603 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10604 goto done;
10607 error = got_ref_open(&branch, repo,
10608 got_worktree_get_head_ref_name(worktree), 0);
10609 if (error != NULL)
10610 goto done;
10612 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10613 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10614 "will not edit commit history of a branch outside "
10615 "the \"refs/heads/\" reference namespace");
10616 goto done;
10619 error = got_ref_resolve(&head_commit_id, repo, branch);
10620 got_ref_close(branch);
10621 branch = NULL;
10622 if (error)
10623 goto done;
10625 error = got_object_open_as_commit(&commit, repo,
10626 head_commit_id);
10627 if (error)
10628 goto done;
10629 parent_ids = got_object_commit_get_parent_ids(commit);
10630 pid = STAILQ_FIRST(parent_ids);
10631 if (pid == NULL) {
10632 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10633 goto done;
10635 error = collect_commits(&commits, head_commit_id, pid->id,
10636 got_worktree_get_base_commit_id(worktree),
10637 got_worktree_get_path_prefix(worktree),
10638 GOT_ERR_HISTEDIT_PATH, repo);
10639 got_object_commit_close(commit);
10640 commit = NULL;
10641 if (error)
10642 goto done;
10644 if (STAILQ_EMPTY(&commits)) {
10645 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10646 goto done;
10649 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10650 &base_commit_id, &fileindex, worktree, repo);
10651 if (error)
10652 goto done;
10654 if (edit_script_path) {
10655 error = histedit_load_list(&histedit_cmds,
10656 edit_script_path, repo);
10657 if (error) {
10658 got_worktree_histedit_abort(worktree, fileindex,
10659 repo, branch, base_commit_id,
10660 abort_progress, &upa);
10661 print_merge_progress_stats(&upa);
10662 goto done;
10664 } else {
10665 const char *branch_name;
10666 branch_name = got_ref_get_symref_target(branch);
10667 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10668 branch_name += 11;
10669 error = histedit_edit_script(&histedit_cmds, &commits,
10670 branch_name, edit_logmsg_only, fold_only,
10671 edit_only, repo);
10672 if (error) {
10673 got_worktree_histedit_abort(worktree, fileindex,
10674 repo, branch, base_commit_id,
10675 abort_progress, &upa);
10676 print_merge_progress_stats(&upa);
10677 goto done;
10682 error = histedit_save_list(&histedit_cmds, worktree,
10683 repo);
10684 if (error) {
10685 got_worktree_histedit_abort(worktree, fileindex,
10686 repo, branch, base_commit_id,
10687 abort_progress, &upa);
10688 print_merge_progress_stats(&upa);
10689 goto done;
10694 error = histedit_check_script(&histedit_cmds, &commits, repo);
10695 if (error)
10696 goto done;
10698 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10699 if (resume_commit_id) {
10700 if (got_object_id_cmp(hle->commit_id,
10701 resume_commit_id) != 0)
10702 continue;
10704 resume_commit_id = NULL;
10705 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10706 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10707 error = histedit_skip_commit(hle, worktree,
10708 repo);
10709 if (error)
10710 goto done;
10711 } else {
10712 struct got_pathlist_head paths;
10713 int have_changes = 0;
10715 TAILQ_INIT(&paths);
10716 error = got_pathlist_append(&paths, "", NULL);
10717 if (error)
10718 goto done;
10719 error = got_worktree_status(worktree, &paths,
10720 repo, 0, check_local_changes, &have_changes,
10721 check_cancelled, NULL);
10722 got_pathlist_free(&paths);
10723 if (error) {
10724 if (error->code != GOT_ERR_CANCELLED)
10725 goto done;
10726 if (sigint_received || sigpipe_received)
10727 goto done;
10729 if (have_changes) {
10730 error = histedit_commit(NULL, worktree,
10731 fileindex, tmp_branch, hle, repo);
10732 if (error)
10733 goto done;
10734 } else {
10735 error = got_object_open_as_commit(
10736 &commit, repo, hle->commit_id);
10737 if (error)
10738 goto done;
10739 error = show_histedit_progress(commit,
10740 hle, NULL);
10741 got_object_commit_close(commit);
10742 commit = NULL;
10743 if (error)
10744 goto done;
10747 continue;
10750 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10751 error = histedit_skip_commit(hle, worktree, repo);
10752 if (error)
10753 goto done;
10754 continue;
10757 error = got_object_open_as_commit(&commit, repo,
10758 hle->commit_id);
10759 if (error)
10760 goto done;
10761 parent_ids = got_object_commit_get_parent_ids(commit);
10762 pid = STAILQ_FIRST(parent_ids);
10764 error = got_worktree_histedit_merge_files(&merged_paths,
10765 worktree, fileindex, pid->id, hle->commit_id, repo,
10766 update_progress, &upa, check_cancelled, NULL);
10767 if (error)
10768 goto done;
10769 got_object_commit_close(commit);
10770 commit = NULL;
10772 print_merge_progress_stats(&upa);
10773 if (upa.conflicts > 0 || upa.missing > 0 ||
10774 upa.not_deleted > 0 || upa.unversioned > 0) {
10775 if (upa.conflicts > 0) {
10776 error = show_rebase_merge_conflict(
10777 hle->commit_id, repo);
10778 if (error)
10779 goto done;
10781 got_worktree_rebase_pathlist_free(&merged_paths);
10782 break;
10785 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10786 char *id_str;
10787 error = got_object_id_str(&id_str, hle->commit_id);
10788 if (error)
10789 goto done;
10790 printf("Stopping histedit for amending commit %s\n",
10791 id_str);
10792 free(id_str);
10793 got_worktree_rebase_pathlist_free(&merged_paths);
10794 error = got_worktree_histedit_postpone(worktree,
10795 fileindex);
10796 goto done;
10799 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10800 error = histedit_skip_commit(hle, worktree, repo);
10801 if (error)
10802 goto done;
10803 continue;
10806 error = histedit_commit(&merged_paths, worktree, fileindex,
10807 tmp_branch, hle, repo);
10808 got_worktree_rebase_pathlist_free(&merged_paths);
10809 if (error)
10810 goto done;
10813 if (upa.conflicts > 0 || upa.missing > 0 ||
10814 upa.not_deleted > 0 || upa.unversioned > 0) {
10815 error = got_worktree_histedit_postpone(worktree, fileindex);
10816 if (error)
10817 goto done;
10818 if (upa.conflicts > 0 && upa.missing == 0 &&
10819 upa.not_deleted == 0 && upa.unversioned == 0) {
10820 error = got_error_msg(GOT_ERR_CONFLICTS,
10821 "conflicts must be resolved before histedit "
10822 "can continue");
10823 } else if (upa.conflicts > 0) {
10824 error = got_error_msg(GOT_ERR_CONFLICTS,
10825 "conflicts must be resolved before histedit "
10826 "can continue; changes destined for some "
10827 "files were not yet merged and should be "
10828 "merged manually if required before the "
10829 "histedit operation is continued");
10830 } else {
10831 error = got_error_msg(GOT_ERR_CONFLICTS,
10832 "changes destined for some files were not "
10833 "yet merged and should be merged manually "
10834 "if required before the histedit operation "
10835 "is continued");
10837 } else
10838 error = histedit_complete(worktree, fileindex, tmp_branch,
10839 branch, repo);
10840 done:
10841 got_object_id_queue_free(&commits);
10842 histedit_free_list(&histedit_cmds);
10843 free(head_commit_id);
10844 free(base_commit_id);
10845 free(resume_commit_id);
10846 if (commit)
10847 got_object_commit_close(commit);
10848 if (branch)
10849 got_ref_close(branch);
10850 if (tmp_branch)
10851 got_ref_close(tmp_branch);
10852 if (worktree)
10853 got_worktree_close(worktree);
10854 if (repo) {
10855 const struct got_error *close_err = got_repo_close(repo);
10856 if (error == NULL)
10857 error = close_err;
10859 return error;
10862 __dead static void
10863 usage_integrate(void)
10865 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10866 exit(1);
10869 static const struct got_error *
10870 cmd_integrate(int argc, char *argv[])
10872 const struct got_error *error = NULL;
10873 struct got_repository *repo = NULL;
10874 struct got_worktree *worktree = NULL;
10875 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10876 const char *branch_arg = NULL;
10877 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10878 struct got_fileindex *fileindex = NULL;
10879 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10880 int ch;
10881 struct got_update_progress_arg upa;
10883 while ((ch = getopt(argc, argv, "")) != -1) {
10884 switch (ch) {
10885 default:
10886 usage_integrate();
10887 /* NOTREACHED */
10891 argc -= optind;
10892 argv += optind;
10894 if (argc != 1)
10895 usage_integrate();
10896 branch_arg = argv[0];
10897 #ifndef PROFILE
10898 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10899 "unveil", NULL) == -1)
10900 err(1, "pledge");
10901 #endif
10902 cwd = getcwd(NULL, 0);
10903 if (cwd == NULL) {
10904 error = got_error_from_errno("getcwd");
10905 goto done;
10908 error = got_worktree_open(&worktree, cwd);
10909 if (error) {
10910 if (error->code == GOT_ERR_NOT_WORKTREE)
10911 error = wrap_not_worktree_error(error, "integrate",
10912 cwd);
10913 goto done;
10916 error = check_rebase_or_histedit_in_progress(worktree);
10917 if (error)
10918 goto done;
10920 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10921 NULL);
10922 if (error != NULL)
10923 goto done;
10925 error = apply_unveil(got_repo_get_path(repo), 0,
10926 got_worktree_get_root_path(worktree));
10927 if (error)
10928 goto done;
10930 error = check_merge_in_progress(worktree, repo);
10931 if (error)
10932 goto done;
10934 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10935 error = got_error_from_errno("asprintf");
10936 goto done;
10939 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10940 &base_branch_ref, worktree, refname, repo);
10941 if (error)
10942 goto done;
10944 refname = strdup(got_ref_get_name(branch_ref));
10945 if (refname == NULL) {
10946 error = got_error_from_errno("strdup");
10947 got_worktree_integrate_abort(worktree, fileindex, repo,
10948 branch_ref, base_branch_ref);
10949 goto done;
10951 base_refname = strdup(got_ref_get_name(base_branch_ref));
10952 if (base_refname == NULL) {
10953 error = got_error_from_errno("strdup");
10954 got_worktree_integrate_abort(worktree, fileindex, repo,
10955 branch_ref, base_branch_ref);
10956 goto done;
10959 error = got_ref_resolve(&commit_id, repo, branch_ref);
10960 if (error)
10961 goto done;
10963 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10964 if (error)
10965 goto done;
10967 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10968 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10969 "specified branch has already been integrated");
10970 got_worktree_integrate_abort(worktree, fileindex, repo,
10971 branch_ref, base_branch_ref);
10972 goto done;
10975 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10976 if (error) {
10977 if (error->code == GOT_ERR_ANCESTRY)
10978 error = got_error(GOT_ERR_REBASE_REQUIRED);
10979 got_worktree_integrate_abort(worktree, fileindex, repo,
10980 branch_ref, base_branch_ref);
10981 goto done;
10984 memset(&upa, 0, sizeof(upa));
10985 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10986 branch_ref, base_branch_ref, update_progress, &upa,
10987 check_cancelled, NULL);
10988 if (error)
10989 goto done;
10991 printf("Integrated %s into %s\n", refname, base_refname);
10992 print_update_progress_stats(&upa);
10993 done:
10994 if (repo) {
10995 const struct got_error *close_err = got_repo_close(repo);
10996 if (error == NULL)
10997 error = close_err;
10999 if (worktree)
11000 got_worktree_close(worktree);
11001 free(cwd);
11002 free(base_commit_id);
11003 free(commit_id);
11004 free(refname);
11005 free(base_refname);
11006 return error;
11009 __dead static void
11010 usage_merge(void)
11012 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11013 getprogname());
11014 exit(1);
11017 static const struct got_error *
11018 cmd_merge(int argc, char *argv[])
11020 const struct got_error *error = NULL;
11021 struct got_worktree *worktree = NULL;
11022 struct got_repository *repo = NULL;
11023 struct got_fileindex *fileindex = NULL;
11024 char *cwd = NULL, *id_str = NULL, *author = NULL;
11025 struct got_reference *branch = NULL, *wt_branch = NULL;
11026 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11027 struct got_object_id *wt_branch_tip = NULL;
11028 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11029 int interrupt_merge = 0;
11030 struct got_update_progress_arg upa;
11031 struct got_object_id *merge_commit_id = NULL;
11032 char *branch_name = NULL;
11034 memset(&upa, 0, sizeof(upa));
11036 while ((ch = getopt(argc, argv, "acn")) != -1) {
11037 switch (ch) {
11038 case 'a':
11039 abort_merge = 1;
11040 break;
11041 case 'c':
11042 continue_merge = 1;
11043 break;
11044 case 'n':
11045 interrupt_merge = 1;
11046 break;
11047 default:
11048 usage_rebase();
11049 /* NOTREACHED */
11053 argc -= optind;
11054 argv += optind;
11056 #ifndef PROFILE
11057 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11058 "unveil", NULL) == -1)
11059 err(1, "pledge");
11060 #endif
11062 if (abort_merge && continue_merge)
11063 option_conflict('a', 'c');
11064 if (abort_merge || continue_merge) {
11065 if (argc != 0)
11066 usage_merge();
11067 } else if (argc != 1)
11068 usage_merge();
11070 cwd = getcwd(NULL, 0);
11071 if (cwd == NULL) {
11072 error = got_error_from_errno("getcwd");
11073 goto done;
11076 error = got_worktree_open(&worktree, cwd);
11077 if (error) {
11078 if (error->code == GOT_ERR_NOT_WORKTREE)
11079 error = wrap_not_worktree_error(error,
11080 "merge", cwd);
11081 goto done;
11084 error = got_repo_open(&repo,
11085 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11086 if (error != NULL)
11087 goto done;
11089 error = apply_unveil(got_repo_get_path(repo), 0,
11090 worktree ? got_worktree_get_root_path(worktree) : NULL);
11091 if (error)
11092 goto done;
11094 error = check_rebase_or_histedit_in_progress(worktree);
11095 if (error)
11096 goto done;
11098 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11099 repo);
11100 if (error)
11101 goto done;
11103 if (abort_merge) {
11104 if (!merge_in_progress) {
11105 error = got_error(GOT_ERR_NOT_MERGING);
11106 goto done;
11108 error = got_worktree_merge_continue(&branch_name,
11109 &branch_tip, &fileindex, worktree, repo);
11110 if (error)
11111 goto done;
11112 error = got_worktree_merge_abort(worktree, fileindex, repo,
11113 abort_progress, &upa);
11114 if (error)
11115 goto done;
11116 printf("Merge of %s aborted\n", branch_name);
11117 goto done; /* nothing else to do */
11120 error = get_author(&author, repo, worktree);
11121 if (error)
11122 goto done;
11124 if (continue_merge) {
11125 if (!merge_in_progress) {
11126 error = got_error(GOT_ERR_NOT_MERGING);
11127 goto done;
11129 error = got_worktree_merge_continue(&branch_name,
11130 &branch_tip, &fileindex, worktree, repo);
11131 if (error)
11132 goto done;
11133 } else {
11134 error = got_ref_open(&branch, repo, argv[0], 0);
11135 if (error != NULL)
11136 goto done;
11137 branch_name = strdup(got_ref_get_name(branch));
11138 if (branch_name == NULL) {
11139 error = got_error_from_errno("strdup");
11140 goto done;
11142 error = got_ref_resolve(&branch_tip, repo, branch);
11143 if (error)
11144 goto done;
11147 error = got_ref_open(&wt_branch, repo,
11148 got_worktree_get_head_ref_name(worktree), 0);
11149 if (error)
11150 goto done;
11151 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11152 if (error)
11153 goto done;
11154 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11155 wt_branch_tip, branch_tip, 0, repo,
11156 check_cancelled, NULL);
11157 if (error && error->code != GOT_ERR_ANCESTRY)
11158 goto done;
11160 if (!continue_merge) {
11161 error = check_path_prefix(wt_branch_tip, branch_tip,
11162 got_worktree_get_path_prefix(worktree),
11163 GOT_ERR_MERGE_PATH, repo);
11164 if (error)
11165 goto done;
11166 if (yca_id) {
11167 error = check_same_branch(wt_branch_tip, branch,
11168 yca_id, repo);
11169 if (error) {
11170 if (error->code != GOT_ERR_ANCESTRY)
11171 goto done;
11172 error = NULL;
11173 } else {
11174 static char msg[512];
11175 snprintf(msg, sizeof(msg),
11176 "cannot create a merge commit because "
11177 "%s is based on %s; %s can be integrated "
11178 "with 'got integrate' instead", branch_name,
11179 got_worktree_get_head_ref_name(worktree),
11180 branch_name);
11181 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11182 goto done;
11185 error = got_worktree_merge_prepare(&fileindex, worktree,
11186 branch, repo);
11187 if (error)
11188 goto done;
11190 error = got_worktree_merge_branch(worktree, fileindex,
11191 yca_id, branch_tip, repo, update_progress, &upa,
11192 check_cancelled, NULL);
11193 if (error)
11194 goto done;
11195 print_merge_progress_stats(&upa);
11196 if (!upa.did_something) {
11197 error = got_worktree_merge_abort(worktree, fileindex,
11198 repo, abort_progress, &upa);
11199 if (error)
11200 goto done;
11201 printf("Already up-to-date\n");
11202 goto done;
11206 if (interrupt_merge) {
11207 error = got_worktree_merge_postpone(worktree, fileindex);
11208 if (error)
11209 goto done;
11210 printf("Merge of %s interrupted on request\n", branch_name);
11211 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11212 upa.not_deleted > 0 || upa.unversioned > 0) {
11213 error = got_worktree_merge_postpone(worktree, fileindex);
11214 if (error)
11215 goto done;
11216 if (upa.conflicts > 0 && upa.missing == 0 &&
11217 upa.not_deleted == 0 && upa.unversioned == 0) {
11218 error = got_error_msg(GOT_ERR_CONFLICTS,
11219 "conflicts must be resolved before merging "
11220 "can continue");
11221 } else if (upa.conflicts > 0) {
11222 error = got_error_msg(GOT_ERR_CONFLICTS,
11223 "conflicts must be resolved before merging "
11224 "can continue; changes destined for some "
11225 "files were not yet merged and "
11226 "should be merged manually if required before the "
11227 "merge operation is continued");
11228 } else {
11229 error = got_error_msg(GOT_ERR_CONFLICTS,
11230 "changes destined for some "
11231 "files were not yet merged and should be "
11232 "merged manually if required before the "
11233 "merge operation is continued");
11235 goto done;
11236 } else {
11237 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11238 fileindex, author, NULL, 1, branch_tip, branch_name,
11239 repo, continue_merge ? print_status : NULL, NULL);
11240 if (error)
11241 goto done;
11242 error = got_worktree_merge_complete(worktree, fileindex, repo);
11243 if (error)
11244 goto done;
11245 error = got_object_id_str(&id_str, merge_commit_id);
11246 if (error)
11247 goto done;
11248 printf("Merged %s into %s: %s\n", branch_name,
11249 got_worktree_get_head_ref_name(worktree),
11250 id_str);
11253 done:
11254 free(id_str);
11255 free(merge_commit_id);
11256 free(author);
11257 free(branch_tip);
11258 free(branch_name);
11259 free(yca_id);
11260 if (branch)
11261 got_ref_close(branch);
11262 if (wt_branch)
11263 got_ref_close(wt_branch);
11264 if (worktree)
11265 got_worktree_close(worktree);
11266 if (repo) {
11267 const struct got_error *close_err = got_repo_close(repo);
11268 if (error == NULL)
11269 error = close_err;
11271 return error;
11274 __dead static void
11275 usage_stage(void)
11277 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11278 "[-S] [file-path ...]\n",
11279 getprogname());
11280 exit(1);
11283 static const struct got_error *
11284 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11285 const char *path, struct got_object_id *blob_id,
11286 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11287 int dirfd, const char *de_name)
11289 const struct got_error *err = NULL;
11290 char *id_str = NULL;
11292 if (staged_status != GOT_STATUS_ADD &&
11293 staged_status != GOT_STATUS_MODIFY &&
11294 staged_status != GOT_STATUS_DELETE)
11295 return NULL;
11297 if (staged_status == GOT_STATUS_ADD ||
11298 staged_status == GOT_STATUS_MODIFY)
11299 err = got_object_id_str(&id_str, staged_blob_id);
11300 else
11301 err = got_object_id_str(&id_str, blob_id);
11302 if (err)
11303 return err;
11305 printf("%s %c %s\n", id_str, staged_status, path);
11306 free(id_str);
11307 return NULL;
11310 static const struct got_error *
11311 cmd_stage(int argc, char *argv[])
11313 const struct got_error *error = NULL;
11314 struct got_repository *repo = NULL;
11315 struct got_worktree *worktree = NULL;
11316 char *cwd = NULL;
11317 struct got_pathlist_head paths;
11318 struct got_pathlist_entry *pe;
11319 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11320 FILE *patch_script_file = NULL;
11321 const char *patch_script_path = NULL;
11322 struct choose_patch_arg cpa;
11324 TAILQ_INIT(&paths);
11326 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11327 switch (ch) {
11328 case 'l':
11329 list_stage = 1;
11330 break;
11331 case 'p':
11332 pflag = 1;
11333 break;
11334 case 'F':
11335 patch_script_path = optarg;
11336 break;
11337 case 'S':
11338 allow_bad_symlinks = 1;
11339 break;
11340 default:
11341 usage_stage();
11342 /* NOTREACHED */
11346 argc -= optind;
11347 argv += optind;
11349 #ifndef PROFILE
11350 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11351 "unveil", NULL) == -1)
11352 err(1, "pledge");
11353 #endif
11354 if (list_stage && (pflag || patch_script_path))
11355 errx(1, "-l option cannot be used with other options");
11356 if (patch_script_path && !pflag)
11357 errx(1, "-F option can only be used together with -p option");
11359 cwd = getcwd(NULL, 0);
11360 if (cwd == NULL) {
11361 error = got_error_from_errno("getcwd");
11362 goto done;
11365 error = got_worktree_open(&worktree, cwd);
11366 if (error) {
11367 if (error->code == GOT_ERR_NOT_WORKTREE)
11368 error = wrap_not_worktree_error(error, "stage", cwd);
11369 goto done;
11372 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11373 NULL);
11374 if (error != NULL)
11375 goto done;
11377 if (patch_script_path) {
11378 patch_script_file = fopen(patch_script_path, "re");
11379 if (patch_script_file == NULL) {
11380 error = got_error_from_errno2("fopen",
11381 patch_script_path);
11382 goto done;
11385 error = apply_unveil(got_repo_get_path(repo), 0,
11386 got_worktree_get_root_path(worktree));
11387 if (error)
11388 goto done;
11390 error = check_merge_in_progress(worktree, repo);
11391 if (error)
11392 goto done;
11394 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11395 if (error)
11396 goto done;
11398 if (list_stage)
11399 error = got_worktree_status(worktree, &paths, repo, 0,
11400 print_stage, NULL, check_cancelled, NULL);
11401 else {
11402 cpa.patch_script_file = patch_script_file;
11403 cpa.action = "stage";
11404 error = got_worktree_stage(worktree, &paths,
11405 pflag ? NULL : print_status, NULL,
11406 pflag ? choose_patch : NULL, &cpa,
11407 allow_bad_symlinks, repo);
11409 done:
11410 if (patch_script_file && fclose(patch_script_file) == EOF &&
11411 error == NULL)
11412 error = got_error_from_errno2("fclose", patch_script_path);
11413 if (repo) {
11414 const struct got_error *close_err = got_repo_close(repo);
11415 if (error == NULL)
11416 error = close_err;
11418 if (worktree)
11419 got_worktree_close(worktree);
11420 TAILQ_FOREACH(pe, &paths, entry)
11421 free((char *)pe->path);
11422 got_pathlist_free(&paths);
11423 free(cwd);
11424 return error;
11427 __dead static void
11428 usage_unstage(void)
11430 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11431 "[file-path ...]\n",
11432 getprogname());
11433 exit(1);
11437 static const struct got_error *
11438 cmd_unstage(int argc, char *argv[])
11440 const struct got_error *error = NULL;
11441 struct got_repository *repo = NULL;
11442 struct got_worktree *worktree = NULL;
11443 char *cwd = NULL;
11444 struct got_pathlist_head paths;
11445 struct got_pathlist_entry *pe;
11446 int ch, pflag = 0;
11447 struct got_update_progress_arg upa;
11448 FILE *patch_script_file = NULL;
11449 const char *patch_script_path = NULL;
11450 struct choose_patch_arg cpa;
11452 TAILQ_INIT(&paths);
11454 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11455 switch (ch) {
11456 case 'p':
11457 pflag = 1;
11458 break;
11459 case 'F':
11460 patch_script_path = optarg;
11461 break;
11462 default:
11463 usage_unstage();
11464 /* NOTREACHED */
11468 argc -= optind;
11469 argv += optind;
11471 #ifndef PROFILE
11472 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11473 "unveil", NULL) == -1)
11474 err(1, "pledge");
11475 #endif
11476 if (patch_script_path && !pflag)
11477 errx(1, "-F option can only be used together with -p option");
11479 cwd = getcwd(NULL, 0);
11480 if (cwd == NULL) {
11481 error = got_error_from_errno("getcwd");
11482 goto done;
11485 error = got_worktree_open(&worktree, cwd);
11486 if (error) {
11487 if (error->code == GOT_ERR_NOT_WORKTREE)
11488 error = wrap_not_worktree_error(error, "unstage", cwd);
11489 goto done;
11492 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11493 NULL);
11494 if (error != NULL)
11495 goto done;
11497 if (patch_script_path) {
11498 patch_script_file = fopen(patch_script_path, "re");
11499 if (patch_script_file == NULL) {
11500 error = got_error_from_errno2("fopen",
11501 patch_script_path);
11502 goto done;
11506 error = apply_unveil(got_repo_get_path(repo), 0,
11507 got_worktree_get_root_path(worktree));
11508 if (error)
11509 goto done;
11511 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11512 if (error)
11513 goto done;
11515 cpa.patch_script_file = patch_script_file;
11516 cpa.action = "unstage";
11517 memset(&upa, 0, sizeof(upa));
11518 error = got_worktree_unstage(worktree, &paths, update_progress,
11519 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11520 if (!error)
11521 print_merge_progress_stats(&upa);
11522 done:
11523 if (patch_script_file && fclose(patch_script_file) == EOF &&
11524 error == NULL)
11525 error = got_error_from_errno2("fclose", patch_script_path);
11526 if (repo) {
11527 const struct got_error *close_err = got_repo_close(repo);
11528 if (error == NULL)
11529 error = close_err;
11531 if (worktree)
11532 got_worktree_close(worktree);
11533 TAILQ_FOREACH(pe, &paths, entry)
11534 free((char *)pe->path);
11535 got_pathlist_free(&paths);
11536 free(cwd);
11537 return error;
11540 __dead static void
11541 usage_cat(void)
11543 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11544 "arg1 [arg2 ...]\n", getprogname());
11545 exit(1);
11548 static const struct got_error *
11549 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11551 const struct got_error *err;
11552 struct got_blob_object *blob;
11554 err = got_object_open_as_blob(&blob, repo, id, 8192);
11555 if (err)
11556 return err;
11558 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11559 got_object_blob_close(blob);
11560 return err;
11563 static const struct got_error *
11564 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11566 const struct got_error *err;
11567 struct got_tree_object *tree;
11568 int nentries, i;
11570 err = got_object_open_as_tree(&tree, repo, id);
11571 if (err)
11572 return err;
11574 nentries = got_object_tree_get_nentries(tree);
11575 for (i = 0; i < nentries; i++) {
11576 struct got_tree_entry *te;
11577 char *id_str;
11578 if (sigint_received || sigpipe_received)
11579 break;
11580 te = got_object_tree_get_entry(tree, i);
11581 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11582 if (err)
11583 break;
11584 fprintf(outfile, "%s %.7o %s\n", id_str,
11585 got_tree_entry_get_mode(te),
11586 got_tree_entry_get_name(te));
11587 free(id_str);
11590 got_object_tree_close(tree);
11591 return err;
11594 static void
11595 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11597 long long h, m;
11598 char sign = '+';
11600 if (gmtoff < 0) {
11601 sign = '-';
11602 gmtoff = -gmtoff;
11605 h = (long long)gmtoff / 3600;
11606 m = ((long long)gmtoff - h*3600) / 60;
11607 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11610 static const struct got_error *
11611 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11613 const struct got_error *err;
11614 struct got_commit_object *commit;
11615 const struct got_object_id_queue *parent_ids;
11616 struct got_object_qid *pid;
11617 char *id_str = NULL;
11618 const char *logmsg = NULL;
11619 char gmtoff[6];
11621 err = got_object_open_as_commit(&commit, repo, id);
11622 if (err)
11623 return err;
11625 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11626 if (err)
11627 goto done;
11629 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11630 parent_ids = got_object_commit_get_parent_ids(commit);
11631 fprintf(outfile, "numparents %d\n",
11632 got_object_commit_get_nparents(commit));
11633 STAILQ_FOREACH(pid, parent_ids, entry) {
11634 char *pid_str;
11635 err = got_object_id_str(&pid_str, pid->id);
11636 if (err)
11637 goto done;
11638 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11639 free(pid_str);
11641 format_gmtoff(gmtoff, sizeof(gmtoff),
11642 got_object_commit_get_author_gmtoff(commit));
11643 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11644 got_object_commit_get_author(commit),
11645 (long long)got_object_commit_get_author_time(commit),
11646 gmtoff);
11648 format_gmtoff(gmtoff, sizeof(gmtoff),
11649 got_object_commit_get_committer_gmtoff(commit));
11650 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11651 got_object_commit_get_author(commit),
11652 (long long)got_object_commit_get_committer_time(commit),
11653 gmtoff);
11655 logmsg = got_object_commit_get_logmsg_raw(commit);
11656 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11657 fprintf(outfile, "%s", logmsg);
11658 done:
11659 free(id_str);
11660 got_object_commit_close(commit);
11661 return err;
11664 static const struct got_error *
11665 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11667 const struct got_error *err;
11668 struct got_tag_object *tag;
11669 char *id_str = NULL;
11670 const char *tagmsg = NULL;
11671 char gmtoff[6];
11673 err = got_object_open_as_tag(&tag, repo, id);
11674 if (err)
11675 return err;
11677 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11678 if (err)
11679 goto done;
11681 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11683 switch (got_object_tag_get_object_type(tag)) {
11684 case GOT_OBJ_TYPE_BLOB:
11685 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11686 GOT_OBJ_LABEL_BLOB);
11687 break;
11688 case GOT_OBJ_TYPE_TREE:
11689 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11690 GOT_OBJ_LABEL_TREE);
11691 break;
11692 case GOT_OBJ_TYPE_COMMIT:
11693 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11694 GOT_OBJ_LABEL_COMMIT);
11695 break;
11696 case GOT_OBJ_TYPE_TAG:
11697 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11698 GOT_OBJ_LABEL_TAG);
11699 break;
11700 default:
11701 break;
11704 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11705 got_object_tag_get_name(tag));
11707 format_gmtoff(gmtoff, sizeof(gmtoff),
11708 got_object_tag_get_tagger_gmtoff(tag));
11709 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11710 got_object_tag_get_tagger(tag),
11711 (long long)got_object_tag_get_tagger_time(tag),
11712 gmtoff);
11714 tagmsg = got_object_tag_get_message(tag);
11715 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11716 fprintf(outfile, "%s", tagmsg);
11717 done:
11718 free(id_str);
11719 got_object_tag_close(tag);
11720 return err;
11723 static const struct got_error *
11724 cmd_cat(int argc, char *argv[])
11726 const struct got_error *error;
11727 struct got_repository *repo = NULL;
11728 struct got_worktree *worktree = NULL;
11729 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11730 const char *commit_id_str = NULL;
11731 struct got_object_id *id = NULL, *commit_id = NULL;
11732 int ch, obj_type, i, force_path = 0;
11733 struct got_reflist_head refs;
11735 TAILQ_INIT(&refs);
11737 #ifndef PROFILE
11738 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11739 NULL) == -1)
11740 err(1, "pledge");
11741 #endif
11743 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11744 switch (ch) {
11745 case 'c':
11746 commit_id_str = optarg;
11747 break;
11748 case 'r':
11749 repo_path = realpath(optarg, NULL);
11750 if (repo_path == NULL)
11751 return got_error_from_errno2("realpath",
11752 optarg);
11753 got_path_strip_trailing_slashes(repo_path);
11754 break;
11755 case 'P':
11756 force_path = 1;
11757 break;
11758 default:
11759 usage_cat();
11760 /* NOTREACHED */
11764 argc -= optind;
11765 argv += optind;
11767 cwd = getcwd(NULL, 0);
11768 if (cwd == NULL) {
11769 error = got_error_from_errno("getcwd");
11770 goto done;
11772 error = got_worktree_open(&worktree, cwd);
11773 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11774 goto done;
11775 if (worktree) {
11776 if (repo_path == NULL) {
11777 repo_path = strdup(
11778 got_worktree_get_repo_path(worktree));
11779 if (repo_path == NULL) {
11780 error = got_error_from_errno("strdup");
11781 goto done;
11786 if (repo_path == NULL) {
11787 repo_path = getcwd(NULL, 0);
11788 if (repo_path == NULL)
11789 return got_error_from_errno("getcwd");
11792 error = got_repo_open(&repo, repo_path, NULL);
11793 free(repo_path);
11794 if (error != NULL)
11795 goto done;
11797 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11798 if (error)
11799 goto done;
11801 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11802 if (error)
11803 goto done;
11805 if (commit_id_str == NULL)
11806 commit_id_str = GOT_REF_HEAD;
11807 error = got_repo_match_object_id(&commit_id, NULL,
11808 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11809 if (error)
11810 goto done;
11812 for (i = 0; i < argc; i++) {
11813 if (force_path) {
11814 error = got_object_id_by_path(&id, repo, commit_id,
11815 argv[i]);
11816 if (error)
11817 break;
11818 } else {
11819 error = got_repo_match_object_id(&id, &label, argv[i],
11820 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11821 repo);
11822 if (error) {
11823 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11824 error->code != GOT_ERR_NOT_REF)
11825 break;
11826 error = got_object_id_by_path(&id, repo,
11827 commit_id, argv[i]);
11828 if (error)
11829 break;
11833 error = got_object_get_type(&obj_type, repo, id);
11834 if (error)
11835 break;
11837 switch (obj_type) {
11838 case GOT_OBJ_TYPE_BLOB:
11839 error = cat_blob(id, repo, stdout);
11840 break;
11841 case GOT_OBJ_TYPE_TREE:
11842 error = cat_tree(id, repo, stdout);
11843 break;
11844 case GOT_OBJ_TYPE_COMMIT:
11845 error = cat_commit(id, repo, stdout);
11846 break;
11847 case GOT_OBJ_TYPE_TAG:
11848 error = cat_tag(id, repo, stdout);
11849 break;
11850 default:
11851 error = got_error(GOT_ERR_OBJ_TYPE);
11852 break;
11854 if (error)
11855 break;
11856 free(label);
11857 label = NULL;
11858 free(id);
11859 id = NULL;
11861 done:
11862 free(label);
11863 free(id);
11864 free(commit_id);
11865 if (worktree)
11866 got_worktree_close(worktree);
11867 if (repo) {
11868 const struct got_error *close_err = got_repo_close(repo);
11869 if (error == NULL)
11870 error = close_err;
11872 got_ref_list_free(&refs);
11873 return error;
11876 __dead static void
11877 usage_info(void)
11879 fprintf(stderr, "usage: %s info [path ...]\n",
11880 getprogname());
11881 exit(1);
11884 static const struct got_error *
11885 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11886 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11887 struct got_object_id *commit_id)
11889 const struct got_error *err = NULL;
11890 char *id_str = NULL;
11891 char datebuf[128];
11892 struct tm mytm, *tm;
11893 struct got_pathlist_head *paths = arg;
11894 struct got_pathlist_entry *pe;
11897 * Clear error indication from any of the path arguments which
11898 * would cause this file index entry to be displayed.
11900 TAILQ_FOREACH(pe, paths, entry) {
11901 if (got_path_cmp(path, pe->path, strlen(path),
11902 pe->path_len) == 0 ||
11903 got_path_is_child(path, pe->path, pe->path_len))
11904 pe->data = NULL; /* no error */
11907 printf(GOT_COMMIT_SEP_STR);
11908 if (S_ISLNK(mode))
11909 printf("symlink: %s\n", path);
11910 else if (S_ISREG(mode)) {
11911 printf("file: %s\n", path);
11912 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11913 } else if (S_ISDIR(mode))
11914 printf("directory: %s\n", path);
11915 else
11916 printf("something: %s\n", path);
11918 tm = localtime_r(&mtime, &mytm);
11919 if (tm == NULL)
11920 return NULL;
11921 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11922 return got_error(GOT_ERR_NO_SPACE);
11923 printf("timestamp: %s\n", datebuf);
11925 if (blob_id) {
11926 err = got_object_id_str(&id_str, blob_id);
11927 if (err)
11928 return err;
11929 printf("based on blob: %s\n", id_str);
11930 free(id_str);
11933 if (staged_blob_id) {
11934 err = got_object_id_str(&id_str, staged_blob_id);
11935 if (err)
11936 return err;
11937 printf("based on staged blob: %s\n", id_str);
11938 free(id_str);
11941 if (commit_id) {
11942 err = got_object_id_str(&id_str, commit_id);
11943 if (err)
11944 return err;
11945 printf("based on commit: %s\n", id_str);
11946 free(id_str);
11949 return NULL;
11952 static const struct got_error *
11953 cmd_info(int argc, char *argv[])
11955 const struct got_error *error = NULL;
11956 struct got_worktree *worktree = NULL;
11957 char *cwd = NULL, *id_str = NULL;
11958 struct got_pathlist_head paths;
11959 struct got_pathlist_entry *pe;
11960 char *uuidstr = NULL;
11961 int ch, show_files = 0;
11963 TAILQ_INIT(&paths);
11965 while ((ch = getopt(argc, argv, "")) != -1) {
11966 switch (ch) {
11967 default:
11968 usage_info();
11969 /* NOTREACHED */
11973 argc -= optind;
11974 argv += optind;
11976 #ifndef PROFILE
11977 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11978 NULL) == -1)
11979 err(1, "pledge");
11980 #endif
11981 cwd = getcwd(NULL, 0);
11982 if (cwd == NULL) {
11983 error = got_error_from_errno("getcwd");
11984 goto done;
11987 error = got_worktree_open(&worktree, cwd);
11988 if (error) {
11989 if (error->code == GOT_ERR_NOT_WORKTREE)
11990 error = wrap_not_worktree_error(error, "info", cwd);
11991 goto done;
11994 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11995 if (error)
11996 goto done;
11998 if (argc >= 1) {
11999 error = get_worktree_paths_from_argv(&paths, argc, argv,
12000 worktree);
12001 if (error)
12002 goto done;
12003 show_files = 1;
12006 error = got_object_id_str(&id_str,
12007 got_worktree_get_base_commit_id(worktree));
12008 if (error)
12009 goto done;
12011 error = got_worktree_get_uuid(&uuidstr, worktree);
12012 if (error)
12013 goto done;
12015 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12016 printf("work tree base commit: %s\n", id_str);
12017 printf("work tree path prefix: %s\n",
12018 got_worktree_get_path_prefix(worktree));
12019 printf("work tree branch reference: %s\n",
12020 got_worktree_get_head_ref_name(worktree));
12021 printf("work tree UUID: %s\n", uuidstr);
12022 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12024 if (show_files) {
12025 struct got_pathlist_entry *pe;
12026 TAILQ_FOREACH(pe, &paths, entry) {
12027 if (pe->path_len == 0)
12028 continue;
12030 * Assume this path will fail. This will be corrected
12031 * in print_path_info() in case the path does suceeed.
12033 pe->data = (void *)got_error_path(pe->path,
12034 GOT_ERR_BAD_PATH);
12036 error = got_worktree_path_info(worktree, &paths,
12037 print_path_info, &paths, check_cancelled, NULL);
12038 if (error)
12039 goto done;
12040 TAILQ_FOREACH(pe, &paths, entry) {
12041 if (pe->data != NULL) {
12042 error = pe->data; /* bad path */
12043 break;
12047 done:
12048 TAILQ_FOREACH(pe, &paths, entry)
12049 free((char *)pe->path);
12050 got_pathlist_free(&paths);
12051 free(cwd);
12052 free(id_str);
12053 free(uuidstr);
12054 return error;