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/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
60 #ifndef nitems
61 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
62 #endif
64 static volatile sig_atomic_t sigint_received;
65 static volatile sig_atomic_t sigpipe_received;
67 static void
68 catch_sigint(int signo)
69 {
70 sigint_received = 1;
71 }
73 static void
74 catch_sigpipe(int signo)
75 {
76 sigpipe_received = 1;
77 }
80 struct got_cmd {
81 const char *cmd_name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 const char *cmd_alias;
85 };
87 __dead static void usage(int, int);
88 __dead static void usage_init(void);
89 __dead static void usage_import(void);
90 __dead static void usage_clone(void);
91 __dead static void usage_fetch(void);
92 __dead static void usage_checkout(void);
93 __dead static void usage_update(void);
94 __dead static void usage_log(void);
95 __dead static void usage_diff(void);
96 __dead static void usage_blame(void);
97 __dead static void usage_tree(void);
98 __dead static void usage_status(void);
99 __dead static void usage_ref(void);
100 __dead static void usage_branch(void);
101 __dead static void usage_tag(void);
102 __dead static void usage_add(void);
103 __dead static void usage_remove(void);
104 __dead static void usage_revert(void);
105 __dead static void usage_commit(void);
106 __dead static void usage_send(void);
107 __dead static void usage_cherrypick(void);
108 __dead static void usage_backout(void);
109 __dead static void usage_rebase(void);
110 __dead static void usage_histedit(void);
111 __dead static void usage_integrate(void);
112 __dead static void usage_merge(void);
113 __dead static void usage_stage(void);
114 __dead static void usage_unstage(void);
115 __dead static void usage_cat(void);
116 __dead static void usage_info(void);
118 static const struct got_error* cmd_init(int, char *[]);
119 static const struct got_error* cmd_import(int, char *[]);
120 static const struct got_error* cmd_clone(int, char *[]);
121 static const struct got_error* cmd_fetch(int, char *[]);
122 static const struct got_error* cmd_checkout(int, char *[]);
123 static const struct got_error* cmd_update(int, char *[]);
124 static const struct got_error* cmd_log(int, char *[]);
125 static const struct got_error* cmd_diff(int, char *[]);
126 static const struct got_error* cmd_blame(int, char *[]);
127 static const struct got_error* cmd_tree(int, char *[]);
128 static const struct got_error* cmd_status(int, char *[]);
129 static const struct got_error* cmd_ref(int, char *[]);
130 static const struct got_error* cmd_branch(int, char *[]);
131 static const struct got_error* cmd_tag(int, char *[]);
132 static const struct got_error* cmd_add(int, char *[]);
133 static const struct got_error* cmd_remove(int, char *[]);
134 static const struct got_error* cmd_revert(int, char *[]);
135 static const struct got_error* cmd_commit(int, char *[]);
136 static const struct got_error* cmd_send(int, char *[]);
137 static const struct got_error* cmd_cherrypick(int, char *[]);
138 static const struct got_error* cmd_backout(int, char *[]);
139 static const struct got_error* cmd_rebase(int, char *[]);
140 static const struct got_error* cmd_histedit(int, char *[]);
141 static const struct got_error* cmd_integrate(int, char *[]);
142 static const struct got_error* cmd_merge(int, char *[]);
143 static const struct got_error* cmd_stage(int, char *[]);
144 static const struct got_error* cmd_unstage(int, char *[]);
145 static const struct got_error* cmd_cat(int, char *[]);
146 static const struct got_error* cmd_info(int, char *[]);
148 static const struct got_cmd got_commands[] = {
149 { "init", cmd_init, usage_init, "" },
150 { "import", cmd_import, usage_import, "im" },
151 { "clone", cmd_clone, usage_clone, "cl" },
152 { "fetch", cmd_fetch, usage_fetch, "fe" },
153 { "checkout", cmd_checkout, usage_checkout, "co" },
154 { "update", cmd_update, usage_update, "up" },
155 { "log", cmd_log, usage_log, "" },
156 { "diff", cmd_diff, usage_diff, "di" },
157 { "blame", cmd_blame, usage_blame, "bl" },
158 { "tree", cmd_tree, usage_tree, "tr" },
159 { "status", cmd_status, usage_status, "st" },
160 { "ref", cmd_ref, usage_ref, "" },
161 { "branch", cmd_branch, usage_branch, "br" },
162 { "tag", cmd_tag, usage_tag, "" },
163 { "add", cmd_add, usage_add, "" },
164 { "remove", cmd_remove, usage_remove, "rm" },
165 { "revert", cmd_revert, usage_revert, "rv" },
166 { "commit", cmd_commit, usage_commit, "ci" },
167 { "send", cmd_send, usage_send, "se" },
168 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
169 { "backout", cmd_backout, usage_backout, "bo" },
170 { "rebase", cmd_rebase, usage_rebase, "rb" },
171 { "histedit", cmd_histedit, usage_histedit, "he" },
172 { "integrate", cmd_integrate, usage_integrate,"ig" },
173 { "merge", cmd_merge, usage_merge, "mg" },
174 { "stage", cmd_stage, usage_stage, "sg" },
175 { "unstage", cmd_unstage, usage_unstage, "ug" },
176 { "cat", cmd_cat, usage_cat, "" },
177 { "info", cmd_info, usage_info, "" },
178 };
180 static void
181 list_commands(FILE *fp)
183 size_t i;
185 fprintf(fp, "commands:");
186 for (i = 0; i < nitems(got_commands); i++) {
187 const struct got_cmd *cmd = &got_commands[i];
188 fprintf(fp, " %s", cmd->cmd_name);
190 fputc('\n', fp);
193 __dead static void
194 option_conflict(char a, char b)
196 errx(1, "-%c and -%c options are mutually exclusive", a, b);
199 int
200 main(int argc, char *argv[])
202 const struct got_cmd *cmd;
203 size_t i;
204 int ch;
205 int hflag = 0, Vflag = 0;
206 static const struct option longopts[] = {
207 { "version", no_argument, NULL, 'V' },
208 { NULL, 0, NULL, 0 }
209 };
211 setlocale(LC_CTYPE, "");
213 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
214 switch (ch) {
215 case 'h':
216 hflag = 1;
217 break;
218 case 'V':
219 Vflag = 1;
220 break;
221 default:
222 usage(hflag, 1);
223 /* NOTREACHED */
227 argc -= optind;
228 argv += optind;
229 optind = 1;
230 optreset = 1;
232 if (Vflag) {
233 got_version_print_str();
234 return 0;
237 if (argc <= 0)
238 usage(hflag, hflag ? 0 : 1);
240 signal(SIGINT, catch_sigint);
241 signal(SIGPIPE, catch_sigpipe);
243 for (i = 0; i < nitems(got_commands); i++) {
244 const struct got_error *error;
246 cmd = &got_commands[i];
248 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
249 strcmp(cmd->cmd_alias, argv[0]) != 0)
250 continue;
252 if (hflag)
253 cmd->cmd_usage();
255 error = cmd->cmd_main(argc, argv);
256 if (error && error->code != GOT_ERR_CANCELLED &&
257 error->code != GOT_ERR_PRIVSEP_EXIT &&
258 !(sigpipe_received &&
259 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
260 !(sigint_received &&
261 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
262 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
263 return 1;
266 return 0;
269 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
270 list_commands(stderr);
271 return 1;
274 __dead static void
275 usage(int hflag, int status)
277 FILE *fp = (status == 0) ? stdout : stderr;
279 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
280 getprogname());
281 if (hflag)
282 list_commands(fp);
283 exit(status);
286 static const struct got_error *
287 get_editor(char **abspath)
289 const struct got_error *err = NULL;
290 const char *editor;
292 *abspath = NULL;
294 editor = getenv("VISUAL");
295 if (editor == NULL)
296 editor = getenv("EDITOR");
298 if (editor) {
299 err = got_path_find_prog(abspath, editor);
300 if (err)
301 return err;
304 if (*abspath == NULL) {
305 *abspath = strdup("/bin/ed");
306 if (*abspath == NULL)
307 return got_error_from_errno("strdup");
310 return NULL;
313 static const struct got_error *
314 apply_unveil(const char *repo_path, int repo_read_only,
315 const char *worktree_path)
317 const struct got_error *err;
319 #ifdef PROFILE
320 if (unveil("gmon.out", "rwc") != 0)
321 return got_error_from_errno2("unveil", "gmon.out");
322 #endif
323 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
324 return got_error_from_errno2("unveil", repo_path);
326 if (worktree_path && unveil(worktree_path, "rwc") != 0)
327 return got_error_from_errno2("unveil", worktree_path);
329 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
330 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
332 err = got_privsep_unveil_exec_helpers();
333 if (err != NULL)
334 return err;
336 if (unveil(NULL, NULL) != 0)
337 return got_error_from_errno("unveil");
339 return NULL;
342 __dead static void
343 usage_init(void)
345 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
346 exit(1);
349 static const struct got_error *
350 cmd_init(int argc, char *argv[])
352 const struct got_error *error = NULL;
353 char *repo_path = NULL;
354 int ch;
356 while ((ch = getopt(argc, argv, "")) != -1) {
357 switch (ch) {
358 default:
359 usage_init();
360 /* NOTREACHED */
364 argc -= optind;
365 argv += optind;
367 #ifndef PROFILE
368 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
369 err(1, "pledge");
370 #endif
371 if (argc != 1)
372 usage_init();
374 repo_path = strdup(argv[0]);
375 if (repo_path == NULL)
376 return got_error_from_errno("strdup");
378 got_path_strip_trailing_slashes(repo_path);
380 error = got_path_mkdir(repo_path);
381 if (error &&
382 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
383 goto done;
385 error = apply_unveil(repo_path, 0, NULL);
386 if (error)
387 goto done;
389 error = got_repo_init(repo_path);
390 done:
391 free(repo_path);
392 return error;
395 __dead static void
396 usage_import(void)
398 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
399 "[-r repository-path] [-I pattern] path\n", getprogname());
400 exit(1);
403 int
404 spawn_editor(const char *editor, const char *file)
406 pid_t pid;
407 sig_t sighup, sigint, sigquit;
408 int st = -1;
410 sighup = signal(SIGHUP, SIG_IGN);
411 sigint = signal(SIGINT, SIG_IGN);
412 sigquit = signal(SIGQUIT, SIG_IGN);
414 switch (pid = fork()) {
415 case -1:
416 goto doneediting;
417 case 0:
418 execl(editor, editor, file, (char *)NULL);
419 _exit(127);
422 while (waitpid(pid, &st, 0) == -1)
423 if (errno != EINTR)
424 break;
426 doneediting:
427 (void)signal(SIGHUP, sighup);
428 (void)signal(SIGINT, sigint);
429 (void)signal(SIGQUIT, sigquit);
431 if (!WIFEXITED(st)) {
432 errno = EINTR;
433 return -1;
436 return WEXITSTATUS(st);
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 char *line = NULL;
446 size_t linesize = 0;
447 ssize_t linelen;
448 struct stat st, st2;
449 FILE *fp = NULL;
450 size_t len, logmsg_len;
451 char *initial_content_stripped = NULL, *buf = NULL, *s;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (stat(logmsg_path, &st2) == -1)
462 return got_error_from_errno("stat");
464 if (require_modification &&
465 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
466 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
467 "no changes made to commit message, aborting");
469 /*
470 * Set up a stripped version of the initial content without comments
471 * and blank lines. We need this in order to check if the message
472 * has in fact been edited.
473 */
474 initial_content_stripped = malloc(initial_content_len + 1);
475 if (initial_content_stripped == NULL)
476 return got_error_from_errno("malloc");
477 initial_content_stripped[0] = '\0';
479 buf = strdup(initial_content);
480 if (buf == NULL) {
481 err = got_error_from_errno("strdup");
482 goto done;
484 s = buf;
485 len = 0;
486 while ((line = strsep(&s, "\n")) != NULL) {
487 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
488 continue; /* remove comments and leading empty lines */
489 len = strlcat(initial_content_stripped, line,
490 initial_content_len + 1);
491 if (len >= initial_content_len + 1) {
492 err = got_error(GOT_ERR_NO_SPACE);
493 goto done;
496 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
497 initial_content_stripped[len - 1] = '\0';
498 len--;
501 logmsg_len = st2.st_size;
502 *logmsg = malloc(logmsg_len + 1);
503 if (*logmsg == NULL)
504 return got_error_from_errno("malloc");
505 (*logmsg)[0] = '\0';
507 fp = fopen(logmsg_path, "re");
508 if (fp == NULL) {
509 err = got_error_from_errno("fopen");
510 goto done;
513 len = 0;
514 while ((linelen = getline(&line, &linesize, fp)) != -1) {
515 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
516 continue; /* remove comments and leading empty lines */
517 len = strlcat(*logmsg, line, logmsg_len + 1);
518 if (len >= logmsg_len + 1) {
519 err = got_error(GOT_ERR_NO_SPACE);
520 goto done;
523 free(line);
524 if (ferror(fp)) {
525 err = got_ferror(fp, GOT_ERR_IO);
526 goto done;
528 while (len > 0 && (*logmsg)[len - 1] == '\n') {
529 (*logmsg)[len - 1] = '\0';
530 len--;
533 if (len == 0) {
534 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
535 "commit message cannot be empty, aborting");
536 goto done;
538 if (require_modification &&
539 strcmp(*logmsg, initial_content_stripped) == 0)
540 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
541 "no changes made to commit message, aborting");
542 done:
543 free(initial_content_stripped);
544 free(buf);
545 if (fp && fclose(fp) == EOF && err == NULL)
546 err = got_error_from_errno("fclose");
547 if (err) {
548 free(*logmsg);
549 *logmsg = NULL;
551 return err;
554 static const struct got_error *
555 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
556 const char *path_dir, const char *branch_name)
558 char *initial_content = NULL;
559 const struct got_error *err = NULL;
560 int initial_content_len;
561 int fd = -1;
563 initial_content_len = asprintf(&initial_content,
564 "\n# %s to be imported to branch %s\n", path_dir,
565 branch_name);
566 if (initial_content_len == -1)
567 return got_error_from_errno("asprintf");
569 err = got_opentemp_named_fd(logmsg_path, &fd,
570 GOT_TMPDIR_STR "/got-importmsg");
571 if (err)
572 goto done;
574 if (write(fd, initial_content, initial_content_len) == -1) {
575 err = got_error_from_errno2("write", *logmsg_path);
576 goto done;
579 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
580 initial_content_len, 1);
581 done:
582 if (fd != -1 && close(fd) == -1 && err == NULL)
583 err = got_error_from_errno2("close", *logmsg_path);
584 free(initial_content);
585 if (err) {
586 free(*logmsg_path);
587 *logmsg_path = NULL;
589 return err;
592 static const struct got_error *
593 import_progress(void *arg, const char *path)
595 printf("A %s\n", path);
596 return NULL;
599 static int
600 valid_author(const char *author)
602 /*
603 * Really dumb email address check; we're only doing this to
604 * avoid git's object parser breaking on commits we create.
605 */
606 while (*author && *author != '<')
607 author++;
608 if (*author != '<')
609 return 0;
610 while (*author && *author != '@')
611 author++;
612 if (*author != '@')
613 return 0;
614 while (*author && *author != '>')
615 author++;
616 return *author == '>';
619 static const struct got_error *
620 get_author(char **author, struct got_repository *repo,
621 struct got_worktree *worktree)
623 const struct got_error *err = NULL;
624 const char *got_author = NULL, *name, *email;
625 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
627 *author = NULL;
629 if (worktree)
630 worktree_conf = got_worktree_get_gotconfig(worktree);
631 repo_conf = got_repo_get_gotconfig(repo);
633 /*
634 * Priority of potential author information sources, from most
635 * significant to least significant:
636 * 1) work tree's .got/got.conf file
637 * 2) repository's got.conf file
638 * 3) repository's git config file
639 * 4) environment variables
640 * 5) global git config files (in user's home directory or /etc)
641 */
643 if (worktree_conf)
644 got_author = got_gotconfig_get_author(worktree_conf);
645 if (got_author == NULL)
646 got_author = got_gotconfig_get_author(repo_conf);
647 if (got_author == NULL) {
648 name = got_repo_get_gitconfig_author_name(repo);
649 email = got_repo_get_gitconfig_author_email(repo);
650 if (name && email) {
651 if (asprintf(author, "%s <%s>", name, email) == -1)
652 return got_error_from_errno("asprintf");
653 return NULL;
656 got_author = getenv("GOT_AUTHOR");
657 if (got_author == NULL) {
658 name = got_repo_get_global_gitconfig_author_name(repo);
659 email = got_repo_get_global_gitconfig_author_email(
660 repo);
661 if (name && email) {
662 if (asprintf(author, "%s <%s>", name, email)
663 == -1)
664 return got_error_from_errno("asprintf");
665 return NULL;
667 /* TODO: Look up user in password database? */
668 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
672 *author = strdup(got_author);
673 if (*author == NULL)
674 return got_error_from_errno("strdup");
676 if (!valid_author(*author)) {
677 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
678 free(*author);
679 *author = NULL;
681 return err;
684 static const struct got_error *
685 get_gitconfig_path(char **gitconfig_path)
687 const char *homedir = getenv("HOME");
689 *gitconfig_path = NULL;
690 if (homedir) {
691 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
692 return got_error_from_errno("asprintf");
695 return NULL;
698 static const struct got_error *
699 cmd_import(int argc, char *argv[])
701 const struct got_error *error = NULL;
702 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
703 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
704 const char *branch_name = "main";
705 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
706 struct got_repository *repo = NULL;
707 struct got_reference *branch_ref = NULL, *head_ref = NULL;
708 struct got_object_id *new_commit_id = NULL;
709 int ch;
710 struct got_pathlist_head ignores;
711 struct got_pathlist_entry *pe;
712 int preserve_logmsg = 0;
714 TAILQ_INIT(&ignores);
716 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
717 switch (ch) {
718 case 'b':
719 branch_name = optarg;
720 break;
721 case 'm':
722 logmsg = strdup(optarg);
723 if (logmsg == NULL) {
724 error = got_error_from_errno("strdup");
725 goto done;
727 break;
728 case 'r':
729 repo_path = realpath(optarg, NULL);
730 if (repo_path == NULL) {
731 error = got_error_from_errno2("realpath",
732 optarg);
733 goto done;
735 break;
736 case 'I':
737 if (optarg[0] == '\0')
738 break;
739 error = got_pathlist_insert(&pe, &ignores, optarg,
740 NULL);
741 if (error)
742 goto done;
743 break;
744 default:
745 usage_import();
746 /* NOTREACHED */
750 argc -= optind;
751 argv += optind;
753 #ifndef PROFILE
754 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
755 "unveil",
756 NULL) == -1)
757 err(1, "pledge");
758 #endif
759 if (argc != 1)
760 usage_import();
762 if (repo_path == NULL) {
763 repo_path = getcwd(NULL, 0);
764 if (repo_path == NULL)
765 return got_error_from_errno("getcwd");
767 got_path_strip_trailing_slashes(repo_path);
768 error = get_gitconfig_path(&gitconfig_path);
769 if (error)
770 goto done;
771 error = got_repo_open(&repo, repo_path, gitconfig_path);
772 if (error)
773 goto done;
775 error = get_author(&author, repo, NULL);
776 if (error)
777 return error;
779 /*
780 * Don't let the user create a branch name with a leading '-'.
781 * While technically a valid reference name, this case is usually
782 * an unintended typo.
783 */
784 if (branch_name[0] == '-')
785 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
787 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
788 error = got_error_from_errno("asprintf");
789 goto done;
792 error = got_ref_open(&branch_ref, repo, refname, 0);
793 if (error) {
794 if (error->code != GOT_ERR_NOT_REF)
795 goto done;
796 } else {
797 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
798 "import target branch already exists");
799 goto done;
802 path_dir = realpath(argv[0], NULL);
803 if (path_dir == NULL) {
804 error = got_error_from_errno2("realpath", argv[0]);
805 goto done;
807 got_path_strip_trailing_slashes(path_dir);
809 /*
810 * unveil(2) traverses exec(2); if an editor is used we have
811 * to apply unveil after the log message has been written.
812 */
813 if (logmsg == NULL || strlen(logmsg) == 0) {
814 error = get_editor(&editor);
815 if (error)
816 goto done;
817 free(logmsg);
818 error = collect_import_msg(&logmsg, &logmsg_path, editor,
819 path_dir, refname);
820 if (error) {
821 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
822 logmsg_path != NULL)
823 preserve_logmsg = 1;
824 goto done;
828 if (unveil(path_dir, "r") != 0) {
829 error = got_error_from_errno2("unveil", path_dir);
830 if (logmsg_path)
831 preserve_logmsg = 1;
832 goto done;
835 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
836 if (error) {
837 if (logmsg_path)
838 preserve_logmsg = 1;
839 goto done;
842 error = got_repo_import(&new_commit_id, path_dir, logmsg,
843 author, &ignores, repo, import_progress, NULL);
844 if (error) {
845 if (logmsg_path)
846 preserve_logmsg = 1;
847 goto done;
850 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
851 if (error) {
852 if (logmsg_path)
853 preserve_logmsg = 1;
854 goto done;
857 error = got_ref_write(branch_ref, repo);
858 if (error) {
859 if (logmsg_path)
860 preserve_logmsg = 1;
861 goto done;
864 error = got_object_id_str(&id_str, new_commit_id);
865 if (error) {
866 if (logmsg_path)
867 preserve_logmsg = 1;
868 goto done;
871 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
872 if (error) {
873 if (error->code != GOT_ERR_NOT_REF) {
874 if (logmsg_path)
875 preserve_logmsg = 1;
876 goto done;
879 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
880 branch_ref);
881 if (error) {
882 if (logmsg_path)
883 preserve_logmsg = 1;
884 goto done;
887 error = got_ref_write(head_ref, repo);
888 if (error) {
889 if (logmsg_path)
890 preserve_logmsg = 1;
891 goto done;
895 printf("Created branch %s with commit %s\n",
896 got_ref_get_name(branch_ref), id_str);
897 done:
898 if (preserve_logmsg) {
899 fprintf(stderr, "%s: log message preserved in %s\n",
900 getprogname(), logmsg_path);
901 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
902 error = got_error_from_errno2("unlink", logmsg_path);
903 free(logmsg);
904 free(logmsg_path);
905 free(repo_path);
906 free(editor);
907 free(refname);
908 free(new_commit_id);
909 free(id_str);
910 free(author);
911 free(gitconfig_path);
912 if (branch_ref)
913 got_ref_close(branch_ref);
914 if (head_ref)
915 got_ref_close(head_ref);
916 return error;
919 __dead static void
920 usage_clone(void)
922 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
923 "[-R reference] repository-url [directory]\n", getprogname());
924 exit(1);
927 struct got_fetch_progress_arg {
928 char last_scaled_size[FMT_SCALED_STRSIZE];
929 int last_p_indexed;
930 int last_p_resolved;
931 int verbosity;
933 struct got_repository *repo;
935 int create_configs;
936 int configs_created;
937 struct {
938 struct got_pathlist_head *symrefs;
939 struct got_pathlist_head *wanted_branches;
940 struct got_pathlist_head *wanted_refs;
941 const char *proto;
942 const char *host;
943 const char *port;
944 const char *remote_repo_path;
945 const char *git_url;
946 int fetch_all_branches;
947 int mirror_references;
948 } config_info;
949 };
951 /* XXX forward declaration */
952 static const struct got_error *
953 create_config_files(const char *proto, const char *host, const char *port,
954 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
955 int mirror_references, struct got_pathlist_head *symrefs,
956 struct got_pathlist_head *wanted_branches,
957 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
959 static const struct got_error *
960 fetch_progress(void *arg, const char *message, off_t packfile_size,
961 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
963 const struct got_error *err = NULL;
964 struct got_fetch_progress_arg *a = arg;
965 char scaled_size[FMT_SCALED_STRSIZE];
966 int p_indexed, p_resolved;
967 int print_size = 0, print_indexed = 0, print_resolved = 0;
969 /*
970 * In order to allow a failed clone to be resumed with 'got fetch'
971 * we try to create configuration files as soon as possible.
972 * Once the server has sent information about its default branch
973 * we have all required information.
974 */
975 if (a->create_configs && !a->configs_created &&
976 !TAILQ_EMPTY(a->config_info.symrefs)) {
977 err = create_config_files(a->config_info.proto,
978 a->config_info.host, a->config_info.port,
979 a->config_info.remote_repo_path,
980 a->config_info.git_url,
981 a->config_info.fetch_all_branches,
982 a->config_info.mirror_references,
983 a->config_info.symrefs,
984 a->config_info.wanted_branches,
985 a->config_info.wanted_refs, a->repo);
986 if (err)
987 return err;
988 a->configs_created = 1;
991 if (a->verbosity < 0)
992 return NULL;
994 if (message && message[0] != '\0') {
995 printf("\rserver: %s", message);
996 fflush(stdout);
997 return NULL;
1000 if (packfile_size > 0 || nobj_indexed > 0) {
1001 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1002 (a->last_scaled_size[0] == '\0' ||
1003 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1004 print_size = 1;
1005 if (strlcpy(a->last_scaled_size, scaled_size,
1006 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1007 return got_error(GOT_ERR_NO_SPACE);
1009 if (nobj_indexed > 0) {
1010 p_indexed = (nobj_indexed * 100) / nobj_total;
1011 if (p_indexed != a->last_p_indexed) {
1012 a->last_p_indexed = p_indexed;
1013 print_indexed = 1;
1014 print_size = 1;
1017 if (nobj_resolved > 0) {
1018 p_resolved = (nobj_resolved * 100) /
1019 (nobj_total - nobj_loose);
1020 if (p_resolved != a->last_p_resolved) {
1021 a->last_p_resolved = p_resolved;
1022 print_resolved = 1;
1023 print_indexed = 1;
1024 print_size = 1;
1029 if (print_size || print_indexed || print_resolved)
1030 printf("\r");
1031 if (print_size)
1032 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1033 if (print_indexed)
1034 printf("; indexing %d%%", p_indexed);
1035 if (print_resolved)
1036 printf("; resolving deltas %d%%", p_resolved);
1037 if (print_size || print_indexed || print_resolved)
1038 fflush(stdout);
1040 return NULL;
1043 static const struct got_error *
1044 create_symref(const char *refname, struct got_reference *target_ref,
1045 int verbosity, struct got_repository *repo)
1047 const struct got_error *err;
1048 struct got_reference *head_symref;
1050 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1051 if (err)
1052 return err;
1054 err = got_ref_write(head_symref, repo);
1055 if (err == NULL && verbosity > 0) {
1056 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1057 got_ref_get_name(target_ref));
1059 got_ref_close(head_symref);
1060 return err;
1063 static const struct got_error *
1064 list_remote_refs(struct got_pathlist_head *symrefs,
1065 struct got_pathlist_head *refs)
1067 const struct got_error *err;
1068 struct got_pathlist_entry *pe;
1070 TAILQ_FOREACH(pe, symrefs, entry) {
1071 const char *refname = pe->path;
1072 const char *targetref = pe->data;
1074 printf("%s: %s\n", refname, targetref);
1077 TAILQ_FOREACH(pe, refs, entry) {
1078 const char *refname = pe->path;
1079 struct got_object_id *id = pe->data;
1080 char *id_str;
1082 err = got_object_id_str(&id_str, id);
1083 if (err)
1084 return err;
1085 printf("%s: %s\n", refname, id_str);
1086 free(id_str);
1089 return NULL;
1092 static const struct got_error *
1093 create_ref(const char *refname, struct got_object_id *id,
1094 int verbosity, struct got_repository *repo)
1096 const struct got_error *err = NULL;
1097 struct got_reference *ref;
1098 char *id_str;
1100 err = got_object_id_str(&id_str, id);
1101 if (err)
1102 return err;
1104 err = got_ref_alloc(&ref, refname, id);
1105 if (err)
1106 goto done;
1108 err = got_ref_write(ref, repo);
1109 got_ref_close(ref);
1111 if (err == NULL && verbosity >= 0)
1112 printf("Created reference %s: %s\n", refname, id_str);
1113 done:
1114 free(id_str);
1115 return err;
1118 static int
1119 match_wanted_ref(const char *refname, const char *wanted_ref)
1121 if (strncmp(refname, "refs/", 5) != 0)
1122 return 0;
1123 refname += 5;
1126 * Prevent fetching of references that won't make any
1127 * sense outside of the remote repository's context.
1129 if (strncmp(refname, "got/", 4) == 0)
1130 return 0;
1131 if (strncmp(refname, "remotes/", 8) == 0)
1132 return 0;
1134 if (strncmp(wanted_ref, "refs/", 5) == 0)
1135 wanted_ref += 5;
1137 /* Allow prefix match. */
1138 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1139 return 1;
1141 /* Allow exact match. */
1142 return (strcmp(refname, wanted_ref) == 0);
1145 static int
1146 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1148 struct got_pathlist_entry *pe;
1150 TAILQ_FOREACH(pe, wanted_refs, entry) {
1151 if (match_wanted_ref(refname, pe->path))
1152 return 1;
1155 return 0;
1158 static const struct got_error *
1159 create_wanted_ref(const char *refname, struct got_object_id *id,
1160 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1162 const struct got_error *err;
1163 char *remote_refname;
1165 if (strncmp("refs/", refname, 5) == 0)
1166 refname += 5;
1168 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1169 remote_repo_name, refname) == -1)
1170 return got_error_from_errno("asprintf");
1172 err = create_ref(remote_refname, id, verbosity, repo);
1173 free(remote_refname);
1174 return err;
1177 static const struct got_error *
1178 create_gotconfig(const char *proto, const char *host, const char *port,
1179 const char *remote_repo_path, const char *default_branch,
1180 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1181 struct got_pathlist_head *wanted_refs, int mirror_references,
1182 struct got_repository *repo)
1184 const struct got_error *err = NULL;
1185 char *gotconfig_path = NULL;
1186 char *gotconfig = NULL;
1187 FILE *gotconfig_file = NULL;
1188 const char *branchname = NULL;
1189 char *branches = NULL, *refs = NULL;
1190 ssize_t n;
1192 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1193 struct got_pathlist_entry *pe;
1194 TAILQ_FOREACH(pe, wanted_branches, entry) {
1195 char *s;
1196 branchname = pe->path;
1197 if (strncmp(branchname, "refs/heads/", 11) == 0)
1198 branchname += 11;
1199 if (asprintf(&s, "%s\"%s\" ",
1200 branches ? branches : "", branchname) == -1) {
1201 err = got_error_from_errno("asprintf");
1202 goto done;
1204 free(branches);
1205 branches = s;
1207 } else if (!fetch_all_branches && default_branch) {
1208 branchname = default_branch;
1209 if (strncmp(branchname, "refs/heads/", 11) == 0)
1210 branchname += 11;
1211 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1212 err = got_error_from_errno("asprintf");
1213 goto done;
1216 if (!TAILQ_EMPTY(wanted_refs)) {
1217 struct got_pathlist_entry *pe;
1218 TAILQ_FOREACH(pe, wanted_refs, entry) {
1219 char *s;
1220 const char *refname = pe->path;
1221 if (strncmp(refname, "refs/", 5) == 0)
1222 branchname += 5;
1223 if (asprintf(&s, "%s\"%s\" ",
1224 refs ? refs : "", refname) == -1) {
1225 err = got_error_from_errno("asprintf");
1226 goto done;
1228 free(refs);
1229 refs = s;
1233 /* Create got.conf(5). */
1234 gotconfig_path = got_repo_get_path_gotconfig(repo);
1235 if (gotconfig_path == NULL) {
1236 err = got_error_from_errno("got_repo_get_path_gotconfig");
1237 goto done;
1239 gotconfig_file = fopen(gotconfig_path, "ae");
1240 if (gotconfig_file == NULL) {
1241 err = got_error_from_errno2("fopen", gotconfig_path);
1242 goto done;
1244 if (asprintf(&gotconfig,
1245 "remote \"%s\" {\n"
1246 "\tserver %s\n"
1247 "\tprotocol %s\n"
1248 "%s%s%s"
1249 "\trepository \"%s\"\n"
1250 "%s%s%s"
1251 "%s%s%s"
1252 "%s"
1253 "%s"
1254 "}\n",
1255 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1256 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1257 remote_repo_path, branches ? "\tbranch { " : "",
1258 branches ? branches : "", branches ? "}\n" : "",
1259 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1260 mirror_references ? "\tmirror-references yes\n" : "",
1261 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1262 err = got_error_from_errno("asprintf");
1263 goto done;
1265 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1266 if (n != strlen(gotconfig)) {
1267 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1268 goto done;
1271 done:
1272 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1273 err = got_error_from_errno2("fclose", gotconfig_path);
1274 free(gotconfig_path);
1275 free(branches);
1276 return err;
1279 static const struct got_error *
1280 create_gitconfig(const char *git_url, const char *default_branch,
1281 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1282 struct got_pathlist_head *wanted_refs, int mirror_references,
1283 struct got_repository *repo)
1285 const struct got_error *err = NULL;
1286 char *gitconfig_path = NULL;
1287 char *gitconfig = NULL;
1288 FILE *gitconfig_file = NULL;
1289 char *branches = NULL, *refs = NULL;
1290 const char *branchname;
1291 ssize_t n;
1293 /* Create a config file Git can understand. */
1294 gitconfig_path = got_repo_get_path_gitconfig(repo);
1295 if (gitconfig_path == NULL) {
1296 err = got_error_from_errno("got_repo_get_path_gitconfig");
1297 goto done;
1299 gitconfig_file = fopen(gitconfig_path, "ae");
1300 if (gitconfig_file == NULL) {
1301 err = got_error_from_errno2("fopen", gitconfig_path);
1302 goto done;
1304 if (fetch_all_branches) {
1305 if (mirror_references) {
1306 if (asprintf(&branches,
1307 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1308 err = got_error_from_errno("asprintf");
1309 goto done;
1311 } else if (asprintf(&branches,
1312 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1313 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1314 err = got_error_from_errno("asprintf");
1315 goto done;
1317 } else if (!TAILQ_EMPTY(wanted_branches)) {
1318 struct got_pathlist_entry *pe;
1319 TAILQ_FOREACH(pe, wanted_branches, entry) {
1320 char *s;
1321 branchname = pe->path;
1322 if (strncmp(branchname, "refs/heads/", 11) == 0)
1323 branchname += 11;
1324 if (mirror_references) {
1325 if (asprintf(&s,
1326 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1327 branches ? branches : "",
1328 branchname, branchname) == -1) {
1329 err = got_error_from_errno("asprintf");
1330 goto done;
1332 } else if (asprintf(&s,
1333 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1334 branches ? branches : "",
1335 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1336 branchname) == -1) {
1337 err = got_error_from_errno("asprintf");
1338 goto done;
1340 free(branches);
1341 branches = s;
1343 } else {
1345 * If the server specified a default branch, use just that one.
1346 * Otherwise fall back to fetching all branches on next fetch.
1348 if (default_branch) {
1349 branchname = default_branch;
1350 if (strncmp(branchname, "refs/heads/", 11) == 0)
1351 branchname += 11;
1352 } else
1353 branchname = "*"; /* fall back to all branches */
1354 if (mirror_references) {
1355 if (asprintf(&branches,
1356 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1357 branchname, branchname) == -1) {
1358 err = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (asprintf(&branches,
1362 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1363 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1364 branchname) == -1) {
1365 err = got_error_from_errno("asprintf");
1366 goto done;
1369 if (!TAILQ_EMPTY(wanted_refs)) {
1370 struct got_pathlist_entry *pe;
1371 TAILQ_FOREACH(pe, wanted_refs, entry) {
1372 char *s;
1373 const char *refname = pe->path;
1374 if (strncmp(refname, "refs/", 5) == 0)
1375 refname += 5;
1376 if (mirror_references) {
1377 if (asprintf(&s,
1378 "%s\tfetch = refs/%s:refs/%s\n",
1379 refs ? refs : "", refname, refname) == -1) {
1380 err = got_error_from_errno("asprintf");
1381 goto done;
1383 } else if (asprintf(&s,
1384 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1385 refs ? refs : "",
1386 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1387 refname) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 free(refs);
1392 refs = s;
1396 if (asprintf(&gitconfig,
1397 "[remote \"%s\"]\n"
1398 "\turl = %s\n"
1399 "%s"
1400 "%s"
1401 "\tfetch = refs/tags/*:refs/tags/*\n",
1402 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1403 refs ? refs : "") == -1) {
1404 err = got_error_from_errno("asprintf");
1405 goto done;
1407 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1408 if (n != strlen(gitconfig)) {
1409 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1410 goto done;
1412 done:
1413 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1414 err = got_error_from_errno2("fclose", gitconfig_path);
1415 free(gitconfig_path);
1416 free(branches);
1417 return err;
1420 static const struct got_error *
1421 create_config_files(const char *proto, const char *host, const char *port,
1422 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1423 int mirror_references, struct got_pathlist_head *symrefs,
1424 struct got_pathlist_head *wanted_branches,
1425 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1427 const struct got_error *err = NULL;
1428 const char *default_branch = NULL;
1429 struct got_pathlist_entry *pe;
1432 * If we asked for a set of wanted branches then use the first
1433 * one of those.
1435 if (!TAILQ_EMPTY(wanted_branches)) {
1436 pe = TAILQ_FIRST(wanted_branches);
1437 default_branch = pe->path;
1438 } else {
1439 /* First HEAD ref listed by server is the default branch. */
1440 TAILQ_FOREACH(pe, symrefs, entry) {
1441 const char *refname = pe->path;
1442 const char *target = pe->data;
1444 if (strcmp(refname, GOT_REF_HEAD) != 0)
1445 continue;
1447 default_branch = target;
1448 break;
1452 /* Create got.conf(5). */
1453 err = create_gotconfig(proto, host, port, remote_repo_path,
1454 default_branch, fetch_all_branches, wanted_branches,
1455 wanted_refs, mirror_references, repo);
1456 if (err)
1457 return err;
1459 /* Create a config file Git can understand. */
1460 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1461 wanted_branches, wanted_refs, mirror_references, repo);
1464 static const struct got_error *
1465 cmd_clone(int argc, char *argv[])
1467 const struct got_error *error = NULL;
1468 const char *uri, *dirname;
1469 char *proto, *host, *port, *repo_name, *server_path;
1470 char *default_destdir = NULL, *id_str = NULL;
1471 const char *repo_path;
1472 struct got_repository *repo = NULL;
1473 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1474 struct got_pathlist_entry *pe;
1475 struct got_object_id *pack_hash = NULL;
1476 int ch, fetchfd = -1, fetchstatus;
1477 pid_t fetchpid = -1;
1478 struct got_fetch_progress_arg fpa;
1479 char *git_url = NULL;
1480 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1481 int list_refs_only = 0;
1483 TAILQ_INIT(&refs);
1484 TAILQ_INIT(&symrefs);
1485 TAILQ_INIT(&wanted_branches);
1486 TAILQ_INIT(&wanted_refs);
1488 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1489 switch (ch) {
1490 case 'a':
1491 fetch_all_branches = 1;
1492 break;
1493 case 'b':
1494 error = got_pathlist_append(&wanted_branches,
1495 optarg, NULL);
1496 if (error)
1497 return error;
1498 break;
1499 case 'l':
1500 list_refs_only = 1;
1501 break;
1502 case 'm':
1503 mirror_references = 1;
1504 break;
1505 case 'v':
1506 if (verbosity < 0)
1507 verbosity = 0;
1508 else if (verbosity < 3)
1509 verbosity++;
1510 break;
1511 case 'q':
1512 verbosity = -1;
1513 break;
1514 case 'R':
1515 error = got_pathlist_append(&wanted_refs,
1516 optarg, NULL);
1517 if (error)
1518 return error;
1519 break;
1520 default:
1521 usage_clone();
1522 break;
1525 argc -= optind;
1526 argv += optind;
1528 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1529 option_conflict('a', 'b');
1530 if (list_refs_only) {
1531 if (!TAILQ_EMPTY(&wanted_branches))
1532 option_conflict('l', 'b');
1533 if (fetch_all_branches)
1534 option_conflict('l', 'a');
1535 if (mirror_references)
1536 option_conflict('l', 'm');
1537 if (!TAILQ_EMPTY(&wanted_refs))
1538 option_conflict('l', 'R');
1541 uri = argv[0];
1543 if (argc == 1)
1544 dirname = NULL;
1545 else if (argc == 2)
1546 dirname = argv[1];
1547 else
1548 usage_clone();
1550 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1551 &repo_name, uri);
1552 if (error)
1553 goto done;
1555 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1556 host, port ? ":" : "", port ? port : "",
1557 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1558 error = got_error_from_errno("asprintf");
1559 goto done;
1562 if (strcmp(proto, "git") == 0) {
1563 #ifndef PROFILE
1564 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1565 "sendfd dns inet unveil", NULL) == -1)
1566 err(1, "pledge");
1567 #endif
1568 } else if (strcmp(proto, "git+ssh") == 0 ||
1569 strcmp(proto, "ssh") == 0) {
1570 #ifndef PROFILE
1571 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1572 "sendfd unveil", NULL) == -1)
1573 err(1, "pledge");
1574 #endif
1575 } else if (strcmp(proto, "http") == 0 ||
1576 strcmp(proto, "git+http") == 0) {
1577 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1578 goto done;
1579 } else {
1580 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1581 goto done;
1583 if (dirname == NULL) {
1584 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1585 error = got_error_from_errno("asprintf");
1586 goto done;
1588 repo_path = default_destdir;
1589 } else
1590 repo_path = dirname;
1592 if (!list_refs_only) {
1593 error = got_path_mkdir(repo_path);
1594 if (error &&
1595 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1596 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1597 goto done;
1598 if (!got_path_dir_is_empty(repo_path)) {
1599 error = got_error_path(repo_path,
1600 GOT_ERR_DIR_NOT_EMPTY);
1601 goto done;
1605 error = got_dial_apply_unveil(proto);
1606 if (error)
1607 goto done;
1609 error = apply_unveil(repo_path, 0, NULL);
1610 if (error)
1611 goto done;
1613 if (verbosity >= 0)
1614 printf("Connecting to %s%s%s\n", host,
1615 port ? ":" : "", port ? port : "");
1617 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1618 server_path, verbosity);
1619 if (error)
1620 goto done;
1622 if (!list_refs_only) {
1623 error = got_repo_init(repo_path);
1624 if (error)
1625 goto done;
1626 error = got_repo_open(&repo, repo_path, NULL);
1627 if (error)
1628 goto done;
1631 fpa.last_scaled_size[0] = '\0';
1632 fpa.last_p_indexed = -1;
1633 fpa.last_p_resolved = -1;
1634 fpa.verbosity = verbosity;
1635 fpa.create_configs = 1;
1636 fpa.configs_created = 0;
1637 fpa.repo = repo;
1638 fpa.config_info.symrefs = &symrefs;
1639 fpa.config_info.wanted_branches = &wanted_branches;
1640 fpa.config_info.wanted_refs = &wanted_refs;
1641 fpa.config_info.proto = proto;
1642 fpa.config_info.host = host;
1643 fpa.config_info.port = port;
1644 fpa.config_info.remote_repo_path = server_path;
1645 fpa.config_info.git_url = git_url;
1646 fpa.config_info.fetch_all_branches = fetch_all_branches;
1647 fpa.config_info.mirror_references = mirror_references;
1648 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1649 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1650 fetch_all_branches, &wanted_branches, &wanted_refs,
1651 list_refs_only, verbosity, fetchfd, repo,
1652 fetch_progress, &fpa);
1653 if (error)
1654 goto done;
1656 if (list_refs_only) {
1657 error = list_remote_refs(&symrefs, &refs);
1658 goto done;
1661 if (pack_hash == NULL) {
1662 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1663 "server sent an empty pack file");
1664 goto done;
1666 error = got_object_id_str(&id_str, pack_hash);
1667 if (error)
1668 goto done;
1669 if (verbosity >= 0)
1670 printf("\nFetched %s.pack\n", id_str);
1671 free(id_str);
1673 /* Set up references provided with the pack file. */
1674 TAILQ_FOREACH(pe, &refs, entry) {
1675 const char *refname = pe->path;
1676 struct got_object_id *id = pe->data;
1677 char *remote_refname;
1679 if (is_wanted_ref(&wanted_refs, refname) &&
1680 !mirror_references) {
1681 error = create_wanted_ref(refname, id,
1682 GOT_FETCH_DEFAULT_REMOTE_NAME,
1683 verbosity - 1, repo);
1684 if (error)
1685 goto done;
1686 continue;
1689 error = create_ref(refname, id, verbosity - 1, repo);
1690 if (error)
1691 goto done;
1693 if (mirror_references)
1694 continue;
1696 if (strncmp("refs/heads/", refname, 11) != 0)
1697 continue;
1699 if (asprintf(&remote_refname,
1700 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1701 refname + 11) == -1) {
1702 error = got_error_from_errno("asprintf");
1703 goto done;
1705 error = create_ref(remote_refname, id, verbosity - 1, repo);
1706 free(remote_refname);
1707 if (error)
1708 goto done;
1711 /* Set the HEAD reference if the server provided one. */
1712 TAILQ_FOREACH(pe, &symrefs, entry) {
1713 struct got_reference *target_ref;
1714 const char *refname = pe->path;
1715 const char *target = pe->data;
1716 char *remote_refname = NULL, *remote_target = NULL;
1718 if (strcmp(refname, GOT_REF_HEAD) != 0)
1719 continue;
1721 error = got_ref_open(&target_ref, repo, target, 0);
1722 if (error) {
1723 if (error->code == GOT_ERR_NOT_REF) {
1724 error = NULL;
1725 continue;
1727 goto done;
1730 error = create_symref(refname, target_ref, verbosity, repo);
1731 got_ref_close(target_ref);
1732 if (error)
1733 goto done;
1735 if (mirror_references)
1736 continue;
1738 if (strncmp("refs/heads/", target, 11) != 0)
1739 continue;
1741 if (asprintf(&remote_refname,
1742 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1743 refname) == -1) {
1744 error = got_error_from_errno("asprintf");
1745 goto done;
1747 if (asprintf(&remote_target,
1748 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1749 target + 11) == -1) {
1750 error = got_error_from_errno("asprintf");
1751 free(remote_refname);
1752 goto done;
1754 error = got_ref_open(&target_ref, repo, remote_target, 0);
1755 if (error) {
1756 free(remote_refname);
1757 free(remote_target);
1758 if (error->code == GOT_ERR_NOT_REF) {
1759 error = NULL;
1760 continue;
1762 goto done;
1764 error = create_symref(remote_refname, target_ref,
1765 verbosity - 1, repo);
1766 free(remote_refname);
1767 free(remote_target);
1768 got_ref_close(target_ref);
1769 if (error)
1770 goto done;
1772 if (pe == NULL) {
1774 * We failed to set the HEAD reference. If we asked for
1775 * a set of wanted branches use the first of one of those
1776 * which could be fetched instead.
1778 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1779 const char *target = pe->path;
1780 struct got_reference *target_ref;
1782 error = got_ref_open(&target_ref, repo, target, 0);
1783 if (error) {
1784 if (error->code == GOT_ERR_NOT_REF) {
1785 error = NULL;
1786 continue;
1788 goto done;
1791 error = create_symref(GOT_REF_HEAD, target_ref,
1792 verbosity, repo);
1793 got_ref_close(target_ref);
1794 if (error)
1795 goto done;
1796 break;
1800 if (verbosity >= 0)
1801 printf("Created %s repository '%s'\n",
1802 mirror_references ? "mirrored" : "cloned", repo_path);
1803 done:
1804 if (fetchpid > 0) {
1805 if (kill(fetchpid, SIGTERM) == -1)
1806 error = got_error_from_errno("kill");
1807 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1808 error = got_error_from_errno("waitpid");
1810 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1811 error = got_error_from_errno("close");
1812 if (repo) {
1813 const struct got_error *close_err = got_repo_close(repo);
1814 if (error == NULL)
1815 error = close_err;
1817 TAILQ_FOREACH(pe, &refs, entry) {
1818 free((void *)pe->path);
1819 free(pe->data);
1821 got_pathlist_free(&refs);
1822 TAILQ_FOREACH(pe, &symrefs, entry) {
1823 free((void *)pe->path);
1824 free(pe->data);
1826 got_pathlist_free(&symrefs);
1827 got_pathlist_free(&wanted_branches);
1828 got_pathlist_free(&wanted_refs);
1829 free(pack_hash);
1830 free(proto);
1831 free(host);
1832 free(port);
1833 free(server_path);
1834 free(repo_name);
1835 free(default_destdir);
1836 free(git_url);
1837 return error;
1840 static const struct got_error *
1841 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1842 int replace_tags, int verbosity, struct got_repository *repo)
1844 const struct got_error *err = NULL;
1845 char *new_id_str = NULL;
1846 struct got_object_id *old_id = NULL;
1848 err = got_object_id_str(&new_id_str, new_id);
1849 if (err)
1850 goto done;
1852 if (!replace_tags &&
1853 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1854 err = got_ref_resolve(&old_id, repo, ref);
1855 if (err)
1856 goto done;
1857 if (got_object_id_cmp(old_id, new_id) == 0)
1858 goto done;
1859 if (verbosity >= 0) {
1860 printf("Rejecting update of existing tag %s: %s\n",
1861 got_ref_get_name(ref), new_id_str);
1863 goto done;
1866 if (got_ref_is_symbolic(ref)) {
1867 if (verbosity >= 0) {
1868 printf("Replacing reference %s: %s\n",
1869 got_ref_get_name(ref),
1870 got_ref_get_symref_target(ref));
1872 err = got_ref_change_symref_to_ref(ref, new_id);
1873 if (err)
1874 goto done;
1875 err = got_ref_write(ref, repo);
1876 if (err)
1877 goto done;
1878 } else {
1879 err = got_ref_resolve(&old_id, repo, ref);
1880 if (err)
1881 goto done;
1882 if (got_object_id_cmp(old_id, new_id) == 0)
1883 goto done;
1885 err = got_ref_change_ref(ref, new_id);
1886 if (err)
1887 goto done;
1888 err = got_ref_write(ref, repo);
1889 if (err)
1890 goto done;
1893 if (verbosity >= 0)
1894 printf("Updated %s: %s\n", got_ref_get_name(ref),
1895 new_id_str);
1896 done:
1897 free(old_id);
1898 free(new_id_str);
1899 return err;
1902 static const struct got_error *
1903 update_symref(const char *refname, struct got_reference *target_ref,
1904 int verbosity, struct got_repository *repo)
1906 const struct got_error *err = NULL, *unlock_err;
1907 struct got_reference *symref;
1908 int symref_is_locked = 0;
1910 err = got_ref_open(&symref, repo, refname, 1);
1911 if (err) {
1912 if (err->code != GOT_ERR_NOT_REF)
1913 return err;
1914 err = got_ref_alloc_symref(&symref, refname, target_ref);
1915 if (err)
1916 goto done;
1918 err = got_ref_write(symref, repo);
1919 if (err)
1920 goto done;
1922 if (verbosity >= 0)
1923 printf("Created reference %s: %s\n",
1924 got_ref_get_name(symref),
1925 got_ref_get_symref_target(symref));
1926 } else {
1927 symref_is_locked = 1;
1929 if (strcmp(got_ref_get_symref_target(symref),
1930 got_ref_get_name(target_ref)) == 0)
1931 goto done;
1933 err = got_ref_change_symref(symref,
1934 got_ref_get_name(target_ref));
1935 if (err)
1936 goto done;
1938 err = got_ref_write(symref, repo);
1939 if (err)
1940 goto done;
1942 if (verbosity >= 0)
1943 printf("Updated %s: %s\n", got_ref_get_name(symref),
1944 got_ref_get_symref_target(symref));
1947 done:
1948 if (symref_is_locked) {
1949 unlock_err = got_ref_unlock(symref);
1950 if (unlock_err && err == NULL)
1951 err = unlock_err;
1953 got_ref_close(symref);
1954 return err;
1957 __dead static void
1958 usage_fetch(void)
1960 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1961 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1962 "[remote-repository-name]\n",
1963 getprogname());
1964 exit(1);
1967 static const struct got_error *
1968 delete_missing_ref(struct got_reference *ref,
1969 int verbosity, struct got_repository *repo)
1971 const struct got_error *err = NULL;
1972 struct got_object_id *id = NULL;
1973 char *id_str = NULL;
1975 if (got_ref_is_symbolic(ref)) {
1976 err = got_ref_delete(ref, repo);
1977 if (err)
1978 return err;
1979 if (verbosity >= 0) {
1980 printf("Deleted %s: %s\n",
1981 got_ref_get_name(ref),
1982 got_ref_get_symref_target(ref));
1984 } else {
1985 err = got_ref_resolve(&id, repo, ref);
1986 if (err)
1987 return err;
1988 err = got_object_id_str(&id_str, id);
1989 if (err)
1990 goto done;
1992 err = got_ref_delete(ref, repo);
1993 if (err)
1994 goto done;
1995 if (verbosity >= 0) {
1996 printf("Deleted %s: %s\n",
1997 got_ref_get_name(ref), id_str);
2000 done:
2001 free(id);
2002 free(id_str);
2003 return NULL;
2006 static const struct got_error *
2007 delete_missing_refs(struct got_pathlist_head *their_refs,
2008 struct got_pathlist_head *their_symrefs,
2009 const struct got_remote_repo *remote,
2010 int verbosity, struct got_repository *repo)
2012 const struct got_error *err = NULL, *unlock_err;
2013 struct got_reflist_head my_refs;
2014 struct got_reflist_entry *re;
2015 struct got_pathlist_entry *pe;
2016 char *remote_namespace = NULL;
2017 char *local_refname = NULL;
2019 TAILQ_INIT(&my_refs);
2021 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2022 == -1)
2023 return got_error_from_errno("asprintf");
2025 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2026 if (err)
2027 goto done;
2029 TAILQ_FOREACH(re, &my_refs, entry) {
2030 const char *refname = got_ref_get_name(re->ref);
2031 const char *their_refname;
2033 if (remote->mirror_references) {
2034 their_refname = refname;
2035 } else {
2036 if (strncmp(refname, remote_namespace,
2037 strlen(remote_namespace)) == 0) {
2038 if (strcmp(refname + strlen(remote_namespace),
2039 GOT_REF_HEAD) == 0)
2040 continue;
2041 if (asprintf(&local_refname, "refs/heads/%s",
2042 refname + strlen(remote_namespace)) == -1) {
2043 err = got_error_from_errno("asprintf");
2044 goto done;
2046 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2047 continue;
2049 their_refname = local_refname;
2052 TAILQ_FOREACH(pe, their_refs, entry) {
2053 if (strcmp(their_refname, pe->path) == 0)
2054 break;
2056 if (pe != NULL)
2057 continue;
2059 TAILQ_FOREACH(pe, their_symrefs, entry) {
2060 if (strcmp(their_refname, pe->path) == 0)
2061 break;
2063 if (pe != NULL)
2064 continue;
2066 err = delete_missing_ref(re->ref, verbosity, repo);
2067 if (err)
2068 break;
2070 if (local_refname) {
2071 struct got_reference *ref;
2072 err = got_ref_open(&ref, repo, local_refname, 1);
2073 if (err) {
2074 if (err->code != GOT_ERR_NOT_REF)
2075 break;
2076 free(local_refname);
2077 local_refname = NULL;
2078 continue;
2080 err = delete_missing_ref(ref, verbosity, repo);
2081 if (err)
2082 break;
2083 unlock_err = got_ref_unlock(ref);
2084 got_ref_close(ref);
2085 if (unlock_err && err == NULL) {
2086 err = unlock_err;
2087 break;
2090 free(local_refname);
2091 local_refname = NULL;
2094 done:
2095 free(remote_namespace);
2096 free(local_refname);
2097 return err;
2100 static const struct got_error *
2101 update_wanted_ref(const char *refname, struct got_object_id *id,
2102 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2104 const struct got_error *err, *unlock_err;
2105 char *remote_refname;
2106 struct got_reference *ref;
2108 if (strncmp("refs/", refname, 5) == 0)
2109 refname += 5;
2111 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2112 remote_repo_name, refname) == -1)
2113 return got_error_from_errno("asprintf");
2115 err = got_ref_open(&ref, repo, remote_refname, 1);
2116 if (err) {
2117 if (err->code != GOT_ERR_NOT_REF)
2118 goto done;
2119 err = create_ref(remote_refname, id, verbosity, repo);
2120 } else {
2121 err = update_ref(ref, id, 0, verbosity, repo);
2122 unlock_err = got_ref_unlock(ref);
2123 if (unlock_err && err == NULL)
2124 err = unlock_err;
2125 got_ref_close(ref);
2127 done:
2128 free(remote_refname);
2129 return err;
2132 static const struct got_error *
2133 delete_ref(struct got_repository *repo, struct got_reference *ref)
2135 const struct got_error *err = NULL;
2136 struct got_object_id *id = NULL;
2137 char *id_str = NULL;
2138 const char *target;
2140 if (got_ref_is_symbolic(ref)) {
2141 target = got_ref_get_symref_target(ref);
2142 } else {
2143 err = got_ref_resolve(&id, repo, ref);
2144 if (err)
2145 goto done;
2146 err = got_object_id_str(&id_str, id);
2147 if (err)
2148 goto done;
2149 target = id_str;
2152 err = got_ref_delete(ref, repo);
2153 if (err)
2154 goto done;
2156 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2157 done:
2158 free(id);
2159 free(id_str);
2160 return err;
2163 static const struct got_error *
2164 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2166 const struct got_error *err = NULL;
2167 struct got_reflist_head refs;
2168 struct got_reflist_entry *re;
2169 char *prefix;
2171 TAILQ_INIT(&refs);
2173 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2174 err = got_error_from_errno("asprintf");
2175 goto done;
2177 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2178 if (err)
2179 goto done;
2181 TAILQ_FOREACH(re, &refs, entry)
2182 delete_ref(repo, re->ref);
2183 done:
2184 got_ref_list_free(&refs);
2185 return err;
2188 static const struct got_error *
2189 cmd_fetch(int argc, char *argv[])
2191 const struct got_error *error = NULL, *unlock_err;
2192 char *cwd = NULL, *repo_path = NULL;
2193 const char *remote_name;
2194 char *proto = NULL, *host = NULL, *port = NULL;
2195 char *repo_name = NULL, *server_path = NULL;
2196 const struct got_remote_repo *remotes, *remote = NULL;
2197 int nremotes;
2198 char *id_str = NULL;
2199 struct got_repository *repo = NULL;
2200 struct got_worktree *worktree = NULL;
2201 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2202 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2203 struct got_pathlist_entry *pe;
2204 struct got_object_id *pack_hash = NULL;
2205 int i, ch, fetchfd = -1, fetchstatus;
2206 pid_t fetchpid = -1;
2207 struct got_fetch_progress_arg fpa;
2208 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2209 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2211 TAILQ_INIT(&refs);
2212 TAILQ_INIT(&symrefs);
2213 TAILQ_INIT(&wanted_branches);
2214 TAILQ_INIT(&wanted_refs);
2216 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2217 switch (ch) {
2218 case 'a':
2219 fetch_all_branches = 1;
2220 break;
2221 case 'b':
2222 error = got_pathlist_append(&wanted_branches,
2223 optarg, NULL);
2224 if (error)
2225 return error;
2226 break;
2227 case 'd':
2228 delete_refs = 1;
2229 break;
2230 case 'l':
2231 list_refs_only = 1;
2232 break;
2233 case 'r':
2234 repo_path = realpath(optarg, NULL);
2235 if (repo_path == NULL)
2236 return got_error_from_errno2("realpath",
2237 optarg);
2238 got_path_strip_trailing_slashes(repo_path);
2239 break;
2240 case 't':
2241 replace_tags = 1;
2242 break;
2243 case 'v':
2244 if (verbosity < 0)
2245 verbosity = 0;
2246 else if (verbosity < 3)
2247 verbosity++;
2248 break;
2249 case 'q':
2250 verbosity = -1;
2251 break;
2252 case 'R':
2253 error = got_pathlist_append(&wanted_refs,
2254 optarg, NULL);
2255 if (error)
2256 return error;
2257 break;
2258 case 'X':
2259 delete_remote = 1;
2260 break;
2261 default:
2262 usage_fetch();
2263 break;
2266 argc -= optind;
2267 argv += optind;
2269 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2270 option_conflict('a', 'b');
2271 if (list_refs_only) {
2272 if (!TAILQ_EMPTY(&wanted_branches))
2273 option_conflict('l', 'b');
2274 if (fetch_all_branches)
2275 option_conflict('l', 'a');
2276 if (delete_refs)
2277 option_conflict('l', 'd');
2278 if (delete_remote)
2279 option_conflict('l', 'X');
2281 if (delete_remote) {
2282 if (fetch_all_branches)
2283 option_conflict('X', 'a');
2284 if (!TAILQ_EMPTY(&wanted_branches))
2285 option_conflict('X', 'b');
2286 if (delete_refs)
2287 option_conflict('X', 'd');
2288 if (replace_tags)
2289 option_conflict('X', 't');
2290 if (!TAILQ_EMPTY(&wanted_refs))
2291 option_conflict('X', 'R');
2294 if (argc == 0) {
2295 if (delete_remote)
2296 errx(1, "-X option requires a remote name");
2297 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2298 } else if (argc == 1)
2299 remote_name = argv[0];
2300 else
2301 usage_fetch();
2303 cwd = getcwd(NULL, 0);
2304 if (cwd == NULL) {
2305 error = got_error_from_errno("getcwd");
2306 goto done;
2309 if (repo_path == NULL) {
2310 error = got_worktree_open(&worktree, cwd);
2311 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2312 goto done;
2313 else
2314 error = NULL;
2315 if (worktree) {
2316 repo_path =
2317 strdup(got_worktree_get_repo_path(worktree));
2318 if (repo_path == NULL)
2319 error = got_error_from_errno("strdup");
2320 if (error)
2321 goto done;
2322 } else {
2323 repo_path = strdup(cwd);
2324 if (repo_path == NULL) {
2325 error = got_error_from_errno("strdup");
2326 goto done;
2331 error = got_repo_open(&repo, repo_path, NULL);
2332 if (error)
2333 goto done;
2335 if (delete_remote) {
2336 error = delete_refs_for_remote(repo, remote_name);
2337 goto done; /* nothing else to do */
2340 if (worktree) {
2341 worktree_conf = got_worktree_get_gotconfig(worktree);
2342 if (worktree_conf) {
2343 got_gotconfig_get_remotes(&nremotes, &remotes,
2344 worktree_conf);
2345 for (i = 0; i < nremotes; i++) {
2346 if (strcmp(remotes[i].name, remote_name) == 0) {
2347 remote = &remotes[i];
2348 break;
2353 if (remote == NULL) {
2354 repo_conf = got_repo_get_gotconfig(repo);
2355 if (repo_conf) {
2356 got_gotconfig_get_remotes(&nremotes, &remotes,
2357 repo_conf);
2358 for (i = 0; i < nremotes; i++) {
2359 if (strcmp(remotes[i].name, remote_name) == 0) {
2360 remote = &remotes[i];
2361 break;
2366 if (remote == NULL) {
2367 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2368 for (i = 0; i < nremotes; i++) {
2369 if (strcmp(remotes[i].name, remote_name) == 0) {
2370 remote = &remotes[i];
2371 break;
2375 if (remote == NULL) {
2376 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2377 goto done;
2380 if (TAILQ_EMPTY(&wanted_branches)) {
2381 if (!fetch_all_branches)
2382 fetch_all_branches = remote->fetch_all_branches;
2383 for (i = 0; i < remote->nfetch_branches; i++) {
2384 got_pathlist_append(&wanted_branches,
2385 remote->fetch_branches[i], NULL);
2388 if (TAILQ_EMPTY(&wanted_refs)) {
2389 for (i = 0; i < remote->nfetch_refs; i++) {
2390 got_pathlist_append(&wanted_refs,
2391 remote->fetch_refs[i], NULL);
2395 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2396 &repo_name, remote->fetch_url);
2397 if (error)
2398 goto done;
2400 if (strcmp(proto, "git") == 0) {
2401 #ifndef PROFILE
2402 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2403 "sendfd dns inet unveil", NULL) == -1)
2404 err(1, "pledge");
2405 #endif
2406 } else if (strcmp(proto, "git+ssh") == 0 ||
2407 strcmp(proto, "ssh") == 0) {
2408 #ifndef PROFILE
2409 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2410 "sendfd unveil", NULL) == -1)
2411 err(1, "pledge");
2412 #endif
2413 } else if (strcmp(proto, "http") == 0 ||
2414 strcmp(proto, "git+http") == 0) {
2415 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2416 goto done;
2417 } else {
2418 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2419 goto done;
2422 error = got_dial_apply_unveil(proto);
2423 if (error)
2424 goto done;
2426 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2427 if (error)
2428 goto done;
2430 if (verbosity >= 0)
2431 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2432 port ? ":" : "", port ? port : "");
2434 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2435 server_path, verbosity);
2436 if (error)
2437 goto done;
2439 fpa.last_scaled_size[0] = '\0';
2440 fpa.last_p_indexed = -1;
2441 fpa.last_p_resolved = -1;
2442 fpa.verbosity = verbosity;
2443 fpa.repo = repo;
2444 fpa.create_configs = 0;
2445 fpa.configs_created = 0;
2446 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2447 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2448 remote->mirror_references, fetch_all_branches, &wanted_branches,
2449 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2450 fetch_progress, &fpa);
2451 if (error)
2452 goto done;
2454 if (list_refs_only) {
2455 error = list_remote_refs(&symrefs, &refs);
2456 goto done;
2459 if (pack_hash == NULL) {
2460 if (verbosity >= 0)
2461 printf("Already up-to-date\n");
2462 } else if (verbosity >= 0) {
2463 error = got_object_id_str(&id_str, pack_hash);
2464 if (error)
2465 goto done;
2466 printf("\nFetched %s.pack\n", id_str);
2467 free(id_str);
2468 id_str = NULL;
2471 /* Update references provided with the pack file. */
2472 TAILQ_FOREACH(pe, &refs, entry) {
2473 const char *refname = pe->path;
2474 struct got_object_id *id = pe->data;
2475 struct got_reference *ref;
2476 char *remote_refname;
2478 if (is_wanted_ref(&wanted_refs, refname) &&
2479 !remote->mirror_references) {
2480 error = update_wanted_ref(refname, id,
2481 remote->name, verbosity, repo);
2482 if (error)
2483 goto done;
2484 continue;
2487 if (remote->mirror_references ||
2488 strncmp("refs/tags/", refname, 10) == 0) {
2489 error = got_ref_open(&ref, repo, refname, 1);
2490 if (error) {
2491 if (error->code != GOT_ERR_NOT_REF)
2492 goto done;
2493 error = create_ref(refname, id, verbosity,
2494 repo);
2495 if (error)
2496 goto done;
2497 } else {
2498 error = update_ref(ref, id, replace_tags,
2499 verbosity, repo);
2500 unlock_err = got_ref_unlock(ref);
2501 if (unlock_err && error == NULL)
2502 error = unlock_err;
2503 got_ref_close(ref);
2504 if (error)
2505 goto done;
2507 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2508 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2509 remote_name, refname + 11) == -1) {
2510 error = got_error_from_errno("asprintf");
2511 goto done;
2514 error = got_ref_open(&ref, repo, remote_refname, 1);
2515 if (error) {
2516 if (error->code != GOT_ERR_NOT_REF)
2517 goto done;
2518 error = create_ref(remote_refname, id,
2519 verbosity, repo);
2520 if (error)
2521 goto done;
2522 } else {
2523 error = update_ref(ref, id, replace_tags,
2524 verbosity, repo);
2525 unlock_err = got_ref_unlock(ref);
2526 if (unlock_err && error == NULL)
2527 error = unlock_err;
2528 got_ref_close(ref);
2529 if (error)
2530 goto done;
2533 /* Also create a local branch if none exists yet. */
2534 error = got_ref_open(&ref, repo, refname, 1);
2535 if (error) {
2536 if (error->code != GOT_ERR_NOT_REF)
2537 goto done;
2538 error = create_ref(refname, id, verbosity,
2539 repo);
2540 if (error)
2541 goto done;
2542 } else {
2543 unlock_err = got_ref_unlock(ref);
2544 if (unlock_err && error == NULL)
2545 error = unlock_err;
2546 got_ref_close(ref);
2550 if (delete_refs) {
2551 error = delete_missing_refs(&refs, &symrefs, remote,
2552 verbosity, repo);
2553 if (error)
2554 goto done;
2557 if (!remote->mirror_references) {
2558 /* Update remote HEAD reference if the server provided one. */
2559 TAILQ_FOREACH(pe, &symrefs, entry) {
2560 struct got_reference *target_ref;
2561 const char *refname = pe->path;
2562 const char *target = pe->data;
2563 char *remote_refname = NULL, *remote_target = NULL;
2565 if (strcmp(refname, GOT_REF_HEAD) != 0)
2566 continue;
2568 if (strncmp("refs/heads/", target, 11) != 0)
2569 continue;
2571 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2572 remote->name, refname) == -1) {
2573 error = got_error_from_errno("asprintf");
2574 goto done;
2576 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2577 remote->name, target + 11) == -1) {
2578 error = got_error_from_errno("asprintf");
2579 free(remote_refname);
2580 goto done;
2583 error = got_ref_open(&target_ref, repo, remote_target,
2584 0);
2585 if (error) {
2586 free(remote_refname);
2587 free(remote_target);
2588 if (error->code == GOT_ERR_NOT_REF) {
2589 error = NULL;
2590 continue;
2592 goto done;
2594 error = update_symref(remote_refname, target_ref,
2595 verbosity, repo);
2596 free(remote_refname);
2597 free(remote_target);
2598 got_ref_close(target_ref);
2599 if (error)
2600 goto done;
2603 done:
2604 if (fetchpid > 0) {
2605 if (kill(fetchpid, SIGTERM) == -1)
2606 error = got_error_from_errno("kill");
2607 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2608 error = got_error_from_errno("waitpid");
2610 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2611 error = got_error_from_errno("close");
2612 if (repo) {
2613 const struct got_error *close_err = got_repo_close(repo);
2614 if (error == NULL)
2615 error = close_err;
2617 if (worktree)
2618 got_worktree_close(worktree);
2619 TAILQ_FOREACH(pe, &refs, entry) {
2620 free((void *)pe->path);
2621 free(pe->data);
2623 got_pathlist_free(&refs);
2624 TAILQ_FOREACH(pe, &symrefs, entry) {
2625 free((void *)pe->path);
2626 free(pe->data);
2628 got_pathlist_free(&symrefs);
2629 got_pathlist_free(&wanted_branches);
2630 got_pathlist_free(&wanted_refs);
2631 free(id_str);
2632 free(cwd);
2633 free(repo_path);
2634 free(pack_hash);
2635 free(proto);
2636 free(host);
2637 free(port);
2638 free(server_path);
2639 free(repo_name);
2640 return error;
2644 __dead static void
2645 usage_checkout(void)
2647 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2648 "[-p prefix] [-q] repository-path [worktree-path]\n",
2649 getprogname());
2650 exit(1);
2653 static void
2654 show_worktree_base_ref_warning(void)
2656 fprintf(stderr, "%s: warning: could not create a reference "
2657 "to the work tree's base commit; the commit could be "
2658 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2659 "repository writable and running 'got update' will prevent this\n",
2660 getprogname());
2663 struct got_checkout_progress_arg {
2664 const char *worktree_path;
2665 int had_base_commit_ref_error;
2666 int verbosity;
2669 static const struct got_error *
2670 checkout_progress(void *arg, unsigned char status, const char *path)
2672 struct got_checkout_progress_arg *a = arg;
2674 /* Base commit bump happens silently. */
2675 if (status == GOT_STATUS_BUMP_BASE)
2676 return NULL;
2678 if (status == GOT_STATUS_BASE_REF_ERR) {
2679 a->had_base_commit_ref_error = 1;
2680 return NULL;
2683 while (path[0] == '/')
2684 path++;
2686 if (a->verbosity >= 0)
2687 printf("%c %s/%s\n", status, a->worktree_path, path);
2689 return NULL;
2692 static const struct got_error *
2693 check_cancelled(void *arg)
2695 if (sigint_received || sigpipe_received)
2696 return got_error(GOT_ERR_CANCELLED);
2697 return NULL;
2700 static const struct got_error *
2701 check_linear_ancestry(struct got_object_id *commit_id,
2702 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2703 struct got_repository *repo)
2705 const struct got_error *err = NULL;
2706 struct got_object_id *yca_id;
2708 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2709 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2710 if (err)
2711 return err;
2713 if (yca_id == NULL)
2714 return got_error(GOT_ERR_ANCESTRY);
2717 * Require a straight line of history between the target commit
2718 * and the work tree's base commit.
2720 * Non-linear situations such as this require a rebase:
2722 * (commit) D F (base_commit)
2723 * \ /
2724 * C E
2725 * \ /
2726 * B (yca)
2727 * |
2728 * A
2730 * 'got update' only handles linear cases:
2731 * Update forwards in time: A (base/yca) - B - C - D (commit)
2732 * Update backwards in time: D (base) - C - B - A (commit/yca)
2734 if (allow_forwards_in_time_only) {
2735 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2736 return got_error(GOT_ERR_ANCESTRY);
2737 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2738 got_object_id_cmp(base_commit_id, yca_id) != 0)
2739 return got_error(GOT_ERR_ANCESTRY);
2741 free(yca_id);
2742 return NULL;
2745 static const struct got_error *
2746 check_same_branch(struct got_object_id *commit_id,
2747 struct got_reference *head_ref, struct got_object_id *yca_id,
2748 struct got_repository *repo)
2750 const struct got_error *err = NULL;
2751 struct got_commit_graph *graph = NULL;
2752 struct got_object_id *head_commit_id = NULL;
2753 int is_same_branch = 0;
2755 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2756 if (err)
2757 goto done;
2759 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2760 is_same_branch = 1;
2761 goto done;
2763 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2764 is_same_branch = 1;
2765 goto done;
2768 err = got_commit_graph_open(&graph, "/", 1);
2769 if (err)
2770 goto done;
2772 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2773 check_cancelled, NULL);
2774 if (err)
2775 goto done;
2777 for (;;) {
2778 struct got_object_id *id;
2779 err = got_commit_graph_iter_next(&id, graph, repo,
2780 check_cancelled, NULL);
2781 if (err) {
2782 if (err->code == GOT_ERR_ITER_COMPLETED)
2783 err = NULL;
2784 break;
2787 if (id) {
2788 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2789 break;
2790 if (got_object_id_cmp(id, commit_id) == 0) {
2791 is_same_branch = 1;
2792 break;
2796 done:
2797 if (graph)
2798 got_commit_graph_close(graph);
2799 free(head_commit_id);
2800 if (!err && !is_same_branch)
2801 err = got_error(GOT_ERR_ANCESTRY);
2802 return err;
2805 static const struct got_error *
2806 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2808 static char msg[512];
2809 const char *branch_name;
2811 if (got_ref_is_symbolic(ref))
2812 branch_name = got_ref_get_symref_target(ref);
2813 else
2814 branch_name = got_ref_get_name(ref);
2816 if (strncmp("refs/heads/", branch_name, 11) == 0)
2817 branch_name += 11;
2819 snprintf(msg, sizeof(msg),
2820 "target commit is not contained in branch '%s'; "
2821 "the branch to use must be specified with -b; "
2822 "if necessary a new branch can be created for "
2823 "this commit with 'got branch -c %s BRANCH_NAME'",
2824 branch_name, commit_id_str);
2826 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2829 static const struct got_error *
2830 cmd_checkout(int argc, char *argv[])
2832 const struct got_error *error = NULL;
2833 struct got_repository *repo = NULL;
2834 struct got_reference *head_ref = NULL, *ref = NULL;
2835 struct got_worktree *worktree = NULL;
2836 char *repo_path = NULL;
2837 char *worktree_path = NULL;
2838 const char *path_prefix = "";
2839 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2840 char *commit_id_str = NULL;
2841 struct got_object_id *commit_id = NULL;
2842 char *cwd = NULL;
2843 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2844 struct got_pathlist_head paths;
2845 struct got_checkout_progress_arg cpa;
2847 TAILQ_INIT(&paths);
2849 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2850 switch (ch) {
2851 case 'b':
2852 branch_name = optarg;
2853 break;
2854 case 'c':
2855 commit_id_str = strdup(optarg);
2856 if (commit_id_str == NULL)
2857 return got_error_from_errno("strdup");
2858 break;
2859 case 'E':
2860 allow_nonempty = 1;
2861 break;
2862 case 'p':
2863 path_prefix = optarg;
2864 break;
2865 case 'q':
2866 verbosity = -1;
2867 break;
2868 default:
2869 usage_checkout();
2870 /* NOTREACHED */
2874 argc -= optind;
2875 argv += optind;
2877 #ifndef PROFILE
2878 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2879 "unveil", NULL) == -1)
2880 err(1, "pledge");
2881 #endif
2882 if (argc == 1) {
2883 char *base, *dotgit;
2884 const char *path;
2885 repo_path = realpath(argv[0], NULL);
2886 if (repo_path == NULL)
2887 return got_error_from_errno2("realpath", argv[0]);
2888 cwd = getcwd(NULL, 0);
2889 if (cwd == NULL) {
2890 error = got_error_from_errno("getcwd");
2891 goto done;
2893 if (path_prefix[0])
2894 path = path_prefix;
2895 else
2896 path = repo_path;
2897 error = got_path_basename(&base, path);
2898 if (error)
2899 goto done;
2900 dotgit = strstr(base, ".git");
2901 if (dotgit)
2902 *dotgit = '\0';
2903 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2904 error = got_error_from_errno("asprintf");
2905 free(base);
2906 goto done;
2908 free(base);
2909 } else if (argc == 2) {
2910 repo_path = realpath(argv[0], NULL);
2911 if (repo_path == NULL) {
2912 error = got_error_from_errno2("realpath", argv[0]);
2913 goto done;
2915 worktree_path = realpath(argv[1], NULL);
2916 if (worktree_path == NULL) {
2917 if (errno != ENOENT) {
2918 error = got_error_from_errno2("realpath",
2919 argv[1]);
2920 goto done;
2922 worktree_path = strdup(argv[1]);
2923 if (worktree_path == NULL) {
2924 error = got_error_from_errno("strdup");
2925 goto done;
2928 } else
2929 usage_checkout();
2931 got_path_strip_trailing_slashes(repo_path);
2932 got_path_strip_trailing_slashes(worktree_path);
2934 error = got_repo_open(&repo, repo_path, NULL);
2935 if (error != NULL)
2936 goto done;
2938 /* Pre-create work tree path for unveil(2) */
2939 error = got_path_mkdir(worktree_path);
2940 if (error) {
2941 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2942 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2943 goto done;
2944 if (!allow_nonempty &&
2945 !got_path_dir_is_empty(worktree_path)) {
2946 error = got_error_path(worktree_path,
2947 GOT_ERR_DIR_NOT_EMPTY);
2948 goto done;
2952 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2953 if (error)
2954 goto done;
2956 error = got_ref_open(&head_ref, repo, branch_name, 0);
2957 if (error != NULL)
2958 goto done;
2960 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2961 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2962 goto done;
2964 error = got_worktree_open(&worktree, worktree_path);
2965 if (error != NULL)
2966 goto done;
2968 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2969 path_prefix);
2970 if (error != NULL)
2971 goto done;
2972 if (!same_path_prefix) {
2973 error = got_error(GOT_ERR_PATH_PREFIX);
2974 goto done;
2977 if (commit_id_str) {
2978 struct got_reflist_head refs;
2979 TAILQ_INIT(&refs);
2980 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2981 NULL);
2982 if (error)
2983 goto done;
2984 error = got_repo_match_object_id(&commit_id, NULL,
2985 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2986 got_ref_list_free(&refs);
2987 if (error)
2988 goto done;
2989 error = check_linear_ancestry(commit_id,
2990 got_worktree_get_base_commit_id(worktree), 0, repo);
2991 if (error != NULL) {
2992 free(commit_id);
2993 if (error->code == GOT_ERR_ANCESTRY) {
2994 error = checkout_ancestry_error(
2995 head_ref, commit_id_str);
2997 goto done;
2999 error = check_same_branch(commit_id, head_ref, NULL, repo);
3000 if (error) {
3001 if (error->code == GOT_ERR_ANCESTRY) {
3002 error = checkout_ancestry_error(
3003 head_ref, commit_id_str);
3005 goto done;
3007 error = got_worktree_set_base_commit_id(worktree, repo,
3008 commit_id);
3009 if (error)
3010 goto done;
3011 /* Expand potentially abbreviated commit ID string. */
3012 free(commit_id_str);
3013 error = got_object_id_str(&commit_id_str, commit_id);
3014 if (error)
3015 goto done;
3016 } else {
3017 commit_id = got_object_id_dup(
3018 got_worktree_get_base_commit_id(worktree));
3019 if (commit_id == NULL) {
3020 error = got_error_from_errno("got_object_id_dup");
3021 goto done;
3023 error = got_object_id_str(&commit_id_str, commit_id);
3024 if (error)
3025 goto done;
3028 error = got_pathlist_append(&paths, "", NULL);
3029 if (error)
3030 goto done;
3031 cpa.worktree_path = worktree_path;
3032 cpa.had_base_commit_ref_error = 0;
3033 cpa.verbosity = verbosity;
3034 error = got_worktree_checkout_files(worktree, &paths, repo,
3035 checkout_progress, &cpa, check_cancelled, NULL);
3036 if (error != NULL)
3037 goto done;
3039 if (got_ref_is_symbolic(head_ref)) {
3040 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3041 if (error)
3042 goto done;
3043 refname = got_ref_get_name(ref);
3044 } else
3045 refname = got_ref_get_name(head_ref);
3046 printf("Checked out %s: %s\n", refname, commit_id_str);
3047 printf("Now shut up and hack\n");
3048 if (cpa.had_base_commit_ref_error)
3049 show_worktree_base_ref_warning();
3050 done:
3051 if (head_ref)
3052 got_ref_close(head_ref);
3053 if (ref)
3054 got_ref_close(ref);
3055 got_pathlist_free(&paths);
3056 free(commit_id_str);
3057 free(commit_id);
3058 free(repo_path);
3059 free(worktree_path);
3060 free(cwd);
3061 return error;
3064 struct got_update_progress_arg {
3065 int did_something;
3066 int conflicts;
3067 int obstructed;
3068 int not_updated;
3069 int missing;
3070 int not_deleted;
3071 int unversioned;
3072 int verbosity;
3075 void
3076 print_update_progress_stats(struct got_update_progress_arg *upa)
3078 if (!upa->did_something)
3079 return;
3081 if (upa->conflicts > 0)
3082 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3083 if (upa->obstructed > 0)
3084 printf("File paths obstructed by a non-regular file: %d\n",
3085 upa->obstructed);
3086 if (upa->not_updated > 0)
3087 printf("Files not updated because of existing merge "
3088 "conflicts: %d\n", upa->not_updated);
3092 * The meaning of some status codes differs between merge-style operations and
3093 * update operations. For example, the ! status code means "file was missing"
3094 * if changes were merged into the work tree, and "missing file was restored"
3095 * if the work tree was updated. This function should be used by any operation
3096 * which merges changes into the work tree without updating the work tree.
3098 void
3099 print_merge_progress_stats(struct got_update_progress_arg *upa)
3101 if (!upa->did_something)
3102 return;
3104 if (upa->conflicts > 0)
3105 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3106 if (upa->obstructed > 0)
3107 printf("File paths obstructed by a non-regular file: %d\n",
3108 upa->obstructed);
3109 if (upa->missing > 0)
3110 printf("Files which had incoming changes but could not be "
3111 "found in the work tree: %d\n", upa->missing);
3112 if (upa->not_deleted > 0)
3113 printf("Files not deleted due to differences in deleted "
3114 "content: %d\n", upa->not_deleted);
3115 if (upa->unversioned > 0)
3116 printf("Files not merged because an unversioned file was "
3117 "found in the work tree: %d\n", upa->unversioned);
3120 __dead static void
3121 usage_update(void)
3123 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3124 "[path ...]\n",
3125 getprogname());
3126 exit(1);
3129 static const struct got_error *
3130 update_progress(void *arg, unsigned char status, const char *path)
3132 struct got_update_progress_arg *upa = arg;
3134 if (status == GOT_STATUS_EXISTS ||
3135 status == GOT_STATUS_BASE_REF_ERR)
3136 return NULL;
3138 upa->did_something = 1;
3140 /* Base commit bump happens silently. */
3141 if (status == GOT_STATUS_BUMP_BASE)
3142 return NULL;
3144 if (status == GOT_STATUS_CONFLICT)
3145 upa->conflicts++;
3146 if (status == GOT_STATUS_OBSTRUCTED)
3147 upa->obstructed++;
3148 if (status == GOT_STATUS_CANNOT_UPDATE)
3149 upa->not_updated++;
3150 if (status == GOT_STATUS_MISSING)
3151 upa->missing++;
3152 if (status == GOT_STATUS_CANNOT_DELETE)
3153 upa->not_deleted++;
3154 if (status == GOT_STATUS_UNVERSIONED)
3155 upa->unversioned++;
3157 while (path[0] == '/')
3158 path++;
3159 if (upa->verbosity >= 0)
3160 printf("%c %s\n", status, path);
3162 return NULL;
3165 static const struct got_error *
3166 switch_head_ref(struct got_reference *head_ref,
3167 struct got_object_id *commit_id, struct got_worktree *worktree,
3168 struct got_repository *repo)
3170 const struct got_error *err = NULL;
3171 char *base_id_str;
3172 int ref_has_moved = 0;
3174 /* Trivial case: switching between two different references. */
3175 if (strcmp(got_ref_get_name(head_ref),
3176 got_worktree_get_head_ref_name(worktree)) != 0) {
3177 printf("Switching work tree from %s to %s\n",
3178 got_worktree_get_head_ref_name(worktree),
3179 got_ref_get_name(head_ref));
3180 return got_worktree_set_head_ref(worktree, head_ref);
3183 err = check_linear_ancestry(commit_id,
3184 got_worktree_get_base_commit_id(worktree), 0, repo);
3185 if (err) {
3186 if (err->code != GOT_ERR_ANCESTRY)
3187 return err;
3188 ref_has_moved = 1;
3190 if (!ref_has_moved)
3191 return NULL;
3193 /* Switching to a rebased branch with the same reference name. */
3194 err = got_object_id_str(&base_id_str,
3195 got_worktree_get_base_commit_id(worktree));
3196 if (err)
3197 return err;
3198 printf("Reference %s now points at a different branch\n",
3199 got_worktree_get_head_ref_name(worktree));
3200 printf("Switching work tree from %s to %s\n", base_id_str,
3201 got_worktree_get_head_ref_name(worktree));
3202 return NULL;
3205 static const struct got_error *
3206 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3208 const struct got_error *err;
3209 int in_progress;
3211 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3212 if (err)
3213 return err;
3214 if (in_progress)
3215 return got_error(GOT_ERR_REBASING);
3217 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3218 if (err)
3219 return err;
3220 if (in_progress)
3221 return got_error(GOT_ERR_HISTEDIT_BUSY);
3223 return NULL;
3226 static const struct got_error *
3227 check_merge_in_progress(struct got_worktree *worktree,
3228 struct got_repository *repo)
3230 const struct got_error *err;
3231 int in_progress;
3233 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3234 if (err)
3235 return err;
3236 if (in_progress)
3237 return got_error(GOT_ERR_MERGE_BUSY);
3239 return NULL;
3242 static const struct got_error *
3243 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3244 char *argv[], struct got_worktree *worktree)
3246 const struct got_error *err = NULL;
3247 char *path;
3248 struct got_pathlist_entry *new;
3249 int i;
3251 if (argc == 0) {
3252 path = strdup("");
3253 if (path == NULL)
3254 return got_error_from_errno("strdup");
3255 return got_pathlist_append(paths, path, NULL);
3258 for (i = 0; i < argc; i++) {
3259 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3260 if (err)
3261 break;
3262 err = got_pathlist_insert(&new, paths, path, NULL);
3263 if (err || new == NULL /* duplicate */) {
3264 free(path);
3265 if (err)
3266 break;
3270 return err;
3273 static const struct got_error *
3274 wrap_not_worktree_error(const struct got_error *orig_err,
3275 const char *cmdname, const char *path)
3277 const struct got_error *err;
3278 struct got_repository *repo;
3279 static char msg[512];
3281 err = got_repo_open(&repo, path, NULL);
3282 if (err)
3283 return orig_err;
3285 snprintf(msg, sizeof(msg),
3286 "'got %s' needs a work tree in addition to a git repository\n"
3287 "Work trees can be checked out from this Git repository with "
3288 "'got checkout'.\n"
3289 "The got(1) manual page contains more information.", cmdname);
3290 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3291 got_repo_close(repo);
3292 return err;
3295 static const struct got_error *
3296 cmd_update(int argc, char *argv[])
3298 const struct got_error *error = NULL;
3299 struct got_repository *repo = NULL;
3300 struct got_worktree *worktree = NULL;
3301 char *worktree_path = NULL;
3302 struct got_object_id *commit_id = NULL;
3303 char *commit_id_str = NULL;
3304 const char *branch_name = NULL;
3305 struct got_reference *head_ref = NULL;
3306 struct got_pathlist_head paths;
3307 struct got_pathlist_entry *pe;
3308 int ch, verbosity = 0;
3309 struct got_update_progress_arg upa;
3311 TAILQ_INIT(&paths);
3313 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3314 switch (ch) {
3315 case 'b':
3316 branch_name = optarg;
3317 break;
3318 case 'c':
3319 commit_id_str = strdup(optarg);
3320 if (commit_id_str == NULL)
3321 return got_error_from_errno("strdup");
3322 break;
3323 case 'q':
3324 verbosity = -1;
3325 break;
3326 default:
3327 usage_update();
3328 /* NOTREACHED */
3332 argc -= optind;
3333 argv += optind;
3335 #ifndef PROFILE
3336 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3337 "unveil", NULL) == -1)
3338 err(1, "pledge");
3339 #endif
3340 worktree_path = getcwd(NULL, 0);
3341 if (worktree_path == NULL) {
3342 error = got_error_from_errno("getcwd");
3343 goto done;
3345 error = got_worktree_open(&worktree, worktree_path);
3346 if (error) {
3347 if (error->code == GOT_ERR_NOT_WORKTREE)
3348 error = wrap_not_worktree_error(error, "update",
3349 worktree_path);
3350 goto done;
3353 error = check_rebase_or_histedit_in_progress(worktree);
3354 if (error)
3355 goto done;
3357 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3358 NULL);
3359 if (error != NULL)
3360 goto done;
3362 error = apply_unveil(got_repo_get_path(repo), 0,
3363 got_worktree_get_root_path(worktree));
3364 if (error)
3365 goto done;
3367 error = check_merge_in_progress(worktree, repo);
3368 if (error)
3369 goto done;
3371 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3372 if (error)
3373 goto done;
3375 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3376 got_worktree_get_head_ref_name(worktree), 0);
3377 if (error != NULL)
3378 goto done;
3379 if (commit_id_str == NULL) {
3380 error = got_ref_resolve(&commit_id, repo, head_ref);
3381 if (error != NULL)
3382 goto done;
3383 error = got_object_id_str(&commit_id_str, commit_id);
3384 if (error != NULL)
3385 goto done;
3386 } else {
3387 struct got_reflist_head refs;
3388 TAILQ_INIT(&refs);
3389 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3390 NULL);
3391 if (error)
3392 goto done;
3393 error = got_repo_match_object_id(&commit_id, NULL,
3394 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3395 got_ref_list_free(&refs);
3396 free(commit_id_str);
3397 commit_id_str = NULL;
3398 if (error)
3399 goto done;
3400 error = got_object_id_str(&commit_id_str, commit_id);
3401 if (error)
3402 goto done;
3405 if (branch_name) {
3406 struct got_object_id *head_commit_id;
3407 TAILQ_FOREACH(pe, &paths, entry) {
3408 if (pe->path_len == 0)
3409 continue;
3410 error = got_error_msg(GOT_ERR_BAD_PATH,
3411 "switching between branches requires that "
3412 "the entire work tree gets updated");
3413 goto done;
3415 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3416 if (error)
3417 goto done;
3418 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3419 repo);
3420 free(head_commit_id);
3421 if (error != NULL)
3422 goto done;
3423 error = check_same_branch(commit_id, head_ref, NULL, repo);
3424 if (error)
3425 goto done;
3426 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3427 if (error)
3428 goto done;
3429 } else {
3430 error = check_linear_ancestry(commit_id,
3431 got_worktree_get_base_commit_id(worktree), 0, repo);
3432 if (error != NULL) {
3433 if (error->code == GOT_ERR_ANCESTRY)
3434 error = got_error(GOT_ERR_BRANCH_MOVED);
3435 goto done;
3437 error = check_same_branch(commit_id, head_ref, NULL, repo);
3438 if (error)
3439 goto done;
3442 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3443 commit_id) != 0) {
3444 error = got_worktree_set_base_commit_id(worktree, repo,
3445 commit_id);
3446 if (error)
3447 goto done;
3450 memset(&upa, 0, sizeof(upa));
3451 upa.verbosity = verbosity;
3452 error = got_worktree_checkout_files(worktree, &paths, repo,
3453 update_progress, &upa, check_cancelled, NULL);
3454 if (error != NULL)
3455 goto done;
3457 if (upa.did_something) {
3458 printf("Updated to %s: %s\n",
3459 got_worktree_get_head_ref_name(worktree), commit_id_str);
3460 } else
3461 printf("Already up-to-date\n");
3462 print_update_progress_stats(&upa);
3463 done:
3464 free(worktree_path);
3465 TAILQ_FOREACH(pe, &paths, entry)
3466 free((char *)pe->path);
3467 got_pathlist_free(&paths);
3468 free(commit_id);
3469 free(commit_id_str);
3470 return error;
3473 static const struct got_error *
3474 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3475 const char *path, int diff_context, int ignore_whitespace,
3476 int force_text_diff, struct got_repository *repo)
3478 const struct got_error *err = NULL;
3479 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3481 if (blob_id1) {
3482 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3483 if (err)
3484 goto done;
3487 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3488 if (err)
3489 goto done;
3491 while (path[0] == '/')
3492 path++;
3493 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3494 diff_context, ignore_whitespace, force_text_diff, stdout);
3495 done:
3496 if (blob1)
3497 got_object_blob_close(blob1);
3498 got_object_blob_close(blob2);
3499 return err;
3502 static const struct got_error *
3503 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3504 const char *path, int diff_context, int ignore_whitespace,
3505 int force_text_diff, struct got_repository *repo)
3507 const struct got_error *err = NULL;
3508 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3509 struct got_diff_blob_output_unidiff_arg arg;
3511 if (tree_id1) {
3512 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3513 if (err)
3514 goto done;
3517 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3518 if (err)
3519 goto done;
3521 arg.diff_context = diff_context;
3522 arg.ignore_whitespace = ignore_whitespace;
3523 arg.force_text_diff = force_text_diff;
3524 arg.outfile = stdout;
3525 arg.line_offsets = NULL;
3526 arg.nlines = 0;
3527 while (path[0] == '/')
3528 path++;
3529 err = got_diff_tree(tree1, tree2, path, path, repo,
3530 got_diff_blob_output_unidiff, &arg, 1);
3531 done:
3532 if (tree1)
3533 got_object_tree_close(tree1);
3534 if (tree2)
3535 got_object_tree_close(tree2);
3536 return err;
3539 static const struct got_error *
3540 get_changed_paths(struct got_pathlist_head *paths,
3541 struct got_commit_object *commit, struct got_repository *repo)
3543 const struct got_error *err = NULL;
3544 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3545 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3546 struct got_object_qid *qid;
3548 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3549 if (qid != NULL) {
3550 struct got_commit_object *pcommit;
3551 err = got_object_open_as_commit(&pcommit, repo,
3552 qid->id);
3553 if (err)
3554 return err;
3556 tree_id1 = got_object_id_dup(
3557 got_object_commit_get_tree_id(pcommit));
3558 if (tree_id1 == NULL) {
3559 got_object_commit_close(pcommit);
3560 return got_error_from_errno("got_object_id_dup");
3562 got_object_commit_close(pcommit);
3566 if (tree_id1) {
3567 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3568 if (err)
3569 goto done;
3572 tree_id2 = got_object_commit_get_tree_id(commit);
3573 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3574 if (err)
3575 goto done;
3577 err = got_diff_tree(tree1, tree2, "", "", repo,
3578 got_diff_tree_collect_changed_paths, paths, 0);
3579 done:
3580 if (tree1)
3581 got_object_tree_close(tree1);
3582 if (tree2)
3583 got_object_tree_close(tree2);
3584 free(tree_id1);
3585 return err;
3588 static const struct got_error *
3589 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3590 const char *path, int diff_context, struct got_repository *repo)
3592 const struct got_error *err = NULL;
3593 struct got_commit_object *pcommit = NULL;
3594 char *id_str1 = NULL, *id_str2 = NULL;
3595 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3596 struct got_object_qid *qid;
3598 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3599 if (qid != NULL) {
3600 err = got_object_open_as_commit(&pcommit, repo,
3601 qid->id);
3602 if (err)
3603 return err;
3606 if (path && path[0] != '\0') {
3607 int obj_type;
3608 err = got_object_id_by_path(&obj_id2, repo, id, path);
3609 if (err)
3610 goto done;
3611 err = got_object_id_str(&id_str2, obj_id2);
3612 if (err) {
3613 free(obj_id2);
3614 goto done;
3616 if (pcommit) {
3617 err = got_object_id_by_path(&obj_id1, repo,
3618 qid->id, path);
3619 if (err) {
3620 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3621 free(obj_id2);
3622 goto done;
3624 } else {
3625 err = got_object_id_str(&id_str1, obj_id1);
3626 if (err) {
3627 free(obj_id2);
3628 goto done;
3632 err = got_object_get_type(&obj_type, repo, obj_id2);
3633 if (err) {
3634 free(obj_id2);
3635 goto done;
3637 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3638 switch (obj_type) {
3639 case GOT_OBJ_TYPE_BLOB:
3640 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3641 0, 0, repo);
3642 break;
3643 case GOT_OBJ_TYPE_TREE:
3644 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3645 0, 0, repo);
3646 break;
3647 default:
3648 err = got_error(GOT_ERR_OBJ_TYPE);
3649 break;
3651 free(obj_id1);
3652 free(obj_id2);
3653 } else {
3654 obj_id2 = got_object_commit_get_tree_id(commit);
3655 err = got_object_id_str(&id_str2, obj_id2);
3656 if (err)
3657 goto done;
3658 if (pcommit) {
3659 obj_id1 = got_object_commit_get_tree_id(pcommit);
3660 err = got_object_id_str(&id_str1, obj_id1);
3661 if (err)
3662 goto done;
3664 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3665 id_str2);
3666 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3667 repo);
3669 done:
3670 free(id_str1);
3671 free(id_str2);
3672 if (pcommit)
3673 got_object_commit_close(pcommit);
3674 return err;
3677 static char *
3678 get_datestr(time_t *time, char *datebuf)
3680 struct tm mytm, *tm;
3681 char *p, *s;
3683 tm = gmtime_r(time, &mytm);
3684 if (tm == NULL)
3685 return NULL;
3686 s = asctime_r(tm, datebuf);
3687 if (s == NULL)
3688 return NULL;
3689 p = strchr(s, '\n');
3690 if (p)
3691 *p = '\0';
3692 return s;
3695 static const struct got_error *
3696 match_logmsg(int *have_match, struct got_object_id *id,
3697 struct got_commit_object *commit, regex_t *regex)
3699 const struct got_error *err = NULL;
3700 regmatch_t regmatch;
3701 char *id_str = NULL, *logmsg = NULL;
3703 *have_match = 0;
3705 err = got_object_id_str(&id_str, id);
3706 if (err)
3707 return err;
3709 err = got_object_commit_get_logmsg(&logmsg, commit);
3710 if (err)
3711 goto done;
3713 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3714 *have_match = 1;
3715 done:
3716 free(id_str);
3717 free(logmsg);
3718 return err;
3721 static void
3722 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3723 regex_t *regex)
3725 regmatch_t regmatch;
3726 struct got_pathlist_entry *pe;
3728 *have_match = 0;
3730 TAILQ_FOREACH(pe, changed_paths, entry) {
3731 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3732 *have_match = 1;
3733 break;
3738 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3740 static const struct got_error*
3741 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3742 struct got_object_id *id, struct got_repository *repo)
3744 static const struct got_error *err = NULL;
3745 struct got_reflist_entry *re;
3746 char *s;
3747 const char *name;
3749 *refs_str = NULL;
3751 TAILQ_FOREACH(re, refs, entry) {
3752 struct got_tag_object *tag = NULL;
3753 struct got_object_id *ref_id;
3754 int cmp;
3756 name = got_ref_get_name(re->ref);
3757 if (strcmp(name, GOT_REF_HEAD) == 0)
3758 continue;
3759 if (strncmp(name, "refs/", 5) == 0)
3760 name += 5;
3761 if (strncmp(name, "got/", 4) == 0)
3762 continue;
3763 if (strncmp(name, "heads/", 6) == 0)
3764 name += 6;
3765 if (strncmp(name, "remotes/", 8) == 0) {
3766 name += 8;
3767 s = strstr(name, "/" GOT_REF_HEAD);
3768 if (s != NULL && s[strlen(s)] == '\0')
3769 continue;
3771 err = got_ref_resolve(&ref_id, repo, re->ref);
3772 if (err)
3773 break;
3774 if (strncmp(name, "tags/", 5) == 0) {
3775 err = got_object_open_as_tag(&tag, repo, ref_id);
3776 if (err) {
3777 if (err->code != GOT_ERR_OBJ_TYPE) {
3778 free(ref_id);
3779 break;
3781 /* Ref points at something other than a tag. */
3782 err = NULL;
3783 tag = NULL;
3786 cmp = got_object_id_cmp(tag ?
3787 got_object_tag_get_object_id(tag) : ref_id, id);
3788 free(ref_id);
3789 if (tag)
3790 got_object_tag_close(tag);
3791 if (cmp != 0)
3792 continue;
3793 s = *refs_str;
3794 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3795 s ? ", " : "", name) == -1) {
3796 err = got_error_from_errno("asprintf");
3797 free(s);
3798 *refs_str = NULL;
3799 break;
3801 free(s);
3804 return err;
3807 static const struct got_error *
3808 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3809 struct got_repository *repo, const char *path,
3810 struct got_pathlist_head *changed_paths, int show_patch,
3811 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3812 const char *custom_refs_str)
3814 const struct got_error *err = NULL;
3815 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3816 char datebuf[26];
3817 time_t committer_time;
3818 const char *author, *committer;
3819 char *refs_str = NULL;
3821 err = got_object_id_str(&id_str, id);
3822 if (err)
3823 return err;
3825 if (custom_refs_str == NULL) {
3826 struct got_reflist_head *refs;
3827 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3828 if (refs) {
3829 err = build_refs_str(&refs_str, refs, id, repo);
3830 if (err)
3831 goto done;
3835 printf(GOT_COMMIT_SEP_STR);
3836 if (custom_refs_str)
3837 printf("commit %s (%s)\n", id_str, custom_refs_str);
3838 else
3839 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3840 refs_str ? refs_str : "", refs_str ? ")" : "");
3841 free(id_str);
3842 id_str = NULL;
3843 free(refs_str);
3844 refs_str = NULL;
3845 printf("from: %s\n", got_object_commit_get_author(commit));
3846 committer_time = got_object_commit_get_committer_time(commit);
3847 datestr = get_datestr(&committer_time, datebuf);
3848 if (datestr)
3849 printf("date: %s UTC\n", datestr);
3850 author = got_object_commit_get_author(commit);
3851 committer = got_object_commit_get_committer(commit);
3852 if (strcmp(author, committer) != 0)
3853 printf("via: %s\n", committer);
3854 if (got_object_commit_get_nparents(commit) > 1) {
3855 const struct got_object_id_queue *parent_ids;
3856 struct got_object_qid *qid;
3857 int n = 1;
3858 parent_ids = got_object_commit_get_parent_ids(commit);
3859 STAILQ_FOREACH(qid, parent_ids, entry) {
3860 err = got_object_id_str(&id_str, qid->id);
3861 if (err)
3862 goto done;
3863 printf("parent %d: %s\n", n++, id_str);
3864 free(id_str);
3865 id_str = NULL;
3869 err = got_object_commit_get_logmsg(&logmsg0, commit);
3870 if (err)
3871 goto done;
3873 logmsg = logmsg0;
3874 do {
3875 line = strsep(&logmsg, "\n");
3876 if (line)
3877 printf(" %s\n", line);
3878 } while (line);
3879 free(logmsg0);
3881 if (changed_paths) {
3882 struct got_pathlist_entry *pe;
3883 TAILQ_FOREACH(pe, changed_paths, entry) {
3884 struct got_diff_changed_path *cp = pe->data;
3885 printf(" %c %s\n", cp->status, pe->path);
3887 printf("\n");
3889 if (show_patch) {
3890 err = print_patch(commit, id, path, diff_context, repo);
3891 if (err == 0)
3892 printf("\n");
3895 if (fflush(stdout) != 0 && err == NULL)
3896 err = got_error_from_errno("fflush");
3897 done:
3898 free(id_str);
3899 free(refs_str);
3900 return err;
3903 static const struct got_error *
3904 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3905 struct got_repository *repo, const char *path, int show_changed_paths,
3906 int show_patch, const char *search_pattern, int diff_context, int limit,
3907 int log_branches, int reverse_display_order,
3908 struct got_reflist_object_id_map *refs_idmap)
3910 const struct got_error *err;
3911 struct got_commit_graph *graph;
3912 regex_t regex;
3913 int have_match;
3914 struct got_object_id_queue reversed_commits;
3915 struct got_object_qid *qid;
3916 struct got_commit_object *commit;
3917 struct got_pathlist_head changed_paths;
3918 struct got_pathlist_entry *pe;
3920 STAILQ_INIT(&reversed_commits);
3921 TAILQ_INIT(&changed_paths);
3923 if (search_pattern && regcomp(&regex, search_pattern,
3924 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3925 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3927 err = got_commit_graph_open(&graph, path, !log_branches);
3928 if (err)
3929 return err;
3930 err = got_commit_graph_iter_start(graph, root_id, repo,
3931 check_cancelled, NULL);
3932 if (err)
3933 goto done;
3934 for (;;) {
3935 struct got_object_id *id;
3937 if (sigint_received || sigpipe_received)
3938 break;
3940 err = got_commit_graph_iter_next(&id, graph, repo,
3941 check_cancelled, NULL);
3942 if (err) {
3943 if (err->code == GOT_ERR_ITER_COMPLETED)
3944 err = NULL;
3945 break;
3947 if (id == NULL)
3948 break;
3950 err = got_object_open_as_commit(&commit, repo, id);
3951 if (err)
3952 break;
3954 if (show_changed_paths && !reverse_display_order) {
3955 err = get_changed_paths(&changed_paths, commit, repo);
3956 if (err)
3957 break;
3960 if (search_pattern) {
3961 err = match_logmsg(&have_match, id, commit, &regex);
3962 if (err) {
3963 got_object_commit_close(commit);
3964 break;
3966 if (have_match == 0 && show_changed_paths)
3967 match_changed_paths(&have_match,
3968 &changed_paths, &regex);
3969 if (have_match == 0) {
3970 got_object_commit_close(commit);
3971 TAILQ_FOREACH(pe, &changed_paths, entry) {
3972 free((char *)pe->path);
3973 free(pe->data);
3975 got_pathlist_free(&changed_paths);
3976 continue;
3980 if (reverse_display_order) {
3981 err = got_object_qid_alloc(&qid, id);
3982 if (err)
3983 break;
3984 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3985 got_object_commit_close(commit);
3986 } else {
3987 err = print_commit(commit, id, repo, path,
3988 show_changed_paths ? &changed_paths : NULL,
3989 show_patch, diff_context, refs_idmap, NULL);
3990 got_object_commit_close(commit);
3991 if (err)
3992 break;
3994 if ((limit && --limit == 0) ||
3995 (end_id && got_object_id_cmp(id, end_id) == 0))
3996 break;
3998 TAILQ_FOREACH(pe, &changed_paths, entry) {
3999 free((char *)pe->path);
4000 free(pe->data);
4002 got_pathlist_free(&changed_paths);
4004 if (reverse_display_order) {
4005 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4006 err = got_object_open_as_commit(&commit, repo, qid->id);
4007 if (err)
4008 break;
4009 if (show_changed_paths) {
4010 err = get_changed_paths(&changed_paths,
4011 commit, repo);
4012 if (err)
4013 break;
4015 err = print_commit(commit, qid->id, repo, path,
4016 show_changed_paths ? &changed_paths : NULL,
4017 show_patch, diff_context, refs_idmap, NULL);
4018 got_object_commit_close(commit);
4019 if (err)
4020 break;
4021 TAILQ_FOREACH(pe, &changed_paths, entry) {
4022 free((char *)pe->path);
4023 free(pe->data);
4025 got_pathlist_free(&changed_paths);
4028 done:
4029 while (!STAILQ_EMPTY(&reversed_commits)) {
4030 qid = STAILQ_FIRST(&reversed_commits);
4031 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4032 got_object_qid_free(qid);
4034 TAILQ_FOREACH(pe, &changed_paths, entry) {
4035 free((char *)pe->path);
4036 free(pe->data);
4038 got_pathlist_free(&changed_paths);
4039 if (search_pattern)
4040 regfree(&regex);
4041 got_commit_graph_close(graph);
4042 return err;
4045 __dead static void
4046 usage_log(void)
4048 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4049 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4050 "[-R] [path]\n", getprogname());
4051 exit(1);
4054 static int
4055 get_default_log_limit(void)
4057 const char *got_default_log_limit;
4058 long long n;
4059 const char *errstr;
4061 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4062 if (got_default_log_limit == NULL)
4063 return 0;
4064 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4065 if (errstr != NULL)
4066 return 0;
4067 return n;
4070 static const struct got_error *
4071 cmd_log(int argc, char *argv[])
4073 const struct got_error *error;
4074 struct got_repository *repo = NULL;
4075 struct got_worktree *worktree = NULL;
4076 struct got_object_id *start_id = NULL, *end_id = NULL;
4077 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4078 const char *start_commit = NULL, *end_commit = NULL;
4079 const char *search_pattern = NULL;
4080 int diff_context = -1, ch;
4081 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4082 int reverse_display_order = 0;
4083 const char *errstr;
4084 struct got_reflist_head refs;
4085 struct got_reflist_object_id_map *refs_idmap = NULL;
4087 TAILQ_INIT(&refs);
4089 #ifndef PROFILE
4090 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4091 NULL)
4092 == -1)
4093 err(1, "pledge");
4094 #endif
4096 limit = get_default_log_limit();
4098 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4099 switch (ch) {
4100 case 'p':
4101 show_patch = 1;
4102 break;
4103 case 'P':
4104 show_changed_paths = 1;
4105 break;
4106 case 'c':
4107 start_commit = optarg;
4108 break;
4109 case 'C':
4110 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4111 &errstr);
4112 if (errstr != NULL)
4113 errx(1, "number of context lines is %s: %s",
4114 errstr, optarg);
4115 break;
4116 case 'l':
4117 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4118 if (errstr != NULL)
4119 errx(1, "number of commits is %s: %s",
4120 errstr, optarg);
4121 break;
4122 case 'b':
4123 log_branches = 1;
4124 break;
4125 case 'r':
4126 repo_path = realpath(optarg, NULL);
4127 if (repo_path == NULL)
4128 return got_error_from_errno2("realpath",
4129 optarg);
4130 got_path_strip_trailing_slashes(repo_path);
4131 break;
4132 case 'R':
4133 reverse_display_order = 1;
4134 break;
4135 case 's':
4136 search_pattern = optarg;
4137 break;
4138 case 'x':
4139 end_commit = optarg;
4140 break;
4141 default:
4142 usage_log();
4143 /* NOTREACHED */
4147 argc -= optind;
4148 argv += optind;
4150 if (diff_context == -1)
4151 diff_context = 3;
4152 else if (!show_patch)
4153 errx(1, "-C requires -p");
4155 cwd = getcwd(NULL, 0);
4156 if (cwd == NULL) {
4157 error = got_error_from_errno("getcwd");
4158 goto done;
4161 if (repo_path == NULL) {
4162 error = got_worktree_open(&worktree, cwd);
4163 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4164 goto done;
4165 error = NULL;
4168 if (argc == 1) {
4169 if (worktree) {
4170 error = got_worktree_resolve_path(&path, worktree,
4171 argv[0]);
4172 if (error)
4173 goto done;
4174 } else {
4175 path = strdup(argv[0]);
4176 if (path == NULL) {
4177 error = got_error_from_errno("strdup");
4178 goto done;
4181 } else if (argc != 0)
4182 usage_log();
4184 if (repo_path == NULL) {
4185 repo_path = worktree ?
4186 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4188 if (repo_path == NULL) {
4189 error = got_error_from_errno("strdup");
4190 goto done;
4193 error = got_repo_open(&repo, repo_path, NULL);
4194 if (error != NULL)
4195 goto done;
4197 error = apply_unveil(got_repo_get_path(repo), 1,
4198 worktree ? got_worktree_get_root_path(worktree) : NULL);
4199 if (error)
4200 goto done;
4202 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4203 if (error)
4204 goto done;
4206 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4207 if (error)
4208 goto done;
4210 if (start_commit == NULL) {
4211 struct got_reference *head_ref;
4212 struct got_commit_object *commit = NULL;
4213 error = got_ref_open(&head_ref, repo,
4214 worktree ? got_worktree_get_head_ref_name(worktree)
4215 : GOT_REF_HEAD, 0);
4216 if (error != NULL)
4217 goto done;
4218 error = got_ref_resolve(&start_id, repo, head_ref);
4219 got_ref_close(head_ref);
4220 if (error != NULL)
4221 goto done;
4222 error = got_object_open_as_commit(&commit, repo,
4223 start_id);
4224 if (error != NULL)
4225 goto done;
4226 got_object_commit_close(commit);
4227 } else {
4228 error = got_repo_match_object_id(&start_id, NULL,
4229 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4230 if (error != NULL)
4231 goto done;
4233 if (end_commit != NULL) {
4234 error = got_repo_match_object_id(&end_id, NULL,
4235 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4236 if (error != NULL)
4237 goto done;
4240 if (worktree) {
4242 * If a path was specified on the command line it was resolved
4243 * to a path in the work tree above. Prepend the work tree's
4244 * path prefix to obtain the corresponding in-repository path.
4246 if (path) {
4247 const char *prefix;
4248 prefix = got_worktree_get_path_prefix(worktree);
4249 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4250 (path[0] != '\0') ? "/" : "", path) == -1) {
4251 error = got_error_from_errno("asprintf");
4252 goto done;
4255 } else
4256 error = got_repo_map_path(&in_repo_path, repo,
4257 path ? path : "");
4258 if (error != NULL)
4259 goto done;
4260 if (in_repo_path) {
4261 free(path);
4262 path = in_repo_path;
4265 error = print_commits(start_id, end_id, repo, path ? path : "",
4266 show_changed_paths, show_patch, search_pattern, diff_context,
4267 limit, log_branches, reverse_display_order, refs_idmap);
4268 done:
4269 free(path);
4270 free(repo_path);
4271 free(cwd);
4272 if (worktree)
4273 got_worktree_close(worktree);
4274 if (repo) {
4275 const struct got_error *close_err = got_repo_close(repo);
4276 if (error == NULL)
4277 error = close_err;
4279 if (refs_idmap)
4280 got_reflist_object_id_map_free(refs_idmap);
4281 got_ref_list_free(&refs);
4282 return error;
4285 __dead static void
4286 usage_diff(void)
4288 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4289 "[-r repository-path] [-s] [-w] [-P] "
4290 "[object1 object2 | path ...]\n", getprogname());
4291 exit(1);
4294 struct print_diff_arg {
4295 struct got_repository *repo;
4296 struct got_worktree *worktree;
4297 int diff_context;
4298 const char *id_str;
4299 int header_shown;
4300 int diff_staged;
4301 int ignore_whitespace;
4302 int force_text_diff;
4306 * Create a file which contains the target path of a symlink so we can feed
4307 * it as content to the diff engine.
4309 static const struct got_error *
4310 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4311 const char *abspath)
4313 const struct got_error *err = NULL;
4314 char target_path[PATH_MAX];
4315 ssize_t target_len, outlen;
4317 *fd = -1;
4319 if (dirfd != -1) {
4320 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4321 if (target_len == -1)
4322 return got_error_from_errno2("readlinkat", abspath);
4323 } else {
4324 target_len = readlink(abspath, target_path, PATH_MAX);
4325 if (target_len == -1)
4326 return got_error_from_errno2("readlink", abspath);
4329 *fd = got_opentempfd();
4330 if (*fd == -1)
4331 return got_error_from_errno("got_opentempfd");
4333 outlen = write(*fd, target_path, target_len);
4334 if (outlen == -1) {
4335 err = got_error_from_errno("got_opentempfd");
4336 goto done;
4339 if (lseek(*fd, 0, SEEK_SET) == -1) {
4340 err = got_error_from_errno2("lseek", abspath);
4341 goto done;
4343 done:
4344 if (err) {
4345 close(*fd);
4346 *fd = -1;
4348 return err;
4351 static const struct got_error *
4352 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4353 const char *path, struct got_object_id *blob_id,
4354 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4355 int dirfd, const char *de_name)
4357 struct print_diff_arg *a = arg;
4358 const struct got_error *err = NULL;
4359 struct got_blob_object *blob1 = NULL;
4360 int fd = -1;
4361 FILE *f2 = NULL;
4362 char *abspath = NULL, *label1 = NULL;
4363 struct stat sb;
4365 if (a->diff_staged) {
4366 if (staged_status != GOT_STATUS_MODIFY &&
4367 staged_status != GOT_STATUS_ADD &&
4368 staged_status != GOT_STATUS_DELETE)
4369 return NULL;
4370 } else {
4371 if (staged_status == GOT_STATUS_DELETE)
4372 return NULL;
4373 if (status == GOT_STATUS_NONEXISTENT)
4374 return got_error_set_errno(ENOENT, path);
4375 if (status != GOT_STATUS_MODIFY &&
4376 status != GOT_STATUS_ADD &&
4377 status != GOT_STATUS_DELETE &&
4378 status != GOT_STATUS_CONFLICT)
4379 return NULL;
4382 if (!a->header_shown) {
4383 printf("diff %s %s%s\n", a->id_str,
4384 got_worktree_get_root_path(a->worktree),
4385 a->diff_staged ? " (staged changes)" : "");
4386 a->header_shown = 1;
4389 if (a->diff_staged) {
4390 const char *label1 = NULL, *label2 = NULL;
4391 switch (staged_status) {
4392 case GOT_STATUS_MODIFY:
4393 label1 = path;
4394 label2 = path;
4395 break;
4396 case GOT_STATUS_ADD:
4397 label2 = path;
4398 break;
4399 case GOT_STATUS_DELETE:
4400 label1 = path;
4401 break;
4402 default:
4403 return got_error(GOT_ERR_FILE_STATUS);
4405 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4406 staged_blob_id, label1, label2, a->diff_context,
4407 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4410 if (staged_status == GOT_STATUS_ADD ||
4411 staged_status == GOT_STATUS_MODIFY) {
4412 char *id_str;
4413 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4414 8192);
4415 if (err)
4416 goto done;
4417 err = got_object_id_str(&id_str, staged_blob_id);
4418 if (err)
4419 goto done;
4420 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4421 err = got_error_from_errno("asprintf");
4422 free(id_str);
4423 goto done;
4425 free(id_str);
4426 } else if (status != GOT_STATUS_ADD) {
4427 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4428 if (err)
4429 goto done;
4432 if (status != GOT_STATUS_DELETE) {
4433 if (asprintf(&abspath, "%s/%s",
4434 got_worktree_get_root_path(a->worktree), path) == -1) {
4435 err = got_error_from_errno("asprintf");
4436 goto done;
4439 if (dirfd != -1) {
4440 fd = openat(dirfd, de_name,
4441 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4442 if (fd == -1) {
4443 if (!got_err_open_nofollow_on_symlink()) {
4444 err = got_error_from_errno2("openat",
4445 abspath);
4446 goto done;
4448 err = get_symlink_target_file(&fd, dirfd,
4449 de_name, abspath);
4450 if (err)
4451 goto done;
4453 } else {
4454 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4455 if (fd == -1) {
4456 if (!got_err_open_nofollow_on_symlink()) {
4457 err = got_error_from_errno2("open",
4458 abspath);
4459 goto done;
4461 err = get_symlink_target_file(&fd, dirfd,
4462 de_name, abspath);
4463 if (err)
4464 goto done;
4467 if (fstat(fd, &sb) == -1) {
4468 err = got_error_from_errno2("fstat", abspath);
4469 goto done;
4471 f2 = fdopen(fd, "r");
4472 if (f2 == NULL) {
4473 err = got_error_from_errno2("fdopen", abspath);
4474 goto done;
4476 fd = -1;
4477 } else
4478 sb.st_size = 0;
4480 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4481 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4482 done:
4483 if (blob1)
4484 got_object_blob_close(blob1);
4485 if (f2 && fclose(f2) == EOF && err == NULL)
4486 err = got_error_from_errno("fclose");
4487 if (fd != -1 && close(fd) == -1 && err == NULL)
4488 err = got_error_from_errno("close");
4489 free(abspath);
4490 return err;
4493 static const struct got_error *
4494 cmd_diff(int argc, char *argv[])
4496 const struct got_error *error;
4497 struct got_repository *repo = NULL;
4498 struct got_worktree *worktree = NULL;
4499 char *cwd = NULL, *repo_path = NULL;
4500 const char *commit_args[2] = { NULL, NULL };
4501 int ncommit_args = 0;
4502 struct got_object_id *ids[2] = { NULL, NULL };
4503 char *labels[2] = { NULL, NULL };
4504 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4505 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4506 int force_text_diff = 0, force_path = 0, rflag = 0;
4507 const char *errstr;
4508 struct got_reflist_head refs;
4509 struct got_pathlist_head paths;
4510 struct got_pathlist_entry *pe;
4512 TAILQ_INIT(&refs);
4513 TAILQ_INIT(&paths);
4515 #ifndef PROFILE
4516 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4517 NULL) == -1)
4518 err(1, "pledge");
4519 #endif
4521 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4522 switch (ch) {
4523 case 'a':
4524 force_text_diff = 1;
4525 break;
4526 case 'c':
4527 if (ncommit_args >= 2)
4528 errx(1, "too many -c options used");
4529 commit_args[ncommit_args++] = optarg;
4530 break;
4531 case 'C':
4532 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4533 &errstr);
4534 if (errstr != NULL)
4535 errx(1, "number of context lines is %s: %s",
4536 errstr, optarg);
4537 break;
4538 case 'r':
4539 repo_path = realpath(optarg, NULL);
4540 if (repo_path == NULL)
4541 return got_error_from_errno2("realpath",
4542 optarg);
4543 got_path_strip_trailing_slashes(repo_path);
4544 rflag = 1;
4545 break;
4546 case 's':
4547 diff_staged = 1;
4548 break;
4549 case 'w':
4550 ignore_whitespace = 1;
4551 break;
4552 case 'P':
4553 force_path = 1;
4554 break;
4555 default:
4556 usage_diff();
4557 /* NOTREACHED */
4561 argc -= optind;
4562 argv += optind;
4564 cwd = getcwd(NULL, 0);
4565 if (cwd == NULL) {
4566 error = got_error_from_errno("getcwd");
4567 goto done;
4570 if (repo_path == NULL) {
4571 error = got_worktree_open(&worktree, cwd);
4572 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4573 goto done;
4574 else
4575 error = NULL;
4576 if (worktree) {
4577 repo_path =
4578 strdup(got_worktree_get_repo_path(worktree));
4579 if (repo_path == NULL) {
4580 error = got_error_from_errno("strdup");
4581 goto done;
4583 } else {
4584 repo_path = strdup(cwd);
4585 if (repo_path == NULL) {
4586 error = got_error_from_errno("strdup");
4587 goto done;
4592 error = got_repo_open(&repo, repo_path, NULL);
4593 free(repo_path);
4594 if (error != NULL)
4595 goto done;
4597 if (rflag || worktree == NULL || ncommit_args > 0) {
4598 if (force_path) {
4599 error = got_error_msg(GOT_ERR_NOT_IMPL,
4600 "-P option can only be used when diffing "
4601 "a work tree");
4602 goto done;
4604 if (diff_staged) {
4605 error = got_error_msg(GOT_ERR_NOT_IMPL,
4606 "-s option can only be used when diffing "
4607 "a work tree");
4608 goto done;
4612 error = apply_unveil(got_repo_get_path(repo), 1,
4613 worktree ? got_worktree_get_root_path(worktree) : NULL);
4614 if (error)
4615 goto done;
4617 if ((!force_path && argc == 2) || ncommit_args > 0) {
4618 int obj_type = (ncommit_args > 0 ?
4619 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4620 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4621 NULL);
4622 if (error)
4623 goto done;
4624 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4625 const char *arg;
4626 if (ncommit_args > 0)
4627 arg = commit_args[i];
4628 else
4629 arg = argv[i];
4630 error = got_repo_match_object_id(&ids[i], &labels[i],
4631 arg, obj_type, &refs, repo);
4632 if (error) {
4633 if (error->code != GOT_ERR_NOT_REF &&
4634 error->code != GOT_ERR_NO_OBJ)
4635 goto done;
4636 if (ncommit_args > 0)
4637 goto done;
4638 error = NULL;
4639 break;
4644 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4645 struct print_diff_arg arg;
4646 char *id_str;
4648 if (worktree == NULL) {
4649 if (argc == 2 && ids[0] == NULL) {
4650 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4651 goto done;
4652 } else if (argc == 2 && ids[1] == NULL) {
4653 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4654 goto done;
4655 } else if (argc > 0) {
4656 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4657 "%s", "specified paths cannot be resolved");
4658 goto done;
4659 } else {
4660 error = got_error(GOT_ERR_NOT_WORKTREE);
4661 goto done;
4665 error = get_worktree_paths_from_argv(&paths, argc, argv,
4666 worktree);
4667 if (error)
4668 goto done;
4670 error = got_object_id_str(&id_str,
4671 got_worktree_get_base_commit_id(worktree));
4672 if (error)
4673 goto done;
4674 arg.repo = repo;
4675 arg.worktree = worktree;
4676 arg.diff_context = diff_context;
4677 arg.id_str = id_str;
4678 arg.header_shown = 0;
4679 arg.diff_staged = diff_staged;
4680 arg.ignore_whitespace = ignore_whitespace;
4681 arg.force_text_diff = force_text_diff;
4683 error = got_worktree_status(worktree, &paths, repo, 0,
4684 print_diff, &arg, check_cancelled, NULL);
4685 free(id_str);
4686 goto done;
4689 if (ncommit_args == 1) {
4690 struct got_commit_object *commit;
4691 error = got_object_open_as_commit(&commit, repo, ids[0]);
4692 if (error)
4693 goto done;
4695 labels[1] = labels[0];
4696 ids[1] = ids[0];
4697 if (got_object_commit_get_nparents(commit) > 0) {
4698 const struct got_object_id_queue *pids;
4699 struct got_object_qid *pid;
4700 pids = got_object_commit_get_parent_ids(commit);
4701 pid = STAILQ_FIRST(pids);
4702 ids[0] = got_object_id_dup(pid->id);
4703 if (ids[0] == NULL) {
4704 error = got_error_from_errno(
4705 "got_object_id_dup");
4706 got_object_commit_close(commit);
4707 goto done;
4709 error = got_object_id_str(&labels[0], ids[0]);
4710 if (error) {
4711 got_object_commit_close(commit);
4712 goto done;
4714 } else {
4715 ids[0] = NULL;
4716 labels[0] = strdup("/dev/null");
4717 if (labels[0] == NULL) {
4718 error = got_error_from_errno("strdup");
4719 got_object_commit_close(commit);
4720 goto done;
4724 got_object_commit_close(commit);
4727 if (ncommit_args == 0 && argc > 2) {
4728 error = got_error_msg(GOT_ERR_BAD_PATH,
4729 "path arguments cannot be used when diffing two objects");
4730 goto done;
4733 if (ids[0]) {
4734 error = got_object_get_type(&type1, repo, ids[0]);
4735 if (error)
4736 goto done;
4739 error = got_object_get_type(&type2, repo, ids[1]);
4740 if (error)
4741 goto done;
4742 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4743 error = got_error(GOT_ERR_OBJ_TYPE);
4744 goto done;
4746 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4747 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4748 "path arguments cannot be used when diffing blobs");
4749 goto done;
4752 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4753 char *in_repo_path;
4754 struct got_pathlist_entry *new;
4755 if (worktree) {
4756 const char *prefix;
4757 char *p;
4758 error = got_worktree_resolve_path(&p, worktree,
4759 argv[i]);
4760 if (error)
4761 goto done;
4762 prefix = got_worktree_get_path_prefix(worktree);
4763 while (prefix[0] == '/')
4764 prefix++;
4765 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4766 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4767 p) == -1) {
4768 error = got_error_from_errno("asprintf");
4769 free(p);
4770 goto done;
4772 free(p);
4773 } else {
4774 char *mapped_path, *s;
4775 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4776 if (error)
4777 goto done;
4778 s = mapped_path;
4779 while (s[0] == '/')
4780 s++;
4781 in_repo_path = strdup(s);
4782 if (in_repo_path == NULL) {
4783 error = got_error_from_errno("asprintf");
4784 free(mapped_path);
4785 goto done;
4787 free(mapped_path);
4790 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4791 if (error || new == NULL /* duplicate */)
4792 free(in_repo_path);
4793 if (error)
4794 goto done;
4797 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4798 case GOT_OBJ_TYPE_BLOB:
4799 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4800 NULL, NULL, diff_context, ignore_whitespace,
4801 force_text_diff, repo, stdout);
4802 break;
4803 case GOT_OBJ_TYPE_TREE:
4804 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4805 &paths, "", "", diff_context, ignore_whitespace,
4806 force_text_diff, repo, stdout);
4807 break;
4808 case GOT_OBJ_TYPE_COMMIT:
4809 printf("diff %s %s\n", labels[0], labels[1]);
4810 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4811 &paths, diff_context, ignore_whitespace, force_text_diff,
4812 repo, stdout);
4813 break;
4814 default:
4815 error = got_error(GOT_ERR_OBJ_TYPE);
4817 done:
4818 free(labels[0]);
4819 free(labels[1]);
4820 free(ids[0]);
4821 free(ids[1]);
4822 if (worktree)
4823 got_worktree_close(worktree);
4824 if (repo) {
4825 const struct got_error *close_err = got_repo_close(repo);
4826 if (error == NULL)
4827 error = close_err;
4829 TAILQ_FOREACH(pe, &paths, entry)
4830 free((char *)pe->path);
4831 got_pathlist_free(&paths);
4832 got_ref_list_free(&refs);
4833 return error;
4836 __dead static void
4837 usage_blame(void)
4839 fprintf(stderr,
4840 "usage: %s blame [-c commit] [-r repository-path] path\n",
4841 getprogname());
4842 exit(1);
4845 struct blame_line {
4846 int annotated;
4847 char *id_str;
4848 char *committer;
4849 char datebuf[11]; /* YYYY-MM-DD + NUL */
4852 struct blame_cb_args {
4853 struct blame_line *lines;
4854 int nlines;
4855 int nlines_prec;
4856 int lineno_cur;
4857 off_t *line_offsets;
4858 FILE *f;
4859 struct got_repository *repo;
4862 static const struct got_error *
4863 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4865 const struct got_error *err = NULL;
4866 struct blame_cb_args *a = arg;
4867 struct blame_line *bline;
4868 char *line = NULL;
4869 size_t linesize = 0;
4870 struct got_commit_object *commit = NULL;
4871 off_t offset;
4872 struct tm tm;
4873 time_t committer_time;
4875 if (nlines != a->nlines ||
4876 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4877 return got_error(GOT_ERR_RANGE);
4879 if (sigint_received)
4880 return got_error(GOT_ERR_ITER_COMPLETED);
4882 if (lineno == -1)
4883 return NULL; /* no change in this commit */
4885 /* Annotate this line. */
4886 bline = &a->lines[lineno - 1];
4887 if (bline->annotated)
4888 return NULL;
4889 err = got_object_id_str(&bline->id_str, id);
4890 if (err)
4891 return err;
4893 err = got_object_open_as_commit(&commit, a->repo, id);
4894 if (err)
4895 goto done;
4897 bline->committer = strdup(got_object_commit_get_committer(commit));
4898 if (bline->committer == NULL) {
4899 err = got_error_from_errno("strdup");
4900 goto done;
4903 committer_time = got_object_commit_get_committer_time(commit);
4904 if (gmtime_r(&committer_time, &tm) == NULL)
4905 return got_error_from_errno("gmtime_r");
4906 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4907 &tm) == 0) {
4908 err = got_error(GOT_ERR_NO_SPACE);
4909 goto done;
4911 bline->annotated = 1;
4913 /* Print lines annotated so far. */
4914 bline = &a->lines[a->lineno_cur - 1];
4915 if (!bline->annotated)
4916 goto done;
4918 offset = a->line_offsets[a->lineno_cur - 1];
4919 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4920 err = got_error_from_errno("fseeko");
4921 goto done;
4924 while (bline->annotated) {
4925 char *smallerthan, *at, *nl, *committer;
4926 size_t len;
4928 if (getline(&line, &linesize, a->f) == -1) {
4929 if (ferror(a->f))
4930 err = got_error_from_errno("getline");
4931 break;
4934 committer = bline->committer;
4935 smallerthan = strchr(committer, '<');
4936 if (smallerthan && smallerthan[1] != '\0')
4937 committer = smallerthan + 1;
4938 at = strchr(committer, '@');
4939 if (at)
4940 *at = '\0';
4941 len = strlen(committer);
4942 if (len >= 9)
4943 committer[8] = '\0';
4945 nl = strchr(line, '\n');
4946 if (nl)
4947 *nl = '\0';
4948 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4949 bline->id_str, bline->datebuf, committer, line);
4951 a->lineno_cur++;
4952 bline = &a->lines[a->lineno_cur - 1];
4954 done:
4955 if (commit)
4956 got_object_commit_close(commit);
4957 free(line);
4958 return err;
4961 static const struct got_error *
4962 cmd_blame(int argc, char *argv[])
4964 const struct got_error *error;
4965 struct got_repository *repo = NULL;
4966 struct got_worktree *worktree = NULL;
4967 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4968 char *link_target = NULL;
4969 struct got_object_id *obj_id = NULL;
4970 struct got_object_id *commit_id = NULL;
4971 struct got_blob_object *blob = NULL;
4972 char *commit_id_str = NULL;
4973 struct blame_cb_args bca;
4974 int ch, obj_type, i;
4975 off_t filesize;
4977 memset(&bca, 0, sizeof(bca));
4979 #ifndef PROFILE
4980 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4981 NULL) == -1)
4982 err(1, "pledge");
4983 #endif
4985 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4986 switch (ch) {
4987 case 'c':
4988 commit_id_str = optarg;
4989 break;
4990 case 'r':
4991 repo_path = realpath(optarg, NULL);
4992 if (repo_path == NULL)
4993 return got_error_from_errno2("realpath",
4994 optarg);
4995 got_path_strip_trailing_slashes(repo_path);
4996 break;
4997 default:
4998 usage_blame();
4999 /* NOTREACHED */
5003 argc -= optind;
5004 argv += optind;
5006 if (argc == 1)
5007 path = argv[0];
5008 else
5009 usage_blame();
5011 cwd = getcwd(NULL, 0);
5012 if (cwd == NULL) {
5013 error = got_error_from_errno("getcwd");
5014 goto done;
5016 if (repo_path == NULL) {
5017 error = got_worktree_open(&worktree, cwd);
5018 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5019 goto done;
5020 else
5021 error = NULL;
5022 if (worktree) {
5023 repo_path =
5024 strdup(got_worktree_get_repo_path(worktree));
5025 if (repo_path == NULL) {
5026 error = got_error_from_errno("strdup");
5027 if (error)
5028 goto done;
5030 } else {
5031 repo_path = strdup(cwd);
5032 if (repo_path == NULL) {
5033 error = got_error_from_errno("strdup");
5034 goto done;
5039 error = got_repo_open(&repo, repo_path, NULL);
5040 if (error != NULL)
5041 goto done;
5043 if (worktree) {
5044 const char *prefix = got_worktree_get_path_prefix(worktree);
5045 char *p;
5047 error = got_worktree_resolve_path(&p, worktree, path);
5048 if (error)
5049 goto done;
5050 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5051 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5052 p) == -1) {
5053 error = got_error_from_errno("asprintf");
5054 free(p);
5055 goto done;
5057 free(p);
5058 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5059 } else {
5060 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5061 if (error)
5062 goto done;
5063 error = got_repo_map_path(&in_repo_path, repo, path);
5065 if (error)
5066 goto done;
5068 if (commit_id_str == NULL) {
5069 struct got_reference *head_ref;
5070 error = got_ref_open(&head_ref, repo, worktree ?
5071 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5072 if (error != NULL)
5073 goto done;
5074 error = got_ref_resolve(&commit_id, repo, head_ref);
5075 got_ref_close(head_ref);
5076 if (error != NULL)
5077 goto done;
5078 } else {
5079 struct got_reflist_head refs;
5080 TAILQ_INIT(&refs);
5081 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5082 NULL);
5083 if (error)
5084 goto done;
5085 error = got_repo_match_object_id(&commit_id, NULL,
5086 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5087 got_ref_list_free(&refs);
5088 if (error)
5089 goto done;
5092 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5093 commit_id, repo);
5094 if (error)
5095 goto done;
5097 error = got_object_id_by_path(&obj_id, repo, commit_id,
5098 link_target ? link_target : in_repo_path);
5099 if (error)
5100 goto done;
5102 error = got_object_get_type(&obj_type, repo, obj_id);
5103 if (error)
5104 goto done;
5106 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5107 error = got_error_path(link_target ? link_target : in_repo_path,
5108 GOT_ERR_OBJ_TYPE);
5109 goto done;
5112 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5113 if (error)
5114 goto done;
5115 bca.f = got_opentemp();
5116 if (bca.f == NULL) {
5117 error = got_error_from_errno("got_opentemp");
5118 goto done;
5120 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5121 &bca.line_offsets, bca.f, blob);
5122 if (error || bca.nlines == 0)
5123 goto done;
5125 /* Don't include \n at EOF in the blame line count. */
5126 if (bca.line_offsets[bca.nlines - 1] == filesize)
5127 bca.nlines--;
5129 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5130 if (bca.lines == NULL) {
5131 error = got_error_from_errno("calloc");
5132 goto done;
5134 bca.lineno_cur = 1;
5135 bca.nlines_prec = 0;
5136 i = bca.nlines;
5137 while (i > 0) {
5138 i /= 10;
5139 bca.nlines_prec++;
5141 bca.repo = repo;
5143 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5144 repo, blame_cb, &bca, check_cancelled, NULL);
5145 done:
5146 free(in_repo_path);
5147 free(link_target);
5148 free(repo_path);
5149 free(cwd);
5150 free(commit_id);
5151 free(obj_id);
5152 if (blob)
5153 got_object_blob_close(blob);
5154 if (worktree)
5155 got_worktree_close(worktree);
5156 if (repo) {
5157 const struct got_error *close_err = got_repo_close(repo);
5158 if (error == NULL)
5159 error = close_err;
5161 if (bca.lines) {
5162 for (i = 0; i < bca.nlines; i++) {
5163 struct blame_line *bline = &bca.lines[i];
5164 free(bline->id_str);
5165 free(bline->committer);
5167 free(bca.lines);
5169 free(bca.line_offsets);
5170 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5171 error = got_error_from_errno("fclose");
5172 return error;
5175 __dead static void
5176 usage_tree(void)
5178 fprintf(stderr,
5179 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5180 getprogname());
5181 exit(1);
5184 static const struct got_error *
5185 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5186 const char *root_path, struct got_repository *repo)
5188 const struct got_error *err = NULL;
5189 int is_root_path = (strcmp(path, root_path) == 0);
5190 const char *modestr = "";
5191 mode_t mode = got_tree_entry_get_mode(te);
5192 char *link_target = NULL;
5194 path += strlen(root_path);
5195 while (path[0] == '/')
5196 path++;
5198 if (got_object_tree_entry_is_submodule(te))
5199 modestr = "$";
5200 else if (S_ISLNK(mode)) {
5201 int i;
5203 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5204 if (err)
5205 return err;
5206 for (i = 0; i < strlen(link_target); i++) {
5207 if (!isprint((unsigned char)link_target[i]))
5208 link_target[i] = '?';
5211 modestr = "@";
5213 else if (S_ISDIR(mode))
5214 modestr = "/";
5215 else if (mode & S_IXUSR)
5216 modestr = "*";
5218 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5219 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5220 link_target ? " -> ": "", link_target ? link_target : "");
5222 free(link_target);
5223 return NULL;
5226 static const struct got_error *
5227 print_tree(const char *path, struct got_object_id *commit_id,
5228 int show_ids, int recurse, const char *root_path,
5229 struct got_repository *repo)
5231 const struct got_error *err = NULL;
5232 struct got_object_id *tree_id = NULL;
5233 struct got_tree_object *tree = NULL;
5234 int nentries, i;
5236 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5237 if (err)
5238 goto done;
5240 err = got_object_open_as_tree(&tree, repo, tree_id);
5241 if (err)
5242 goto done;
5243 nentries = got_object_tree_get_nentries(tree);
5244 for (i = 0; i < nentries; i++) {
5245 struct got_tree_entry *te;
5246 char *id = NULL;
5248 if (sigint_received || sigpipe_received)
5249 break;
5251 te = got_object_tree_get_entry(tree, i);
5252 if (show_ids) {
5253 char *id_str;
5254 err = got_object_id_str(&id_str,
5255 got_tree_entry_get_id(te));
5256 if (err)
5257 goto done;
5258 if (asprintf(&id, "%s ", id_str) == -1) {
5259 err = got_error_from_errno("asprintf");
5260 free(id_str);
5261 goto done;
5263 free(id_str);
5265 err = print_entry(te, id, path, root_path, repo);
5266 free(id);
5267 if (err)
5268 goto done;
5270 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5271 char *child_path;
5272 if (asprintf(&child_path, "%s%s%s", path,
5273 path[0] == '/' && path[1] == '\0' ? "" : "/",
5274 got_tree_entry_get_name(te)) == -1) {
5275 err = got_error_from_errno("asprintf");
5276 goto done;
5278 err = print_tree(child_path, commit_id, show_ids, 1,
5279 root_path, repo);
5280 free(child_path);
5281 if (err)
5282 goto done;
5285 done:
5286 if (tree)
5287 got_object_tree_close(tree);
5288 free(tree_id);
5289 return err;
5292 static const struct got_error *
5293 cmd_tree(int argc, char *argv[])
5295 const struct got_error *error;
5296 struct got_repository *repo = NULL;
5297 struct got_worktree *worktree = NULL;
5298 const char *path, *refname = NULL;
5299 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5300 struct got_object_id *commit_id = NULL;
5301 char *commit_id_str = NULL;
5302 int show_ids = 0, recurse = 0;
5303 int ch;
5305 #ifndef PROFILE
5306 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5307 NULL) == -1)
5308 err(1, "pledge");
5309 #endif
5311 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5312 switch (ch) {
5313 case 'c':
5314 commit_id_str = optarg;
5315 break;
5316 case 'r':
5317 repo_path = realpath(optarg, NULL);
5318 if (repo_path == NULL)
5319 return got_error_from_errno2("realpath",
5320 optarg);
5321 got_path_strip_trailing_slashes(repo_path);
5322 break;
5323 case 'i':
5324 show_ids = 1;
5325 break;
5326 case 'R':
5327 recurse = 1;
5328 break;
5329 default:
5330 usage_tree();
5331 /* NOTREACHED */
5335 argc -= optind;
5336 argv += optind;
5338 if (argc == 1)
5339 path = argv[0];
5340 else if (argc > 1)
5341 usage_tree();
5342 else
5343 path = NULL;
5345 cwd = getcwd(NULL, 0);
5346 if (cwd == NULL) {
5347 error = got_error_from_errno("getcwd");
5348 goto done;
5350 if (repo_path == NULL) {
5351 error = got_worktree_open(&worktree, cwd);
5352 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5353 goto done;
5354 else
5355 error = NULL;
5356 if (worktree) {
5357 repo_path =
5358 strdup(got_worktree_get_repo_path(worktree));
5359 if (repo_path == NULL)
5360 error = got_error_from_errno("strdup");
5361 if (error)
5362 goto done;
5363 } else {
5364 repo_path = strdup(cwd);
5365 if (repo_path == NULL) {
5366 error = got_error_from_errno("strdup");
5367 goto done;
5372 error = got_repo_open(&repo, repo_path, NULL);
5373 if (error != NULL)
5374 goto done;
5376 if (worktree) {
5377 const char *prefix = got_worktree_get_path_prefix(worktree);
5378 char *p;
5380 if (path == NULL)
5381 path = "";
5382 error = got_worktree_resolve_path(&p, worktree, path);
5383 if (error)
5384 goto done;
5385 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5386 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5387 p) == -1) {
5388 error = got_error_from_errno("asprintf");
5389 free(p);
5390 goto done;
5392 free(p);
5393 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5394 if (error)
5395 goto done;
5396 } else {
5397 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5398 if (error)
5399 goto done;
5400 if (path == NULL)
5401 path = "/";
5402 error = got_repo_map_path(&in_repo_path, repo, path);
5403 if (error != NULL)
5404 goto done;
5407 if (commit_id_str == NULL) {
5408 struct got_reference *head_ref;
5409 if (worktree)
5410 refname = got_worktree_get_head_ref_name(worktree);
5411 else
5412 refname = GOT_REF_HEAD;
5413 error = got_ref_open(&head_ref, repo, refname, 0);
5414 if (error != NULL)
5415 goto done;
5416 error = got_ref_resolve(&commit_id, repo, head_ref);
5417 got_ref_close(head_ref);
5418 if (error != NULL)
5419 goto done;
5420 } else {
5421 struct got_reflist_head refs;
5422 TAILQ_INIT(&refs);
5423 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5424 NULL);
5425 if (error)
5426 goto done;
5427 error = got_repo_match_object_id(&commit_id, NULL,
5428 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5429 got_ref_list_free(&refs);
5430 if (error)
5431 goto done;
5434 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5435 in_repo_path, repo);
5436 done:
5437 free(in_repo_path);
5438 free(repo_path);
5439 free(cwd);
5440 free(commit_id);
5441 if (worktree)
5442 got_worktree_close(worktree);
5443 if (repo) {
5444 const struct got_error *close_err = got_repo_close(repo);
5445 if (error == NULL)
5446 error = close_err;
5448 return error;
5451 __dead static void
5452 usage_status(void)
5454 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5455 "[-S status-codes] [path ...]\n", getprogname());
5456 exit(1);
5459 struct got_status_arg {
5460 char *status_codes;
5461 int suppress;
5464 static const struct got_error *
5465 print_status(void *arg, unsigned char status, unsigned char staged_status,
5466 const char *path, struct got_object_id *blob_id,
5467 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5468 int dirfd, const char *de_name)
5470 struct got_status_arg *st = arg;
5472 if (status == staged_status && (status == GOT_STATUS_DELETE))
5473 status = GOT_STATUS_NO_CHANGE;
5474 if (st != NULL && st->status_codes) {
5475 size_t ncodes = strlen(st->status_codes);
5476 int i, j = 0;
5478 for (i = 0; i < ncodes ; i++) {
5479 if (st->suppress) {
5480 if (status == st->status_codes[i] ||
5481 staged_status == st->status_codes[i]) {
5482 j++;
5483 continue;
5485 } else {
5486 if (status == st->status_codes[i] ||
5487 staged_status == st->status_codes[i])
5488 break;
5492 if (st->suppress && j == 0)
5493 goto print;
5495 if (i == ncodes)
5496 return NULL;
5498 print:
5499 printf("%c%c %s\n", status, staged_status, path);
5500 return NULL;
5503 static const struct got_error *
5504 cmd_status(int argc, char *argv[])
5506 const struct got_error *error = NULL;
5507 struct got_repository *repo = NULL;
5508 struct got_worktree *worktree = NULL;
5509 struct got_status_arg st;
5510 char *cwd = NULL;
5511 struct got_pathlist_head paths;
5512 struct got_pathlist_entry *pe;
5513 int ch, i, no_ignores = 0;
5515 TAILQ_INIT(&paths);
5517 memset(&st, 0, sizeof(st));
5518 st.status_codes = NULL;
5519 st.suppress = 0;
5521 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5522 switch (ch) {
5523 case 'I':
5524 no_ignores = 1;
5525 break;
5526 case 'S':
5527 if (st.status_codes != NULL && st.suppress == 0)
5528 option_conflict('S', 's');
5529 st.suppress = 1;
5530 /* fallthrough */
5531 case 's':
5532 for (i = 0; i < strlen(optarg); i++) {
5533 switch (optarg[i]) {
5534 case GOT_STATUS_MODIFY:
5535 case GOT_STATUS_ADD:
5536 case GOT_STATUS_DELETE:
5537 case GOT_STATUS_CONFLICT:
5538 case GOT_STATUS_MISSING:
5539 case GOT_STATUS_OBSTRUCTED:
5540 case GOT_STATUS_UNVERSIONED:
5541 case GOT_STATUS_MODE_CHANGE:
5542 case GOT_STATUS_NONEXISTENT:
5543 break;
5544 default:
5545 errx(1, "invalid status code '%c'",
5546 optarg[i]);
5549 if (ch == 's' && st.suppress)
5550 option_conflict('s', 'S');
5551 st.status_codes = optarg;
5552 break;
5553 default:
5554 usage_status();
5555 /* NOTREACHED */
5559 argc -= optind;
5560 argv += optind;
5562 #ifndef PROFILE
5563 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5564 NULL) == -1)
5565 err(1, "pledge");
5566 #endif
5567 cwd = getcwd(NULL, 0);
5568 if (cwd == NULL) {
5569 error = got_error_from_errno("getcwd");
5570 goto done;
5573 error = got_worktree_open(&worktree, cwd);
5574 if (error) {
5575 if (error->code == GOT_ERR_NOT_WORKTREE)
5576 error = wrap_not_worktree_error(error, "status", cwd);
5577 goto done;
5580 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5581 NULL);
5582 if (error != NULL)
5583 goto done;
5585 error = apply_unveil(got_repo_get_path(repo), 1,
5586 got_worktree_get_root_path(worktree));
5587 if (error)
5588 goto done;
5590 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5591 if (error)
5592 goto done;
5594 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5595 print_status, &st, check_cancelled, NULL);
5596 done:
5597 TAILQ_FOREACH(pe, &paths, entry)
5598 free((char *)pe->path);
5599 got_pathlist_free(&paths);
5600 free(cwd);
5601 return error;
5604 __dead static void
5605 usage_ref(void)
5607 fprintf(stderr,
5608 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5609 "[-s reference] [-d] [name]\n",
5610 getprogname());
5611 exit(1);
5614 static const struct got_error *
5615 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5617 static const struct got_error *err = NULL;
5618 struct got_reflist_head refs;
5619 struct got_reflist_entry *re;
5621 TAILQ_INIT(&refs);
5622 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5623 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5624 repo);
5625 if (err)
5626 return err;
5628 TAILQ_FOREACH(re, &refs, entry) {
5629 char *refstr;
5630 refstr = got_ref_to_str(re->ref);
5631 if (refstr == NULL)
5632 return got_error_from_errno("got_ref_to_str");
5633 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5634 free(refstr);
5637 got_ref_list_free(&refs);
5638 return NULL;
5641 static const struct got_error *
5642 delete_ref_by_name(struct got_repository *repo, const char *refname)
5644 const struct got_error *err;
5645 struct got_reference *ref;
5647 err = got_ref_open(&ref, repo, refname, 0);
5648 if (err)
5649 return err;
5651 err = delete_ref(repo, ref);
5652 got_ref_close(ref);
5653 return err;
5656 static const struct got_error *
5657 add_ref(struct got_repository *repo, const char *refname, const char *target)
5659 const struct got_error *err = NULL;
5660 struct got_object_id *id;
5661 struct got_reference *ref = NULL;
5664 * Don't let the user create a reference name with a leading '-'.
5665 * While technically a valid reference name, this case is usually
5666 * an unintended typo.
5668 if (refname[0] == '-')
5669 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5671 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5672 repo);
5673 if (err) {
5674 struct got_reference *target_ref;
5676 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5677 return err;
5678 err = got_ref_open(&target_ref, repo, target, 0);
5679 if (err)
5680 return err;
5681 err = got_ref_resolve(&id, repo, target_ref);
5682 got_ref_close(target_ref);
5683 if (err)
5684 return err;
5687 err = got_ref_alloc(&ref, refname, id);
5688 if (err)
5689 goto done;
5691 err = got_ref_write(ref, repo);
5692 done:
5693 if (ref)
5694 got_ref_close(ref);
5695 free(id);
5696 return err;
5699 static const struct got_error *
5700 add_symref(struct got_repository *repo, const char *refname, const char *target)
5702 const struct got_error *err = NULL;
5703 struct got_reference *ref = NULL;
5704 struct got_reference *target_ref = NULL;
5707 * Don't let the user create a reference name with a leading '-'.
5708 * While technically a valid reference name, this case is usually
5709 * an unintended typo.
5711 if (refname[0] == '-')
5712 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5714 err = got_ref_open(&target_ref, repo, target, 0);
5715 if (err)
5716 return err;
5718 err = got_ref_alloc_symref(&ref, refname, target_ref);
5719 if (err)
5720 goto done;
5722 err = got_ref_write(ref, repo);
5723 done:
5724 if (target_ref)
5725 got_ref_close(target_ref);
5726 if (ref)
5727 got_ref_close(ref);
5728 return err;
5731 static const struct got_error *
5732 cmd_ref(int argc, char *argv[])
5734 const struct got_error *error = NULL;
5735 struct got_repository *repo = NULL;
5736 struct got_worktree *worktree = NULL;
5737 char *cwd = NULL, *repo_path = NULL;
5738 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5739 const char *obj_arg = NULL, *symref_target= NULL;
5740 char *refname = NULL;
5742 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5743 switch (ch) {
5744 case 'c':
5745 obj_arg = optarg;
5746 break;
5747 case 'd':
5748 do_delete = 1;
5749 break;
5750 case 'r':
5751 repo_path = realpath(optarg, NULL);
5752 if (repo_path == NULL)
5753 return got_error_from_errno2("realpath",
5754 optarg);
5755 got_path_strip_trailing_slashes(repo_path);
5756 break;
5757 case 'l':
5758 do_list = 1;
5759 break;
5760 case 's':
5761 symref_target = optarg;
5762 break;
5763 case 't':
5764 sort_by_time = 1;
5765 break;
5766 default:
5767 usage_ref();
5768 /* NOTREACHED */
5772 if (obj_arg && do_list)
5773 option_conflict('c', 'l');
5774 if (obj_arg && do_delete)
5775 option_conflict('c', 'd');
5776 if (obj_arg && symref_target)
5777 option_conflict('c', 's');
5778 if (symref_target && do_delete)
5779 option_conflict('s', 'd');
5780 if (symref_target && do_list)
5781 option_conflict('s', 'l');
5782 if (do_delete && do_list)
5783 option_conflict('d', 'l');
5784 if (sort_by_time && !do_list)
5785 errx(1, "-t option requires -l option");
5787 argc -= optind;
5788 argv += optind;
5790 if (do_list) {
5791 if (argc != 0 && argc != 1)
5792 usage_ref();
5793 if (argc == 1) {
5794 refname = strdup(argv[0]);
5795 if (refname == NULL) {
5796 error = got_error_from_errno("strdup");
5797 goto done;
5800 } else {
5801 if (argc != 1)
5802 usage_ref();
5803 refname = strdup(argv[0]);
5804 if (refname == NULL) {
5805 error = got_error_from_errno("strdup");
5806 goto done;
5810 if (refname)
5811 got_path_strip_trailing_slashes(refname);
5813 #ifndef PROFILE
5814 if (do_list) {
5815 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5816 NULL) == -1)
5817 err(1, "pledge");
5818 } else {
5819 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5820 "sendfd unveil", NULL) == -1)
5821 err(1, "pledge");
5823 #endif
5824 cwd = getcwd(NULL, 0);
5825 if (cwd == NULL) {
5826 error = got_error_from_errno("getcwd");
5827 goto done;
5830 if (repo_path == NULL) {
5831 error = got_worktree_open(&worktree, cwd);
5832 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5833 goto done;
5834 else
5835 error = NULL;
5836 if (worktree) {
5837 repo_path =
5838 strdup(got_worktree_get_repo_path(worktree));
5839 if (repo_path == NULL)
5840 error = got_error_from_errno("strdup");
5841 if (error)
5842 goto done;
5843 } else {
5844 repo_path = strdup(cwd);
5845 if (repo_path == NULL) {
5846 error = got_error_from_errno("strdup");
5847 goto done;
5852 error = got_repo_open(&repo, repo_path, NULL);
5853 if (error != NULL)
5854 goto done;
5856 error = apply_unveil(got_repo_get_path(repo), do_list,
5857 worktree ? got_worktree_get_root_path(worktree) : NULL);
5858 if (error)
5859 goto done;
5861 if (do_list)
5862 error = list_refs(repo, refname, sort_by_time);
5863 else if (do_delete)
5864 error = delete_ref_by_name(repo, refname);
5865 else if (symref_target)
5866 error = add_symref(repo, refname, symref_target);
5867 else {
5868 if (obj_arg == NULL)
5869 usage_ref();
5870 error = add_ref(repo, refname, obj_arg);
5872 done:
5873 free(refname);
5874 if (repo) {
5875 const struct got_error *close_err = got_repo_close(repo);
5876 if (error == NULL)
5877 error = close_err;
5879 if (worktree)
5880 got_worktree_close(worktree);
5881 free(cwd);
5882 free(repo_path);
5883 return error;
5886 __dead static void
5887 usage_branch(void)
5889 fprintf(stderr,
5890 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5891 "[-n] [name]\n", getprogname());
5892 exit(1);
5895 static const struct got_error *
5896 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5897 struct got_reference *ref)
5899 const struct got_error *err = NULL;
5900 const char *refname, *marker = " ";
5901 char *refstr;
5903 refname = got_ref_get_name(ref);
5904 if (worktree && strcmp(refname,
5905 got_worktree_get_head_ref_name(worktree)) == 0) {
5906 struct got_object_id *id = NULL;
5908 err = got_ref_resolve(&id, repo, ref);
5909 if (err)
5910 return err;
5911 if (got_object_id_cmp(id,
5912 got_worktree_get_base_commit_id(worktree)) == 0)
5913 marker = "* ";
5914 else
5915 marker = "~ ";
5916 free(id);
5919 if (strncmp(refname, "refs/heads/", 11) == 0)
5920 refname += 11;
5921 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5922 refname += 18;
5923 if (strncmp(refname, "refs/remotes/", 13) == 0)
5924 refname += 13;
5926 refstr = got_ref_to_str(ref);
5927 if (refstr == NULL)
5928 return got_error_from_errno("got_ref_to_str");
5930 printf("%s%s: %s\n", marker, refname, refstr);
5931 free(refstr);
5932 return NULL;
5935 static const struct got_error *
5936 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5938 const char *refname;
5940 if (worktree == NULL)
5941 return got_error(GOT_ERR_NOT_WORKTREE);
5943 refname = got_worktree_get_head_ref_name(worktree);
5945 if (strncmp(refname, "refs/heads/", 11) == 0)
5946 refname += 11;
5947 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5948 refname += 18;
5950 printf("%s\n", refname);
5952 return NULL;
5955 static const struct got_error *
5956 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5957 int sort_by_time)
5959 static const struct got_error *err = NULL;
5960 struct got_reflist_head refs;
5961 struct got_reflist_entry *re;
5962 struct got_reference *temp_ref = NULL;
5963 int rebase_in_progress, histedit_in_progress;
5965 TAILQ_INIT(&refs);
5967 if (worktree) {
5968 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5969 worktree);
5970 if (err)
5971 return err;
5973 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5974 worktree);
5975 if (err)
5976 return err;
5978 if (rebase_in_progress || histedit_in_progress) {
5979 err = got_ref_open(&temp_ref, repo,
5980 got_worktree_get_head_ref_name(worktree), 0);
5981 if (err)
5982 return err;
5983 list_branch(repo, worktree, temp_ref);
5984 got_ref_close(temp_ref);
5988 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
5989 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5990 repo);
5991 if (err)
5992 return err;
5994 TAILQ_FOREACH(re, &refs, entry)
5995 list_branch(repo, worktree, re->ref);
5997 got_ref_list_free(&refs);
5999 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6000 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6001 repo);
6002 if (err)
6003 return err;
6005 TAILQ_FOREACH(re, &refs, entry)
6006 list_branch(repo, worktree, re->ref);
6008 got_ref_list_free(&refs);
6010 return NULL;
6013 static const struct got_error *
6014 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6015 const char *branch_name)
6017 const struct got_error *err = NULL;
6018 struct got_reference *ref = NULL;
6019 char *refname, *remote_refname = NULL;
6021 if (strncmp(branch_name, "refs/", 5) == 0)
6022 branch_name += 5;
6023 if (strncmp(branch_name, "heads/", 6) == 0)
6024 branch_name += 6;
6025 else if (strncmp(branch_name, "remotes/", 8) == 0)
6026 branch_name += 8;
6028 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6029 return got_error_from_errno("asprintf");
6031 if (asprintf(&remote_refname, "refs/remotes/%s",
6032 branch_name) == -1) {
6033 err = got_error_from_errno("asprintf");
6034 goto done;
6037 err = got_ref_open(&ref, repo, refname, 0);
6038 if (err) {
6039 const struct got_error *err2;
6040 if (err->code != GOT_ERR_NOT_REF)
6041 goto done;
6043 * Keep 'err' intact such that if neither branch exists
6044 * we report "refs/heads" rather than "refs/remotes" in
6045 * our error message.
6047 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6048 if (err2)
6049 goto done;
6050 err = NULL;
6053 if (worktree &&
6054 strcmp(got_worktree_get_head_ref_name(worktree),
6055 got_ref_get_name(ref)) == 0) {
6056 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6057 "will not delete this work tree's current branch");
6058 goto done;
6061 err = delete_ref(repo, ref);
6062 done:
6063 if (ref)
6064 got_ref_close(ref);
6065 free(refname);
6066 free(remote_refname);
6067 return err;
6070 static const struct got_error *
6071 add_branch(struct got_repository *repo, const char *branch_name,
6072 struct got_object_id *base_commit_id)
6074 const struct got_error *err = NULL;
6075 struct got_reference *ref = NULL;
6076 char *base_refname = NULL, *refname = NULL;
6079 * Don't let the user create a branch name with a leading '-'.
6080 * While technically a valid reference name, this case is usually
6081 * an unintended typo.
6083 if (branch_name[0] == '-')
6084 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6086 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6087 branch_name += 11;
6089 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6090 err = got_error_from_errno("asprintf");
6091 goto done;
6094 err = got_ref_open(&ref, repo, refname, 0);
6095 if (err == NULL) {
6096 err = got_error(GOT_ERR_BRANCH_EXISTS);
6097 goto done;
6098 } else if (err->code != GOT_ERR_NOT_REF)
6099 goto done;
6101 err = got_ref_alloc(&ref, refname, base_commit_id);
6102 if (err)
6103 goto done;
6105 err = got_ref_write(ref, repo);
6106 done:
6107 if (ref)
6108 got_ref_close(ref);
6109 free(base_refname);
6110 free(refname);
6111 return err;
6114 static const struct got_error *
6115 cmd_branch(int argc, char *argv[])
6117 const struct got_error *error = NULL;
6118 struct got_repository *repo = NULL;
6119 struct got_worktree *worktree = NULL;
6120 char *cwd = NULL, *repo_path = NULL;
6121 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6122 const char *delref = NULL, *commit_id_arg = NULL;
6123 struct got_reference *ref = NULL;
6124 struct got_pathlist_head paths;
6125 struct got_pathlist_entry *pe;
6126 struct got_object_id *commit_id = NULL;
6127 char *commit_id_str = NULL;
6129 TAILQ_INIT(&paths);
6131 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6132 switch (ch) {
6133 case 'c':
6134 commit_id_arg = optarg;
6135 break;
6136 case 'd':
6137 delref = optarg;
6138 break;
6139 case 'r':
6140 repo_path = realpath(optarg, NULL);
6141 if (repo_path == NULL)
6142 return got_error_from_errno2("realpath",
6143 optarg);
6144 got_path_strip_trailing_slashes(repo_path);
6145 break;
6146 case 'l':
6147 do_list = 1;
6148 break;
6149 case 'n':
6150 do_update = 0;
6151 break;
6152 case 't':
6153 sort_by_time = 1;
6154 break;
6155 default:
6156 usage_branch();
6157 /* NOTREACHED */
6161 if (do_list && delref)
6162 option_conflict('l', 'd');
6163 if (sort_by_time && !do_list)
6164 errx(1, "-t option requires -l option");
6166 argc -= optind;
6167 argv += optind;
6169 if (!do_list && !delref && argc == 0)
6170 do_show = 1;
6172 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6173 errx(1, "-c option can only be used when creating a branch");
6175 if (do_list || delref) {
6176 if (argc > 0)
6177 usage_branch();
6178 } else if (!do_show && argc != 1)
6179 usage_branch();
6181 #ifndef PROFILE
6182 if (do_list || do_show) {
6183 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6184 NULL) == -1)
6185 err(1, "pledge");
6186 } else {
6187 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6188 "sendfd unveil", NULL) == -1)
6189 err(1, "pledge");
6191 #endif
6192 cwd = getcwd(NULL, 0);
6193 if (cwd == NULL) {
6194 error = got_error_from_errno("getcwd");
6195 goto done;
6198 if (repo_path == NULL) {
6199 error = got_worktree_open(&worktree, cwd);
6200 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6201 goto done;
6202 else
6203 error = NULL;
6204 if (worktree) {
6205 repo_path =
6206 strdup(got_worktree_get_repo_path(worktree));
6207 if (repo_path == NULL)
6208 error = got_error_from_errno("strdup");
6209 if (error)
6210 goto done;
6211 } else {
6212 repo_path = strdup(cwd);
6213 if (repo_path == NULL) {
6214 error = got_error_from_errno("strdup");
6215 goto done;
6220 error = got_repo_open(&repo, repo_path, NULL);
6221 if (error != NULL)
6222 goto done;
6224 error = apply_unveil(got_repo_get_path(repo), do_list,
6225 worktree ? got_worktree_get_root_path(worktree) : NULL);
6226 if (error)
6227 goto done;
6229 if (do_show)
6230 error = show_current_branch(repo, worktree);
6231 else if (do_list)
6232 error = list_branches(repo, worktree, sort_by_time);
6233 else if (delref)
6234 error = delete_branch(repo, worktree, delref);
6235 else {
6236 struct got_reflist_head refs;
6237 TAILQ_INIT(&refs);
6238 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6239 NULL);
6240 if (error)
6241 goto done;
6242 if (commit_id_arg == NULL)
6243 commit_id_arg = worktree ?
6244 got_worktree_get_head_ref_name(worktree) :
6245 GOT_REF_HEAD;
6246 error = got_repo_match_object_id(&commit_id, NULL,
6247 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6248 got_ref_list_free(&refs);
6249 if (error)
6250 goto done;
6251 error = add_branch(repo, argv[0], commit_id);
6252 if (error)
6253 goto done;
6254 if (worktree && do_update) {
6255 struct got_update_progress_arg upa;
6256 char *branch_refname = NULL;
6258 error = got_object_id_str(&commit_id_str, commit_id);
6259 if (error)
6260 goto done;
6261 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6262 worktree);
6263 if (error)
6264 goto done;
6265 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6266 == -1) {
6267 error = got_error_from_errno("asprintf");
6268 goto done;
6270 error = got_ref_open(&ref, repo, branch_refname, 0);
6271 free(branch_refname);
6272 if (error)
6273 goto done;
6274 error = switch_head_ref(ref, commit_id, worktree,
6275 repo);
6276 if (error)
6277 goto done;
6278 error = got_worktree_set_base_commit_id(worktree, repo,
6279 commit_id);
6280 if (error)
6281 goto done;
6282 memset(&upa, 0, sizeof(upa));
6283 error = got_worktree_checkout_files(worktree, &paths,
6284 repo, update_progress, &upa, check_cancelled,
6285 NULL);
6286 if (error)
6287 goto done;
6288 if (upa.did_something) {
6289 printf("Updated to %s: %s\n",
6290 got_worktree_get_head_ref_name(worktree),
6291 commit_id_str);
6293 print_update_progress_stats(&upa);
6296 done:
6297 if (ref)
6298 got_ref_close(ref);
6299 if (repo) {
6300 const struct got_error *close_err = got_repo_close(repo);
6301 if (error == NULL)
6302 error = close_err;
6304 if (worktree)
6305 got_worktree_close(worktree);
6306 free(cwd);
6307 free(repo_path);
6308 free(commit_id);
6309 free(commit_id_str);
6310 TAILQ_FOREACH(pe, &paths, entry)
6311 free((char *)pe->path);
6312 got_pathlist_free(&paths);
6313 return error;
6317 __dead static void
6318 usage_tag(void)
6320 fprintf(stderr,
6321 "usage: %s tag [-c commit] [-r repository] [-l] "
6322 "[-m message] name\n", getprogname());
6323 exit(1);
6326 #if 0
6327 static const struct got_error *
6328 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6330 const struct got_error *err = NULL;
6331 struct got_reflist_entry *re, *se, *new;
6332 struct got_object_id *re_id, *se_id;
6333 struct got_tag_object *re_tag, *se_tag;
6334 time_t re_time, se_time;
6336 STAILQ_FOREACH(re, tags, entry) {
6337 se = STAILQ_FIRST(sorted);
6338 if (se == NULL) {
6339 err = got_reflist_entry_dup(&new, re);
6340 if (err)
6341 return err;
6342 STAILQ_INSERT_HEAD(sorted, new, entry);
6343 continue;
6344 } else {
6345 err = got_ref_resolve(&re_id, repo, re->ref);
6346 if (err)
6347 break;
6348 err = got_object_open_as_tag(&re_tag, repo, re_id);
6349 free(re_id);
6350 if (err)
6351 break;
6352 re_time = got_object_tag_get_tagger_time(re_tag);
6353 got_object_tag_close(re_tag);
6356 while (se) {
6357 err = got_ref_resolve(&se_id, repo, re->ref);
6358 if (err)
6359 break;
6360 err = got_object_open_as_tag(&se_tag, repo, se_id);
6361 free(se_id);
6362 if (err)
6363 break;
6364 se_time = got_object_tag_get_tagger_time(se_tag);
6365 got_object_tag_close(se_tag);
6367 if (se_time > re_time) {
6368 err = got_reflist_entry_dup(&new, re);
6369 if (err)
6370 return err;
6371 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6372 break;
6374 se = STAILQ_NEXT(se, entry);
6375 continue;
6378 done:
6379 return err;
6381 #endif
6383 static const struct got_error *
6384 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6386 static const struct got_error *err = NULL;
6387 struct got_reflist_head refs;
6388 struct got_reflist_entry *re;
6390 TAILQ_INIT(&refs);
6392 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6393 if (err)
6394 return err;
6396 TAILQ_FOREACH(re, &refs, entry) {
6397 const char *refname;
6398 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6399 char datebuf[26];
6400 const char *tagger;
6401 time_t tagger_time;
6402 struct got_object_id *id;
6403 struct got_tag_object *tag;
6404 struct got_commit_object *commit = NULL;
6406 refname = got_ref_get_name(re->ref);
6407 if (strncmp(refname, "refs/tags/", 10) != 0)
6408 continue;
6409 refname += 10;
6410 refstr = got_ref_to_str(re->ref);
6411 if (refstr == NULL) {
6412 err = got_error_from_errno("got_ref_to_str");
6413 break;
6415 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6416 free(refstr);
6418 err = got_ref_resolve(&id, repo, re->ref);
6419 if (err)
6420 break;
6421 err = got_object_open_as_tag(&tag, repo, id);
6422 if (err) {
6423 if (err->code != GOT_ERR_OBJ_TYPE) {
6424 free(id);
6425 break;
6427 /* "lightweight" tag */
6428 err = got_object_open_as_commit(&commit, repo, id);
6429 if (err) {
6430 free(id);
6431 break;
6433 tagger = got_object_commit_get_committer(commit);
6434 tagger_time =
6435 got_object_commit_get_committer_time(commit);
6436 err = got_object_id_str(&id_str, id);
6437 free(id);
6438 if (err)
6439 break;
6440 } else {
6441 free(id);
6442 tagger = got_object_tag_get_tagger(tag);
6443 tagger_time = got_object_tag_get_tagger_time(tag);
6444 err = got_object_id_str(&id_str,
6445 got_object_tag_get_object_id(tag));
6446 if (err)
6447 break;
6449 printf("from: %s\n", tagger);
6450 datestr = get_datestr(&tagger_time, datebuf);
6451 if (datestr)
6452 printf("date: %s UTC\n", datestr);
6453 if (commit)
6454 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6455 else {
6456 switch (got_object_tag_get_object_type(tag)) {
6457 case GOT_OBJ_TYPE_BLOB:
6458 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6459 id_str);
6460 break;
6461 case GOT_OBJ_TYPE_TREE:
6462 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6463 id_str);
6464 break;
6465 case GOT_OBJ_TYPE_COMMIT:
6466 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6467 id_str);
6468 break;
6469 case GOT_OBJ_TYPE_TAG:
6470 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6471 id_str);
6472 break;
6473 default:
6474 break;
6477 free(id_str);
6478 if (commit) {
6479 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6480 if (err)
6481 break;
6482 got_object_commit_close(commit);
6483 } else {
6484 tagmsg0 = strdup(got_object_tag_get_message(tag));
6485 got_object_tag_close(tag);
6486 if (tagmsg0 == NULL) {
6487 err = got_error_from_errno("strdup");
6488 break;
6492 tagmsg = tagmsg0;
6493 do {
6494 line = strsep(&tagmsg, "\n");
6495 if (line)
6496 printf(" %s\n", line);
6497 } while (line);
6498 free(tagmsg0);
6501 got_ref_list_free(&refs);
6502 return NULL;
6505 static const struct got_error *
6506 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6507 const char *tag_name, const char *repo_path)
6509 const struct got_error *err = NULL;
6510 char *template = NULL, *initial_content = NULL;
6511 char *editor = NULL;
6512 int initial_content_len;
6513 int fd = -1;
6515 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6516 err = got_error_from_errno("asprintf");
6517 goto done;
6520 initial_content_len = asprintf(&initial_content,
6521 "\n# tagging commit %s as %s\n",
6522 commit_id_str, tag_name);
6523 if (initial_content_len == -1) {
6524 err = got_error_from_errno("asprintf");
6525 goto done;
6528 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6529 if (err)
6530 goto done;
6532 if (write(fd, initial_content, initial_content_len) == -1) {
6533 err = got_error_from_errno2("write", *tagmsg_path);
6534 goto done;
6537 err = get_editor(&editor);
6538 if (err)
6539 goto done;
6540 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6541 initial_content_len, 1);
6542 done:
6543 free(initial_content);
6544 free(template);
6545 free(editor);
6547 if (fd != -1 && close(fd) == -1 && err == NULL)
6548 err = got_error_from_errno2("close", *tagmsg_path);
6550 /* Editor is done; we can now apply unveil(2) */
6551 if (err == NULL)
6552 err = apply_unveil(repo_path, 0, NULL);
6553 if (err) {
6554 free(*tagmsg);
6555 *tagmsg = NULL;
6557 return err;
6560 static const struct got_error *
6561 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6562 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6564 const struct got_error *err = NULL;
6565 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6566 char *label = NULL, *commit_id_str = NULL;
6567 struct got_reference *ref = NULL;
6568 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6569 char *tagmsg_path = NULL, *tag_id_str = NULL;
6570 int preserve_tagmsg = 0;
6571 struct got_reflist_head refs;
6573 TAILQ_INIT(&refs);
6576 * Don't let the user create a tag name with a leading '-'.
6577 * While technically a valid reference name, this case is usually
6578 * an unintended typo.
6580 if (tag_name[0] == '-')
6581 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6583 err = get_author(&tagger, repo, worktree);
6584 if (err)
6585 return err;
6587 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6588 if (err)
6589 goto done;
6591 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6592 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6593 if (err)
6594 goto done;
6596 err = got_object_id_str(&commit_id_str, commit_id);
6597 if (err)
6598 goto done;
6600 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6601 refname = strdup(tag_name);
6602 if (refname == NULL) {
6603 err = got_error_from_errno("strdup");
6604 goto done;
6606 tag_name += 10;
6607 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6608 err = got_error_from_errno("asprintf");
6609 goto done;
6612 err = got_ref_open(&ref, repo, refname, 0);
6613 if (err == NULL) {
6614 err = got_error(GOT_ERR_TAG_EXISTS);
6615 goto done;
6616 } else if (err->code != GOT_ERR_NOT_REF)
6617 goto done;
6619 if (tagmsg_arg == NULL) {
6620 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6621 tag_name, got_repo_get_path(repo));
6622 if (err) {
6623 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6624 tagmsg_path != NULL)
6625 preserve_tagmsg = 1;
6626 goto done;
6630 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6631 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6632 if (err) {
6633 if (tagmsg_path)
6634 preserve_tagmsg = 1;
6635 goto done;
6638 err = got_ref_alloc(&ref, refname, tag_id);
6639 if (err) {
6640 if (tagmsg_path)
6641 preserve_tagmsg = 1;
6642 goto done;
6645 err = got_ref_write(ref, repo);
6646 if (err) {
6647 if (tagmsg_path)
6648 preserve_tagmsg = 1;
6649 goto done;
6652 err = got_object_id_str(&tag_id_str, tag_id);
6653 if (err) {
6654 if (tagmsg_path)
6655 preserve_tagmsg = 1;
6656 goto done;
6658 printf("Created tag %s\n", tag_id_str);
6659 done:
6660 if (preserve_tagmsg) {
6661 fprintf(stderr, "%s: tag message preserved in %s\n",
6662 getprogname(), tagmsg_path);
6663 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6664 err = got_error_from_errno2("unlink", tagmsg_path);
6665 free(tag_id_str);
6666 if (ref)
6667 got_ref_close(ref);
6668 free(commit_id);
6669 free(commit_id_str);
6670 free(refname);
6671 free(tagmsg);
6672 free(tagmsg_path);
6673 free(tagger);
6674 got_ref_list_free(&refs);
6675 return err;
6678 static const struct got_error *
6679 cmd_tag(int argc, char *argv[])
6681 const struct got_error *error = NULL;
6682 struct got_repository *repo = NULL;
6683 struct got_worktree *worktree = NULL;
6684 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6685 char *gitconfig_path = NULL;
6686 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6687 int ch, do_list = 0;
6689 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6690 switch (ch) {
6691 case 'c':
6692 commit_id_arg = optarg;
6693 break;
6694 case 'm':
6695 tagmsg = optarg;
6696 break;
6697 case 'r':
6698 repo_path = realpath(optarg, NULL);
6699 if (repo_path == NULL)
6700 return got_error_from_errno2("realpath",
6701 optarg);
6702 got_path_strip_trailing_slashes(repo_path);
6703 break;
6704 case 'l':
6705 do_list = 1;
6706 break;
6707 default:
6708 usage_tag();
6709 /* NOTREACHED */
6713 argc -= optind;
6714 argv += optind;
6716 if (do_list) {
6717 if (commit_id_arg != NULL)
6718 errx(1,
6719 "-c option can only be used when creating a tag");
6720 if (tagmsg)
6721 option_conflict('l', 'm');
6722 if (argc > 0)
6723 usage_tag();
6724 } else if (argc != 1)
6725 usage_tag();
6727 tag_name = argv[0];
6729 #ifndef PROFILE
6730 if (do_list) {
6731 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6732 NULL) == -1)
6733 err(1, "pledge");
6734 } else {
6735 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6736 "sendfd unveil", NULL) == -1)
6737 err(1, "pledge");
6739 #endif
6740 cwd = getcwd(NULL, 0);
6741 if (cwd == NULL) {
6742 error = got_error_from_errno("getcwd");
6743 goto done;
6746 if (repo_path == NULL) {
6747 error = got_worktree_open(&worktree, cwd);
6748 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6749 goto done;
6750 else
6751 error = NULL;
6752 if (worktree) {
6753 repo_path =
6754 strdup(got_worktree_get_repo_path(worktree));
6755 if (repo_path == NULL)
6756 error = got_error_from_errno("strdup");
6757 if (error)
6758 goto done;
6759 } else {
6760 repo_path = strdup(cwd);
6761 if (repo_path == NULL) {
6762 error = got_error_from_errno("strdup");
6763 goto done;
6768 if (do_list) {
6769 error = got_repo_open(&repo, repo_path, NULL);
6770 if (error != NULL)
6771 goto done;
6772 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6773 if (error)
6774 goto done;
6775 error = list_tags(repo, worktree);
6776 } else {
6777 error = get_gitconfig_path(&gitconfig_path);
6778 if (error)
6779 goto done;
6780 error = got_repo_open(&repo, repo_path, gitconfig_path);
6781 if (error != NULL)
6782 goto done;
6784 if (tagmsg) {
6785 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6786 if (error)
6787 goto done;
6790 if (commit_id_arg == NULL) {
6791 struct got_reference *head_ref;
6792 struct got_object_id *commit_id;
6793 error = got_ref_open(&head_ref, repo,
6794 worktree ? got_worktree_get_head_ref_name(worktree)
6795 : GOT_REF_HEAD, 0);
6796 if (error)
6797 goto done;
6798 error = got_ref_resolve(&commit_id, repo, head_ref);
6799 got_ref_close(head_ref);
6800 if (error)
6801 goto done;
6802 error = got_object_id_str(&commit_id_str, commit_id);
6803 free(commit_id);
6804 if (error)
6805 goto done;
6808 error = add_tag(repo, worktree, tag_name,
6809 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6811 done:
6812 if (repo) {
6813 const struct got_error *close_err = got_repo_close(repo);
6814 if (error == NULL)
6815 error = close_err;
6817 if (worktree)
6818 got_worktree_close(worktree);
6819 free(cwd);
6820 free(repo_path);
6821 free(gitconfig_path);
6822 free(commit_id_str);
6823 return error;
6826 __dead static void
6827 usage_add(void)
6829 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6830 getprogname());
6831 exit(1);
6834 static const struct got_error *
6835 add_progress(void *arg, unsigned char status, const char *path)
6837 while (path[0] == '/')
6838 path++;
6839 printf("%c %s\n", status, path);
6840 return NULL;
6843 static const struct got_error *
6844 cmd_add(int argc, char *argv[])
6846 const struct got_error *error = NULL;
6847 struct got_repository *repo = NULL;
6848 struct got_worktree *worktree = NULL;
6849 char *cwd = NULL;
6850 struct got_pathlist_head paths;
6851 struct got_pathlist_entry *pe;
6852 int ch, can_recurse = 0, no_ignores = 0;
6854 TAILQ_INIT(&paths);
6856 while ((ch = getopt(argc, argv, "IR")) != -1) {
6857 switch (ch) {
6858 case 'I':
6859 no_ignores = 1;
6860 break;
6861 case 'R':
6862 can_recurse = 1;
6863 break;
6864 default:
6865 usage_add();
6866 /* NOTREACHED */
6870 argc -= optind;
6871 argv += optind;
6873 #ifndef PROFILE
6874 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6875 NULL) == -1)
6876 err(1, "pledge");
6877 #endif
6878 if (argc < 1)
6879 usage_add();
6881 cwd = getcwd(NULL, 0);
6882 if (cwd == NULL) {
6883 error = got_error_from_errno("getcwd");
6884 goto done;
6887 error = got_worktree_open(&worktree, cwd);
6888 if (error) {
6889 if (error->code == GOT_ERR_NOT_WORKTREE)
6890 error = wrap_not_worktree_error(error, "add", cwd);
6891 goto done;
6894 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6895 NULL);
6896 if (error != NULL)
6897 goto done;
6899 error = apply_unveil(got_repo_get_path(repo), 1,
6900 got_worktree_get_root_path(worktree));
6901 if (error)
6902 goto done;
6904 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6905 if (error)
6906 goto done;
6908 if (!can_recurse) {
6909 char *ondisk_path;
6910 struct stat sb;
6911 TAILQ_FOREACH(pe, &paths, entry) {
6912 if (asprintf(&ondisk_path, "%s/%s",
6913 got_worktree_get_root_path(worktree),
6914 pe->path) == -1) {
6915 error = got_error_from_errno("asprintf");
6916 goto done;
6918 if (lstat(ondisk_path, &sb) == -1) {
6919 if (errno == ENOENT) {
6920 free(ondisk_path);
6921 continue;
6923 error = got_error_from_errno2("lstat",
6924 ondisk_path);
6925 free(ondisk_path);
6926 goto done;
6928 free(ondisk_path);
6929 if (S_ISDIR(sb.st_mode)) {
6930 error = got_error_msg(GOT_ERR_BAD_PATH,
6931 "adding directories requires -R option");
6932 goto done;
6937 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6938 NULL, repo, no_ignores);
6939 done:
6940 if (repo) {
6941 const struct got_error *close_err = got_repo_close(repo);
6942 if (error == NULL)
6943 error = close_err;
6945 if (worktree)
6946 got_worktree_close(worktree);
6947 TAILQ_FOREACH(pe, &paths, entry)
6948 free((char *)pe->path);
6949 got_pathlist_free(&paths);
6950 free(cwd);
6951 return error;
6954 __dead static void
6955 usage_remove(void)
6957 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6958 "path ...\n", getprogname());
6959 exit(1);
6962 static const struct got_error *
6963 print_remove_status(void *arg, unsigned char status,
6964 unsigned char staged_status, const char *path)
6966 while (path[0] == '/')
6967 path++;
6968 if (status == GOT_STATUS_NONEXISTENT)
6969 return NULL;
6970 if (status == staged_status && (status == GOT_STATUS_DELETE))
6971 status = GOT_STATUS_NO_CHANGE;
6972 printf("%c%c %s\n", status, staged_status, path);
6973 return NULL;
6976 static const struct got_error *
6977 cmd_remove(int argc, char *argv[])
6979 const struct got_error *error = NULL;
6980 struct got_worktree *worktree = NULL;
6981 struct got_repository *repo = NULL;
6982 const char *status_codes = NULL;
6983 char *cwd = NULL;
6984 struct got_pathlist_head paths;
6985 struct got_pathlist_entry *pe;
6986 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6987 int ignore_missing_paths = 0;
6989 TAILQ_INIT(&paths);
6991 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6992 switch (ch) {
6993 case 'f':
6994 delete_local_mods = 1;
6995 ignore_missing_paths = 1;
6996 break;
6997 case 'k':
6998 keep_on_disk = 1;
6999 break;
7000 case 'R':
7001 can_recurse = 1;
7002 break;
7003 case 's':
7004 for (i = 0; i < strlen(optarg); i++) {
7005 switch (optarg[i]) {
7006 case GOT_STATUS_MODIFY:
7007 delete_local_mods = 1;
7008 break;
7009 case GOT_STATUS_MISSING:
7010 ignore_missing_paths = 1;
7011 break;
7012 default:
7013 errx(1, "invalid status code '%c'",
7014 optarg[i]);
7017 status_codes = optarg;
7018 break;
7019 default:
7020 usage_remove();
7021 /* NOTREACHED */
7025 argc -= optind;
7026 argv += optind;
7028 #ifndef PROFILE
7029 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7030 NULL) == -1)
7031 err(1, "pledge");
7032 #endif
7033 if (argc < 1)
7034 usage_remove();
7036 cwd = getcwd(NULL, 0);
7037 if (cwd == NULL) {
7038 error = got_error_from_errno("getcwd");
7039 goto done;
7041 error = got_worktree_open(&worktree, cwd);
7042 if (error) {
7043 if (error->code == GOT_ERR_NOT_WORKTREE)
7044 error = wrap_not_worktree_error(error, "remove", cwd);
7045 goto done;
7048 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7049 NULL);
7050 if (error)
7051 goto done;
7053 error = apply_unveil(got_repo_get_path(repo), 1,
7054 got_worktree_get_root_path(worktree));
7055 if (error)
7056 goto done;
7058 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7059 if (error)
7060 goto done;
7062 if (!can_recurse) {
7063 char *ondisk_path;
7064 struct stat sb;
7065 TAILQ_FOREACH(pe, &paths, entry) {
7066 if (asprintf(&ondisk_path, "%s/%s",
7067 got_worktree_get_root_path(worktree),
7068 pe->path) == -1) {
7069 error = got_error_from_errno("asprintf");
7070 goto done;
7072 if (lstat(ondisk_path, &sb) == -1) {
7073 if (errno == ENOENT) {
7074 free(ondisk_path);
7075 continue;
7077 error = got_error_from_errno2("lstat",
7078 ondisk_path);
7079 free(ondisk_path);
7080 goto done;
7082 free(ondisk_path);
7083 if (S_ISDIR(sb.st_mode)) {
7084 error = got_error_msg(GOT_ERR_BAD_PATH,
7085 "removing directories requires -R option");
7086 goto done;
7091 error = got_worktree_schedule_delete(worktree, &paths,
7092 delete_local_mods, status_codes, print_remove_status, NULL,
7093 repo, keep_on_disk, ignore_missing_paths);
7094 done:
7095 if (repo) {
7096 const struct got_error *close_err = got_repo_close(repo);
7097 if (error == NULL)
7098 error = close_err;
7100 if (worktree)
7101 got_worktree_close(worktree);
7102 TAILQ_FOREACH(pe, &paths, entry)
7103 free((char *)pe->path);
7104 got_pathlist_free(&paths);
7105 free(cwd);
7106 return error;
7109 __dead static void
7110 usage_revert(void)
7112 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7113 "path ...\n", getprogname());
7114 exit(1);
7117 static const struct got_error *
7118 revert_progress(void *arg, unsigned char status, const char *path)
7120 if (status == GOT_STATUS_UNVERSIONED)
7121 return NULL;
7123 while (path[0] == '/')
7124 path++;
7125 printf("%c %s\n", status, path);
7126 return NULL;
7129 struct choose_patch_arg {
7130 FILE *patch_script_file;
7131 const char *action;
7134 static const struct got_error *
7135 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7136 int nchanges, const char *action)
7138 char *line = NULL;
7139 size_t linesize = 0;
7140 ssize_t linelen;
7142 switch (status) {
7143 case GOT_STATUS_ADD:
7144 printf("A %s\n%s this addition? [y/n] ", path, action);
7145 break;
7146 case GOT_STATUS_DELETE:
7147 printf("D %s\n%s this deletion? [y/n] ", path, action);
7148 break;
7149 case GOT_STATUS_MODIFY:
7150 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7151 return got_error_from_errno("fseek");
7152 printf(GOT_COMMIT_SEP_STR);
7153 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7154 printf("%s", line);
7155 if (ferror(patch_file))
7156 return got_error_from_errno("getline");
7157 printf(GOT_COMMIT_SEP_STR);
7158 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7159 path, n, nchanges, action);
7160 break;
7161 default:
7162 return got_error_path(path, GOT_ERR_FILE_STATUS);
7165 return NULL;
7168 static const struct got_error *
7169 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7170 FILE *patch_file, int n, int nchanges)
7172 const struct got_error *err = NULL;
7173 char *line = NULL;
7174 size_t linesize = 0;
7175 ssize_t linelen;
7176 int resp = ' ';
7177 struct choose_patch_arg *a = arg;
7179 *choice = GOT_PATCH_CHOICE_NONE;
7181 if (a->patch_script_file) {
7182 char *nl;
7183 err = show_change(status, path, patch_file, n, nchanges,
7184 a->action);
7185 if (err)
7186 return err;
7187 linelen = getline(&line, &linesize, a->patch_script_file);
7188 if (linelen == -1) {
7189 if (ferror(a->patch_script_file))
7190 return got_error_from_errno("getline");
7191 return NULL;
7193 nl = strchr(line, '\n');
7194 if (nl)
7195 *nl = '\0';
7196 if (strcmp(line, "y") == 0) {
7197 *choice = GOT_PATCH_CHOICE_YES;
7198 printf("y\n");
7199 } else if (strcmp(line, "n") == 0) {
7200 *choice = GOT_PATCH_CHOICE_NO;
7201 printf("n\n");
7202 } else if (strcmp(line, "q") == 0 &&
7203 status == GOT_STATUS_MODIFY) {
7204 *choice = GOT_PATCH_CHOICE_QUIT;
7205 printf("q\n");
7206 } else
7207 printf("invalid response '%s'\n", line);
7208 free(line);
7209 return NULL;
7212 while (resp != 'y' && resp != 'n' && resp != 'q') {
7213 err = show_change(status, path, patch_file, n, nchanges,
7214 a->action);
7215 if (err)
7216 return err;
7217 resp = getchar();
7218 if (resp == '\n')
7219 resp = getchar();
7220 if (status == GOT_STATUS_MODIFY) {
7221 if (resp != 'y' && resp != 'n' && resp != 'q') {
7222 printf("invalid response '%c'\n", resp);
7223 resp = ' ';
7225 } else if (resp != 'y' && resp != 'n') {
7226 printf("invalid response '%c'\n", resp);
7227 resp = ' ';
7231 if (resp == 'y')
7232 *choice = GOT_PATCH_CHOICE_YES;
7233 else if (resp == 'n')
7234 *choice = GOT_PATCH_CHOICE_NO;
7235 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7236 *choice = GOT_PATCH_CHOICE_QUIT;
7238 return NULL;
7242 static const struct got_error *
7243 cmd_revert(int argc, char *argv[])
7245 const struct got_error *error = NULL;
7246 struct got_worktree *worktree = NULL;
7247 struct got_repository *repo = NULL;
7248 char *cwd = NULL, *path = NULL;
7249 struct got_pathlist_head paths;
7250 struct got_pathlist_entry *pe;
7251 int ch, can_recurse = 0, pflag = 0;
7252 FILE *patch_script_file = NULL;
7253 const char *patch_script_path = NULL;
7254 struct choose_patch_arg cpa;
7256 TAILQ_INIT(&paths);
7258 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7259 switch (ch) {
7260 case 'p':
7261 pflag = 1;
7262 break;
7263 case 'F':
7264 patch_script_path = optarg;
7265 break;
7266 case 'R':
7267 can_recurse = 1;
7268 break;
7269 default:
7270 usage_revert();
7271 /* NOTREACHED */
7275 argc -= optind;
7276 argv += optind;
7278 #ifndef PROFILE
7279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7280 "unveil", NULL) == -1)
7281 err(1, "pledge");
7282 #endif
7283 if (argc < 1)
7284 usage_revert();
7285 if (patch_script_path && !pflag)
7286 errx(1, "-F option can only be used together with -p option");
7288 cwd = getcwd(NULL, 0);
7289 if (cwd == NULL) {
7290 error = got_error_from_errno("getcwd");
7291 goto done;
7293 error = got_worktree_open(&worktree, cwd);
7294 if (error) {
7295 if (error->code == GOT_ERR_NOT_WORKTREE)
7296 error = wrap_not_worktree_error(error, "revert", cwd);
7297 goto done;
7300 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7301 NULL);
7302 if (error != NULL)
7303 goto done;
7305 if (patch_script_path) {
7306 patch_script_file = fopen(patch_script_path, "re");
7307 if (patch_script_file == NULL) {
7308 error = got_error_from_errno2("fopen",
7309 patch_script_path);
7310 goto done;
7313 error = apply_unveil(got_repo_get_path(repo), 1,
7314 got_worktree_get_root_path(worktree));
7315 if (error)
7316 goto done;
7318 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7319 if (error)
7320 goto done;
7322 if (!can_recurse) {
7323 char *ondisk_path;
7324 struct stat sb;
7325 TAILQ_FOREACH(pe, &paths, entry) {
7326 if (asprintf(&ondisk_path, "%s/%s",
7327 got_worktree_get_root_path(worktree),
7328 pe->path) == -1) {
7329 error = got_error_from_errno("asprintf");
7330 goto done;
7332 if (lstat(ondisk_path, &sb) == -1) {
7333 if (errno == ENOENT) {
7334 free(ondisk_path);
7335 continue;
7337 error = got_error_from_errno2("lstat",
7338 ondisk_path);
7339 free(ondisk_path);
7340 goto done;
7342 free(ondisk_path);
7343 if (S_ISDIR(sb.st_mode)) {
7344 error = got_error_msg(GOT_ERR_BAD_PATH,
7345 "reverting directories requires -R option");
7346 goto done;
7351 cpa.patch_script_file = patch_script_file;
7352 cpa.action = "revert";
7353 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7354 pflag ? choose_patch : NULL, &cpa, repo);
7355 done:
7356 if (patch_script_file && fclose(patch_script_file) == EOF &&
7357 error == NULL)
7358 error = got_error_from_errno2("fclose", patch_script_path);
7359 if (repo) {
7360 const struct got_error *close_err = got_repo_close(repo);
7361 if (error == NULL)
7362 error = close_err;
7364 if (worktree)
7365 got_worktree_close(worktree);
7366 free(path);
7367 free(cwd);
7368 return error;
7371 __dead static void
7372 usage_commit(void)
7374 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7375 "[path ...]\n", getprogname());
7376 exit(1);
7379 struct collect_commit_logmsg_arg {
7380 const char *cmdline_log;
7381 const char *prepared_log;
7382 int non_interactive;
7383 const char *editor;
7384 const char *worktree_path;
7385 const char *branch_name;
7386 const char *repo_path;
7387 char *logmsg_path;
7391 static const struct got_error *
7392 read_prepared_logmsg(char **logmsg, const char *path)
7394 const struct got_error *err = NULL;
7395 FILE *f = NULL;
7396 struct stat sb;
7397 size_t r;
7399 *logmsg = NULL;
7400 memset(&sb, 0, sizeof(sb));
7402 f = fopen(path, "re");
7403 if (f == NULL)
7404 return got_error_from_errno2("fopen", path);
7406 if (fstat(fileno(f), &sb) == -1) {
7407 err = got_error_from_errno2("fstat", path);
7408 goto done;
7410 if (sb.st_size == 0) {
7411 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7412 goto done;
7415 *logmsg = malloc(sb.st_size + 1);
7416 if (*logmsg == NULL) {
7417 err = got_error_from_errno("malloc");
7418 goto done;
7421 r = fread(*logmsg, 1, sb.st_size, f);
7422 if (r != sb.st_size) {
7423 if (ferror(f))
7424 err = got_error_from_errno2("fread", path);
7425 else
7426 err = got_error(GOT_ERR_IO);
7427 goto done;
7429 (*logmsg)[sb.st_size] = '\0';
7430 done:
7431 if (fclose(f) == EOF && err == NULL)
7432 err = got_error_from_errno2("fclose", path);
7433 if (err) {
7434 free(*logmsg);
7435 *logmsg = NULL;
7437 return err;
7441 static const struct got_error *
7442 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7443 void *arg)
7445 char *initial_content = NULL;
7446 struct got_pathlist_entry *pe;
7447 const struct got_error *err = NULL;
7448 char *template = NULL;
7449 struct collect_commit_logmsg_arg *a = arg;
7450 int initial_content_len;
7451 int fd = -1;
7452 size_t len;
7454 /* if a message was specified on the command line, just use it */
7455 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7456 len = strlen(a->cmdline_log) + 1;
7457 *logmsg = malloc(len + 1);
7458 if (*logmsg == NULL)
7459 return got_error_from_errno("malloc");
7460 strlcpy(*logmsg, a->cmdline_log, len);
7461 return NULL;
7462 } else if (a->prepared_log != NULL && a->non_interactive)
7463 return read_prepared_logmsg(logmsg, a->prepared_log);
7465 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7466 return got_error_from_errno("asprintf");
7468 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7469 if (err)
7470 goto done;
7472 if (a->prepared_log) {
7473 char *msg;
7474 err = read_prepared_logmsg(&msg, a->prepared_log);
7475 if (err)
7476 goto done;
7477 if (write(fd, msg, strlen(msg)) == -1) {
7478 err = got_error_from_errno2("write", a->logmsg_path);
7479 free(msg);
7480 goto done;
7482 free(msg);
7485 initial_content_len = asprintf(&initial_content,
7486 "\n# changes to be committed on branch %s:\n",
7487 a->branch_name);
7488 if (initial_content_len == -1) {
7489 err = got_error_from_errno("asprintf");
7490 goto done;
7493 if (write(fd, initial_content, initial_content_len) == -1) {
7494 err = got_error_from_errno2("write", a->logmsg_path);
7495 goto done;
7498 TAILQ_FOREACH(pe, commitable_paths, entry) {
7499 struct got_commitable *ct = pe->data;
7500 dprintf(fd, "# %c %s\n",
7501 got_commitable_get_status(ct),
7502 got_commitable_get_path(ct));
7505 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7506 initial_content_len, a->prepared_log ? 0 : 1);
7507 done:
7508 free(initial_content);
7509 free(template);
7511 if (fd != -1 && close(fd) == -1 && err == NULL)
7512 err = got_error_from_errno2("close", a->logmsg_path);
7514 /* Editor is done; we can now apply unveil(2) */
7515 if (err == NULL)
7516 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7517 if (err) {
7518 free(*logmsg);
7519 *logmsg = NULL;
7521 return err;
7524 static const struct got_error *
7525 cmd_commit(int argc, char *argv[])
7527 const struct got_error *error = NULL;
7528 struct got_worktree *worktree = NULL;
7529 struct got_repository *repo = NULL;
7530 char *cwd = NULL, *id_str = NULL;
7531 struct got_object_id *id = NULL;
7532 const char *logmsg = NULL;
7533 char *prepared_logmsg = NULL;
7534 struct collect_commit_logmsg_arg cl_arg;
7535 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7536 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7537 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7538 struct got_pathlist_head paths;
7540 TAILQ_INIT(&paths);
7541 cl_arg.logmsg_path = NULL;
7543 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7544 switch (ch) {
7545 case 'F':
7546 if (logmsg != NULL)
7547 option_conflict('F', 'm');
7548 prepared_logmsg = realpath(optarg, NULL);
7549 if (prepared_logmsg == NULL)
7550 return got_error_from_errno2("realpath",
7551 optarg);
7552 break;
7553 case 'm':
7554 if (prepared_logmsg)
7555 option_conflict('m', 'F');
7556 logmsg = optarg;
7557 break;
7558 case 'N':
7559 non_interactive = 1;
7560 break;
7561 case 'S':
7562 allow_bad_symlinks = 1;
7563 break;
7564 default:
7565 usage_commit();
7566 /* NOTREACHED */
7570 argc -= optind;
7571 argv += optind;
7573 #ifndef PROFILE
7574 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7575 "unveil", NULL) == -1)
7576 err(1, "pledge");
7577 #endif
7578 cwd = getcwd(NULL, 0);
7579 if (cwd == NULL) {
7580 error = got_error_from_errno("getcwd");
7581 goto done;
7583 error = got_worktree_open(&worktree, cwd);
7584 if (error) {
7585 if (error->code == GOT_ERR_NOT_WORKTREE)
7586 error = wrap_not_worktree_error(error, "commit", cwd);
7587 goto done;
7590 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7591 if (error)
7592 goto done;
7593 if (rebase_in_progress) {
7594 error = got_error(GOT_ERR_REBASING);
7595 goto done;
7598 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7599 worktree);
7600 if (error)
7601 goto done;
7603 error = get_gitconfig_path(&gitconfig_path);
7604 if (error)
7605 goto done;
7606 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7607 gitconfig_path);
7608 if (error != NULL)
7609 goto done;
7611 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7612 if (error)
7613 goto done;
7614 if (merge_in_progress) {
7615 error = got_error(GOT_ERR_MERGE_BUSY);
7616 goto done;
7619 error = get_author(&author, repo, worktree);
7620 if (error)
7621 return error;
7624 * unveil(2) traverses exec(2); if an editor is used we have
7625 * to apply unveil after the log message has been written.
7627 if (logmsg == NULL || strlen(logmsg) == 0)
7628 error = get_editor(&editor);
7629 else
7630 error = apply_unveil(got_repo_get_path(repo), 0,
7631 got_worktree_get_root_path(worktree));
7632 if (error)
7633 goto done;
7635 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7636 if (error)
7637 goto done;
7639 cl_arg.editor = editor;
7640 cl_arg.cmdline_log = logmsg;
7641 cl_arg.prepared_log = prepared_logmsg;
7642 cl_arg.non_interactive = non_interactive;
7643 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7644 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7645 if (!histedit_in_progress) {
7646 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7647 error = got_error(GOT_ERR_COMMIT_BRANCH);
7648 goto done;
7650 cl_arg.branch_name += 11;
7652 cl_arg.repo_path = got_repo_get_path(repo);
7653 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7654 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7655 print_status, NULL, repo);
7656 if (error) {
7657 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7658 cl_arg.logmsg_path != NULL)
7659 preserve_logmsg = 1;
7660 goto done;
7663 error = got_object_id_str(&id_str, id);
7664 if (error)
7665 goto done;
7666 printf("Created commit %s\n", id_str);
7667 done:
7668 if (preserve_logmsg) {
7669 fprintf(stderr, "%s: log message preserved in %s\n",
7670 getprogname(), cl_arg.logmsg_path);
7671 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7672 error == NULL)
7673 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7674 free(cl_arg.logmsg_path);
7675 if (repo) {
7676 const struct got_error *close_err = got_repo_close(repo);
7677 if (error == NULL)
7678 error = close_err;
7680 if (worktree)
7681 got_worktree_close(worktree);
7682 free(cwd);
7683 free(id_str);
7684 free(gitconfig_path);
7685 free(editor);
7686 free(author);
7687 free(prepared_logmsg);
7688 return error;
7691 __dead static void
7692 usage_send(void)
7694 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7695 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7696 "[remote-repository]\n", getprogname());
7697 exit(1);
7700 struct got_send_progress_arg {
7701 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7702 int verbosity;
7703 int last_ncommits;
7704 int last_nobj_total;
7705 int last_p_deltify;
7706 int last_p_written;
7707 int last_p_sent;
7708 int printed_something;
7709 int sent_something;
7710 struct got_pathlist_head *delete_branches;
7713 static const struct got_error *
7714 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7715 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7716 int success)
7718 struct got_send_progress_arg *a = arg;
7719 char scaled_packsize[FMT_SCALED_STRSIZE];
7720 char scaled_sent[FMT_SCALED_STRSIZE];
7721 int p_deltify = 0, p_written = 0, p_sent = 0;
7722 int print_searching = 0, print_total = 0;
7723 int print_deltify = 0, print_written = 0, print_sent = 0;
7725 if (a->verbosity < 0)
7726 return NULL;
7728 if (refname) {
7729 const char *status = success ? "accepted" : "rejected";
7731 if (success) {
7732 struct got_pathlist_entry *pe;
7733 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7734 const char *branchname = pe->path;
7735 if (got_path_cmp(branchname, refname,
7736 strlen(branchname), strlen(refname)) == 0) {
7737 status = "deleted";
7738 a->sent_something = 1;
7739 break;
7744 if (a->printed_something)
7745 putchar('\n');
7746 printf("Server has %s %s", status, refname);
7747 a->printed_something = 1;
7748 return NULL;
7751 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7752 return got_error_from_errno("fmt_scaled");
7753 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7754 return got_error_from_errno("fmt_scaled");
7756 if (a->last_ncommits != ncommits) {
7757 print_searching = 1;
7758 a->last_ncommits = ncommits;
7761 if (a->last_nobj_total != nobj_total) {
7762 print_searching = 1;
7763 print_total = 1;
7764 a->last_nobj_total = nobj_total;
7767 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7768 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7769 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7770 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7771 return got_error(GOT_ERR_NO_SPACE);
7774 if (nobj_deltify > 0 || nobj_written > 0) {
7775 if (nobj_deltify > 0) {
7776 p_deltify = (nobj_deltify * 100) / nobj_total;
7777 if (p_deltify != a->last_p_deltify) {
7778 a->last_p_deltify = p_deltify;
7779 print_searching = 1;
7780 print_total = 1;
7781 print_deltify = 1;
7784 if (nobj_written > 0) {
7785 p_written = (nobj_written * 100) / nobj_total;
7786 if (p_written != a->last_p_written) {
7787 a->last_p_written = p_written;
7788 print_searching = 1;
7789 print_total = 1;
7790 print_deltify = 1;
7791 print_written = 1;
7796 if (bytes_sent > 0) {
7797 p_sent = (bytes_sent * 100) / packfile_size;
7798 if (p_sent != a->last_p_sent) {
7799 a->last_p_sent = p_sent;
7800 print_searching = 1;
7801 print_total = 1;
7802 print_deltify = 1;
7803 print_written = 1;
7804 print_sent = 1;
7806 a->sent_something = 1;
7809 if (print_searching || print_total || print_deltify || print_written ||
7810 print_sent)
7811 printf("\r");
7812 if (print_searching)
7813 printf("packing %d reference%s", ncommits,
7814 ncommits == 1 ? "" : "s");
7815 if (print_total)
7816 printf("; %d object%s", nobj_total,
7817 nobj_total == 1 ? "" : "s");
7818 if (print_deltify)
7819 printf("; deltify: %d%%", p_deltify);
7820 if (print_sent)
7821 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
7822 scaled_packsize, p_sent);
7823 else if (print_written)
7824 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
7825 scaled_packsize, p_written);
7826 if (print_searching || print_total || print_deltify ||
7827 print_written || print_sent) {
7828 a->printed_something = 1;
7829 fflush(stdout);
7831 return NULL;
7834 static const struct got_error *
7835 cmd_send(int argc, char *argv[])
7837 const struct got_error *error = NULL;
7838 char *cwd = NULL, *repo_path = NULL;
7839 const char *remote_name;
7840 char *proto = NULL, *host = NULL, *port = NULL;
7841 char *repo_name = NULL, *server_path = NULL;
7842 const struct got_remote_repo *remotes, *remote = NULL;
7843 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7844 struct got_repository *repo = NULL;
7845 struct got_worktree *worktree = NULL;
7846 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7847 struct got_pathlist_head branches;
7848 struct got_pathlist_head tags;
7849 struct got_reflist_head all_branches;
7850 struct got_reflist_head all_tags;
7851 struct got_pathlist_head delete_args;
7852 struct got_pathlist_head delete_branches;
7853 struct got_reflist_entry *re;
7854 struct got_pathlist_entry *pe;
7855 int i, ch, sendfd = -1, sendstatus;
7856 pid_t sendpid = -1;
7857 struct got_send_progress_arg spa;
7858 int verbosity = 0, overwrite_refs = 0;
7859 int send_all_branches = 0, send_all_tags = 0;
7860 struct got_reference *ref = NULL;
7862 TAILQ_INIT(&branches);
7863 TAILQ_INIT(&tags);
7864 TAILQ_INIT(&all_branches);
7865 TAILQ_INIT(&all_tags);
7866 TAILQ_INIT(&delete_args);
7867 TAILQ_INIT(&delete_branches);
7869 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7870 switch (ch) {
7871 case 'a':
7872 send_all_branches = 1;
7873 break;
7874 case 'b':
7875 error = got_pathlist_append(&branches, optarg, NULL);
7876 if (error)
7877 return error;
7878 nbranches++;
7879 break;
7880 case 'd':
7881 error = got_pathlist_append(&delete_args, optarg, NULL);
7882 if (error)
7883 return error;
7884 break;
7885 case 'f':
7886 overwrite_refs = 1;
7887 break;
7888 case 'r':
7889 repo_path = realpath(optarg, NULL);
7890 if (repo_path == NULL)
7891 return got_error_from_errno2("realpath",
7892 optarg);
7893 got_path_strip_trailing_slashes(repo_path);
7894 break;
7895 case 't':
7896 error = got_pathlist_append(&tags, optarg, NULL);
7897 if (error)
7898 return error;
7899 ntags++;
7900 break;
7901 case 'T':
7902 send_all_tags = 1;
7903 break;
7904 case 'v':
7905 if (verbosity < 0)
7906 verbosity = 0;
7907 else if (verbosity < 3)
7908 verbosity++;
7909 break;
7910 case 'q':
7911 verbosity = -1;
7912 break;
7913 default:
7914 usage_send();
7915 /* NOTREACHED */
7918 argc -= optind;
7919 argv += optind;
7921 if (send_all_branches && !TAILQ_EMPTY(&branches))
7922 option_conflict('a', 'b');
7923 if (send_all_tags && !TAILQ_EMPTY(&tags))
7924 option_conflict('T', 't');
7927 if (argc == 0)
7928 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7929 else if (argc == 1)
7930 remote_name = argv[0];
7931 else
7932 usage_send();
7934 cwd = getcwd(NULL, 0);
7935 if (cwd == NULL) {
7936 error = got_error_from_errno("getcwd");
7937 goto done;
7940 if (repo_path == NULL) {
7941 error = got_worktree_open(&worktree, cwd);
7942 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7943 goto done;
7944 else
7945 error = NULL;
7946 if (worktree) {
7947 repo_path =
7948 strdup(got_worktree_get_repo_path(worktree));
7949 if (repo_path == NULL)
7950 error = got_error_from_errno("strdup");
7951 if (error)
7952 goto done;
7953 } else {
7954 repo_path = strdup(cwd);
7955 if (repo_path == NULL) {
7956 error = got_error_from_errno("strdup");
7957 goto done;
7962 error = got_repo_open(&repo, repo_path, NULL);
7963 if (error)
7964 goto done;
7966 if (worktree) {
7967 worktree_conf = got_worktree_get_gotconfig(worktree);
7968 if (worktree_conf) {
7969 got_gotconfig_get_remotes(&nremotes, &remotes,
7970 worktree_conf);
7971 for (i = 0; i < nremotes; i++) {
7972 if (strcmp(remotes[i].name, remote_name) == 0) {
7973 remote = &remotes[i];
7974 break;
7979 if (remote == NULL) {
7980 repo_conf = got_repo_get_gotconfig(repo);
7981 if (repo_conf) {
7982 got_gotconfig_get_remotes(&nremotes, &remotes,
7983 repo_conf);
7984 for (i = 0; i < nremotes; i++) {
7985 if (strcmp(remotes[i].name, remote_name) == 0) {
7986 remote = &remotes[i];
7987 break;
7992 if (remote == NULL) {
7993 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7994 for (i = 0; i < nremotes; i++) {
7995 if (strcmp(remotes[i].name, remote_name) == 0) {
7996 remote = &remotes[i];
7997 break;
8001 if (remote == NULL) {
8002 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8003 goto done;
8006 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8007 &repo_name, remote->send_url);
8008 if (error)
8009 goto done;
8011 if (strcmp(proto, "git") == 0) {
8012 #ifndef PROFILE
8013 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8014 "sendfd dns inet unveil", NULL) == -1)
8015 err(1, "pledge");
8016 #endif
8017 } else if (strcmp(proto, "git+ssh") == 0 ||
8018 strcmp(proto, "ssh") == 0) {
8019 #ifndef PROFILE
8020 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8021 "sendfd unveil", NULL) == -1)
8022 err(1, "pledge");
8023 #endif
8024 } else if (strcmp(proto, "http") == 0 ||
8025 strcmp(proto, "git+http") == 0) {
8026 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8027 goto done;
8028 } else {
8029 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8030 goto done;
8033 error = got_dial_apply_unveil(proto);
8034 if (error)
8035 goto done;
8037 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8038 if (error)
8039 goto done;
8041 if (send_all_branches) {
8042 error = got_ref_list(&all_branches, repo, "refs/heads",
8043 got_ref_cmp_by_name, NULL);
8044 if (error)
8045 goto done;
8046 TAILQ_FOREACH(re, &all_branches, entry) {
8047 const char *branchname = got_ref_get_name(re->ref);
8048 error = got_pathlist_append(&branches,
8049 branchname, NULL);
8050 if (error)
8051 goto done;
8052 nbranches++;
8054 } else if (nbranches == 0) {
8055 for (i = 0; i < remote->nsend_branches; i++) {
8056 got_pathlist_append(&branches,
8057 remote->send_branches[i], NULL);
8061 if (send_all_tags) {
8062 error = got_ref_list(&all_tags, repo, "refs/tags",
8063 got_ref_cmp_by_name, NULL);
8064 if (error)
8065 goto done;
8066 TAILQ_FOREACH(re, &all_tags, entry) {
8067 const char *tagname = got_ref_get_name(re->ref);
8068 error = got_pathlist_append(&tags,
8069 tagname, NULL);
8070 if (error)
8071 goto done;
8072 ntags++;
8077 * To prevent accidents only branches in refs/heads/ can be deleted
8078 * with 'got send -d'.
8079 * Deleting anything else requires local repository access or Git.
8081 TAILQ_FOREACH(pe, &delete_args, entry) {
8082 const char *branchname = pe->path;
8083 char *s;
8084 struct got_pathlist_entry *new;
8085 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8086 s = strdup(branchname);
8087 if (s == NULL) {
8088 error = got_error_from_errno("strdup");
8089 goto done;
8091 } else {
8092 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8093 error = got_error_from_errno("asprintf");
8094 goto done;
8097 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8098 if (error || new == NULL /* duplicate */)
8099 free(s);
8100 if (error)
8101 goto done;
8102 ndelete_branches++;
8105 if (nbranches == 0 && ndelete_branches == 0) {
8106 struct got_reference *head_ref;
8107 if (worktree)
8108 error = got_ref_open(&head_ref, repo,
8109 got_worktree_get_head_ref_name(worktree), 0);
8110 else
8111 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8112 if (error)
8113 goto done;
8114 if (got_ref_is_symbolic(head_ref)) {
8115 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8116 got_ref_close(head_ref);
8117 if (error)
8118 goto done;
8119 } else
8120 ref = head_ref;
8121 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8122 NULL);
8123 if (error)
8124 goto done;
8125 nbranches++;
8128 if (verbosity >= 0)
8129 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8130 port ? ":" : "", port ? port : "");
8132 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8133 server_path, verbosity);
8134 if (error)
8135 goto done;
8137 memset(&spa, 0, sizeof(spa));
8138 spa.last_scaled_packsize[0] = '\0';
8139 spa.last_p_deltify = -1;
8140 spa.last_p_written = -1;
8141 spa.verbosity = verbosity;
8142 spa.delete_branches = &delete_branches;
8143 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8144 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8145 check_cancelled, NULL);
8146 if (spa.printed_something)
8147 putchar('\n');
8148 if (error)
8149 goto done;
8150 if (!spa.sent_something && verbosity >= 0)
8151 printf("Already up-to-date\n");
8152 done:
8153 if (sendpid > 0) {
8154 if (kill(sendpid, SIGTERM) == -1)
8155 error = got_error_from_errno("kill");
8156 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8157 error = got_error_from_errno("waitpid");
8159 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8160 error = got_error_from_errno("close");
8161 if (repo) {
8162 const struct got_error *close_err = got_repo_close(repo);
8163 if (error == NULL)
8164 error = close_err;
8166 if (worktree)
8167 got_worktree_close(worktree);
8168 if (ref)
8169 got_ref_close(ref);
8170 got_pathlist_free(&branches);
8171 got_pathlist_free(&tags);
8172 got_ref_list_free(&all_branches);
8173 got_ref_list_free(&all_tags);
8174 got_pathlist_free(&delete_args);
8175 TAILQ_FOREACH(pe, &delete_branches, entry)
8176 free((char *)pe->path);
8177 got_pathlist_free(&delete_branches);
8178 free(cwd);
8179 free(repo_path);
8180 free(proto);
8181 free(host);
8182 free(port);
8183 free(server_path);
8184 free(repo_name);
8185 return error;
8188 __dead static void
8189 usage_cherrypick(void)
8191 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8192 exit(1);
8195 static const struct got_error *
8196 cmd_cherrypick(int argc, char *argv[])
8198 const struct got_error *error = NULL;
8199 struct got_worktree *worktree = NULL;
8200 struct got_repository *repo = NULL;
8201 char *cwd = NULL, *commit_id_str = NULL;
8202 struct got_object_id *commit_id = NULL;
8203 struct got_commit_object *commit = NULL;
8204 struct got_object_qid *pid;
8205 int ch;
8206 struct got_update_progress_arg upa;
8208 while ((ch = getopt(argc, argv, "")) != -1) {
8209 switch (ch) {
8210 default:
8211 usage_cherrypick();
8212 /* NOTREACHED */
8216 argc -= optind;
8217 argv += optind;
8219 #ifndef PROFILE
8220 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8221 "unveil", NULL) == -1)
8222 err(1, "pledge");
8223 #endif
8224 if (argc != 1)
8225 usage_cherrypick();
8227 cwd = getcwd(NULL, 0);
8228 if (cwd == NULL) {
8229 error = got_error_from_errno("getcwd");
8230 goto done;
8232 error = got_worktree_open(&worktree, cwd);
8233 if (error) {
8234 if (error->code == GOT_ERR_NOT_WORKTREE)
8235 error = wrap_not_worktree_error(error, "cherrypick",
8236 cwd);
8237 goto done;
8240 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8241 NULL);
8242 if (error != NULL)
8243 goto done;
8245 error = apply_unveil(got_repo_get_path(repo), 0,
8246 got_worktree_get_root_path(worktree));
8247 if (error)
8248 goto done;
8250 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8251 GOT_OBJ_TYPE_COMMIT, repo);
8252 if (error != NULL) {
8253 struct got_reference *ref;
8254 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8255 goto done;
8256 error = got_ref_open(&ref, repo, argv[0], 0);
8257 if (error != NULL)
8258 goto done;
8259 error = got_ref_resolve(&commit_id, repo, ref);
8260 got_ref_close(ref);
8261 if (error != NULL)
8262 goto done;
8264 error = got_object_id_str(&commit_id_str, commit_id);
8265 if (error)
8266 goto done;
8268 error = got_object_open_as_commit(&commit, repo, commit_id);
8269 if (error)
8270 goto done;
8271 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8272 memset(&upa, 0, sizeof(upa));
8273 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8274 commit_id, repo, update_progress, &upa, check_cancelled,
8275 NULL);
8276 if (error != NULL)
8277 goto done;
8279 if (upa.did_something)
8280 printf("Merged commit %s\n", commit_id_str);
8281 print_merge_progress_stats(&upa);
8282 done:
8283 if (commit)
8284 got_object_commit_close(commit);
8285 free(commit_id_str);
8286 if (worktree)
8287 got_worktree_close(worktree);
8288 if (repo) {
8289 const struct got_error *close_err = got_repo_close(repo);
8290 if (error == NULL)
8291 error = close_err;
8293 return error;
8296 __dead static void
8297 usage_backout(void)
8299 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8300 exit(1);
8303 static const struct got_error *
8304 cmd_backout(int argc, char *argv[])
8306 const struct got_error *error = NULL;
8307 struct got_worktree *worktree = NULL;
8308 struct got_repository *repo = NULL;
8309 char *cwd = NULL, *commit_id_str = NULL;
8310 struct got_object_id *commit_id = NULL;
8311 struct got_commit_object *commit = NULL;
8312 struct got_object_qid *pid;
8313 int ch;
8314 struct got_update_progress_arg upa;
8316 while ((ch = getopt(argc, argv, "")) != -1) {
8317 switch (ch) {
8318 default:
8319 usage_backout();
8320 /* NOTREACHED */
8324 argc -= optind;
8325 argv += optind;
8327 #ifndef PROFILE
8328 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8329 "unveil", NULL) == -1)
8330 err(1, "pledge");
8331 #endif
8332 if (argc != 1)
8333 usage_backout();
8335 cwd = getcwd(NULL, 0);
8336 if (cwd == NULL) {
8337 error = got_error_from_errno("getcwd");
8338 goto done;
8340 error = got_worktree_open(&worktree, cwd);
8341 if (error) {
8342 if (error->code == GOT_ERR_NOT_WORKTREE)
8343 error = wrap_not_worktree_error(error, "backout", cwd);
8344 goto done;
8347 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8348 NULL);
8349 if (error != NULL)
8350 goto done;
8352 error = apply_unveil(got_repo_get_path(repo), 0,
8353 got_worktree_get_root_path(worktree));
8354 if (error)
8355 goto done;
8357 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8358 GOT_OBJ_TYPE_COMMIT, repo);
8359 if (error != NULL) {
8360 struct got_reference *ref;
8361 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8362 goto done;
8363 error = got_ref_open(&ref, repo, argv[0], 0);
8364 if (error != NULL)
8365 goto done;
8366 error = got_ref_resolve(&commit_id, repo, ref);
8367 got_ref_close(ref);
8368 if (error != NULL)
8369 goto done;
8371 error = got_object_id_str(&commit_id_str, commit_id);
8372 if (error)
8373 goto done;
8375 error = got_object_open_as_commit(&commit, repo, commit_id);
8376 if (error)
8377 goto done;
8378 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8379 if (pid == NULL) {
8380 error = got_error(GOT_ERR_ROOT_COMMIT);
8381 goto done;
8384 memset(&upa, 0, sizeof(upa));
8385 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8386 repo, update_progress, &upa, check_cancelled, NULL);
8387 if (error != NULL)
8388 goto done;
8390 if (upa.did_something)
8391 printf("Backed out commit %s\n", commit_id_str);
8392 print_merge_progress_stats(&upa);
8393 done:
8394 if (commit)
8395 got_object_commit_close(commit);
8396 free(commit_id_str);
8397 if (worktree)
8398 got_worktree_close(worktree);
8399 if (repo) {
8400 const struct got_error *close_err = got_repo_close(repo);
8401 if (error == NULL)
8402 error = close_err;
8404 return error;
8407 __dead static void
8408 usage_rebase(void)
8410 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8411 getprogname());
8412 exit(1);
8415 void
8416 trim_logmsg(char *logmsg, int limit)
8418 char *nl;
8419 size_t len;
8421 len = strlen(logmsg);
8422 if (len > limit)
8423 len = limit;
8424 logmsg[len] = '\0';
8425 nl = strchr(logmsg, '\n');
8426 if (nl)
8427 *nl = '\0';
8430 static const struct got_error *
8431 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8433 const struct got_error *err;
8434 char *logmsg0 = NULL;
8435 const char *s;
8437 err = got_object_commit_get_logmsg(&logmsg0, commit);
8438 if (err)
8439 return err;
8441 s = logmsg0;
8442 while (isspace((unsigned char)s[0]))
8443 s++;
8445 *logmsg = strdup(s);
8446 if (*logmsg == NULL) {
8447 err = got_error_from_errno("strdup");
8448 goto done;
8451 trim_logmsg(*logmsg, limit);
8452 done:
8453 free(logmsg0);
8454 return err;
8457 static const struct got_error *
8458 show_rebase_merge_conflict(struct got_object_id *id,
8459 struct got_repository *repo)
8461 const struct got_error *err;
8462 struct got_commit_object *commit = NULL;
8463 char *id_str = NULL, *logmsg = NULL;
8465 err = got_object_open_as_commit(&commit, repo, id);
8466 if (err)
8467 return err;
8469 err = got_object_id_str(&id_str, id);
8470 if (err)
8471 goto done;
8473 id_str[12] = '\0';
8475 err = get_short_logmsg(&logmsg, 42, commit);
8476 if (err)
8477 goto done;
8479 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8480 done:
8481 free(id_str);
8482 got_object_commit_close(commit);
8483 free(logmsg);
8484 return err;
8487 static const struct got_error *
8488 show_rebase_progress(struct got_commit_object *commit,
8489 struct got_object_id *old_id, struct got_object_id *new_id)
8491 const struct got_error *err;
8492 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8494 err = got_object_id_str(&old_id_str, old_id);
8495 if (err)
8496 goto done;
8498 if (new_id) {
8499 err = got_object_id_str(&new_id_str, new_id);
8500 if (err)
8501 goto done;
8504 old_id_str[12] = '\0';
8505 if (new_id_str)
8506 new_id_str[12] = '\0';
8508 err = get_short_logmsg(&logmsg, 42, commit);
8509 if (err)
8510 goto done;
8512 printf("%s -> %s: %s\n", old_id_str,
8513 new_id_str ? new_id_str : "no-op change", logmsg);
8514 done:
8515 free(old_id_str);
8516 free(new_id_str);
8517 free(logmsg);
8518 return err;
8521 static const struct got_error *
8522 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8523 struct got_reference *branch, struct got_reference *new_base_branch,
8524 struct got_reference *tmp_branch, struct got_repository *repo,
8525 int create_backup)
8527 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8528 return got_worktree_rebase_complete(worktree, fileindex,
8529 new_base_branch, tmp_branch, branch, repo, create_backup);
8532 static const struct got_error *
8533 rebase_commit(struct got_pathlist_head *merged_paths,
8534 struct got_worktree *worktree, struct got_fileindex *fileindex,
8535 struct got_reference *tmp_branch,
8536 struct got_object_id *commit_id, struct got_repository *repo)
8538 const struct got_error *error;
8539 struct got_commit_object *commit;
8540 struct got_object_id *new_commit_id;
8542 error = got_object_open_as_commit(&commit, repo, commit_id);
8543 if (error)
8544 return error;
8546 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8547 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8548 if (error) {
8549 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8550 goto done;
8551 error = show_rebase_progress(commit, commit_id, NULL);
8552 } else {
8553 error = show_rebase_progress(commit, commit_id, new_commit_id);
8554 free(new_commit_id);
8556 done:
8557 got_object_commit_close(commit);
8558 return error;
8561 struct check_path_prefix_arg {
8562 const char *path_prefix;
8563 size_t len;
8564 int errcode;
8567 static const struct got_error *
8568 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8569 struct got_blob_object *blob2, struct got_object_id *id1,
8570 struct got_object_id *id2, const char *path1, const char *path2,
8571 mode_t mode1, mode_t mode2, struct got_repository *repo)
8573 struct check_path_prefix_arg *a = arg;
8575 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8576 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8577 return got_error(a->errcode);
8579 return NULL;
8582 static const struct got_error *
8583 check_path_prefix(struct got_object_id *parent_id,
8584 struct got_object_id *commit_id, const char *path_prefix,
8585 int errcode, struct got_repository *repo)
8587 const struct got_error *err;
8588 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8589 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8590 struct check_path_prefix_arg cpp_arg;
8592 if (got_path_is_root_dir(path_prefix))
8593 return NULL;
8595 err = got_object_open_as_commit(&commit, repo, commit_id);
8596 if (err)
8597 goto done;
8599 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8600 if (err)
8601 goto done;
8603 err = got_object_open_as_tree(&tree1, repo,
8604 got_object_commit_get_tree_id(parent_commit));
8605 if (err)
8606 goto done;
8608 err = got_object_open_as_tree(&tree2, repo,
8609 got_object_commit_get_tree_id(commit));
8610 if (err)
8611 goto done;
8613 cpp_arg.path_prefix = path_prefix;
8614 while (cpp_arg.path_prefix[0] == '/')
8615 cpp_arg.path_prefix++;
8616 cpp_arg.len = strlen(cpp_arg.path_prefix);
8617 cpp_arg.errcode = errcode;
8618 err = got_diff_tree(tree1, tree2, "", "", repo,
8619 check_path_prefix_in_diff, &cpp_arg, 0);
8620 done:
8621 if (tree1)
8622 got_object_tree_close(tree1);
8623 if (tree2)
8624 got_object_tree_close(tree2);
8625 if (commit)
8626 got_object_commit_close(commit);
8627 if (parent_commit)
8628 got_object_commit_close(parent_commit);
8629 return err;
8632 static const struct got_error *
8633 collect_commits(struct got_object_id_queue *commits,
8634 struct got_object_id *initial_commit_id,
8635 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8636 const char *path_prefix, int path_prefix_errcode,
8637 struct got_repository *repo)
8639 const struct got_error *err = NULL;
8640 struct got_commit_graph *graph = NULL;
8641 struct got_object_id *parent_id = NULL;
8642 struct got_object_qid *qid;
8643 struct got_object_id *commit_id = initial_commit_id;
8645 err = got_commit_graph_open(&graph, "/", 1);
8646 if (err)
8647 return err;
8649 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8650 check_cancelled, NULL);
8651 if (err)
8652 goto done;
8653 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8654 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8655 check_cancelled, NULL);
8656 if (err) {
8657 if (err->code == GOT_ERR_ITER_COMPLETED) {
8658 err = got_error_msg(GOT_ERR_ANCESTRY,
8659 "ran out of commits to rebase before "
8660 "youngest common ancestor commit has "
8661 "been reached?!?");
8663 goto done;
8664 } else {
8665 err = check_path_prefix(parent_id, commit_id,
8666 path_prefix, path_prefix_errcode, repo);
8667 if (err)
8668 goto done;
8670 err = got_object_qid_alloc(&qid, commit_id);
8671 if (err)
8672 goto done;
8673 STAILQ_INSERT_HEAD(commits, qid, entry);
8674 commit_id = parent_id;
8677 done:
8678 got_commit_graph_close(graph);
8679 return err;
8682 static const struct got_error *
8683 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8685 const struct got_error *err = NULL;
8686 time_t committer_time;
8687 struct tm tm;
8688 char datebuf[11]; /* YYYY-MM-DD + NUL */
8689 char *author0 = NULL, *author, *smallerthan;
8690 char *logmsg0 = NULL, *logmsg, *newline;
8692 committer_time = got_object_commit_get_committer_time(commit);
8693 if (gmtime_r(&committer_time, &tm) == NULL)
8694 return got_error_from_errno("gmtime_r");
8695 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8696 return got_error(GOT_ERR_NO_SPACE);
8698 author0 = strdup(got_object_commit_get_author(commit));
8699 if (author0 == NULL)
8700 return got_error_from_errno("strdup");
8701 author = author0;
8702 smallerthan = strchr(author, '<');
8703 if (smallerthan && smallerthan[1] != '\0')
8704 author = smallerthan + 1;
8705 author[strcspn(author, "@>")] = '\0';
8707 err = got_object_commit_get_logmsg(&logmsg0, commit);
8708 if (err)
8709 goto done;
8710 logmsg = logmsg0;
8711 while (*logmsg == '\n')
8712 logmsg++;
8713 newline = strchr(logmsg, '\n');
8714 if (newline)
8715 *newline = '\0';
8717 if (asprintf(brief_str, "%s %s %s",
8718 datebuf, author, logmsg) == -1)
8719 err = got_error_from_errno("asprintf");
8720 done:
8721 free(author0);
8722 free(logmsg0);
8723 return err;
8726 static const struct got_error *
8727 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8728 struct got_repository *repo)
8730 const struct got_error *err;
8731 char *id_str;
8733 err = got_object_id_str(&id_str, id);
8734 if (err)
8735 return err;
8737 err = got_ref_delete(ref, repo);
8738 if (err)
8739 goto done;
8741 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8742 done:
8743 free(id_str);
8744 return err;
8747 static const struct got_error *
8748 print_backup_ref(const char *branch_name, const char *new_id_str,
8749 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8750 struct got_reflist_object_id_map *refs_idmap,
8751 struct got_repository *repo)
8753 const struct got_error *err = NULL;
8754 struct got_reflist_head *refs;
8755 char *refs_str = NULL;
8756 struct got_object_id *new_commit_id = NULL;
8757 struct got_commit_object *new_commit = NULL;
8758 char *new_commit_brief_str = NULL;
8759 struct got_object_id *yca_id = NULL;
8760 struct got_commit_object *yca_commit = NULL;
8761 char *yca_id_str = NULL, *yca_brief_str = NULL;
8762 char *custom_refs_str;
8764 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8765 return got_error_from_errno("asprintf");
8767 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8768 0, 0, refs_idmap, custom_refs_str);
8769 if (err)
8770 goto done;
8772 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8773 if (err)
8774 goto done;
8776 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8777 if (refs) {
8778 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8779 if (err)
8780 goto done;
8783 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8784 if (err)
8785 goto done;
8787 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8788 if (err)
8789 goto done;
8791 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8792 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8793 if (err)
8794 goto done;
8796 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8797 refs_str ? " (" : "", refs_str ? refs_str : "",
8798 refs_str ? ")" : "", new_commit_brief_str);
8799 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8800 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8801 free(refs_str);
8802 refs_str = NULL;
8804 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8805 if (err)
8806 goto done;
8808 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8809 if (err)
8810 goto done;
8812 err = got_object_id_str(&yca_id_str, yca_id);
8813 if (err)
8814 goto done;
8816 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8817 if (refs) {
8818 err = build_refs_str(&refs_str, refs, yca_id, repo);
8819 if (err)
8820 goto done;
8822 printf("history forked at %s%s%s%s\n %s\n",
8823 yca_id_str,
8824 refs_str ? " (" : "", refs_str ? refs_str : "",
8825 refs_str ? ")" : "", yca_brief_str);
8827 done:
8828 free(custom_refs_str);
8829 free(new_commit_id);
8830 free(refs_str);
8831 free(yca_id);
8832 free(yca_id_str);
8833 free(yca_brief_str);
8834 if (new_commit)
8835 got_object_commit_close(new_commit);
8836 if (yca_commit)
8837 got_object_commit_close(yca_commit);
8839 return NULL;
8842 static const struct got_error *
8843 process_backup_refs(const char *backup_ref_prefix,
8844 const char *wanted_branch_name,
8845 int delete, struct got_repository *repo)
8847 const struct got_error *err;
8848 struct got_reflist_head refs, backup_refs;
8849 struct got_reflist_entry *re;
8850 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8851 struct got_object_id *old_commit_id = NULL;
8852 char *branch_name = NULL;
8853 struct got_commit_object *old_commit = NULL;
8854 struct got_reflist_object_id_map *refs_idmap = NULL;
8855 int wanted_branch_found = 0;
8857 TAILQ_INIT(&refs);
8858 TAILQ_INIT(&backup_refs);
8860 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8861 if (err)
8862 return err;
8864 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8865 if (err)
8866 goto done;
8868 if (wanted_branch_name) {
8869 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8870 wanted_branch_name += 11;
8873 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8874 got_ref_cmp_by_commit_timestamp_descending, repo);
8875 if (err)
8876 goto done;
8878 TAILQ_FOREACH(re, &backup_refs, entry) {
8879 const char *refname = got_ref_get_name(re->ref);
8880 char *slash;
8882 err = check_cancelled(NULL);
8883 if (err)
8884 break;
8886 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8887 if (err)
8888 break;
8890 err = got_object_open_as_commit(&old_commit, repo,
8891 old_commit_id);
8892 if (err)
8893 break;
8895 if (strncmp(backup_ref_prefix, refname,
8896 backup_ref_prefix_len) == 0)
8897 refname += backup_ref_prefix_len;
8899 while (refname[0] == '/')
8900 refname++;
8902 branch_name = strdup(refname);
8903 if (branch_name == NULL) {
8904 err = got_error_from_errno("strdup");
8905 break;
8907 slash = strrchr(branch_name, '/');
8908 if (slash) {
8909 *slash = '\0';
8910 refname += strlen(branch_name) + 1;
8913 if (wanted_branch_name == NULL ||
8914 strcmp(wanted_branch_name, branch_name) == 0) {
8915 wanted_branch_found = 1;
8916 if (delete) {
8917 err = delete_backup_ref(re->ref,
8918 old_commit_id, repo);
8919 } else {
8920 err = print_backup_ref(branch_name, refname,
8921 old_commit_id, old_commit, refs_idmap,
8922 repo);
8924 if (err)
8925 break;
8928 free(old_commit_id);
8929 old_commit_id = NULL;
8930 free(branch_name);
8931 branch_name = NULL;
8932 got_object_commit_close(old_commit);
8933 old_commit = NULL;
8936 if (wanted_branch_name && !wanted_branch_found) {
8937 err = got_error_fmt(GOT_ERR_NOT_REF,
8938 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8940 done:
8941 if (refs_idmap)
8942 got_reflist_object_id_map_free(refs_idmap);
8943 got_ref_list_free(&refs);
8944 got_ref_list_free(&backup_refs);
8945 free(old_commit_id);
8946 free(branch_name);
8947 if (old_commit)
8948 got_object_commit_close(old_commit);
8949 return err;
8952 static const struct got_error *
8953 abort_progress(void *arg, unsigned char status, const char *path)
8956 * Unversioned files should not clutter progress output when
8957 * an operation is aborted.
8959 if (status == GOT_STATUS_UNVERSIONED)
8960 return NULL;
8962 return update_progress(arg, status, path);
8965 static const struct got_error *
8966 cmd_rebase(int argc, char *argv[])
8968 const struct got_error *error = NULL;
8969 struct got_worktree *worktree = NULL;
8970 struct got_repository *repo = NULL;
8971 struct got_fileindex *fileindex = NULL;
8972 char *cwd = NULL;
8973 struct got_reference *branch = NULL;
8974 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8975 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8976 struct got_object_id *resume_commit_id = NULL;
8977 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8978 struct got_commit_object *commit = NULL;
8979 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8980 int histedit_in_progress = 0, merge_in_progress = 0;
8981 int create_backup = 1, list_backups = 0, delete_backups = 0;
8982 struct got_object_id_queue commits;
8983 struct got_pathlist_head merged_paths;
8984 const struct got_object_id_queue *parent_ids;
8985 struct got_object_qid *qid, *pid;
8986 struct got_update_progress_arg upa;
8988 STAILQ_INIT(&commits);
8989 TAILQ_INIT(&merged_paths);
8990 memset(&upa, 0, sizeof(upa));
8992 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8993 switch (ch) {
8994 case 'a':
8995 abort_rebase = 1;
8996 break;
8997 case 'c':
8998 continue_rebase = 1;
8999 break;
9000 case 'l':
9001 list_backups = 1;
9002 break;
9003 case 'X':
9004 delete_backups = 1;
9005 break;
9006 default:
9007 usage_rebase();
9008 /* NOTREACHED */
9012 argc -= optind;
9013 argv += optind;
9015 #ifndef PROFILE
9016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9017 "unveil", NULL) == -1)
9018 err(1, "pledge");
9019 #endif
9020 if (list_backups) {
9021 if (abort_rebase)
9022 option_conflict('l', 'a');
9023 if (continue_rebase)
9024 option_conflict('l', 'c');
9025 if (delete_backups)
9026 option_conflict('l', 'X');
9027 if (argc != 0 && argc != 1)
9028 usage_rebase();
9029 } else if (delete_backups) {
9030 if (abort_rebase)
9031 option_conflict('X', 'a');
9032 if (continue_rebase)
9033 option_conflict('X', 'c');
9034 if (list_backups)
9035 option_conflict('l', 'X');
9036 if (argc != 0 && argc != 1)
9037 usage_rebase();
9038 } else {
9039 if (abort_rebase && continue_rebase)
9040 usage_rebase();
9041 else if (abort_rebase || continue_rebase) {
9042 if (argc != 0)
9043 usage_rebase();
9044 } else if (argc != 1)
9045 usage_rebase();
9048 cwd = getcwd(NULL, 0);
9049 if (cwd == NULL) {
9050 error = got_error_from_errno("getcwd");
9051 goto done;
9053 error = got_worktree_open(&worktree, cwd);
9054 if (error) {
9055 if (list_backups || delete_backups) {
9056 if (error->code != GOT_ERR_NOT_WORKTREE)
9057 goto done;
9058 } else {
9059 if (error->code == GOT_ERR_NOT_WORKTREE)
9060 error = wrap_not_worktree_error(error,
9061 "rebase", cwd);
9062 goto done;
9066 error = got_repo_open(&repo,
9067 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9068 if (error != NULL)
9069 goto done;
9071 error = apply_unveil(got_repo_get_path(repo), 0,
9072 worktree ? got_worktree_get_root_path(worktree) : NULL);
9073 if (error)
9074 goto done;
9076 if (list_backups || delete_backups) {
9077 error = process_backup_refs(
9078 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9079 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9080 goto done; /* nothing else to do */
9083 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9084 worktree);
9085 if (error)
9086 goto done;
9087 if (histedit_in_progress) {
9088 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9089 goto done;
9092 error = got_worktree_merge_in_progress(&merge_in_progress,
9093 worktree, repo);
9094 if (error)
9095 goto done;
9096 if (merge_in_progress) {
9097 error = got_error(GOT_ERR_MERGE_BUSY);
9098 goto done;
9101 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9102 if (error)
9103 goto done;
9105 if (abort_rebase) {
9106 if (!rebase_in_progress) {
9107 error = got_error(GOT_ERR_NOT_REBASING);
9108 goto done;
9110 error = got_worktree_rebase_continue(&resume_commit_id,
9111 &new_base_branch, &tmp_branch, &branch, &fileindex,
9112 worktree, repo);
9113 if (error)
9114 goto done;
9115 printf("Switching work tree to %s\n",
9116 got_ref_get_symref_target(new_base_branch));
9117 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9118 new_base_branch, abort_progress, &upa);
9119 if (error)
9120 goto done;
9121 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9122 print_merge_progress_stats(&upa);
9123 goto done; /* nothing else to do */
9126 if (continue_rebase) {
9127 if (!rebase_in_progress) {
9128 error = got_error(GOT_ERR_NOT_REBASING);
9129 goto done;
9131 error = got_worktree_rebase_continue(&resume_commit_id,
9132 &new_base_branch, &tmp_branch, &branch, &fileindex,
9133 worktree, repo);
9134 if (error)
9135 goto done;
9137 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9138 resume_commit_id, repo);
9139 if (error)
9140 goto done;
9142 yca_id = got_object_id_dup(resume_commit_id);
9143 if (yca_id == NULL) {
9144 error = got_error_from_errno("got_object_id_dup");
9145 goto done;
9147 } else {
9148 error = got_ref_open(&branch, repo, argv[0], 0);
9149 if (error != NULL)
9150 goto done;
9153 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9154 if (error)
9155 goto done;
9157 if (!continue_rebase) {
9158 struct got_object_id *base_commit_id;
9160 base_commit_id = got_worktree_get_base_commit_id(worktree);
9161 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9162 base_commit_id, branch_head_commit_id, 1, repo,
9163 check_cancelled, NULL);
9164 if (error)
9165 goto done;
9166 if (yca_id == NULL) {
9167 error = got_error_msg(GOT_ERR_ANCESTRY,
9168 "specified branch shares no common ancestry "
9169 "with work tree's branch");
9170 goto done;
9173 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9174 if (error) {
9175 if (error->code != GOT_ERR_ANCESTRY)
9176 goto done;
9177 error = NULL;
9178 } else {
9179 struct got_pathlist_head paths;
9180 printf("%s is already based on %s\n",
9181 got_ref_get_name(branch),
9182 got_worktree_get_head_ref_name(worktree));
9183 error = switch_head_ref(branch, branch_head_commit_id,
9184 worktree, repo);
9185 if (error)
9186 goto done;
9187 error = got_worktree_set_base_commit_id(worktree, repo,
9188 branch_head_commit_id);
9189 if (error)
9190 goto done;
9191 TAILQ_INIT(&paths);
9192 error = got_pathlist_append(&paths, "", NULL);
9193 if (error)
9194 goto done;
9195 error = got_worktree_checkout_files(worktree,
9196 &paths, repo, update_progress, &upa,
9197 check_cancelled, NULL);
9198 got_pathlist_free(&paths);
9199 if (error)
9200 goto done;
9201 if (upa.did_something) {
9202 char *id_str;
9203 error = got_object_id_str(&id_str,
9204 branch_head_commit_id);
9205 if (error)
9206 goto done;
9207 printf("Updated to %s: %s\n",
9208 got_worktree_get_head_ref_name(worktree),
9209 id_str);
9210 free(id_str);
9211 } else
9212 printf("Already up-to-date\n");
9213 print_update_progress_stats(&upa);
9214 goto done;
9216 error = got_worktree_rebase_prepare(&new_base_branch,
9217 &tmp_branch, &fileindex, worktree, branch, repo);
9218 if (error)
9219 goto done;
9222 commit_id = branch_head_commit_id;
9223 error = got_object_open_as_commit(&commit, repo, commit_id);
9224 if (error)
9225 goto done;
9227 parent_ids = got_object_commit_get_parent_ids(commit);
9228 pid = STAILQ_FIRST(parent_ids);
9229 if (pid == NULL) {
9230 if (!continue_rebase) {
9231 error = got_worktree_rebase_abort(worktree, fileindex,
9232 repo, new_base_branch, abort_progress, &upa);
9233 if (error)
9234 goto done;
9235 printf("Rebase of %s aborted\n",
9236 got_ref_get_name(branch));
9237 print_merge_progress_stats(&upa);
9240 error = got_error(GOT_ERR_EMPTY_REBASE);
9241 goto done;
9243 error = collect_commits(&commits, commit_id, pid->id,
9244 yca_id, got_worktree_get_path_prefix(worktree),
9245 GOT_ERR_REBASE_PATH, repo);
9246 got_object_commit_close(commit);
9247 commit = NULL;
9248 if (error)
9249 goto done;
9251 if (STAILQ_EMPTY(&commits)) {
9252 if (continue_rebase) {
9253 error = rebase_complete(worktree, fileindex,
9254 branch, new_base_branch, tmp_branch, repo,
9255 create_backup);
9256 goto done;
9257 } else {
9258 /* Fast-forward the reference of the branch. */
9259 struct got_object_id *new_head_commit_id;
9260 char *id_str;
9261 error = got_ref_resolve(&new_head_commit_id, repo,
9262 new_base_branch);
9263 if (error)
9264 goto done;
9265 error = got_object_id_str(&id_str, new_head_commit_id);
9266 printf("Forwarding %s to commit %s\n",
9267 got_ref_get_name(branch), id_str);
9268 free(id_str);
9269 error = got_ref_change_ref(branch,
9270 new_head_commit_id);
9271 if (error)
9272 goto done;
9273 /* No backup needed since objects did not change. */
9274 create_backup = 0;
9278 pid = NULL;
9279 STAILQ_FOREACH(qid, &commits, entry) {
9281 commit_id = qid->id;
9282 parent_id = pid ? pid->id : yca_id;
9283 pid = qid;
9285 memset(&upa, 0, sizeof(upa));
9286 error = got_worktree_rebase_merge_files(&merged_paths,
9287 worktree, fileindex, parent_id, commit_id, repo,
9288 update_progress, &upa, check_cancelled, NULL);
9289 if (error)
9290 goto done;
9292 print_merge_progress_stats(&upa);
9293 if (upa.conflicts > 0 || upa.missing > 0 ||
9294 upa.not_deleted > 0 || upa.unversioned > 0) {
9295 if (upa.conflicts > 0) {
9296 error = show_rebase_merge_conflict(qid->id,
9297 repo);
9298 if (error)
9299 goto done;
9301 got_worktree_rebase_pathlist_free(&merged_paths);
9302 break;
9305 error = rebase_commit(&merged_paths, worktree, fileindex,
9306 tmp_branch, commit_id, repo);
9307 got_worktree_rebase_pathlist_free(&merged_paths);
9308 if (error)
9309 goto done;
9312 if (upa.conflicts > 0 || upa.missing > 0 ||
9313 upa.not_deleted > 0 || upa.unversioned > 0) {
9314 error = got_worktree_rebase_postpone(worktree, fileindex);
9315 if (error)
9316 goto done;
9317 if (upa.conflicts > 0 && upa.missing == 0 &&
9318 upa.not_deleted == 0 && upa.unversioned == 0) {
9319 error = got_error_msg(GOT_ERR_CONFLICTS,
9320 "conflicts must be resolved before rebasing "
9321 "can continue");
9322 } else if (upa.conflicts > 0) {
9323 error = got_error_msg(GOT_ERR_CONFLICTS,
9324 "conflicts must be resolved before rebasing "
9325 "can continue; changes destined for some "
9326 "files were not yet merged and should be "
9327 "merged manually if required before the "
9328 "rebase operation is continued");
9329 } else {
9330 error = got_error_msg(GOT_ERR_CONFLICTS,
9331 "changes destined for some files were not "
9332 "yet merged and should be merged manually "
9333 "if required before the rebase operation "
9334 "is continued");
9336 } else
9337 error = rebase_complete(worktree, fileindex, branch,
9338 new_base_branch, tmp_branch, repo, create_backup);
9339 done:
9340 got_object_id_queue_free(&commits);
9341 free(branch_head_commit_id);
9342 free(resume_commit_id);
9343 free(yca_id);
9344 if (commit)
9345 got_object_commit_close(commit);
9346 if (branch)
9347 got_ref_close(branch);
9348 if (new_base_branch)
9349 got_ref_close(new_base_branch);
9350 if (tmp_branch)
9351 got_ref_close(tmp_branch);
9352 if (worktree)
9353 got_worktree_close(worktree);
9354 if (repo) {
9355 const struct got_error *close_err = got_repo_close(repo);
9356 if (error == NULL)
9357 error = close_err;
9359 return error;
9362 __dead static void
9363 usage_histedit(void)
9365 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9366 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9367 getprogname());
9368 exit(1);
9371 #define GOT_HISTEDIT_PICK 'p'
9372 #define GOT_HISTEDIT_EDIT 'e'
9373 #define GOT_HISTEDIT_FOLD 'f'
9374 #define GOT_HISTEDIT_DROP 'd'
9375 #define GOT_HISTEDIT_MESG 'm'
9377 static const struct got_histedit_cmd {
9378 unsigned char code;
9379 const char *name;
9380 const char *desc;
9381 } got_histedit_cmds[] = {
9382 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9383 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9384 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9385 "be used" },
9386 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9387 { GOT_HISTEDIT_MESG, "mesg",
9388 "single-line log message for commit above (open editor if empty)" },
9391 struct got_histedit_list_entry {
9392 TAILQ_ENTRY(got_histedit_list_entry) entry;
9393 struct got_object_id *commit_id;
9394 const struct got_histedit_cmd *cmd;
9395 char *logmsg;
9397 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9399 static const struct got_error *
9400 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9401 FILE *f, struct got_repository *repo)
9403 const struct got_error *err = NULL;
9404 char *logmsg = NULL, *id_str = NULL;
9405 struct got_commit_object *commit = NULL;
9406 int n;
9408 err = got_object_open_as_commit(&commit, repo, commit_id);
9409 if (err)
9410 goto done;
9412 err = get_short_logmsg(&logmsg, 34, commit);
9413 if (err)
9414 goto done;
9416 err = got_object_id_str(&id_str, commit_id);
9417 if (err)
9418 goto done;
9420 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9421 if (n < 0)
9422 err = got_ferror(f, GOT_ERR_IO);
9423 done:
9424 if (commit)
9425 got_object_commit_close(commit);
9426 free(id_str);
9427 free(logmsg);
9428 return err;
9431 static const struct got_error *
9432 histedit_write_commit_list(struct got_object_id_queue *commits,
9433 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9434 struct got_repository *repo)
9436 const struct got_error *err = NULL;
9437 struct got_object_qid *qid;
9438 const char *histedit_cmd = NULL;
9440 if (STAILQ_EMPTY(commits))
9441 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9443 STAILQ_FOREACH(qid, commits, entry) {
9444 histedit_cmd = got_histedit_cmds[0].name;
9445 if (edit_only)
9446 histedit_cmd = "edit";
9447 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9448 histedit_cmd = "fold";
9449 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9450 if (err)
9451 break;
9452 if (edit_logmsg_only) {
9453 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9454 if (n < 0) {
9455 err = got_ferror(f, GOT_ERR_IO);
9456 break;
9461 return err;
9464 static const struct got_error *
9465 write_cmd_list(FILE *f, const char *branch_name,
9466 struct got_object_id_queue *commits)
9468 const struct got_error *err = NULL;
9469 size_t i;
9470 int n;
9471 char *id_str;
9472 struct got_object_qid *qid;
9474 qid = STAILQ_FIRST(commits);
9475 err = got_object_id_str(&id_str, qid->id);
9476 if (err)
9477 return err;
9479 n = fprintf(f,
9480 "# Editing the history of branch '%s' starting at\n"
9481 "# commit %s\n"
9482 "# Commits will be processed in order from top to "
9483 "bottom of this file.\n", branch_name, id_str);
9484 if (n < 0) {
9485 err = got_ferror(f, GOT_ERR_IO);
9486 goto done;
9489 n = fprintf(f, "# Available histedit commands:\n");
9490 if (n < 0) {
9491 err = got_ferror(f, GOT_ERR_IO);
9492 goto done;
9495 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9496 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9497 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9498 cmd->desc);
9499 if (n < 0) {
9500 err = got_ferror(f, GOT_ERR_IO);
9501 break;
9504 done:
9505 free(id_str);
9506 return err;
9509 static const struct got_error *
9510 histedit_syntax_error(int lineno)
9512 static char msg[42];
9513 int ret;
9515 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9516 lineno);
9517 if (ret == -1 || ret >= sizeof(msg))
9518 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9520 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9523 static const struct got_error *
9524 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9525 char *logmsg, struct got_repository *repo)
9527 const struct got_error *err;
9528 struct got_commit_object *folded_commit = NULL;
9529 char *id_str, *folded_logmsg = NULL;
9531 err = got_object_id_str(&id_str, hle->commit_id);
9532 if (err)
9533 return err;
9535 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9536 if (err)
9537 goto done;
9539 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9540 if (err)
9541 goto done;
9542 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9543 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9544 folded_logmsg) == -1) {
9545 err = got_error_from_errno("asprintf");
9547 done:
9548 if (folded_commit)
9549 got_object_commit_close(folded_commit);
9550 free(id_str);
9551 free(folded_logmsg);
9552 return err;
9555 static struct got_histedit_list_entry *
9556 get_folded_commits(struct got_histedit_list_entry *hle)
9558 struct got_histedit_list_entry *prev, *folded = NULL;
9560 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9561 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9562 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9563 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9564 folded = prev;
9565 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9568 return folded;
9571 static const struct got_error *
9572 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9573 struct got_repository *repo)
9575 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9576 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9577 const struct got_error *err = NULL;
9578 struct got_commit_object *commit = NULL;
9579 int logmsg_len;
9580 int fd;
9581 struct got_histedit_list_entry *folded = NULL;
9583 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9584 if (err)
9585 return err;
9587 folded = get_folded_commits(hle);
9588 if (folded) {
9589 while (folded != hle) {
9590 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9591 folded = TAILQ_NEXT(folded, entry);
9592 continue;
9594 err = append_folded_commit_msg(&new_msg, folded,
9595 logmsg, repo);
9596 if (err)
9597 goto done;
9598 free(logmsg);
9599 logmsg = new_msg;
9600 folded = TAILQ_NEXT(folded, entry);
9604 err = got_object_id_str(&id_str, hle->commit_id);
9605 if (err)
9606 goto done;
9607 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9608 if (err)
9609 goto done;
9610 logmsg_len = asprintf(&new_msg,
9611 "%s\n# original log message of commit %s: %s",
9612 logmsg ? logmsg : "", id_str, orig_logmsg);
9613 if (logmsg_len == -1) {
9614 err = got_error_from_errno("asprintf");
9615 goto done;
9617 free(logmsg);
9618 logmsg = new_msg;
9620 err = got_object_id_str(&id_str, hle->commit_id);
9621 if (err)
9622 goto done;
9624 err = got_opentemp_named_fd(&logmsg_path, &fd,
9625 GOT_TMPDIR_STR "/got-logmsg");
9626 if (err)
9627 goto done;
9629 write(fd, logmsg, logmsg_len);
9630 close(fd);
9632 err = get_editor(&editor);
9633 if (err)
9634 goto done;
9636 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9637 logmsg_len, 0);
9638 if (err) {
9639 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9640 goto done;
9641 err = NULL;
9642 hle->logmsg = strdup(new_msg);
9643 if (hle->logmsg == NULL)
9644 err = got_error_from_errno("strdup");
9646 done:
9647 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9648 err = got_error_from_errno2("unlink", logmsg_path);
9649 free(logmsg_path);
9650 free(logmsg);
9651 free(orig_logmsg);
9652 free(editor);
9653 if (commit)
9654 got_object_commit_close(commit);
9655 return err;
9658 static const struct got_error *
9659 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9660 FILE *f, struct got_repository *repo)
9662 const struct got_error *err = NULL;
9663 char *line = NULL, *p, *end;
9664 size_t i, size;
9665 ssize_t len;
9666 int lineno = 0;
9667 const struct got_histedit_cmd *cmd;
9668 struct got_object_id *commit_id = NULL;
9669 struct got_histedit_list_entry *hle = NULL;
9671 for (;;) {
9672 len = getline(&line, &size, f);
9673 if (len == -1) {
9674 const struct got_error *getline_err;
9675 if (feof(f))
9676 break;
9677 getline_err = got_error_from_errno("getline");
9678 err = got_ferror(f, getline_err->code);
9679 break;
9681 lineno++;
9682 p = line;
9683 while (isspace((unsigned char)p[0]))
9684 p++;
9685 if (p[0] == '#' || p[0] == '\0') {
9686 free(line);
9687 line = NULL;
9688 continue;
9690 cmd = NULL;
9691 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9692 cmd = &got_histedit_cmds[i];
9693 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9694 isspace((unsigned char)p[strlen(cmd->name)])) {
9695 p += strlen(cmd->name);
9696 break;
9698 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9699 p++;
9700 break;
9703 if (i == nitems(got_histedit_cmds)) {
9704 err = histedit_syntax_error(lineno);
9705 break;
9707 while (isspace((unsigned char)p[0]))
9708 p++;
9709 if (cmd->code == GOT_HISTEDIT_MESG) {
9710 if (hle == NULL || hle->logmsg != NULL) {
9711 err = got_error(GOT_ERR_HISTEDIT_CMD);
9712 break;
9714 if (p[0] == '\0') {
9715 err = histedit_edit_logmsg(hle, repo);
9716 if (err)
9717 break;
9718 } else {
9719 hle->logmsg = strdup(p);
9720 if (hle->logmsg == NULL) {
9721 err = got_error_from_errno("strdup");
9722 break;
9725 free(line);
9726 line = NULL;
9727 continue;
9728 } else {
9729 end = p;
9730 while (end[0] && !isspace((unsigned char)end[0]))
9731 end++;
9732 *end = '\0';
9734 err = got_object_resolve_id_str(&commit_id, repo, p);
9735 if (err) {
9736 /* override error code */
9737 err = histedit_syntax_error(lineno);
9738 break;
9741 hle = malloc(sizeof(*hle));
9742 if (hle == NULL) {
9743 err = got_error_from_errno("malloc");
9744 break;
9746 hle->cmd = cmd;
9747 hle->commit_id = commit_id;
9748 hle->logmsg = NULL;
9749 commit_id = NULL;
9750 free(line);
9751 line = NULL;
9752 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9755 free(line);
9756 free(commit_id);
9757 return err;
9760 static const struct got_error *
9761 histedit_check_script(struct got_histedit_list *histedit_cmds,
9762 struct got_object_id_queue *commits, struct got_repository *repo)
9764 const struct got_error *err = NULL;
9765 struct got_object_qid *qid;
9766 struct got_histedit_list_entry *hle;
9767 static char msg[92];
9768 char *id_str;
9770 if (TAILQ_EMPTY(histedit_cmds))
9771 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9772 "histedit script contains no commands");
9773 if (STAILQ_EMPTY(commits))
9774 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9776 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9777 struct got_histedit_list_entry *hle2;
9778 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9779 if (hle == hle2)
9780 continue;
9781 if (got_object_id_cmp(hle->commit_id,
9782 hle2->commit_id) != 0)
9783 continue;
9784 err = got_object_id_str(&id_str, hle->commit_id);
9785 if (err)
9786 return err;
9787 snprintf(msg, sizeof(msg), "commit %s is listed "
9788 "more than once in histedit script", id_str);
9789 free(id_str);
9790 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9794 STAILQ_FOREACH(qid, commits, entry) {
9795 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9796 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9797 break;
9799 if (hle == NULL) {
9800 err = got_object_id_str(&id_str, qid->id);
9801 if (err)
9802 return err;
9803 snprintf(msg, sizeof(msg),
9804 "commit %s missing from histedit script", id_str);
9805 free(id_str);
9806 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9810 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9811 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9812 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9813 "last commit in histedit script cannot be folded");
9815 return NULL;
9818 static const struct got_error *
9819 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9820 const char *path, struct got_object_id_queue *commits,
9821 struct got_repository *repo)
9823 const struct got_error *err = NULL;
9824 char *editor;
9825 FILE *f = NULL;
9827 err = get_editor(&editor);
9828 if (err)
9829 return err;
9831 if (spawn_editor(editor, path) == -1) {
9832 err = got_error_from_errno("failed spawning editor");
9833 goto done;
9836 f = fopen(path, "re");
9837 if (f == NULL) {
9838 err = got_error_from_errno("fopen");
9839 goto done;
9841 err = histedit_parse_list(histedit_cmds, f, repo);
9842 if (err)
9843 goto done;
9845 err = histedit_check_script(histedit_cmds, commits, repo);
9846 done:
9847 if (f && fclose(f) == EOF && err == NULL)
9848 err = got_error_from_errno("fclose");
9849 free(editor);
9850 return err;
9853 static const struct got_error *
9854 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9855 struct got_object_id_queue *, const char *, const char *,
9856 struct got_repository *);
9858 static const struct got_error *
9859 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9860 struct got_object_id_queue *commits, const char *branch_name,
9861 int edit_logmsg_only, int fold_only, int edit_only,
9862 struct got_repository *repo)
9864 const struct got_error *err;
9865 FILE *f = NULL;
9866 char *path = NULL;
9868 err = got_opentemp_named(&path, &f, "got-histedit");
9869 if (err)
9870 return err;
9872 err = write_cmd_list(f, branch_name, commits);
9873 if (err)
9874 goto done;
9876 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9877 fold_only, edit_only, repo);
9878 if (err)
9879 goto done;
9881 if (edit_logmsg_only || fold_only || edit_only) {
9882 rewind(f);
9883 err = histedit_parse_list(histedit_cmds, f, repo);
9884 } else {
9885 if (fclose(f) == EOF) {
9886 err = got_error_from_errno("fclose");
9887 goto done;
9889 f = NULL;
9890 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9891 if (err) {
9892 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9893 err->code != GOT_ERR_HISTEDIT_CMD)
9894 goto done;
9895 err = histedit_edit_list_retry(histedit_cmds, err,
9896 commits, path, branch_name, repo);
9899 done:
9900 if (f && fclose(f) == EOF && err == NULL)
9901 err = got_error_from_errno("fclose");
9902 if (path && unlink(path) != 0 && err == NULL)
9903 err = got_error_from_errno2("unlink", path);
9904 free(path);
9905 return err;
9908 static const struct got_error *
9909 histedit_save_list(struct got_histedit_list *histedit_cmds,
9910 struct got_worktree *worktree, struct got_repository *repo)
9912 const struct got_error *err = NULL;
9913 char *path = NULL;
9914 FILE *f = NULL;
9915 struct got_histedit_list_entry *hle;
9916 struct got_commit_object *commit = NULL;
9918 err = got_worktree_get_histedit_script_path(&path, worktree);
9919 if (err)
9920 return err;
9922 f = fopen(path, "we");
9923 if (f == NULL) {
9924 err = got_error_from_errno2("fopen", path);
9925 goto done;
9927 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9928 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9929 repo);
9930 if (err)
9931 break;
9933 if (hle->logmsg) {
9934 int n = fprintf(f, "%c %s\n",
9935 GOT_HISTEDIT_MESG, hle->logmsg);
9936 if (n < 0) {
9937 err = got_ferror(f, GOT_ERR_IO);
9938 break;
9942 done:
9943 if (f && fclose(f) == EOF && err == NULL)
9944 err = got_error_from_errno("fclose");
9945 free(path);
9946 if (commit)
9947 got_object_commit_close(commit);
9948 return err;
9951 void
9952 histedit_free_list(struct got_histedit_list *histedit_cmds)
9954 struct got_histedit_list_entry *hle;
9956 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9957 TAILQ_REMOVE(histedit_cmds, hle, entry);
9958 free(hle);
9962 static const struct got_error *
9963 histedit_load_list(struct got_histedit_list *histedit_cmds,
9964 const char *path, struct got_repository *repo)
9966 const struct got_error *err = NULL;
9967 FILE *f = NULL;
9969 f = fopen(path, "re");
9970 if (f == NULL) {
9971 err = got_error_from_errno2("fopen", path);
9972 goto done;
9975 err = histedit_parse_list(histedit_cmds, f, repo);
9976 done:
9977 if (f && fclose(f) == EOF && err == NULL)
9978 err = got_error_from_errno("fclose");
9979 return err;
9982 static const struct got_error *
9983 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9984 const struct got_error *edit_err, struct got_object_id_queue *commits,
9985 const char *path, const char *branch_name, struct got_repository *repo)
9987 const struct got_error *err = NULL, *prev_err = edit_err;
9988 int resp = ' ';
9990 while (resp != 'c' && resp != 'r' && resp != 'a') {
9991 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9992 "or (a)bort: ", getprogname(), prev_err->msg);
9993 resp = getchar();
9994 if (resp == '\n')
9995 resp = getchar();
9996 if (resp == 'c') {
9997 histedit_free_list(histedit_cmds);
9998 err = histedit_run_editor(histedit_cmds, path, commits,
9999 repo);
10000 if (err) {
10001 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10002 err->code != GOT_ERR_HISTEDIT_CMD)
10003 break;
10004 prev_err = err;
10005 resp = ' ';
10006 continue;
10008 break;
10009 } else if (resp == 'r') {
10010 histedit_free_list(histedit_cmds);
10011 err = histedit_edit_script(histedit_cmds,
10012 commits, branch_name, 0, 0, 0, repo);
10013 if (err) {
10014 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10015 err->code != GOT_ERR_HISTEDIT_CMD)
10016 break;
10017 prev_err = err;
10018 resp = ' ';
10019 continue;
10021 break;
10022 } else if (resp == 'a') {
10023 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10024 break;
10025 } else
10026 printf("invalid response '%c'\n", resp);
10029 return err;
10032 static const struct got_error *
10033 histedit_complete(struct got_worktree *worktree,
10034 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10035 struct got_reference *branch, struct got_repository *repo)
10037 printf("Switching work tree to %s\n",
10038 got_ref_get_symref_target(branch));
10039 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10040 branch, repo);
10043 static const struct got_error *
10044 show_histedit_progress(struct got_commit_object *commit,
10045 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10047 const struct got_error *err;
10048 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10050 err = got_object_id_str(&old_id_str, hle->commit_id);
10051 if (err)
10052 goto done;
10054 if (new_id) {
10055 err = got_object_id_str(&new_id_str, new_id);
10056 if (err)
10057 goto done;
10060 old_id_str[12] = '\0';
10061 if (new_id_str)
10062 new_id_str[12] = '\0';
10064 if (hle->logmsg) {
10065 logmsg = strdup(hle->logmsg);
10066 if (logmsg == NULL) {
10067 err = got_error_from_errno("strdup");
10068 goto done;
10070 trim_logmsg(logmsg, 42);
10071 } else {
10072 err = get_short_logmsg(&logmsg, 42, commit);
10073 if (err)
10074 goto done;
10077 switch (hle->cmd->code) {
10078 case GOT_HISTEDIT_PICK:
10079 case GOT_HISTEDIT_EDIT:
10080 printf("%s -> %s: %s\n", old_id_str,
10081 new_id_str ? new_id_str : "no-op change", logmsg);
10082 break;
10083 case GOT_HISTEDIT_DROP:
10084 case GOT_HISTEDIT_FOLD:
10085 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10086 logmsg);
10087 break;
10088 default:
10089 break;
10091 done:
10092 free(old_id_str);
10093 free(new_id_str);
10094 return err;
10097 static const struct got_error *
10098 histedit_commit(struct got_pathlist_head *merged_paths,
10099 struct got_worktree *worktree, struct got_fileindex *fileindex,
10100 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10101 struct got_repository *repo)
10103 const struct got_error *err;
10104 struct got_commit_object *commit;
10105 struct got_object_id *new_commit_id;
10107 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10108 && hle->logmsg == NULL) {
10109 err = histedit_edit_logmsg(hle, repo);
10110 if (err)
10111 return err;
10114 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10115 if (err)
10116 return err;
10118 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10119 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10120 hle->logmsg, repo);
10121 if (err) {
10122 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10123 goto done;
10124 err = show_histedit_progress(commit, hle, NULL);
10125 } else {
10126 err = show_histedit_progress(commit, hle, new_commit_id);
10127 free(new_commit_id);
10129 done:
10130 got_object_commit_close(commit);
10131 return err;
10134 static const struct got_error *
10135 histedit_skip_commit(struct got_histedit_list_entry *hle,
10136 struct got_worktree *worktree, struct got_repository *repo)
10138 const struct got_error *error;
10139 struct got_commit_object *commit;
10141 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10142 repo);
10143 if (error)
10144 return error;
10146 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10147 if (error)
10148 return error;
10150 error = show_histedit_progress(commit, hle, NULL);
10151 got_object_commit_close(commit);
10152 return error;
10155 static const struct got_error *
10156 check_local_changes(void *arg, unsigned char status,
10157 unsigned char staged_status, const char *path,
10158 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10159 struct got_object_id *commit_id, int dirfd, const char *de_name)
10161 int *have_local_changes = arg;
10163 switch (status) {
10164 case GOT_STATUS_ADD:
10165 case GOT_STATUS_DELETE:
10166 case GOT_STATUS_MODIFY:
10167 case GOT_STATUS_CONFLICT:
10168 *have_local_changes = 1;
10169 return got_error(GOT_ERR_CANCELLED);
10170 default:
10171 break;
10174 switch (staged_status) {
10175 case GOT_STATUS_ADD:
10176 case GOT_STATUS_DELETE:
10177 case GOT_STATUS_MODIFY:
10178 *have_local_changes = 1;
10179 return got_error(GOT_ERR_CANCELLED);
10180 default:
10181 break;
10184 return NULL;
10187 static const struct got_error *
10188 cmd_histedit(int argc, char *argv[])
10190 const struct got_error *error = NULL;
10191 struct got_worktree *worktree = NULL;
10192 struct got_fileindex *fileindex = NULL;
10193 struct got_repository *repo = NULL;
10194 char *cwd = NULL;
10195 struct got_reference *branch = NULL;
10196 struct got_reference *tmp_branch = NULL;
10197 struct got_object_id *resume_commit_id = NULL;
10198 struct got_object_id *base_commit_id = NULL;
10199 struct got_object_id *head_commit_id = NULL;
10200 struct got_commit_object *commit = NULL;
10201 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10202 struct got_update_progress_arg upa;
10203 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10204 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10205 int list_backups = 0, delete_backups = 0;
10206 const char *edit_script_path = NULL;
10207 struct got_object_id_queue commits;
10208 struct got_pathlist_head merged_paths;
10209 const struct got_object_id_queue *parent_ids;
10210 struct got_object_qid *pid;
10211 struct got_histedit_list histedit_cmds;
10212 struct got_histedit_list_entry *hle;
10214 STAILQ_INIT(&commits);
10215 TAILQ_INIT(&histedit_cmds);
10216 TAILQ_INIT(&merged_paths);
10217 memset(&upa, 0, sizeof(upa));
10219 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10220 switch (ch) {
10221 case 'a':
10222 abort_edit = 1;
10223 break;
10224 case 'c':
10225 continue_edit = 1;
10226 break;
10227 case 'e':
10228 edit_only = 1;
10229 break;
10230 case 'f':
10231 fold_only = 1;
10232 break;
10233 case 'F':
10234 edit_script_path = optarg;
10235 break;
10236 case 'm':
10237 edit_logmsg_only = 1;
10238 break;
10239 case 'l':
10240 list_backups = 1;
10241 break;
10242 case 'X':
10243 delete_backups = 1;
10244 break;
10245 default:
10246 usage_histedit();
10247 /* NOTREACHED */
10251 argc -= optind;
10252 argv += optind;
10254 #ifndef PROFILE
10255 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10256 "unveil", NULL) == -1)
10257 err(1, "pledge");
10258 #endif
10259 if (abort_edit && continue_edit)
10260 option_conflict('a', 'c');
10261 if (edit_script_path && edit_logmsg_only)
10262 option_conflict('F', 'm');
10263 if (abort_edit && edit_logmsg_only)
10264 option_conflict('a', 'm');
10265 if (continue_edit && edit_logmsg_only)
10266 option_conflict('c', 'm');
10267 if (abort_edit && fold_only)
10268 option_conflict('a', 'f');
10269 if (continue_edit && fold_only)
10270 option_conflict('c', 'f');
10271 if (fold_only && edit_logmsg_only)
10272 option_conflict('f', 'm');
10273 if (edit_script_path && fold_only)
10274 option_conflict('F', 'f');
10275 if (abort_edit && edit_only)
10276 option_conflict('a', 'e');
10277 if (continue_edit && edit_only)
10278 option_conflict('c', 'e');
10279 if (edit_only && edit_logmsg_only)
10280 option_conflict('e', 'm');
10281 if (edit_script_path && edit_only)
10282 option_conflict('F', 'e');
10283 if (list_backups) {
10284 if (abort_edit)
10285 option_conflict('l', 'a');
10286 if (continue_edit)
10287 option_conflict('l', 'c');
10288 if (edit_script_path)
10289 option_conflict('l', 'F');
10290 if (edit_logmsg_only)
10291 option_conflict('l', 'm');
10292 if (fold_only)
10293 option_conflict('l', 'f');
10294 if (edit_only)
10295 option_conflict('l', 'e');
10296 if (delete_backups)
10297 option_conflict('l', 'X');
10298 if (argc != 0 && argc != 1)
10299 usage_histedit();
10300 } else if (delete_backups) {
10301 if (abort_edit)
10302 option_conflict('X', 'a');
10303 if (continue_edit)
10304 option_conflict('X', 'c');
10305 if (edit_script_path)
10306 option_conflict('X', 'F');
10307 if (edit_logmsg_only)
10308 option_conflict('X', 'm');
10309 if (fold_only)
10310 option_conflict('X', 'f');
10311 if (edit_only)
10312 option_conflict('X', 'e');
10313 if (list_backups)
10314 option_conflict('X', 'l');
10315 if (argc != 0 && argc != 1)
10316 usage_histedit();
10317 } else if (argc != 0)
10318 usage_histedit();
10321 * This command cannot apply unveil(2) in all cases because the
10322 * user may choose to run an editor to edit the histedit script
10323 * and to edit individual commit log messages.
10324 * unveil(2) traverses exec(2); if an editor is used we have to
10325 * apply unveil after edit script and log messages have been written.
10326 * XXX TODO: Make use of unveil(2) where possible.
10329 cwd = getcwd(NULL, 0);
10330 if (cwd == NULL) {
10331 error = got_error_from_errno("getcwd");
10332 goto done;
10334 error = got_worktree_open(&worktree, cwd);
10335 if (error) {
10336 if (list_backups || delete_backups) {
10337 if (error->code != GOT_ERR_NOT_WORKTREE)
10338 goto done;
10339 } else {
10340 if (error->code == GOT_ERR_NOT_WORKTREE)
10341 error = wrap_not_worktree_error(error,
10342 "histedit", cwd);
10343 goto done;
10347 if (list_backups || delete_backups) {
10348 error = got_repo_open(&repo,
10349 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10350 NULL);
10351 if (error != NULL)
10352 goto done;
10353 error = apply_unveil(got_repo_get_path(repo), 0,
10354 worktree ? got_worktree_get_root_path(worktree) : NULL);
10355 if (error)
10356 goto done;
10357 error = process_backup_refs(
10358 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10359 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10360 goto done; /* nothing else to do */
10363 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10364 NULL);
10365 if (error != NULL)
10366 goto done;
10368 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10369 if (error)
10370 goto done;
10371 if (rebase_in_progress) {
10372 error = got_error(GOT_ERR_REBASING);
10373 goto done;
10376 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10377 repo);
10378 if (error)
10379 goto done;
10380 if (merge_in_progress) {
10381 error = got_error(GOT_ERR_MERGE_BUSY);
10382 goto done;
10385 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10386 if (error)
10387 goto done;
10389 if (edit_in_progress && edit_logmsg_only) {
10390 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10391 "histedit operation is in progress in this "
10392 "work tree and must be continued or aborted "
10393 "before the -m option can be used");
10394 goto done;
10396 if (edit_in_progress && fold_only) {
10397 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10398 "histedit operation is in progress in this "
10399 "work tree and must be continued or aborted "
10400 "before the -f option can be used");
10401 goto done;
10403 if (edit_in_progress && edit_only) {
10404 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10405 "histedit operation is in progress in this "
10406 "work tree and must be continued or aborted "
10407 "before the -e option can be used");
10408 goto done;
10411 if (edit_in_progress && abort_edit) {
10412 error = got_worktree_histedit_continue(&resume_commit_id,
10413 &tmp_branch, &branch, &base_commit_id, &fileindex,
10414 worktree, repo);
10415 if (error)
10416 goto done;
10417 printf("Switching work tree to %s\n",
10418 got_ref_get_symref_target(branch));
10419 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10420 branch, base_commit_id, abort_progress, &upa);
10421 if (error)
10422 goto done;
10423 printf("Histedit of %s aborted\n",
10424 got_ref_get_symref_target(branch));
10425 print_merge_progress_stats(&upa);
10426 goto done; /* nothing else to do */
10427 } else if (abort_edit) {
10428 error = got_error(GOT_ERR_NOT_HISTEDIT);
10429 goto done;
10432 if (continue_edit) {
10433 char *path;
10435 if (!edit_in_progress) {
10436 error = got_error(GOT_ERR_NOT_HISTEDIT);
10437 goto done;
10440 error = got_worktree_get_histedit_script_path(&path, worktree);
10441 if (error)
10442 goto done;
10444 error = histedit_load_list(&histedit_cmds, path, repo);
10445 free(path);
10446 if (error)
10447 goto done;
10449 error = got_worktree_histedit_continue(&resume_commit_id,
10450 &tmp_branch, &branch, &base_commit_id, &fileindex,
10451 worktree, repo);
10452 if (error)
10453 goto done;
10455 error = got_ref_resolve(&head_commit_id, repo, branch);
10456 if (error)
10457 goto done;
10459 error = got_object_open_as_commit(&commit, repo,
10460 head_commit_id);
10461 if (error)
10462 goto done;
10463 parent_ids = got_object_commit_get_parent_ids(commit);
10464 pid = STAILQ_FIRST(parent_ids);
10465 if (pid == NULL) {
10466 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10467 goto done;
10469 error = collect_commits(&commits, head_commit_id, pid->id,
10470 base_commit_id, got_worktree_get_path_prefix(worktree),
10471 GOT_ERR_HISTEDIT_PATH, repo);
10472 got_object_commit_close(commit);
10473 commit = NULL;
10474 if (error)
10475 goto done;
10476 } else {
10477 if (edit_in_progress) {
10478 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10479 goto done;
10482 error = got_ref_open(&branch, repo,
10483 got_worktree_get_head_ref_name(worktree), 0);
10484 if (error != NULL)
10485 goto done;
10487 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10488 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10489 "will not edit commit history of a branch outside "
10490 "the \"refs/heads/\" reference namespace");
10491 goto done;
10494 error = got_ref_resolve(&head_commit_id, repo, branch);
10495 got_ref_close(branch);
10496 branch = NULL;
10497 if (error)
10498 goto done;
10500 error = got_object_open_as_commit(&commit, repo,
10501 head_commit_id);
10502 if (error)
10503 goto done;
10504 parent_ids = got_object_commit_get_parent_ids(commit);
10505 pid = STAILQ_FIRST(parent_ids);
10506 if (pid == NULL) {
10507 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10508 goto done;
10510 error = collect_commits(&commits, head_commit_id, pid->id,
10511 got_worktree_get_base_commit_id(worktree),
10512 got_worktree_get_path_prefix(worktree),
10513 GOT_ERR_HISTEDIT_PATH, repo);
10514 got_object_commit_close(commit);
10515 commit = NULL;
10516 if (error)
10517 goto done;
10519 if (STAILQ_EMPTY(&commits)) {
10520 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10521 goto done;
10524 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10525 &base_commit_id, &fileindex, worktree, repo);
10526 if (error)
10527 goto done;
10529 if (edit_script_path) {
10530 error = histedit_load_list(&histedit_cmds,
10531 edit_script_path, repo);
10532 if (error) {
10533 got_worktree_histedit_abort(worktree, fileindex,
10534 repo, branch, base_commit_id,
10535 abort_progress, &upa);
10536 print_merge_progress_stats(&upa);
10537 goto done;
10539 } else {
10540 const char *branch_name;
10541 branch_name = got_ref_get_symref_target(branch);
10542 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10543 branch_name += 11;
10544 error = histedit_edit_script(&histedit_cmds, &commits,
10545 branch_name, edit_logmsg_only, fold_only,
10546 edit_only, repo);
10547 if (error) {
10548 got_worktree_histedit_abort(worktree, fileindex,
10549 repo, branch, base_commit_id,
10550 abort_progress, &upa);
10551 print_merge_progress_stats(&upa);
10552 goto done;
10557 error = histedit_save_list(&histedit_cmds, worktree,
10558 repo);
10559 if (error) {
10560 got_worktree_histedit_abort(worktree, fileindex,
10561 repo, branch, base_commit_id,
10562 abort_progress, &upa);
10563 print_merge_progress_stats(&upa);
10564 goto done;
10569 error = histedit_check_script(&histedit_cmds, &commits, repo);
10570 if (error)
10571 goto done;
10573 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10574 if (resume_commit_id) {
10575 if (got_object_id_cmp(hle->commit_id,
10576 resume_commit_id) != 0)
10577 continue;
10579 resume_commit_id = NULL;
10580 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10581 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10582 error = histedit_skip_commit(hle, worktree,
10583 repo);
10584 if (error)
10585 goto done;
10586 } else {
10587 struct got_pathlist_head paths;
10588 int have_changes = 0;
10590 TAILQ_INIT(&paths);
10591 error = got_pathlist_append(&paths, "", NULL);
10592 if (error)
10593 goto done;
10594 error = got_worktree_status(worktree, &paths,
10595 repo, 0, check_local_changes, &have_changes,
10596 check_cancelled, NULL);
10597 got_pathlist_free(&paths);
10598 if (error) {
10599 if (error->code != GOT_ERR_CANCELLED)
10600 goto done;
10601 if (sigint_received || sigpipe_received)
10602 goto done;
10604 if (have_changes) {
10605 error = histedit_commit(NULL, worktree,
10606 fileindex, tmp_branch, hle, repo);
10607 if (error)
10608 goto done;
10609 } else {
10610 error = got_object_open_as_commit(
10611 &commit, repo, hle->commit_id);
10612 if (error)
10613 goto done;
10614 error = show_histedit_progress(commit,
10615 hle, NULL);
10616 got_object_commit_close(commit);
10617 commit = NULL;
10618 if (error)
10619 goto done;
10622 continue;
10625 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10626 error = histedit_skip_commit(hle, worktree, repo);
10627 if (error)
10628 goto done;
10629 continue;
10632 error = got_object_open_as_commit(&commit, repo,
10633 hle->commit_id);
10634 if (error)
10635 goto done;
10636 parent_ids = got_object_commit_get_parent_ids(commit);
10637 pid = STAILQ_FIRST(parent_ids);
10639 error = got_worktree_histedit_merge_files(&merged_paths,
10640 worktree, fileindex, pid->id, hle->commit_id, repo,
10641 update_progress, &upa, check_cancelled, NULL);
10642 if (error)
10643 goto done;
10644 got_object_commit_close(commit);
10645 commit = NULL;
10647 print_merge_progress_stats(&upa);
10648 if (upa.conflicts > 0 || upa.missing > 0 ||
10649 upa.not_deleted > 0 || upa.unversioned > 0) {
10650 if (upa.conflicts > 0) {
10651 error = show_rebase_merge_conflict(
10652 hle->commit_id, repo);
10653 if (error)
10654 goto done;
10656 got_worktree_rebase_pathlist_free(&merged_paths);
10657 break;
10660 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10661 char *id_str;
10662 error = got_object_id_str(&id_str, hle->commit_id);
10663 if (error)
10664 goto done;
10665 printf("Stopping histedit for amending commit %s\n",
10666 id_str);
10667 free(id_str);
10668 got_worktree_rebase_pathlist_free(&merged_paths);
10669 error = got_worktree_histedit_postpone(worktree,
10670 fileindex);
10671 goto done;
10674 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10675 error = histedit_skip_commit(hle, worktree, repo);
10676 if (error)
10677 goto done;
10678 continue;
10681 error = histedit_commit(&merged_paths, worktree, fileindex,
10682 tmp_branch, hle, repo);
10683 got_worktree_rebase_pathlist_free(&merged_paths);
10684 if (error)
10685 goto done;
10688 if (upa.conflicts > 0 || upa.missing > 0 ||
10689 upa.not_deleted > 0 || upa.unversioned > 0) {
10690 error = got_worktree_histedit_postpone(worktree, fileindex);
10691 if (error)
10692 goto done;
10693 if (upa.conflicts > 0 && upa.missing == 0 &&
10694 upa.not_deleted == 0 && upa.unversioned == 0) {
10695 error = got_error_msg(GOT_ERR_CONFLICTS,
10696 "conflicts must be resolved before histedit "
10697 "can continue");
10698 } else if (upa.conflicts > 0) {
10699 error = got_error_msg(GOT_ERR_CONFLICTS,
10700 "conflicts must be resolved before histedit "
10701 "can continue; changes destined for some "
10702 "files were not yet merged and should be "
10703 "merged manually if required before the "
10704 "histedit operation is continued");
10705 } else {
10706 error = got_error_msg(GOT_ERR_CONFLICTS,
10707 "changes destined for some files were not "
10708 "yet merged and should be merged manually "
10709 "if required before the histedit operation "
10710 "is continued");
10712 } else
10713 error = histedit_complete(worktree, fileindex, tmp_branch,
10714 branch, repo);
10715 done:
10716 got_object_id_queue_free(&commits);
10717 histedit_free_list(&histedit_cmds);
10718 free(head_commit_id);
10719 free(base_commit_id);
10720 free(resume_commit_id);
10721 if (commit)
10722 got_object_commit_close(commit);
10723 if (branch)
10724 got_ref_close(branch);
10725 if (tmp_branch)
10726 got_ref_close(tmp_branch);
10727 if (worktree)
10728 got_worktree_close(worktree);
10729 if (repo) {
10730 const struct got_error *close_err = got_repo_close(repo);
10731 if (error == NULL)
10732 error = close_err;
10734 return error;
10737 __dead static void
10738 usage_integrate(void)
10740 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10741 exit(1);
10744 static const struct got_error *
10745 cmd_integrate(int argc, char *argv[])
10747 const struct got_error *error = NULL;
10748 struct got_repository *repo = NULL;
10749 struct got_worktree *worktree = NULL;
10750 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10751 const char *branch_arg = NULL;
10752 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10753 struct got_fileindex *fileindex = NULL;
10754 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10755 int ch;
10756 struct got_update_progress_arg upa;
10758 while ((ch = getopt(argc, argv, "")) != -1) {
10759 switch (ch) {
10760 default:
10761 usage_integrate();
10762 /* NOTREACHED */
10766 argc -= optind;
10767 argv += optind;
10769 if (argc != 1)
10770 usage_integrate();
10771 branch_arg = argv[0];
10772 #ifndef PROFILE
10773 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10774 "unveil", NULL) == -1)
10775 err(1, "pledge");
10776 #endif
10777 cwd = getcwd(NULL, 0);
10778 if (cwd == NULL) {
10779 error = got_error_from_errno("getcwd");
10780 goto done;
10783 error = got_worktree_open(&worktree, cwd);
10784 if (error) {
10785 if (error->code == GOT_ERR_NOT_WORKTREE)
10786 error = wrap_not_worktree_error(error, "integrate",
10787 cwd);
10788 goto done;
10791 error = check_rebase_or_histedit_in_progress(worktree);
10792 if (error)
10793 goto done;
10795 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10796 NULL);
10797 if (error != NULL)
10798 goto done;
10800 error = apply_unveil(got_repo_get_path(repo), 0,
10801 got_worktree_get_root_path(worktree));
10802 if (error)
10803 goto done;
10805 error = check_merge_in_progress(worktree, repo);
10806 if (error)
10807 goto done;
10809 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10810 error = got_error_from_errno("asprintf");
10811 goto done;
10814 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10815 &base_branch_ref, worktree, refname, repo);
10816 if (error)
10817 goto done;
10819 refname = strdup(got_ref_get_name(branch_ref));
10820 if (refname == NULL) {
10821 error = got_error_from_errno("strdup");
10822 got_worktree_integrate_abort(worktree, fileindex, repo,
10823 branch_ref, base_branch_ref);
10824 goto done;
10826 base_refname = strdup(got_ref_get_name(base_branch_ref));
10827 if (base_refname == NULL) {
10828 error = got_error_from_errno("strdup");
10829 got_worktree_integrate_abort(worktree, fileindex, repo,
10830 branch_ref, base_branch_ref);
10831 goto done;
10834 error = got_ref_resolve(&commit_id, repo, branch_ref);
10835 if (error)
10836 goto done;
10838 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10839 if (error)
10840 goto done;
10842 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10843 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10844 "specified branch has already been integrated");
10845 got_worktree_integrate_abort(worktree, fileindex, repo,
10846 branch_ref, base_branch_ref);
10847 goto done;
10850 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10851 if (error) {
10852 if (error->code == GOT_ERR_ANCESTRY)
10853 error = got_error(GOT_ERR_REBASE_REQUIRED);
10854 got_worktree_integrate_abort(worktree, fileindex, repo,
10855 branch_ref, base_branch_ref);
10856 goto done;
10859 memset(&upa, 0, sizeof(upa));
10860 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10861 branch_ref, base_branch_ref, update_progress, &upa,
10862 check_cancelled, NULL);
10863 if (error)
10864 goto done;
10866 printf("Integrated %s into %s\n", refname, base_refname);
10867 print_update_progress_stats(&upa);
10868 done:
10869 if (repo) {
10870 const struct got_error *close_err = got_repo_close(repo);
10871 if (error == NULL)
10872 error = close_err;
10874 if (worktree)
10875 got_worktree_close(worktree);
10876 free(cwd);
10877 free(base_commit_id);
10878 free(commit_id);
10879 free(refname);
10880 free(base_refname);
10881 return error;
10884 __dead static void
10885 usage_merge(void)
10887 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
10888 getprogname());
10889 exit(1);
10892 static const struct got_error *
10893 cmd_merge(int argc, char *argv[])
10895 const struct got_error *error = NULL;
10896 struct got_worktree *worktree = NULL;
10897 struct got_repository *repo = NULL;
10898 struct got_fileindex *fileindex = NULL;
10899 char *cwd = NULL, *id_str = NULL, *author = NULL;
10900 struct got_reference *branch = NULL, *wt_branch = NULL;
10901 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
10902 struct got_object_id *wt_branch_tip = NULL;
10903 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
10904 int interrupt_merge = 0;
10905 struct got_update_progress_arg upa;
10906 struct got_object_id *merge_commit_id = NULL;
10907 char *branch_name = NULL;
10909 memset(&upa, 0, sizeof(upa));
10911 while ((ch = getopt(argc, argv, "acn")) != -1) {
10912 switch (ch) {
10913 case 'a':
10914 abort_merge = 1;
10915 break;
10916 case 'c':
10917 continue_merge = 1;
10918 break;
10919 case 'n':
10920 interrupt_merge = 1;
10921 break;
10922 default:
10923 usage_rebase();
10924 /* NOTREACHED */
10928 argc -= optind;
10929 argv += optind;
10931 #ifndef PROFILE
10932 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10933 "unveil", NULL) == -1)
10934 err(1, "pledge");
10935 #endif
10937 if (abort_merge && continue_merge)
10938 option_conflict('a', 'c');
10939 if (abort_merge || continue_merge) {
10940 if (argc != 0)
10941 usage_merge();
10942 } else if (argc != 1)
10943 usage_merge();
10945 cwd = getcwd(NULL, 0);
10946 if (cwd == NULL) {
10947 error = got_error_from_errno("getcwd");
10948 goto done;
10951 error = got_worktree_open(&worktree, cwd);
10952 if (error) {
10953 if (error->code == GOT_ERR_NOT_WORKTREE)
10954 error = wrap_not_worktree_error(error,
10955 "merge", cwd);
10956 goto done;
10959 error = got_repo_open(&repo,
10960 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
10961 if (error != NULL)
10962 goto done;
10964 error = apply_unveil(got_repo_get_path(repo), 0,
10965 worktree ? got_worktree_get_root_path(worktree) : NULL);
10966 if (error)
10967 goto done;
10969 error = check_rebase_or_histedit_in_progress(worktree);
10970 if (error)
10971 goto done;
10973 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10974 repo);
10975 if (error)
10976 goto done;
10978 if (abort_merge) {
10979 if (!merge_in_progress) {
10980 error = got_error(GOT_ERR_NOT_MERGING);
10981 goto done;
10983 error = got_worktree_merge_continue(&branch_name,
10984 &branch_tip, &fileindex, worktree, repo);
10985 if (error)
10986 goto done;
10987 error = got_worktree_merge_abort(worktree, fileindex, repo,
10988 abort_progress, &upa);
10989 if (error)
10990 goto done;
10991 printf("Merge of %s aborted\n", branch_name);
10992 goto done; /* nothing else to do */
10995 error = get_author(&author, repo, worktree);
10996 if (error)
10997 goto done;
10999 if (continue_merge) {
11000 if (!merge_in_progress) {
11001 error = got_error(GOT_ERR_NOT_MERGING);
11002 goto done;
11004 error = got_worktree_merge_continue(&branch_name,
11005 &branch_tip, &fileindex, worktree, repo);
11006 if (error)
11007 goto done;
11008 } else {
11009 error = got_ref_open(&branch, repo, argv[0], 0);
11010 if (error != NULL)
11011 goto done;
11012 branch_name = strdup(got_ref_get_name(branch));
11013 if (branch_name == NULL) {
11014 error = got_error_from_errno("strdup");
11015 goto done;
11017 error = got_ref_resolve(&branch_tip, repo, branch);
11018 if (error)
11019 goto done;
11022 error = got_ref_open(&wt_branch, repo,
11023 got_worktree_get_head_ref_name(worktree), 0);
11024 if (error)
11025 goto done;
11026 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11027 if (error)
11028 goto done;
11029 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11030 wt_branch_tip, branch_tip, 0, repo,
11031 check_cancelled, NULL);
11032 if (error && error->code != GOT_ERR_ANCESTRY)
11033 goto done;
11035 if (!continue_merge) {
11036 error = check_path_prefix(wt_branch_tip, branch_tip,
11037 got_worktree_get_path_prefix(worktree),
11038 GOT_ERR_MERGE_PATH, repo);
11039 if (error)
11040 goto done;
11041 if (yca_id) {
11042 error = check_same_branch(wt_branch_tip, branch,
11043 yca_id, repo);
11044 if (error) {
11045 if (error->code != GOT_ERR_ANCESTRY)
11046 goto done;
11047 error = NULL;
11048 } else {
11049 static char msg[512];
11050 snprintf(msg, sizeof(msg),
11051 "cannot create a merge commit because "
11052 "%s is based on %s; %s can be integrated "
11053 "with 'got integrate' instead", branch_name,
11054 got_worktree_get_head_ref_name(worktree),
11055 branch_name);
11056 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11057 goto done;
11060 error = got_worktree_merge_prepare(&fileindex, worktree,
11061 branch, repo);
11062 if (error)
11063 goto done;
11065 error = got_worktree_merge_branch(worktree, fileindex,
11066 yca_id, branch_tip, repo, update_progress, &upa,
11067 check_cancelled, NULL);
11068 if (error)
11069 goto done;
11070 print_merge_progress_stats(&upa);
11071 if (!upa.did_something) {
11072 error = got_worktree_merge_abort(worktree, fileindex,
11073 repo, abort_progress, &upa);
11074 if (error)
11075 goto done;
11076 printf("Already up-to-date\n");
11077 goto done;
11081 if (interrupt_merge) {
11082 error = got_worktree_merge_postpone(worktree, fileindex);
11083 if (error)
11084 goto done;
11085 printf("Merge of %s interrupted on request\n", branch_name);
11086 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11087 upa.not_deleted > 0 || upa.unversioned > 0) {
11088 error = got_worktree_merge_postpone(worktree, fileindex);
11089 if (error)
11090 goto done;
11091 if (upa.conflicts > 0 && upa.missing == 0 &&
11092 upa.not_deleted == 0 && upa.unversioned == 0) {
11093 error = got_error_msg(GOT_ERR_CONFLICTS,
11094 "conflicts must be resolved before merging "
11095 "can continue");
11096 } else if (upa.conflicts > 0) {
11097 error = got_error_msg(GOT_ERR_CONFLICTS,
11098 "conflicts must be resolved before merging "
11099 "can continue; changes destined for some "
11100 "files were not yet merged and "
11101 "should be merged manually if required before the "
11102 "merge operation is continued");
11103 } else {
11104 error = got_error_msg(GOT_ERR_CONFLICTS,
11105 "changes destined for some "
11106 "files were not yet merged and should be "
11107 "merged manually if required before the "
11108 "merge operation is continued");
11110 goto done;
11111 } else {
11112 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11113 fileindex, author, NULL, 1, branch_tip, branch_name,
11114 repo, continue_merge ? print_status : NULL, NULL);
11115 if (error)
11116 goto done;
11117 error = got_worktree_merge_complete(worktree, fileindex, repo);
11118 if (error)
11119 goto done;
11120 error = got_object_id_str(&id_str, merge_commit_id);
11121 if (error)
11122 goto done;
11123 printf("Merged %s into %s: %s\n", branch_name,
11124 got_worktree_get_head_ref_name(worktree),
11125 id_str);
11128 done:
11129 free(id_str);
11130 free(merge_commit_id);
11131 free(author);
11132 free(branch_tip);
11133 free(branch_name);
11134 free(yca_id);
11135 if (branch)
11136 got_ref_close(branch);
11137 if (wt_branch)
11138 got_ref_close(wt_branch);
11139 if (worktree)
11140 got_worktree_close(worktree);
11141 if (repo) {
11142 const struct got_error *close_err = got_repo_close(repo);
11143 if (error == NULL)
11144 error = close_err;
11146 return error;
11149 __dead static void
11150 usage_stage(void)
11152 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11153 "[-S] [file-path ...]\n",
11154 getprogname());
11155 exit(1);
11158 static const struct got_error *
11159 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11160 const char *path, struct got_object_id *blob_id,
11161 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11162 int dirfd, const char *de_name)
11164 const struct got_error *err = NULL;
11165 char *id_str = NULL;
11167 if (staged_status != GOT_STATUS_ADD &&
11168 staged_status != GOT_STATUS_MODIFY &&
11169 staged_status != GOT_STATUS_DELETE)
11170 return NULL;
11172 if (staged_status == GOT_STATUS_ADD ||
11173 staged_status == GOT_STATUS_MODIFY)
11174 err = got_object_id_str(&id_str, staged_blob_id);
11175 else
11176 err = got_object_id_str(&id_str, blob_id);
11177 if (err)
11178 return err;
11180 printf("%s %c %s\n", id_str, staged_status, path);
11181 free(id_str);
11182 return NULL;
11185 static const struct got_error *
11186 cmd_stage(int argc, char *argv[])
11188 const struct got_error *error = NULL;
11189 struct got_repository *repo = NULL;
11190 struct got_worktree *worktree = NULL;
11191 char *cwd = NULL;
11192 struct got_pathlist_head paths;
11193 struct got_pathlist_entry *pe;
11194 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11195 FILE *patch_script_file = NULL;
11196 const char *patch_script_path = NULL;
11197 struct choose_patch_arg cpa;
11199 TAILQ_INIT(&paths);
11201 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11202 switch (ch) {
11203 case 'l':
11204 list_stage = 1;
11205 break;
11206 case 'p':
11207 pflag = 1;
11208 break;
11209 case 'F':
11210 patch_script_path = optarg;
11211 break;
11212 case 'S':
11213 allow_bad_symlinks = 1;
11214 break;
11215 default:
11216 usage_stage();
11217 /* NOTREACHED */
11221 argc -= optind;
11222 argv += optind;
11224 #ifndef PROFILE
11225 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11226 "unveil", NULL) == -1)
11227 err(1, "pledge");
11228 #endif
11229 if (list_stage && (pflag || patch_script_path))
11230 errx(1, "-l option cannot be used with other options");
11231 if (patch_script_path && !pflag)
11232 errx(1, "-F option can only be used together with -p option");
11234 cwd = getcwd(NULL, 0);
11235 if (cwd == NULL) {
11236 error = got_error_from_errno("getcwd");
11237 goto done;
11240 error = got_worktree_open(&worktree, cwd);
11241 if (error) {
11242 if (error->code == GOT_ERR_NOT_WORKTREE)
11243 error = wrap_not_worktree_error(error, "stage", cwd);
11244 goto done;
11247 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11248 NULL);
11249 if (error != NULL)
11250 goto done;
11252 if (patch_script_path) {
11253 patch_script_file = fopen(patch_script_path, "re");
11254 if (patch_script_file == NULL) {
11255 error = got_error_from_errno2("fopen",
11256 patch_script_path);
11257 goto done;
11260 error = apply_unveil(got_repo_get_path(repo), 0,
11261 got_worktree_get_root_path(worktree));
11262 if (error)
11263 goto done;
11265 error = check_merge_in_progress(worktree, repo);
11266 if (error)
11267 goto done;
11269 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11270 if (error)
11271 goto done;
11273 if (list_stage)
11274 error = got_worktree_status(worktree, &paths, repo, 0,
11275 print_stage, NULL, check_cancelled, NULL);
11276 else {
11277 cpa.patch_script_file = patch_script_file;
11278 cpa.action = "stage";
11279 error = got_worktree_stage(worktree, &paths,
11280 pflag ? NULL : print_status, NULL,
11281 pflag ? choose_patch : NULL, &cpa,
11282 allow_bad_symlinks, repo);
11284 done:
11285 if (patch_script_file && fclose(patch_script_file) == EOF &&
11286 error == NULL)
11287 error = got_error_from_errno2("fclose", patch_script_path);
11288 if (repo) {
11289 const struct got_error *close_err = got_repo_close(repo);
11290 if (error == NULL)
11291 error = close_err;
11293 if (worktree)
11294 got_worktree_close(worktree);
11295 TAILQ_FOREACH(pe, &paths, entry)
11296 free((char *)pe->path);
11297 got_pathlist_free(&paths);
11298 free(cwd);
11299 return error;
11302 __dead static void
11303 usage_unstage(void)
11305 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11306 "[file-path ...]\n",
11307 getprogname());
11308 exit(1);
11312 static const struct got_error *
11313 cmd_unstage(int argc, char *argv[])
11315 const struct got_error *error = NULL;
11316 struct got_repository *repo = NULL;
11317 struct got_worktree *worktree = NULL;
11318 char *cwd = NULL;
11319 struct got_pathlist_head paths;
11320 struct got_pathlist_entry *pe;
11321 int ch, pflag = 0;
11322 struct got_update_progress_arg upa;
11323 FILE *patch_script_file = NULL;
11324 const char *patch_script_path = NULL;
11325 struct choose_patch_arg cpa;
11327 TAILQ_INIT(&paths);
11329 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11330 switch (ch) {
11331 case 'p':
11332 pflag = 1;
11333 break;
11334 case 'F':
11335 patch_script_path = optarg;
11336 break;
11337 default:
11338 usage_unstage();
11339 /* NOTREACHED */
11343 argc -= optind;
11344 argv += optind;
11346 #ifndef PROFILE
11347 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11348 "unveil", NULL) == -1)
11349 err(1, "pledge");
11350 #endif
11351 if (patch_script_path && !pflag)
11352 errx(1, "-F option can only be used together with -p option");
11354 cwd = getcwd(NULL, 0);
11355 if (cwd == NULL) {
11356 error = got_error_from_errno("getcwd");
11357 goto done;
11360 error = got_worktree_open(&worktree, cwd);
11361 if (error) {
11362 if (error->code == GOT_ERR_NOT_WORKTREE)
11363 error = wrap_not_worktree_error(error, "unstage", cwd);
11364 goto done;
11367 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11368 NULL);
11369 if (error != NULL)
11370 goto done;
11372 if (patch_script_path) {
11373 patch_script_file = fopen(patch_script_path, "re");
11374 if (patch_script_file == NULL) {
11375 error = got_error_from_errno2("fopen",
11376 patch_script_path);
11377 goto done;
11381 error = apply_unveil(got_repo_get_path(repo), 0,
11382 got_worktree_get_root_path(worktree));
11383 if (error)
11384 goto done;
11386 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11387 if (error)
11388 goto done;
11390 cpa.patch_script_file = patch_script_file;
11391 cpa.action = "unstage";
11392 memset(&upa, 0, sizeof(upa));
11393 error = got_worktree_unstage(worktree, &paths, update_progress,
11394 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11395 if (!error)
11396 print_merge_progress_stats(&upa);
11397 done:
11398 if (patch_script_file && fclose(patch_script_file) == EOF &&
11399 error == NULL)
11400 error = got_error_from_errno2("fclose", patch_script_path);
11401 if (repo) {
11402 const struct got_error *close_err = got_repo_close(repo);
11403 if (error == NULL)
11404 error = close_err;
11406 if (worktree)
11407 got_worktree_close(worktree);
11408 TAILQ_FOREACH(pe, &paths, entry)
11409 free((char *)pe->path);
11410 got_pathlist_free(&paths);
11411 free(cwd);
11412 return error;
11415 __dead static void
11416 usage_cat(void)
11418 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11419 "arg1 [arg2 ...]\n", getprogname());
11420 exit(1);
11423 static const struct got_error *
11424 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11426 const struct got_error *err;
11427 struct got_blob_object *blob;
11429 err = got_object_open_as_blob(&blob, repo, id, 8192);
11430 if (err)
11431 return err;
11433 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11434 got_object_blob_close(blob);
11435 return err;
11438 static const struct got_error *
11439 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11441 const struct got_error *err;
11442 struct got_tree_object *tree;
11443 int nentries, i;
11445 err = got_object_open_as_tree(&tree, repo, id);
11446 if (err)
11447 return err;
11449 nentries = got_object_tree_get_nentries(tree);
11450 for (i = 0; i < nentries; i++) {
11451 struct got_tree_entry *te;
11452 char *id_str;
11453 if (sigint_received || sigpipe_received)
11454 break;
11455 te = got_object_tree_get_entry(tree, i);
11456 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11457 if (err)
11458 break;
11459 fprintf(outfile, "%s %.7o %s\n", id_str,
11460 got_tree_entry_get_mode(te),
11461 got_tree_entry_get_name(te));
11462 free(id_str);
11465 got_object_tree_close(tree);
11466 return err;
11469 static void
11470 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11472 long long h, m;
11473 char sign = '+';
11475 if (gmtoff < 0) {
11476 sign = '-';
11477 gmtoff = -gmtoff;
11480 h = (long long)gmtoff / 3600;
11481 m = ((long long)gmtoff - h*3600) / 60;
11482 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11485 static const struct got_error *
11486 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11488 const struct got_error *err;
11489 struct got_commit_object *commit;
11490 const struct got_object_id_queue *parent_ids;
11491 struct got_object_qid *pid;
11492 char *id_str = NULL;
11493 const char *logmsg = NULL;
11494 char gmtoff[6];
11496 err = got_object_open_as_commit(&commit, repo, id);
11497 if (err)
11498 return err;
11500 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11501 if (err)
11502 goto done;
11504 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11505 parent_ids = got_object_commit_get_parent_ids(commit);
11506 fprintf(outfile, "numparents %d\n",
11507 got_object_commit_get_nparents(commit));
11508 STAILQ_FOREACH(pid, parent_ids, entry) {
11509 char *pid_str;
11510 err = got_object_id_str(&pid_str, pid->id);
11511 if (err)
11512 goto done;
11513 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11514 free(pid_str);
11516 format_gmtoff(gmtoff, sizeof(gmtoff),
11517 got_object_commit_get_author_gmtoff(commit));
11518 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11519 got_object_commit_get_author(commit),
11520 (long long)got_object_commit_get_author_time(commit),
11521 gmtoff);
11523 format_gmtoff(gmtoff, sizeof(gmtoff),
11524 got_object_commit_get_committer_gmtoff(commit));
11525 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11526 got_object_commit_get_author(commit),
11527 (long long)got_object_commit_get_committer_time(commit),
11528 gmtoff);
11530 logmsg = got_object_commit_get_logmsg_raw(commit);
11531 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11532 fprintf(outfile, "%s", logmsg);
11533 done:
11534 free(id_str);
11535 got_object_commit_close(commit);
11536 return err;
11539 static const struct got_error *
11540 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11542 const struct got_error *err;
11543 struct got_tag_object *tag;
11544 char *id_str = NULL;
11545 const char *tagmsg = NULL;
11546 char gmtoff[6];
11548 err = got_object_open_as_tag(&tag, repo, id);
11549 if (err)
11550 return err;
11552 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11553 if (err)
11554 goto done;
11556 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11558 switch (got_object_tag_get_object_type(tag)) {
11559 case GOT_OBJ_TYPE_BLOB:
11560 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11561 GOT_OBJ_LABEL_BLOB);
11562 break;
11563 case GOT_OBJ_TYPE_TREE:
11564 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11565 GOT_OBJ_LABEL_TREE);
11566 break;
11567 case GOT_OBJ_TYPE_COMMIT:
11568 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11569 GOT_OBJ_LABEL_COMMIT);
11570 break;
11571 case GOT_OBJ_TYPE_TAG:
11572 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11573 GOT_OBJ_LABEL_TAG);
11574 break;
11575 default:
11576 break;
11579 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11580 got_object_tag_get_name(tag));
11582 format_gmtoff(gmtoff, sizeof(gmtoff),
11583 got_object_tag_get_tagger_gmtoff(tag));
11584 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11585 got_object_tag_get_tagger(tag),
11586 (long long)got_object_tag_get_tagger_time(tag),
11587 gmtoff);
11589 tagmsg = got_object_tag_get_message(tag);
11590 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11591 fprintf(outfile, "%s", tagmsg);
11592 done:
11593 free(id_str);
11594 got_object_tag_close(tag);
11595 return err;
11598 static const struct got_error *
11599 cmd_cat(int argc, char *argv[])
11601 const struct got_error *error;
11602 struct got_repository *repo = NULL;
11603 struct got_worktree *worktree = NULL;
11604 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11605 const char *commit_id_str = NULL;
11606 struct got_object_id *id = NULL, *commit_id = NULL;
11607 int ch, obj_type, i, force_path = 0;
11608 struct got_reflist_head refs;
11610 TAILQ_INIT(&refs);
11612 #ifndef PROFILE
11613 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11614 NULL) == -1)
11615 err(1, "pledge");
11616 #endif
11618 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11619 switch (ch) {
11620 case 'c':
11621 commit_id_str = optarg;
11622 break;
11623 case 'r':
11624 repo_path = realpath(optarg, NULL);
11625 if (repo_path == NULL)
11626 return got_error_from_errno2("realpath",
11627 optarg);
11628 got_path_strip_trailing_slashes(repo_path);
11629 break;
11630 case 'P':
11631 force_path = 1;
11632 break;
11633 default:
11634 usage_cat();
11635 /* NOTREACHED */
11639 argc -= optind;
11640 argv += optind;
11642 cwd = getcwd(NULL, 0);
11643 if (cwd == NULL) {
11644 error = got_error_from_errno("getcwd");
11645 goto done;
11647 error = got_worktree_open(&worktree, cwd);
11648 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11649 goto done;
11650 if (worktree) {
11651 if (repo_path == NULL) {
11652 repo_path = strdup(
11653 got_worktree_get_repo_path(worktree));
11654 if (repo_path == NULL) {
11655 error = got_error_from_errno("strdup");
11656 goto done;
11661 if (repo_path == NULL) {
11662 repo_path = getcwd(NULL, 0);
11663 if (repo_path == NULL)
11664 return got_error_from_errno("getcwd");
11667 error = got_repo_open(&repo, repo_path, NULL);
11668 free(repo_path);
11669 if (error != NULL)
11670 goto done;
11672 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11673 if (error)
11674 goto done;
11676 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11677 if (error)
11678 goto done;
11680 if (commit_id_str == NULL)
11681 commit_id_str = GOT_REF_HEAD;
11682 error = got_repo_match_object_id(&commit_id, NULL,
11683 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11684 if (error)
11685 goto done;
11687 for (i = 0; i < argc; i++) {
11688 if (force_path) {
11689 error = got_object_id_by_path(&id, repo, commit_id,
11690 argv[i]);
11691 if (error)
11692 break;
11693 } else {
11694 error = got_repo_match_object_id(&id, &label, argv[i],
11695 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11696 repo);
11697 if (error) {
11698 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11699 error->code != GOT_ERR_NOT_REF)
11700 break;
11701 error = got_object_id_by_path(&id, repo,
11702 commit_id, argv[i]);
11703 if (error)
11704 break;
11708 error = got_object_get_type(&obj_type, repo, id);
11709 if (error)
11710 break;
11712 switch (obj_type) {
11713 case GOT_OBJ_TYPE_BLOB:
11714 error = cat_blob(id, repo, stdout);
11715 break;
11716 case GOT_OBJ_TYPE_TREE:
11717 error = cat_tree(id, repo, stdout);
11718 break;
11719 case GOT_OBJ_TYPE_COMMIT:
11720 error = cat_commit(id, repo, stdout);
11721 break;
11722 case GOT_OBJ_TYPE_TAG:
11723 error = cat_tag(id, repo, stdout);
11724 break;
11725 default:
11726 error = got_error(GOT_ERR_OBJ_TYPE);
11727 break;
11729 if (error)
11730 break;
11731 free(label);
11732 label = NULL;
11733 free(id);
11734 id = NULL;
11736 done:
11737 free(label);
11738 free(id);
11739 free(commit_id);
11740 if (worktree)
11741 got_worktree_close(worktree);
11742 if (repo) {
11743 const struct got_error *close_err = got_repo_close(repo);
11744 if (error == NULL)
11745 error = close_err;
11747 got_ref_list_free(&refs);
11748 return error;
11751 __dead static void
11752 usage_info(void)
11754 fprintf(stderr, "usage: %s info [path ...]\n",
11755 getprogname());
11756 exit(1);
11759 static const struct got_error *
11760 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11761 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11762 struct got_object_id *commit_id)
11764 const struct got_error *err = NULL;
11765 char *id_str = NULL;
11766 char datebuf[128];
11767 struct tm mytm, *tm;
11768 struct got_pathlist_head *paths = arg;
11769 struct got_pathlist_entry *pe;
11772 * Clear error indication from any of the path arguments which
11773 * would cause this file index entry to be displayed.
11775 TAILQ_FOREACH(pe, paths, entry) {
11776 if (got_path_cmp(path, pe->path, strlen(path),
11777 pe->path_len) == 0 ||
11778 got_path_is_child(path, pe->path, pe->path_len))
11779 pe->data = NULL; /* no error */
11782 printf(GOT_COMMIT_SEP_STR);
11783 if (S_ISLNK(mode))
11784 printf("symlink: %s\n", path);
11785 else if (S_ISREG(mode)) {
11786 printf("file: %s\n", path);
11787 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11788 } else if (S_ISDIR(mode))
11789 printf("directory: %s\n", path);
11790 else
11791 printf("something: %s\n", path);
11793 tm = localtime_r(&mtime, &mytm);
11794 if (tm == NULL)
11795 return NULL;
11796 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11797 return got_error(GOT_ERR_NO_SPACE);
11798 printf("timestamp: %s\n", datebuf);
11800 if (blob_id) {
11801 err = got_object_id_str(&id_str, blob_id);
11802 if (err)
11803 return err;
11804 printf("based on blob: %s\n", id_str);
11805 free(id_str);
11808 if (staged_blob_id) {
11809 err = got_object_id_str(&id_str, staged_blob_id);
11810 if (err)
11811 return err;
11812 printf("based on staged blob: %s\n", id_str);
11813 free(id_str);
11816 if (commit_id) {
11817 err = got_object_id_str(&id_str, commit_id);
11818 if (err)
11819 return err;
11820 printf("based on commit: %s\n", id_str);
11821 free(id_str);
11824 return NULL;
11827 static const struct got_error *
11828 cmd_info(int argc, char *argv[])
11830 const struct got_error *error = NULL;
11831 struct got_worktree *worktree = NULL;
11832 char *cwd = NULL, *id_str = NULL;
11833 struct got_pathlist_head paths;
11834 struct got_pathlist_entry *pe;
11835 char *uuidstr = NULL;
11836 int ch, show_files = 0;
11838 TAILQ_INIT(&paths);
11840 while ((ch = getopt(argc, argv, "")) != -1) {
11841 switch (ch) {
11842 default:
11843 usage_info();
11844 /* NOTREACHED */
11848 argc -= optind;
11849 argv += optind;
11851 #ifndef PROFILE
11852 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11853 NULL) == -1)
11854 err(1, "pledge");
11855 #endif
11856 cwd = getcwd(NULL, 0);
11857 if (cwd == NULL) {
11858 error = got_error_from_errno("getcwd");
11859 goto done;
11862 error = got_worktree_open(&worktree, cwd);
11863 if (error) {
11864 if (error->code == GOT_ERR_NOT_WORKTREE)
11865 error = wrap_not_worktree_error(error, "info", cwd);
11866 goto done;
11869 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11870 if (error)
11871 goto done;
11873 if (argc >= 1) {
11874 error = get_worktree_paths_from_argv(&paths, argc, argv,
11875 worktree);
11876 if (error)
11877 goto done;
11878 show_files = 1;
11881 error = got_object_id_str(&id_str,
11882 got_worktree_get_base_commit_id(worktree));
11883 if (error)
11884 goto done;
11886 error = got_worktree_get_uuid(&uuidstr, worktree);
11887 if (error)
11888 goto done;
11890 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11891 printf("work tree base commit: %s\n", id_str);
11892 printf("work tree path prefix: %s\n",
11893 got_worktree_get_path_prefix(worktree));
11894 printf("work tree branch reference: %s\n",
11895 got_worktree_get_head_ref_name(worktree));
11896 printf("work tree UUID: %s\n", uuidstr);
11897 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11899 if (show_files) {
11900 struct got_pathlist_entry *pe;
11901 TAILQ_FOREACH(pe, &paths, entry) {
11902 if (pe->path_len == 0)
11903 continue;
11905 * Assume this path will fail. This will be corrected
11906 * in print_path_info() in case the path does suceeed.
11908 pe->data = (void *)got_error_path(pe->path,
11909 GOT_ERR_BAD_PATH);
11911 error = got_worktree_path_info(worktree, &paths,
11912 print_path_info, &paths, check_cancelled, NULL);
11913 if (error)
11914 goto done;
11915 TAILQ_FOREACH(pe, &paths, entry) {
11916 if (pe->data != NULL) {
11917 error = pe->data; /* bad path */
11918 break;
11922 done:
11923 TAILQ_FOREACH(pe, &paths, entry)
11924 free((char *)pe->path);
11925 got_pathlist_free(&paths);
11926 free(cwd);
11927 free(id_str);
11928 free(uuidstr);
11929 return error;