Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
40 #include <util.h>
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
60 #ifndef nitems
61 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
62 #endif
64 static volatile sig_atomic_t sigint_received;
65 static volatile sig_atomic_t sigpipe_received;
67 static void
68 catch_sigint(int signo)
69 {
70 sigint_received = 1;
71 }
73 static void
74 catch_sigpipe(int signo)
75 {
76 sigpipe_received = 1;
77 }
80 struct got_cmd {
81 const char *cmd_name;
82 const struct got_error *(*cmd_main)(int, char *[]);
83 void (*cmd_usage)(void);
84 const char *cmd_alias;
85 };
87 __dead static void usage(int, int);
88 __dead static void usage_init(void);
89 __dead static void usage_import(void);
90 __dead static void usage_clone(void);
91 __dead static void usage_fetch(void);
92 __dead static void usage_checkout(void);
93 __dead static void usage_update(void);
94 __dead static void usage_log(void);
95 __dead static void usage_diff(void);
96 __dead static void usage_blame(void);
97 __dead static void usage_tree(void);
98 __dead static void usage_status(void);
99 __dead static void usage_ref(void);
100 __dead static void usage_branch(void);
101 __dead static void usage_tag(void);
102 __dead static void usage_add(void);
103 __dead static void usage_remove(void);
104 __dead static void usage_revert(void);
105 __dead static void usage_commit(void);
106 __dead static void usage_send(void);
107 __dead static void usage_cherrypick(void);
108 __dead static void usage_backout(void);
109 __dead static void usage_rebase(void);
110 __dead static void usage_histedit(void);
111 __dead static void usage_integrate(void);
112 __dead static void usage_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 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 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 struct got_cmd *cmd;
203 size_t i;
204 int ch;
205 int hflag = 0, Vflag = 0;
206 static 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 got_commands[i].cmd_usage();
255 error = got_commands[i].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 const struct got_error *
600 get_author(char **author, struct got_repository *repo,
601 struct got_worktree *worktree)
603 const struct got_error *err = NULL;
604 const char *got_author = NULL, *name, *email;
605 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
607 *author = NULL;
609 if (worktree)
610 worktree_conf = got_worktree_get_gotconfig(worktree);
611 repo_conf = got_repo_get_gotconfig(repo);
613 /*
614 * Priority of potential author information sources, from most
615 * significant to least significant:
616 * 1) work tree's .got/got.conf file
617 * 2) repository's got.conf file
618 * 3) repository's git config file
619 * 4) environment variables
620 * 5) global git config files (in user's home directory or /etc)
621 */
623 if (worktree_conf)
624 got_author = got_gotconfig_get_author(worktree_conf);
625 if (got_author == NULL)
626 got_author = got_gotconfig_get_author(repo_conf);
627 if (got_author == NULL) {
628 name = got_repo_get_gitconfig_author_name(repo);
629 email = got_repo_get_gitconfig_author_email(repo);
630 if (name && email) {
631 if (asprintf(author, "%s <%s>", name, email) == -1)
632 return got_error_from_errno("asprintf");
633 return NULL;
636 got_author = getenv("GOT_AUTHOR");
637 if (got_author == NULL) {
638 name = got_repo_get_global_gitconfig_author_name(repo);
639 email = got_repo_get_global_gitconfig_author_email(
640 repo);
641 if (name && email) {
642 if (asprintf(author, "%s <%s>", name, email)
643 == -1)
644 return got_error_from_errno("asprintf");
645 return NULL;
647 /* TODO: Look up user in password database? */
648 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
652 *author = strdup(got_author);
653 if (*author == NULL)
654 return got_error_from_errno("strdup");
656 /*
657 * Really dumb email address check; we're only doing this to
658 * avoid git's object parser breaking on commits we create.
659 */
660 while (*got_author && *got_author != '<')
661 got_author++;
662 if (*got_author != '<') {
663 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
664 goto done;
666 while (*got_author && *got_author != '@')
667 got_author++;
668 if (*got_author != '@') {
669 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
670 goto done;
672 while (*got_author && *got_author != '>')
673 got_author++;
674 if (*got_author != '>')
675 err = got_error(GOT_ERR_COMMIT_NO_EMAIL);
676 done:
677 if (err) {
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, 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 err(1, "-C option %s", errstr);
4114 break;
4115 case 'l':
4116 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4117 if (errstr != NULL)
4118 err(1, "-l option %s", errstr);
4119 break;
4120 case 'b':
4121 log_branches = 1;
4122 break;
4123 case 'r':
4124 repo_path = realpath(optarg, NULL);
4125 if (repo_path == NULL)
4126 return got_error_from_errno2("realpath",
4127 optarg);
4128 got_path_strip_trailing_slashes(repo_path);
4129 break;
4130 case 'R':
4131 reverse_display_order = 1;
4132 break;
4133 case 's':
4134 search_pattern = optarg;
4135 break;
4136 case 'x':
4137 end_commit = optarg;
4138 break;
4139 default:
4140 usage_log();
4141 /* NOTREACHED */
4145 argc -= optind;
4146 argv += optind;
4148 if (diff_context == -1)
4149 diff_context = 3;
4150 else if (!show_patch)
4151 errx(1, "-C requires -p");
4153 cwd = getcwd(NULL, 0);
4154 if (cwd == NULL) {
4155 error = got_error_from_errno("getcwd");
4156 goto done;
4159 if (repo_path == NULL) {
4160 error = got_worktree_open(&worktree, cwd);
4161 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4162 goto done;
4163 error = NULL;
4166 if (argc == 1) {
4167 if (worktree) {
4168 error = got_worktree_resolve_path(&path, worktree,
4169 argv[0]);
4170 if (error)
4171 goto done;
4172 } else {
4173 path = strdup(argv[0]);
4174 if (path == NULL) {
4175 error = got_error_from_errno("strdup");
4176 goto done;
4179 } else if (argc != 0)
4180 usage_log();
4182 if (repo_path == NULL) {
4183 repo_path = worktree ?
4184 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4186 if (repo_path == NULL) {
4187 error = got_error_from_errno("strdup");
4188 goto done;
4191 error = got_repo_open(&repo, repo_path, NULL);
4192 if (error != NULL)
4193 goto done;
4195 error = apply_unveil(got_repo_get_path(repo), 1,
4196 worktree ? got_worktree_get_root_path(worktree) : NULL);
4197 if (error)
4198 goto done;
4200 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4201 if (error)
4202 goto done;
4204 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4205 if (error)
4206 goto done;
4208 if (start_commit == NULL) {
4209 struct got_reference *head_ref;
4210 struct got_commit_object *commit = NULL;
4211 error = got_ref_open(&head_ref, repo,
4212 worktree ? got_worktree_get_head_ref_name(worktree)
4213 : GOT_REF_HEAD, 0);
4214 if (error != NULL)
4215 goto done;
4216 error = got_ref_resolve(&start_id, repo, head_ref);
4217 got_ref_close(head_ref);
4218 if (error != NULL)
4219 goto done;
4220 error = got_object_open_as_commit(&commit, repo,
4221 start_id);
4222 if (error != NULL)
4223 goto done;
4224 got_object_commit_close(commit);
4225 } else {
4226 error = got_repo_match_object_id(&start_id, NULL,
4227 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4228 if (error != NULL)
4229 goto done;
4231 if (end_commit != NULL) {
4232 error = got_repo_match_object_id(&end_id, NULL,
4233 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4234 if (error != NULL)
4235 goto done;
4238 if (worktree) {
4240 * If a path was specified on the command line it was resolved
4241 * to a path in the work tree above. Prepend the work tree's
4242 * path prefix to obtain the corresponding in-repository path.
4244 if (path) {
4245 const char *prefix;
4246 prefix = got_worktree_get_path_prefix(worktree);
4247 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4248 (path[0] != '\0') ? "/" : "", path) == -1) {
4249 error = got_error_from_errno("asprintf");
4250 goto done;
4253 } else
4254 error = got_repo_map_path(&in_repo_path, repo,
4255 path ? path : "");
4256 if (error != NULL)
4257 goto done;
4258 if (in_repo_path) {
4259 free(path);
4260 path = in_repo_path;
4263 error = print_commits(start_id, end_id, repo, path ? path : "",
4264 show_changed_paths, show_patch, search_pattern, diff_context,
4265 limit, log_branches, reverse_display_order, refs_idmap);
4266 done:
4267 free(path);
4268 free(repo_path);
4269 free(cwd);
4270 if (worktree)
4271 got_worktree_close(worktree);
4272 if (repo) {
4273 const struct got_error *close_err = got_repo_close(repo);
4274 if (error == NULL)
4275 error = close_err;
4277 if (refs_idmap)
4278 got_reflist_object_id_map_free(refs_idmap);
4279 got_ref_list_free(&refs);
4280 return error;
4283 __dead static void
4284 usage_diff(void)
4286 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4287 "[-r repository-path] [-s] [-w] [-P] "
4288 "[object1 object2 | path ...]\n", getprogname());
4289 exit(1);
4292 struct print_diff_arg {
4293 struct got_repository *repo;
4294 struct got_worktree *worktree;
4295 int diff_context;
4296 const char *id_str;
4297 int header_shown;
4298 int diff_staged;
4299 int ignore_whitespace;
4300 int force_text_diff;
4304 * Create a file which contains the target path of a symlink so we can feed
4305 * it as content to the diff engine.
4307 static const struct got_error *
4308 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4309 const char *abspath)
4311 const struct got_error *err = NULL;
4312 char target_path[PATH_MAX];
4313 ssize_t target_len, outlen;
4315 *fd = -1;
4317 if (dirfd != -1) {
4318 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4319 if (target_len == -1)
4320 return got_error_from_errno2("readlinkat", abspath);
4321 } else {
4322 target_len = readlink(abspath, target_path, PATH_MAX);
4323 if (target_len == -1)
4324 return got_error_from_errno2("readlink", abspath);
4327 *fd = got_opentempfd();
4328 if (*fd == -1)
4329 return got_error_from_errno("got_opentempfd");
4331 outlen = write(*fd, target_path, target_len);
4332 if (outlen == -1) {
4333 err = got_error_from_errno("got_opentempfd");
4334 goto done;
4337 if (lseek(*fd, 0, SEEK_SET) == -1) {
4338 err = got_error_from_errno2("lseek", abspath);
4339 goto done;
4341 done:
4342 if (err) {
4343 close(*fd);
4344 *fd = -1;
4346 return err;
4349 static const struct got_error *
4350 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4351 const char *path, struct got_object_id *blob_id,
4352 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4353 int dirfd, const char *de_name)
4355 struct print_diff_arg *a = arg;
4356 const struct got_error *err = NULL;
4357 struct got_blob_object *blob1 = NULL;
4358 int fd = -1;
4359 FILE *f2 = NULL;
4360 char *abspath = NULL, *label1 = NULL;
4361 struct stat sb;
4363 if (a->diff_staged) {
4364 if (staged_status != GOT_STATUS_MODIFY &&
4365 staged_status != GOT_STATUS_ADD &&
4366 staged_status != GOT_STATUS_DELETE)
4367 return NULL;
4368 } else {
4369 if (staged_status == GOT_STATUS_DELETE)
4370 return NULL;
4371 if (status == GOT_STATUS_NONEXISTENT)
4372 return got_error_set_errno(ENOENT, path);
4373 if (status != GOT_STATUS_MODIFY &&
4374 status != GOT_STATUS_ADD &&
4375 status != GOT_STATUS_DELETE &&
4376 status != GOT_STATUS_CONFLICT)
4377 return NULL;
4380 if (!a->header_shown) {
4381 printf("diff %s %s%s\n", a->id_str,
4382 got_worktree_get_root_path(a->worktree),
4383 a->diff_staged ? " (staged changes)" : "");
4384 a->header_shown = 1;
4387 if (a->diff_staged) {
4388 const char *label1 = NULL, *label2 = NULL;
4389 switch (staged_status) {
4390 case GOT_STATUS_MODIFY:
4391 label1 = path;
4392 label2 = path;
4393 break;
4394 case GOT_STATUS_ADD:
4395 label2 = path;
4396 break;
4397 case GOT_STATUS_DELETE:
4398 label1 = path;
4399 break;
4400 default:
4401 return got_error(GOT_ERR_FILE_STATUS);
4403 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4404 staged_blob_id, label1, label2, a->diff_context,
4405 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4408 if (staged_status == GOT_STATUS_ADD ||
4409 staged_status == GOT_STATUS_MODIFY) {
4410 char *id_str;
4411 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4412 8192);
4413 if (err)
4414 goto done;
4415 err = got_object_id_str(&id_str, staged_blob_id);
4416 if (err)
4417 goto done;
4418 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4419 err = got_error_from_errno("asprintf");
4420 free(id_str);
4421 goto done;
4423 free(id_str);
4424 } else if (status != GOT_STATUS_ADD) {
4425 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4426 if (err)
4427 goto done;
4430 if (status != GOT_STATUS_DELETE) {
4431 if (asprintf(&abspath, "%s/%s",
4432 got_worktree_get_root_path(a->worktree), path) == -1) {
4433 err = got_error_from_errno("asprintf");
4434 goto done;
4437 if (dirfd != -1) {
4438 fd = openat(dirfd, de_name,
4439 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4440 if (fd == -1) {
4441 if (!got_err_open_nofollow_on_symlink()) {
4442 err = got_error_from_errno2("openat",
4443 abspath);
4444 goto done;
4446 err = get_symlink_target_file(&fd, dirfd,
4447 de_name, abspath);
4448 if (err)
4449 goto done;
4451 } else {
4452 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4453 if (fd == -1) {
4454 if (!got_err_open_nofollow_on_symlink()) {
4455 err = got_error_from_errno2("open",
4456 abspath);
4457 goto done;
4459 err = get_symlink_target_file(&fd, dirfd,
4460 de_name, abspath);
4461 if (err)
4462 goto done;
4465 if (fstat(fd, &sb) == -1) {
4466 err = got_error_from_errno2("fstat", abspath);
4467 goto done;
4469 f2 = fdopen(fd, "r");
4470 if (f2 == NULL) {
4471 err = got_error_from_errno2("fdopen", abspath);
4472 goto done;
4474 fd = -1;
4475 } else
4476 sb.st_size = 0;
4478 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4479 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4480 done:
4481 if (blob1)
4482 got_object_blob_close(blob1);
4483 if (f2 && fclose(f2) == EOF && err == NULL)
4484 err = got_error_from_errno("fclose");
4485 if (fd != -1 && close(fd) == -1 && err == NULL)
4486 err = got_error_from_errno("close");
4487 free(abspath);
4488 return err;
4491 static const struct got_error *
4492 cmd_diff(int argc, char *argv[])
4494 const struct got_error *error;
4495 struct got_repository *repo = NULL;
4496 struct got_worktree *worktree = NULL;
4497 char *cwd = NULL, *repo_path = NULL;
4498 const char *commit_args[2] = { NULL, NULL };
4499 int ncommit_args = 0;
4500 struct got_object_id *ids[2] = { NULL, NULL };
4501 char *labels[2] = { NULL, NULL };
4502 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4503 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4504 int force_text_diff = 0, force_path = 0, rflag = 0;
4505 const char *errstr;
4506 struct got_reflist_head refs;
4507 struct got_pathlist_head paths;
4508 struct got_pathlist_entry *pe;
4510 TAILQ_INIT(&refs);
4511 TAILQ_INIT(&paths);
4513 #ifndef PROFILE
4514 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4515 NULL) == -1)
4516 err(1, "pledge");
4517 #endif
4519 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4520 switch (ch) {
4521 case 'a':
4522 force_text_diff = 1;
4523 break;
4524 case 'c':
4525 if (ncommit_args >= 2)
4526 errx(1, "too many -c options used");
4527 commit_args[ncommit_args++] = optarg;
4528 break;
4529 case 'C':
4530 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4531 &errstr);
4532 if (errstr != NULL)
4533 err(1, "-C option %s", errstr);
4534 break;
4535 case 'r':
4536 repo_path = realpath(optarg, NULL);
4537 if (repo_path == NULL)
4538 return got_error_from_errno2("realpath",
4539 optarg);
4540 got_path_strip_trailing_slashes(repo_path);
4541 rflag = 1;
4542 break;
4543 case 's':
4544 diff_staged = 1;
4545 break;
4546 case 'w':
4547 ignore_whitespace = 1;
4548 break;
4549 case 'P':
4550 force_path = 1;
4551 break;
4552 default:
4553 usage_diff();
4554 /* NOTREACHED */
4558 argc -= optind;
4559 argv += optind;
4561 cwd = getcwd(NULL, 0);
4562 if (cwd == NULL) {
4563 error = got_error_from_errno("getcwd");
4564 goto done;
4567 if (repo_path == NULL) {
4568 error = got_worktree_open(&worktree, cwd);
4569 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4570 goto done;
4571 else
4572 error = NULL;
4573 if (worktree) {
4574 repo_path =
4575 strdup(got_worktree_get_repo_path(worktree));
4576 if (repo_path == NULL) {
4577 error = got_error_from_errno("strdup");
4578 goto done;
4580 } else {
4581 repo_path = strdup(cwd);
4582 if (repo_path == NULL) {
4583 error = got_error_from_errno("strdup");
4584 goto done;
4589 error = got_repo_open(&repo, repo_path, NULL);
4590 free(repo_path);
4591 if (error != NULL)
4592 goto done;
4594 if (rflag || worktree == NULL || ncommit_args > 0) {
4595 if (force_path) {
4596 error = got_error_msg(GOT_ERR_NOT_IMPL,
4597 "-P option can only be used when diffing "
4598 "a work tree");
4599 goto done;
4601 if (diff_staged) {
4602 error = got_error_msg(GOT_ERR_NOT_IMPL,
4603 "-s option can only be used when diffing "
4604 "a work tree");
4605 goto done;
4609 error = apply_unveil(got_repo_get_path(repo), 1,
4610 worktree ? got_worktree_get_root_path(worktree) : NULL);
4611 if (error)
4612 goto done;
4614 if ((!force_path && argc == 2) || ncommit_args > 0) {
4615 int obj_type = (ncommit_args > 0 ?
4616 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4617 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4618 NULL);
4619 if (error)
4620 goto done;
4621 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4622 const char *arg;
4623 if (ncommit_args > 0)
4624 arg = commit_args[i];
4625 else
4626 arg = argv[i];
4627 error = got_repo_match_object_id(&ids[i], &labels[i],
4628 arg, obj_type, &refs, repo);
4629 if (error) {
4630 if (error->code != GOT_ERR_NOT_REF &&
4631 error->code != GOT_ERR_NO_OBJ)
4632 goto done;
4633 if (ncommit_args > 0)
4634 goto done;
4635 error = NULL;
4636 break;
4641 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4642 struct print_diff_arg arg;
4643 char *id_str;
4645 if (worktree == NULL) {
4646 if (argc == 2 && ids[0] == NULL) {
4647 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4648 goto done;
4649 } else if (argc == 2 && ids[1] == NULL) {
4650 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4651 goto done;
4652 } else if (argc > 0) {
4653 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4654 "%s", "specified paths cannot be resolved");
4655 goto done;
4656 } else {
4657 error = got_error(GOT_ERR_NOT_WORKTREE);
4658 goto done;
4662 error = get_worktree_paths_from_argv(&paths, argc, argv,
4663 worktree);
4664 if (error)
4665 goto done;
4667 error = got_object_id_str(&id_str,
4668 got_worktree_get_base_commit_id(worktree));
4669 if (error)
4670 goto done;
4671 arg.repo = repo;
4672 arg.worktree = worktree;
4673 arg.diff_context = diff_context;
4674 arg.id_str = id_str;
4675 arg.header_shown = 0;
4676 arg.diff_staged = diff_staged;
4677 arg.ignore_whitespace = ignore_whitespace;
4678 arg.force_text_diff = force_text_diff;
4680 error = got_worktree_status(worktree, &paths, repo, 0,
4681 print_diff, &arg, check_cancelled, NULL);
4682 free(id_str);
4683 goto done;
4686 if (ncommit_args == 1) {
4687 struct got_commit_object *commit;
4688 error = got_object_open_as_commit(&commit, repo, ids[0]);
4689 if (error)
4690 goto done;
4692 labels[1] = labels[0];
4693 ids[1] = ids[0];
4694 if (got_object_commit_get_nparents(commit) > 0) {
4695 const struct got_object_id_queue *pids;
4696 struct got_object_qid *pid;
4697 pids = got_object_commit_get_parent_ids(commit);
4698 pid = STAILQ_FIRST(pids);
4699 ids[0] = got_object_id_dup(pid->id);
4700 if (ids[0] == NULL) {
4701 error = got_error_from_errno(
4702 "got_object_id_dup");
4703 got_object_commit_close(commit);
4704 goto done;
4706 error = got_object_id_str(&labels[0], ids[0]);
4707 if (error) {
4708 got_object_commit_close(commit);
4709 goto done;
4711 } else {
4712 ids[0] = NULL;
4713 labels[0] = strdup("/dev/null");
4714 if (labels[0] == NULL) {
4715 error = got_error_from_errno("strdup");
4716 got_object_commit_close(commit);
4717 goto done;
4721 got_object_commit_close(commit);
4724 if (ncommit_args == 0 && argc > 2) {
4725 error = got_error_msg(GOT_ERR_BAD_PATH,
4726 "path arguments cannot be used when diffing two objects");
4727 goto done;
4730 if (ids[0]) {
4731 error = got_object_get_type(&type1, repo, ids[0]);
4732 if (error)
4733 goto done;
4736 error = got_object_get_type(&type2, repo, ids[1]);
4737 if (error)
4738 goto done;
4739 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4740 error = got_error(GOT_ERR_OBJ_TYPE);
4741 goto done;
4743 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4744 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4745 "path arguments cannot be used when diffing blobs");
4746 goto done;
4749 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4750 char *in_repo_path;
4751 struct got_pathlist_entry *new;
4752 if (worktree) {
4753 const char *prefix;
4754 char *p;
4755 error = got_worktree_resolve_path(&p, worktree,
4756 argv[i]);
4757 if (error)
4758 goto done;
4759 prefix = got_worktree_get_path_prefix(worktree);
4760 while (prefix[0] == '/')
4761 prefix++;
4762 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4763 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4764 p) == -1) {
4765 error = got_error_from_errno("asprintf");
4766 free(p);
4767 goto done;
4769 free(p);
4770 } else {
4771 char *mapped_path, *s;
4772 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4773 if (error)
4774 goto done;
4775 s = mapped_path;
4776 while (s[0] == '/')
4777 s++;
4778 in_repo_path = strdup(s);
4779 if (in_repo_path == NULL) {
4780 error = got_error_from_errno("asprintf");
4781 free(mapped_path);
4782 goto done;
4784 free(mapped_path);
4787 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4788 if (error || new == NULL /* duplicate */)
4789 free(in_repo_path);
4790 if (error)
4791 goto done;
4794 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4795 case GOT_OBJ_TYPE_BLOB:
4796 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4797 NULL, NULL, diff_context, ignore_whitespace,
4798 force_text_diff, repo, stdout);
4799 break;
4800 case GOT_OBJ_TYPE_TREE:
4801 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4802 &paths, "", "", diff_context, ignore_whitespace,
4803 force_text_diff, repo, stdout);
4804 break;
4805 case GOT_OBJ_TYPE_COMMIT:
4806 printf("diff %s %s\n", labels[0], labels[1]);
4807 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4808 &paths, diff_context, ignore_whitespace, force_text_diff,
4809 repo, stdout);
4810 break;
4811 default:
4812 error = got_error(GOT_ERR_OBJ_TYPE);
4814 done:
4815 free(labels[0]);
4816 free(labels[1]);
4817 free(ids[0]);
4818 free(ids[1]);
4819 if (worktree)
4820 got_worktree_close(worktree);
4821 if (repo) {
4822 const struct got_error *close_err = got_repo_close(repo);
4823 if (error == NULL)
4824 error = close_err;
4826 TAILQ_FOREACH(pe, &paths, entry)
4827 free((char *)pe->path);
4828 got_pathlist_free(&paths);
4829 got_ref_list_free(&refs);
4830 return error;
4833 __dead static void
4834 usage_blame(void)
4836 fprintf(stderr,
4837 "usage: %s blame [-c commit] [-r repository-path] path\n",
4838 getprogname());
4839 exit(1);
4842 struct blame_line {
4843 int annotated;
4844 char *id_str;
4845 char *committer;
4846 char datebuf[11]; /* YYYY-MM-DD + NUL */
4849 struct blame_cb_args {
4850 struct blame_line *lines;
4851 int nlines;
4852 int nlines_prec;
4853 int lineno_cur;
4854 off_t *line_offsets;
4855 FILE *f;
4856 struct got_repository *repo;
4859 static const struct got_error *
4860 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4862 const struct got_error *err = NULL;
4863 struct blame_cb_args *a = arg;
4864 struct blame_line *bline;
4865 char *line = NULL;
4866 size_t linesize = 0;
4867 struct got_commit_object *commit = NULL;
4868 off_t offset;
4869 struct tm tm;
4870 time_t committer_time;
4872 if (nlines != a->nlines ||
4873 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4874 return got_error(GOT_ERR_RANGE);
4876 if (sigint_received)
4877 return got_error(GOT_ERR_ITER_COMPLETED);
4879 if (lineno == -1)
4880 return NULL; /* no change in this commit */
4882 /* Annotate this line. */
4883 bline = &a->lines[lineno - 1];
4884 if (bline->annotated)
4885 return NULL;
4886 err = got_object_id_str(&bline->id_str, id);
4887 if (err)
4888 return err;
4890 err = got_object_open_as_commit(&commit, a->repo, id);
4891 if (err)
4892 goto done;
4894 bline->committer = strdup(got_object_commit_get_committer(commit));
4895 if (bline->committer == NULL) {
4896 err = got_error_from_errno("strdup");
4897 goto done;
4900 committer_time = got_object_commit_get_committer_time(commit);
4901 if (gmtime_r(&committer_time, &tm) == NULL)
4902 return got_error_from_errno("gmtime_r");
4903 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4904 &tm) == 0) {
4905 err = got_error(GOT_ERR_NO_SPACE);
4906 goto done;
4908 bline->annotated = 1;
4910 /* Print lines annotated so far. */
4911 bline = &a->lines[a->lineno_cur - 1];
4912 if (!bline->annotated)
4913 goto done;
4915 offset = a->line_offsets[a->lineno_cur - 1];
4916 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4917 err = got_error_from_errno("fseeko");
4918 goto done;
4921 while (bline->annotated) {
4922 char *smallerthan, *at, *nl, *committer;
4923 size_t len;
4925 if (getline(&line, &linesize, a->f) == -1) {
4926 if (ferror(a->f))
4927 err = got_error_from_errno("getline");
4928 break;
4931 committer = bline->committer;
4932 smallerthan = strchr(committer, '<');
4933 if (smallerthan && smallerthan[1] != '\0')
4934 committer = smallerthan + 1;
4935 at = strchr(committer, '@');
4936 if (at)
4937 *at = '\0';
4938 len = strlen(committer);
4939 if (len >= 9)
4940 committer[8] = '\0';
4942 nl = strchr(line, '\n');
4943 if (nl)
4944 *nl = '\0';
4945 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4946 bline->id_str, bline->datebuf, committer, line);
4948 a->lineno_cur++;
4949 bline = &a->lines[a->lineno_cur - 1];
4951 done:
4952 if (commit)
4953 got_object_commit_close(commit);
4954 free(line);
4955 return err;
4958 static const struct got_error *
4959 cmd_blame(int argc, char *argv[])
4961 const struct got_error *error;
4962 struct got_repository *repo = NULL;
4963 struct got_worktree *worktree = NULL;
4964 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4965 char *link_target = NULL;
4966 struct got_object_id *obj_id = NULL;
4967 struct got_object_id *commit_id = NULL;
4968 struct got_blob_object *blob = NULL;
4969 char *commit_id_str = NULL;
4970 struct blame_cb_args bca;
4971 int ch, obj_type, i;
4972 off_t filesize;
4974 memset(&bca, 0, sizeof(bca));
4976 #ifndef PROFILE
4977 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4978 NULL) == -1)
4979 err(1, "pledge");
4980 #endif
4982 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4983 switch (ch) {
4984 case 'c':
4985 commit_id_str = optarg;
4986 break;
4987 case 'r':
4988 repo_path = realpath(optarg, NULL);
4989 if (repo_path == NULL)
4990 return got_error_from_errno2("realpath",
4991 optarg);
4992 got_path_strip_trailing_slashes(repo_path);
4993 break;
4994 default:
4995 usage_blame();
4996 /* NOTREACHED */
5000 argc -= optind;
5001 argv += optind;
5003 if (argc == 1)
5004 path = argv[0];
5005 else
5006 usage_blame();
5008 cwd = getcwd(NULL, 0);
5009 if (cwd == NULL) {
5010 error = got_error_from_errno("getcwd");
5011 goto done;
5013 if (repo_path == NULL) {
5014 error = got_worktree_open(&worktree, cwd);
5015 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5016 goto done;
5017 else
5018 error = NULL;
5019 if (worktree) {
5020 repo_path =
5021 strdup(got_worktree_get_repo_path(worktree));
5022 if (repo_path == NULL) {
5023 error = got_error_from_errno("strdup");
5024 if (error)
5025 goto done;
5027 } else {
5028 repo_path = strdup(cwd);
5029 if (repo_path == NULL) {
5030 error = got_error_from_errno("strdup");
5031 goto done;
5036 error = got_repo_open(&repo, repo_path, NULL);
5037 if (error != NULL)
5038 goto done;
5040 if (worktree) {
5041 const char *prefix = got_worktree_get_path_prefix(worktree);
5042 char *p;
5044 error = got_worktree_resolve_path(&p, worktree, path);
5045 if (error)
5046 goto done;
5047 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5048 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5049 p) == -1) {
5050 error = got_error_from_errno("asprintf");
5051 free(p);
5052 goto done;
5054 free(p);
5055 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5056 } else {
5057 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5058 if (error)
5059 goto done;
5060 error = got_repo_map_path(&in_repo_path, repo, path);
5062 if (error)
5063 goto done;
5065 if (commit_id_str == NULL) {
5066 struct got_reference *head_ref;
5067 error = got_ref_open(&head_ref, repo, worktree ?
5068 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5069 if (error != NULL)
5070 goto done;
5071 error = got_ref_resolve(&commit_id, repo, head_ref);
5072 got_ref_close(head_ref);
5073 if (error != NULL)
5074 goto done;
5075 } else {
5076 struct got_reflist_head refs;
5077 TAILQ_INIT(&refs);
5078 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5079 NULL);
5080 if (error)
5081 goto done;
5082 error = got_repo_match_object_id(&commit_id, NULL,
5083 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5084 got_ref_list_free(&refs);
5085 if (error)
5086 goto done;
5089 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5090 commit_id, repo);
5091 if (error)
5092 goto done;
5094 error = got_object_id_by_path(&obj_id, repo, commit_id,
5095 link_target ? link_target : in_repo_path);
5096 if (error)
5097 goto done;
5099 error = got_object_get_type(&obj_type, repo, obj_id);
5100 if (error)
5101 goto done;
5103 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5104 error = got_error_path(link_target ? link_target : in_repo_path,
5105 GOT_ERR_OBJ_TYPE);
5106 goto done;
5109 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5110 if (error)
5111 goto done;
5112 bca.f = got_opentemp();
5113 if (bca.f == NULL) {
5114 error = got_error_from_errno("got_opentemp");
5115 goto done;
5117 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5118 &bca.line_offsets, bca.f, blob);
5119 if (error || bca.nlines == 0)
5120 goto done;
5122 /* Don't include \n at EOF in the blame line count. */
5123 if (bca.line_offsets[bca.nlines - 1] == filesize)
5124 bca.nlines--;
5126 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5127 if (bca.lines == NULL) {
5128 error = got_error_from_errno("calloc");
5129 goto done;
5131 bca.lineno_cur = 1;
5132 bca.nlines_prec = 0;
5133 i = bca.nlines;
5134 while (i > 0) {
5135 i /= 10;
5136 bca.nlines_prec++;
5138 bca.repo = repo;
5140 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5141 repo, blame_cb, &bca, check_cancelled, NULL);
5142 done:
5143 free(in_repo_path);
5144 free(link_target);
5145 free(repo_path);
5146 free(cwd);
5147 free(commit_id);
5148 free(obj_id);
5149 if (blob)
5150 got_object_blob_close(blob);
5151 if (worktree)
5152 got_worktree_close(worktree);
5153 if (repo) {
5154 const struct got_error *close_err = got_repo_close(repo);
5155 if (error == NULL)
5156 error = close_err;
5158 if (bca.lines) {
5159 for (i = 0; i < bca.nlines; i++) {
5160 struct blame_line *bline = &bca.lines[i];
5161 free(bline->id_str);
5162 free(bline->committer);
5164 free(bca.lines);
5166 free(bca.line_offsets);
5167 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5168 error = got_error_from_errno("fclose");
5169 return error;
5172 __dead static void
5173 usage_tree(void)
5175 fprintf(stderr,
5176 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5177 getprogname());
5178 exit(1);
5181 static const struct got_error *
5182 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5183 const char *root_path, struct got_repository *repo)
5185 const struct got_error *err = NULL;
5186 int is_root_path = (strcmp(path, root_path) == 0);
5187 const char *modestr = "";
5188 mode_t mode = got_tree_entry_get_mode(te);
5189 char *link_target = NULL;
5191 path += strlen(root_path);
5192 while (path[0] == '/')
5193 path++;
5195 if (got_object_tree_entry_is_submodule(te))
5196 modestr = "$";
5197 else if (S_ISLNK(mode)) {
5198 int i;
5200 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5201 if (err)
5202 return err;
5203 for (i = 0; i < strlen(link_target); i++) {
5204 if (!isprint((unsigned char)link_target[i]))
5205 link_target[i] = '?';
5208 modestr = "@";
5210 else if (S_ISDIR(mode))
5211 modestr = "/";
5212 else if (mode & S_IXUSR)
5213 modestr = "*";
5215 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5216 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5217 link_target ? " -> ": "", link_target ? link_target : "");
5219 free(link_target);
5220 return NULL;
5223 static const struct got_error *
5224 print_tree(const char *path, struct got_object_id *commit_id,
5225 int show_ids, int recurse, const char *root_path,
5226 struct got_repository *repo)
5228 const struct got_error *err = NULL;
5229 struct got_object_id *tree_id = NULL;
5230 struct got_tree_object *tree = NULL;
5231 int nentries, i;
5233 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5234 if (err)
5235 goto done;
5237 err = got_object_open_as_tree(&tree, repo, tree_id);
5238 if (err)
5239 goto done;
5240 nentries = got_object_tree_get_nentries(tree);
5241 for (i = 0; i < nentries; i++) {
5242 struct got_tree_entry *te;
5243 char *id = NULL;
5245 if (sigint_received || sigpipe_received)
5246 break;
5248 te = got_object_tree_get_entry(tree, i);
5249 if (show_ids) {
5250 char *id_str;
5251 err = got_object_id_str(&id_str,
5252 got_tree_entry_get_id(te));
5253 if (err)
5254 goto done;
5255 if (asprintf(&id, "%s ", id_str) == -1) {
5256 err = got_error_from_errno("asprintf");
5257 free(id_str);
5258 goto done;
5260 free(id_str);
5262 err = print_entry(te, id, path, root_path, repo);
5263 free(id);
5264 if (err)
5265 goto done;
5267 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5268 char *child_path;
5269 if (asprintf(&child_path, "%s%s%s", path,
5270 path[0] == '/' && path[1] == '\0' ? "" : "/",
5271 got_tree_entry_get_name(te)) == -1) {
5272 err = got_error_from_errno("asprintf");
5273 goto done;
5275 err = print_tree(child_path, commit_id, show_ids, 1,
5276 root_path, repo);
5277 free(child_path);
5278 if (err)
5279 goto done;
5282 done:
5283 if (tree)
5284 got_object_tree_close(tree);
5285 free(tree_id);
5286 return err;
5289 static const struct got_error *
5290 cmd_tree(int argc, char *argv[])
5292 const struct got_error *error;
5293 struct got_repository *repo = NULL;
5294 struct got_worktree *worktree = NULL;
5295 const char *path, *refname = NULL;
5296 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5297 struct got_object_id *commit_id = NULL;
5298 char *commit_id_str = NULL;
5299 int show_ids = 0, recurse = 0;
5300 int ch;
5302 #ifndef PROFILE
5303 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5304 NULL) == -1)
5305 err(1, "pledge");
5306 #endif
5308 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5309 switch (ch) {
5310 case 'c':
5311 commit_id_str = optarg;
5312 break;
5313 case 'r':
5314 repo_path = realpath(optarg, NULL);
5315 if (repo_path == NULL)
5316 return got_error_from_errno2("realpath",
5317 optarg);
5318 got_path_strip_trailing_slashes(repo_path);
5319 break;
5320 case 'i':
5321 show_ids = 1;
5322 break;
5323 case 'R':
5324 recurse = 1;
5325 break;
5326 default:
5327 usage_tree();
5328 /* NOTREACHED */
5332 argc -= optind;
5333 argv += optind;
5335 if (argc == 1)
5336 path = argv[0];
5337 else if (argc > 1)
5338 usage_tree();
5339 else
5340 path = NULL;
5342 cwd = getcwd(NULL, 0);
5343 if (cwd == NULL) {
5344 error = got_error_from_errno("getcwd");
5345 goto done;
5347 if (repo_path == NULL) {
5348 error = got_worktree_open(&worktree, cwd);
5349 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5350 goto done;
5351 else
5352 error = NULL;
5353 if (worktree) {
5354 repo_path =
5355 strdup(got_worktree_get_repo_path(worktree));
5356 if (repo_path == NULL)
5357 error = got_error_from_errno("strdup");
5358 if (error)
5359 goto done;
5360 } else {
5361 repo_path = strdup(cwd);
5362 if (repo_path == NULL) {
5363 error = got_error_from_errno("strdup");
5364 goto done;
5369 error = got_repo_open(&repo, repo_path, NULL);
5370 if (error != NULL)
5371 goto done;
5373 if (worktree) {
5374 const char *prefix = got_worktree_get_path_prefix(worktree);
5375 char *p;
5377 if (path == NULL)
5378 path = "";
5379 error = got_worktree_resolve_path(&p, worktree, path);
5380 if (error)
5381 goto done;
5382 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5383 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5384 p) == -1) {
5385 error = got_error_from_errno("asprintf");
5386 free(p);
5387 goto done;
5389 free(p);
5390 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5391 if (error)
5392 goto done;
5393 } else {
5394 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5395 if (error)
5396 goto done;
5397 if (path == NULL)
5398 path = "/";
5399 error = got_repo_map_path(&in_repo_path, repo, path);
5400 if (error != NULL)
5401 goto done;
5404 if (commit_id_str == NULL) {
5405 struct got_reference *head_ref;
5406 if (worktree)
5407 refname = got_worktree_get_head_ref_name(worktree);
5408 else
5409 refname = GOT_REF_HEAD;
5410 error = got_ref_open(&head_ref, repo, refname, 0);
5411 if (error != NULL)
5412 goto done;
5413 error = got_ref_resolve(&commit_id, repo, head_ref);
5414 got_ref_close(head_ref);
5415 if (error != NULL)
5416 goto done;
5417 } else {
5418 struct got_reflist_head refs;
5419 TAILQ_INIT(&refs);
5420 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5421 NULL);
5422 if (error)
5423 goto done;
5424 error = got_repo_match_object_id(&commit_id, NULL,
5425 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5426 got_ref_list_free(&refs);
5427 if (error)
5428 goto done;
5431 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5432 in_repo_path, repo);
5433 done:
5434 free(in_repo_path);
5435 free(repo_path);
5436 free(cwd);
5437 free(commit_id);
5438 if (worktree)
5439 got_worktree_close(worktree);
5440 if (repo) {
5441 const struct got_error *close_err = got_repo_close(repo);
5442 if (error == NULL)
5443 error = close_err;
5445 return error;
5448 __dead static void
5449 usage_status(void)
5451 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5452 "[-S status-codes] [path ...]\n", getprogname());
5453 exit(1);
5456 struct got_status_arg {
5457 char *status_codes;
5458 int suppress;
5461 static const struct got_error *
5462 print_status(void *arg, unsigned char status, unsigned char staged_status,
5463 const char *path, struct got_object_id *blob_id,
5464 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5465 int dirfd, const char *de_name)
5467 struct got_status_arg *st = arg;
5469 if (status == staged_status && (status == GOT_STATUS_DELETE))
5470 status = GOT_STATUS_NO_CHANGE;
5471 if (st != NULL && st->status_codes) {
5472 size_t ncodes = strlen(st->status_codes);
5473 int i, j = 0;
5475 for (i = 0; i < ncodes ; i++) {
5476 if (st->suppress) {
5477 if (status == st->status_codes[i] ||
5478 staged_status == st->status_codes[i]) {
5479 j++;
5480 continue;
5482 } else {
5483 if (status == st->status_codes[i] ||
5484 staged_status == st->status_codes[i])
5485 break;
5489 if (st->suppress && j == 0)
5490 goto print;
5492 if (i == ncodes)
5493 return NULL;
5495 print:
5496 printf("%c%c %s\n", status, staged_status, path);
5497 return NULL;
5500 static const struct got_error *
5501 cmd_status(int argc, char *argv[])
5503 const struct got_error *error = NULL;
5504 struct got_repository *repo = NULL;
5505 struct got_worktree *worktree = NULL;
5506 struct got_status_arg st;
5507 char *cwd = NULL;
5508 struct got_pathlist_head paths;
5509 struct got_pathlist_entry *pe;
5510 int ch, i, no_ignores = 0;
5512 TAILQ_INIT(&paths);
5514 memset(&st, 0, sizeof(st));
5515 st.status_codes = NULL;
5516 st.suppress = 0;
5518 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5519 switch (ch) {
5520 case 'I':
5521 no_ignores = 1;
5522 break;
5523 case 'S':
5524 if (st.status_codes != NULL && st.suppress == 0)
5525 option_conflict('S', 's');
5526 st.suppress = 1;
5527 /* fallthrough */
5528 case 's':
5529 for (i = 0; i < strlen(optarg); i++) {
5530 switch (optarg[i]) {
5531 case GOT_STATUS_MODIFY:
5532 case GOT_STATUS_ADD:
5533 case GOT_STATUS_DELETE:
5534 case GOT_STATUS_CONFLICT:
5535 case GOT_STATUS_MISSING:
5536 case GOT_STATUS_OBSTRUCTED:
5537 case GOT_STATUS_UNVERSIONED:
5538 case GOT_STATUS_MODE_CHANGE:
5539 case GOT_STATUS_NONEXISTENT:
5540 break;
5541 default:
5542 errx(1, "invalid status code '%c'",
5543 optarg[i]);
5546 if (ch == 's' && st.suppress)
5547 option_conflict('s', 'S');
5548 st.status_codes = optarg;
5549 break;
5550 default:
5551 usage_status();
5552 /* NOTREACHED */
5556 argc -= optind;
5557 argv += optind;
5559 #ifndef PROFILE
5560 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5561 NULL) == -1)
5562 err(1, "pledge");
5563 #endif
5564 cwd = getcwd(NULL, 0);
5565 if (cwd == NULL) {
5566 error = got_error_from_errno("getcwd");
5567 goto done;
5570 error = got_worktree_open(&worktree, cwd);
5571 if (error) {
5572 if (error->code == GOT_ERR_NOT_WORKTREE)
5573 error = wrap_not_worktree_error(error, "status", cwd);
5574 goto done;
5577 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5578 NULL);
5579 if (error != NULL)
5580 goto done;
5582 error = apply_unveil(got_repo_get_path(repo), 1,
5583 got_worktree_get_root_path(worktree));
5584 if (error)
5585 goto done;
5587 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5588 if (error)
5589 goto done;
5591 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5592 print_status, &st, check_cancelled, NULL);
5593 done:
5594 TAILQ_FOREACH(pe, &paths, entry)
5595 free((char *)pe->path);
5596 got_pathlist_free(&paths);
5597 free(cwd);
5598 return error;
5601 __dead static void
5602 usage_ref(void)
5604 fprintf(stderr,
5605 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5606 "[-s reference] [-d] [name]\n",
5607 getprogname());
5608 exit(1);
5611 static const struct got_error *
5612 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5614 static const struct got_error *err = NULL;
5615 struct got_reflist_head refs;
5616 struct got_reflist_entry *re;
5618 TAILQ_INIT(&refs);
5619 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5620 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5621 repo);
5622 if (err)
5623 return err;
5625 TAILQ_FOREACH(re, &refs, entry) {
5626 char *refstr;
5627 refstr = got_ref_to_str(re->ref);
5628 if (refstr == NULL)
5629 return got_error_from_errno("got_ref_to_str");
5630 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5631 free(refstr);
5634 got_ref_list_free(&refs);
5635 return NULL;
5638 static const struct got_error *
5639 delete_ref_by_name(struct got_repository *repo, const char *refname)
5641 const struct got_error *err;
5642 struct got_reference *ref;
5644 err = got_ref_open(&ref, repo, refname, 0);
5645 if (err)
5646 return err;
5648 err = delete_ref(repo, ref);
5649 got_ref_close(ref);
5650 return err;
5653 static const struct got_error *
5654 add_ref(struct got_repository *repo, const char *refname, const char *target)
5656 const struct got_error *err = NULL;
5657 struct got_object_id *id;
5658 struct got_reference *ref = NULL;
5661 * Don't let the user create a reference name with a leading '-'.
5662 * While technically a valid reference name, this case is usually
5663 * an unintended typo.
5665 if (refname[0] == '-')
5666 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5668 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5669 repo);
5670 if (err) {
5671 struct got_reference *target_ref;
5673 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5674 return err;
5675 err = got_ref_open(&target_ref, repo, target, 0);
5676 if (err)
5677 return err;
5678 err = got_ref_resolve(&id, repo, target_ref);
5679 got_ref_close(target_ref);
5680 if (err)
5681 return err;
5684 err = got_ref_alloc(&ref, refname, id);
5685 if (err)
5686 goto done;
5688 err = got_ref_write(ref, repo);
5689 done:
5690 if (ref)
5691 got_ref_close(ref);
5692 free(id);
5693 return err;
5696 static const struct got_error *
5697 add_symref(struct got_repository *repo, const char *refname, const char *target)
5699 const struct got_error *err = NULL;
5700 struct got_reference *ref = NULL;
5701 struct got_reference *target_ref = NULL;
5704 * Don't let the user create a reference name with a leading '-'.
5705 * While technically a valid reference name, this case is usually
5706 * an unintended typo.
5708 if (refname[0] == '-')
5709 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5711 err = got_ref_open(&target_ref, repo, target, 0);
5712 if (err)
5713 return err;
5715 err = got_ref_alloc_symref(&ref, refname, target_ref);
5716 if (err)
5717 goto done;
5719 err = got_ref_write(ref, repo);
5720 done:
5721 if (target_ref)
5722 got_ref_close(target_ref);
5723 if (ref)
5724 got_ref_close(ref);
5725 return err;
5728 static const struct got_error *
5729 cmd_ref(int argc, char *argv[])
5731 const struct got_error *error = NULL;
5732 struct got_repository *repo = NULL;
5733 struct got_worktree *worktree = NULL;
5734 char *cwd = NULL, *repo_path = NULL;
5735 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5736 const char *obj_arg = NULL, *symref_target= NULL;
5737 char *refname = NULL;
5739 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5740 switch (ch) {
5741 case 'c':
5742 obj_arg = optarg;
5743 break;
5744 case 'd':
5745 do_delete = 1;
5746 break;
5747 case 'r':
5748 repo_path = realpath(optarg, NULL);
5749 if (repo_path == NULL)
5750 return got_error_from_errno2("realpath",
5751 optarg);
5752 got_path_strip_trailing_slashes(repo_path);
5753 break;
5754 case 'l':
5755 do_list = 1;
5756 break;
5757 case 's':
5758 symref_target = optarg;
5759 break;
5760 case 't':
5761 sort_by_time = 1;
5762 break;
5763 default:
5764 usage_ref();
5765 /* NOTREACHED */
5769 if (obj_arg && do_list)
5770 option_conflict('c', 'l');
5771 if (obj_arg && do_delete)
5772 option_conflict('c', 'd');
5773 if (obj_arg && symref_target)
5774 option_conflict('c', 's');
5775 if (symref_target && do_delete)
5776 option_conflict('s', 'd');
5777 if (symref_target && do_list)
5778 option_conflict('s', 'l');
5779 if (do_delete && do_list)
5780 option_conflict('d', 'l');
5781 if (sort_by_time && !do_list)
5782 errx(1, "-t option requires -l option");
5784 argc -= optind;
5785 argv += optind;
5787 if (do_list) {
5788 if (argc != 0 && argc != 1)
5789 usage_ref();
5790 if (argc == 1) {
5791 refname = strdup(argv[0]);
5792 if (refname == NULL) {
5793 error = got_error_from_errno("strdup");
5794 goto done;
5797 } else {
5798 if (argc != 1)
5799 usage_ref();
5800 refname = strdup(argv[0]);
5801 if (refname == NULL) {
5802 error = got_error_from_errno("strdup");
5803 goto done;
5807 if (refname)
5808 got_path_strip_trailing_slashes(refname);
5810 #ifndef PROFILE
5811 if (do_list) {
5812 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5813 NULL) == -1)
5814 err(1, "pledge");
5815 } else {
5816 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5817 "sendfd unveil", NULL) == -1)
5818 err(1, "pledge");
5820 #endif
5821 cwd = getcwd(NULL, 0);
5822 if (cwd == NULL) {
5823 error = got_error_from_errno("getcwd");
5824 goto done;
5827 if (repo_path == NULL) {
5828 error = got_worktree_open(&worktree, cwd);
5829 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5830 goto done;
5831 else
5832 error = NULL;
5833 if (worktree) {
5834 repo_path =
5835 strdup(got_worktree_get_repo_path(worktree));
5836 if (repo_path == NULL)
5837 error = got_error_from_errno("strdup");
5838 if (error)
5839 goto done;
5840 } else {
5841 repo_path = strdup(cwd);
5842 if (repo_path == NULL) {
5843 error = got_error_from_errno("strdup");
5844 goto done;
5849 error = got_repo_open(&repo, repo_path, NULL);
5850 if (error != NULL)
5851 goto done;
5853 error = apply_unveil(got_repo_get_path(repo), do_list,
5854 worktree ? got_worktree_get_root_path(worktree) : NULL);
5855 if (error)
5856 goto done;
5858 if (do_list)
5859 error = list_refs(repo, refname, sort_by_time);
5860 else if (do_delete)
5861 error = delete_ref_by_name(repo, refname);
5862 else if (symref_target)
5863 error = add_symref(repo, refname, symref_target);
5864 else {
5865 if (obj_arg == NULL)
5866 usage_ref();
5867 error = add_ref(repo, refname, obj_arg);
5869 done:
5870 free(refname);
5871 if (repo) {
5872 const struct got_error *close_err = got_repo_close(repo);
5873 if (error == NULL)
5874 error = close_err;
5876 if (worktree)
5877 got_worktree_close(worktree);
5878 free(cwd);
5879 free(repo_path);
5880 return error;
5883 __dead static void
5884 usage_branch(void)
5886 fprintf(stderr,
5887 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5888 "[-n] [name]\n", getprogname());
5889 exit(1);
5892 static const struct got_error *
5893 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5894 struct got_reference *ref)
5896 const struct got_error *err = NULL;
5897 const char *refname, *marker = " ";
5898 char *refstr;
5900 refname = got_ref_get_name(ref);
5901 if (worktree && strcmp(refname,
5902 got_worktree_get_head_ref_name(worktree)) == 0) {
5903 struct got_object_id *id = NULL;
5905 err = got_ref_resolve(&id, repo, ref);
5906 if (err)
5907 return err;
5908 if (got_object_id_cmp(id,
5909 got_worktree_get_base_commit_id(worktree)) == 0)
5910 marker = "* ";
5911 else
5912 marker = "~ ";
5913 free(id);
5916 if (strncmp(refname, "refs/heads/", 11) == 0)
5917 refname += 11;
5918 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5919 refname += 18;
5920 if (strncmp(refname, "refs/remotes/", 13) == 0)
5921 refname += 13;
5923 refstr = got_ref_to_str(ref);
5924 if (refstr == NULL)
5925 return got_error_from_errno("got_ref_to_str");
5927 printf("%s%s: %s\n", marker, refname, refstr);
5928 free(refstr);
5929 return NULL;
5932 static const struct got_error *
5933 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5935 const char *refname;
5937 if (worktree == NULL)
5938 return got_error(GOT_ERR_NOT_WORKTREE);
5940 refname = got_worktree_get_head_ref_name(worktree);
5942 if (strncmp(refname, "refs/heads/", 11) == 0)
5943 refname += 11;
5944 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5945 refname += 18;
5947 printf("%s\n", refname);
5949 return NULL;
5952 static const struct got_error *
5953 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5954 int sort_by_time)
5956 static const struct got_error *err = NULL;
5957 struct got_reflist_head refs;
5958 struct got_reflist_entry *re;
5959 struct got_reference *temp_ref = NULL;
5960 int rebase_in_progress, histedit_in_progress;
5962 TAILQ_INIT(&refs);
5964 if (worktree) {
5965 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5966 worktree);
5967 if (err)
5968 return err;
5970 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5971 worktree);
5972 if (err)
5973 return err;
5975 if (rebase_in_progress || histedit_in_progress) {
5976 err = got_ref_open(&temp_ref, repo,
5977 got_worktree_get_head_ref_name(worktree), 0);
5978 if (err)
5979 return err;
5980 list_branch(repo, worktree, temp_ref);
5981 got_ref_close(temp_ref);
5985 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
5986 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5987 repo);
5988 if (err)
5989 return err;
5991 TAILQ_FOREACH(re, &refs, entry)
5992 list_branch(repo, worktree, re->ref);
5994 got_ref_list_free(&refs);
5996 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
5997 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5998 repo);
5999 if (err)
6000 return err;
6002 TAILQ_FOREACH(re, &refs, entry)
6003 list_branch(repo, worktree, re->ref);
6005 got_ref_list_free(&refs);
6007 return NULL;
6010 static const struct got_error *
6011 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6012 const char *branch_name)
6014 const struct got_error *err = NULL;
6015 struct got_reference *ref = NULL;
6016 char *refname, *remote_refname = NULL;
6018 if (strncmp(branch_name, "refs/", 5) == 0)
6019 branch_name += 5;
6020 if (strncmp(branch_name, "heads/", 6) == 0)
6021 branch_name += 6;
6022 else if (strncmp(branch_name, "remotes/", 8) == 0)
6023 branch_name += 8;
6025 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6026 return got_error_from_errno("asprintf");
6028 if (asprintf(&remote_refname, "refs/remotes/%s",
6029 branch_name) == -1) {
6030 err = got_error_from_errno("asprintf");
6031 goto done;
6034 err = got_ref_open(&ref, repo, refname, 0);
6035 if (err) {
6036 const struct got_error *err2;
6037 if (err->code != GOT_ERR_NOT_REF)
6038 goto done;
6040 * Keep 'err' intact such that if neither branch exists
6041 * we report "refs/heads" rather than "refs/remotes" in
6042 * our error message.
6044 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6045 if (err2)
6046 goto done;
6047 err = NULL;
6050 if (worktree &&
6051 strcmp(got_worktree_get_head_ref_name(worktree),
6052 got_ref_get_name(ref)) == 0) {
6053 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6054 "will not delete this work tree's current branch");
6055 goto done;
6058 err = delete_ref(repo, ref);
6059 done:
6060 if (ref)
6061 got_ref_close(ref);
6062 free(refname);
6063 free(remote_refname);
6064 return err;
6067 static const struct got_error *
6068 add_branch(struct got_repository *repo, const char *branch_name,
6069 struct got_object_id *base_commit_id)
6071 const struct got_error *err = NULL;
6072 struct got_reference *ref = NULL;
6073 char *base_refname = NULL, *refname = NULL;
6076 * Don't let the user create a branch name with a leading '-'.
6077 * While technically a valid reference name, this case is usually
6078 * an unintended typo.
6080 if (branch_name[0] == '-')
6081 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6083 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6084 branch_name += 11;
6086 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6087 err = got_error_from_errno("asprintf");
6088 goto done;
6091 err = got_ref_open(&ref, repo, refname, 0);
6092 if (err == NULL) {
6093 err = got_error(GOT_ERR_BRANCH_EXISTS);
6094 goto done;
6095 } else if (err->code != GOT_ERR_NOT_REF)
6096 goto done;
6098 err = got_ref_alloc(&ref, refname, base_commit_id);
6099 if (err)
6100 goto done;
6102 err = got_ref_write(ref, repo);
6103 done:
6104 if (ref)
6105 got_ref_close(ref);
6106 free(base_refname);
6107 free(refname);
6108 return err;
6111 static const struct got_error *
6112 cmd_branch(int argc, char *argv[])
6114 const struct got_error *error = NULL;
6115 struct got_repository *repo = NULL;
6116 struct got_worktree *worktree = NULL;
6117 char *cwd = NULL, *repo_path = NULL;
6118 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6119 const char *delref = NULL, *commit_id_arg = NULL;
6120 struct got_reference *ref = NULL;
6121 struct got_pathlist_head paths;
6122 struct got_pathlist_entry *pe;
6123 struct got_object_id *commit_id = NULL;
6124 char *commit_id_str = NULL;
6126 TAILQ_INIT(&paths);
6128 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6129 switch (ch) {
6130 case 'c':
6131 commit_id_arg = optarg;
6132 break;
6133 case 'd':
6134 delref = optarg;
6135 break;
6136 case 'r':
6137 repo_path = realpath(optarg, NULL);
6138 if (repo_path == NULL)
6139 return got_error_from_errno2("realpath",
6140 optarg);
6141 got_path_strip_trailing_slashes(repo_path);
6142 break;
6143 case 'l':
6144 do_list = 1;
6145 break;
6146 case 'n':
6147 do_update = 0;
6148 break;
6149 case 't':
6150 sort_by_time = 1;
6151 break;
6152 default:
6153 usage_branch();
6154 /* NOTREACHED */
6158 if (do_list && delref)
6159 option_conflict('l', 'd');
6160 if (sort_by_time && !do_list)
6161 errx(1, "-t option requires -l option");
6163 argc -= optind;
6164 argv += optind;
6166 if (!do_list && !delref && argc == 0)
6167 do_show = 1;
6169 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6170 errx(1, "-c option can only be used when creating a branch");
6172 if (do_list || delref) {
6173 if (argc > 0)
6174 usage_branch();
6175 } else if (!do_show && argc != 1)
6176 usage_branch();
6178 #ifndef PROFILE
6179 if (do_list || do_show) {
6180 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6181 NULL) == -1)
6182 err(1, "pledge");
6183 } else {
6184 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6185 "sendfd unveil", NULL) == -1)
6186 err(1, "pledge");
6188 #endif
6189 cwd = getcwd(NULL, 0);
6190 if (cwd == NULL) {
6191 error = got_error_from_errno("getcwd");
6192 goto done;
6195 if (repo_path == NULL) {
6196 error = got_worktree_open(&worktree, cwd);
6197 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6198 goto done;
6199 else
6200 error = NULL;
6201 if (worktree) {
6202 repo_path =
6203 strdup(got_worktree_get_repo_path(worktree));
6204 if (repo_path == NULL)
6205 error = got_error_from_errno("strdup");
6206 if (error)
6207 goto done;
6208 } else {
6209 repo_path = strdup(cwd);
6210 if (repo_path == NULL) {
6211 error = got_error_from_errno("strdup");
6212 goto done;
6217 error = got_repo_open(&repo, repo_path, NULL);
6218 if (error != NULL)
6219 goto done;
6221 error = apply_unveil(got_repo_get_path(repo), do_list,
6222 worktree ? got_worktree_get_root_path(worktree) : NULL);
6223 if (error)
6224 goto done;
6226 if (do_show)
6227 error = show_current_branch(repo, worktree);
6228 else if (do_list)
6229 error = list_branches(repo, worktree, sort_by_time);
6230 else if (delref)
6231 error = delete_branch(repo, worktree, delref);
6232 else {
6233 struct got_reflist_head refs;
6234 TAILQ_INIT(&refs);
6235 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6236 NULL);
6237 if (error)
6238 goto done;
6239 if (commit_id_arg == NULL)
6240 commit_id_arg = worktree ?
6241 got_worktree_get_head_ref_name(worktree) :
6242 GOT_REF_HEAD;
6243 error = got_repo_match_object_id(&commit_id, NULL,
6244 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6245 got_ref_list_free(&refs);
6246 if (error)
6247 goto done;
6248 error = add_branch(repo, argv[0], commit_id);
6249 if (error)
6250 goto done;
6251 if (worktree && do_update) {
6252 struct got_update_progress_arg upa;
6253 char *branch_refname = NULL;
6255 error = got_object_id_str(&commit_id_str, commit_id);
6256 if (error)
6257 goto done;
6258 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6259 worktree);
6260 if (error)
6261 goto done;
6262 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6263 == -1) {
6264 error = got_error_from_errno("asprintf");
6265 goto done;
6267 error = got_ref_open(&ref, repo, branch_refname, 0);
6268 free(branch_refname);
6269 if (error)
6270 goto done;
6271 error = switch_head_ref(ref, commit_id, worktree,
6272 repo);
6273 if (error)
6274 goto done;
6275 error = got_worktree_set_base_commit_id(worktree, repo,
6276 commit_id);
6277 if (error)
6278 goto done;
6279 memset(&upa, 0, sizeof(upa));
6280 error = got_worktree_checkout_files(worktree, &paths,
6281 repo, update_progress, &upa, check_cancelled,
6282 NULL);
6283 if (error)
6284 goto done;
6285 if (upa.did_something) {
6286 printf("Updated to %s: %s\n",
6287 got_worktree_get_head_ref_name(worktree),
6288 commit_id_str);
6290 print_update_progress_stats(&upa);
6293 done:
6294 if (ref)
6295 got_ref_close(ref);
6296 if (repo) {
6297 const struct got_error *close_err = got_repo_close(repo);
6298 if (error == NULL)
6299 error = close_err;
6301 if (worktree)
6302 got_worktree_close(worktree);
6303 free(cwd);
6304 free(repo_path);
6305 free(commit_id);
6306 free(commit_id_str);
6307 TAILQ_FOREACH(pe, &paths, entry)
6308 free((char *)pe->path);
6309 got_pathlist_free(&paths);
6310 return error;
6314 __dead static void
6315 usage_tag(void)
6317 fprintf(stderr,
6318 "usage: %s tag [-c commit] [-r repository] [-l] "
6319 "[-m message] name\n", getprogname());
6320 exit(1);
6323 #if 0
6324 static const struct got_error *
6325 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6327 const struct got_error *err = NULL;
6328 struct got_reflist_entry *re, *se, *new;
6329 struct got_object_id *re_id, *se_id;
6330 struct got_tag_object *re_tag, *se_tag;
6331 time_t re_time, se_time;
6333 STAILQ_FOREACH(re, tags, entry) {
6334 se = STAILQ_FIRST(sorted);
6335 if (se == NULL) {
6336 err = got_reflist_entry_dup(&new, re);
6337 if (err)
6338 return err;
6339 STAILQ_INSERT_HEAD(sorted, new, entry);
6340 continue;
6341 } else {
6342 err = got_ref_resolve(&re_id, repo, re->ref);
6343 if (err)
6344 break;
6345 err = got_object_open_as_tag(&re_tag, repo, re_id);
6346 free(re_id);
6347 if (err)
6348 break;
6349 re_time = got_object_tag_get_tagger_time(re_tag);
6350 got_object_tag_close(re_tag);
6353 while (se) {
6354 err = got_ref_resolve(&se_id, repo, re->ref);
6355 if (err)
6356 break;
6357 err = got_object_open_as_tag(&se_tag, repo, se_id);
6358 free(se_id);
6359 if (err)
6360 break;
6361 se_time = got_object_tag_get_tagger_time(se_tag);
6362 got_object_tag_close(se_tag);
6364 if (se_time > re_time) {
6365 err = got_reflist_entry_dup(&new, re);
6366 if (err)
6367 return err;
6368 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6369 break;
6371 se = STAILQ_NEXT(se, entry);
6372 continue;
6375 done:
6376 return err;
6378 #endif
6380 static const struct got_error *
6381 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6383 static const struct got_error *err = NULL;
6384 struct got_reflist_head refs;
6385 struct got_reflist_entry *re;
6387 TAILQ_INIT(&refs);
6389 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6390 if (err)
6391 return err;
6393 TAILQ_FOREACH(re, &refs, entry) {
6394 const char *refname;
6395 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6396 char datebuf[26];
6397 const char *tagger;
6398 time_t tagger_time;
6399 struct got_object_id *id;
6400 struct got_tag_object *tag;
6401 struct got_commit_object *commit = NULL;
6403 refname = got_ref_get_name(re->ref);
6404 if (strncmp(refname, "refs/tags/", 10) != 0)
6405 continue;
6406 refname += 10;
6407 refstr = got_ref_to_str(re->ref);
6408 if (refstr == NULL) {
6409 err = got_error_from_errno("got_ref_to_str");
6410 break;
6412 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6413 free(refstr);
6415 err = got_ref_resolve(&id, repo, re->ref);
6416 if (err)
6417 break;
6418 err = got_object_open_as_tag(&tag, repo, id);
6419 if (err) {
6420 if (err->code != GOT_ERR_OBJ_TYPE) {
6421 free(id);
6422 break;
6424 /* "lightweight" tag */
6425 err = got_object_open_as_commit(&commit, repo, id);
6426 if (err) {
6427 free(id);
6428 break;
6430 tagger = got_object_commit_get_committer(commit);
6431 tagger_time =
6432 got_object_commit_get_committer_time(commit);
6433 err = got_object_id_str(&id_str, id);
6434 free(id);
6435 if (err)
6436 break;
6437 } else {
6438 free(id);
6439 tagger = got_object_tag_get_tagger(tag);
6440 tagger_time = got_object_tag_get_tagger_time(tag);
6441 err = got_object_id_str(&id_str,
6442 got_object_tag_get_object_id(tag));
6443 if (err)
6444 break;
6446 printf("from: %s\n", tagger);
6447 datestr = get_datestr(&tagger_time, datebuf);
6448 if (datestr)
6449 printf("date: %s UTC\n", datestr);
6450 if (commit)
6451 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6452 else {
6453 switch (got_object_tag_get_object_type(tag)) {
6454 case GOT_OBJ_TYPE_BLOB:
6455 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6456 id_str);
6457 break;
6458 case GOT_OBJ_TYPE_TREE:
6459 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6460 id_str);
6461 break;
6462 case GOT_OBJ_TYPE_COMMIT:
6463 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6464 id_str);
6465 break;
6466 case GOT_OBJ_TYPE_TAG:
6467 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6468 id_str);
6469 break;
6470 default:
6471 break;
6474 free(id_str);
6475 if (commit) {
6476 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6477 if (err)
6478 break;
6479 got_object_commit_close(commit);
6480 } else {
6481 tagmsg0 = strdup(got_object_tag_get_message(tag));
6482 got_object_tag_close(tag);
6483 if (tagmsg0 == NULL) {
6484 err = got_error_from_errno("strdup");
6485 break;
6489 tagmsg = tagmsg0;
6490 do {
6491 line = strsep(&tagmsg, "\n");
6492 if (line)
6493 printf(" %s\n", line);
6494 } while (line);
6495 free(tagmsg0);
6498 got_ref_list_free(&refs);
6499 return NULL;
6502 static const struct got_error *
6503 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6504 const char *tag_name, const char *repo_path)
6506 const struct got_error *err = NULL;
6507 char *template = NULL, *initial_content = NULL;
6508 char *editor = NULL;
6509 int initial_content_len;
6510 int fd = -1;
6512 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6513 err = got_error_from_errno("asprintf");
6514 goto done;
6517 initial_content_len = asprintf(&initial_content,
6518 "\n# tagging commit %s as %s\n",
6519 commit_id_str, tag_name);
6520 if (initial_content_len == -1) {
6521 err = got_error_from_errno("asprintf");
6522 goto done;
6525 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6526 if (err)
6527 goto done;
6529 if (write(fd, initial_content, initial_content_len) == -1) {
6530 err = got_error_from_errno2("write", *tagmsg_path);
6531 goto done;
6534 err = get_editor(&editor);
6535 if (err)
6536 goto done;
6537 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6538 initial_content_len, 1);
6539 done:
6540 free(initial_content);
6541 free(template);
6542 free(editor);
6544 if (fd != -1 && close(fd) == -1 && err == NULL)
6545 err = got_error_from_errno2("close", *tagmsg_path);
6547 /* Editor is done; we can now apply unveil(2) */
6548 if (err == NULL)
6549 err = apply_unveil(repo_path, 0, NULL);
6550 if (err) {
6551 free(*tagmsg);
6552 *tagmsg = NULL;
6554 return err;
6557 static const struct got_error *
6558 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6559 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6561 const struct got_error *err = NULL;
6562 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6563 char *label = NULL, *commit_id_str = NULL;
6564 struct got_reference *ref = NULL;
6565 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6566 char *tagmsg_path = NULL, *tag_id_str = NULL;
6567 int preserve_tagmsg = 0;
6568 struct got_reflist_head refs;
6570 TAILQ_INIT(&refs);
6573 * Don't let the user create a tag name with a leading '-'.
6574 * While technically a valid reference name, this case is usually
6575 * an unintended typo.
6577 if (tag_name[0] == '-')
6578 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6580 err = get_author(&tagger, repo, worktree);
6581 if (err)
6582 return err;
6584 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6585 if (err)
6586 goto done;
6588 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6589 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6590 if (err)
6591 goto done;
6593 err = got_object_id_str(&commit_id_str, commit_id);
6594 if (err)
6595 goto done;
6597 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6598 refname = strdup(tag_name);
6599 if (refname == NULL) {
6600 err = got_error_from_errno("strdup");
6601 goto done;
6603 tag_name += 10;
6604 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6605 err = got_error_from_errno("asprintf");
6606 goto done;
6609 err = got_ref_open(&ref, repo, refname, 0);
6610 if (err == NULL) {
6611 err = got_error(GOT_ERR_TAG_EXISTS);
6612 goto done;
6613 } else if (err->code != GOT_ERR_NOT_REF)
6614 goto done;
6616 if (tagmsg_arg == NULL) {
6617 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6618 tag_name, got_repo_get_path(repo));
6619 if (err) {
6620 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6621 tagmsg_path != NULL)
6622 preserve_tagmsg = 1;
6623 goto done;
6627 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6628 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6629 if (err) {
6630 if (tagmsg_path)
6631 preserve_tagmsg = 1;
6632 goto done;
6635 err = got_ref_alloc(&ref, refname, tag_id);
6636 if (err) {
6637 if (tagmsg_path)
6638 preserve_tagmsg = 1;
6639 goto done;
6642 err = got_ref_write(ref, repo);
6643 if (err) {
6644 if (tagmsg_path)
6645 preserve_tagmsg = 1;
6646 goto done;
6649 err = got_object_id_str(&tag_id_str, tag_id);
6650 if (err) {
6651 if (tagmsg_path)
6652 preserve_tagmsg = 1;
6653 goto done;
6655 printf("Created tag %s\n", tag_id_str);
6656 done:
6657 if (preserve_tagmsg) {
6658 fprintf(stderr, "%s: tag message preserved in %s\n",
6659 getprogname(), tagmsg_path);
6660 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6661 err = got_error_from_errno2("unlink", tagmsg_path);
6662 free(tag_id_str);
6663 if (ref)
6664 got_ref_close(ref);
6665 free(commit_id);
6666 free(commit_id_str);
6667 free(refname);
6668 free(tagmsg);
6669 free(tagmsg_path);
6670 free(tagger);
6671 got_ref_list_free(&refs);
6672 return err;
6675 static const struct got_error *
6676 cmd_tag(int argc, char *argv[])
6678 const struct got_error *error = NULL;
6679 struct got_repository *repo = NULL;
6680 struct got_worktree *worktree = NULL;
6681 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6682 char *gitconfig_path = NULL;
6683 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6684 int ch, do_list = 0;
6686 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6687 switch (ch) {
6688 case 'c':
6689 commit_id_arg = optarg;
6690 break;
6691 case 'm':
6692 tagmsg = optarg;
6693 break;
6694 case 'r':
6695 repo_path = realpath(optarg, NULL);
6696 if (repo_path == NULL)
6697 return got_error_from_errno2("realpath",
6698 optarg);
6699 got_path_strip_trailing_slashes(repo_path);
6700 break;
6701 case 'l':
6702 do_list = 1;
6703 break;
6704 default:
6705 usage_tag();
6706 /* NOTREACHED */
6710 argc -= optind;
6711 argv += optind;
6713 if (do_list) {
6714 if (commit_id_arg != NULL)
6715 errx(1,
6716 "-c option can only be used when creating a tag");
6717 if (tagmsg)
6718 option_conflict('l', 'm');
6719 if (argc > 0)
6720 usage_tag();
6721 } else if (argc != 1)
6722 usage_tag();
6724 tag_name = argv[0];
6726 #ifndef PROFILE
6727 if (do_list) {
6728 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6729 NULL) == -1)
6730 err(1, "pledge");
6731 } else {
6732 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6733 "sendfd unveil", NULL) == -1)
6734 err(1, "pledge");
6736 #endif
6737 cwd = getcwd(NULL, 0);
6738 if (cwd == NULL) {
6739 error = got_error_from_errno("getcwd");
6740 goto done;
6743 if (repo_path == NULL) {
6744 error = got_worktree_open(&worktree, cwd);
6745 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6746 goto done;
6747 else
6748 error = NULL;
6749 if (worktree) {
6750 repo_path =
6751 strdup(got_worktree_get_repo_path(worktree));
6752 if (repo_path == NULL)
6753 error = got_error_from_errno("strdup");
6754 if (error)
6755 goto done;
6756 } else {
6757 repo_path = strdup(cwd);
6758 if (repo_path == NULL) {
6759 error = got_error_from_errno("strdup");
6760 goto done;
6765 if (do_list) {
6766 error = got_repo_open(&repo, repo_path, NULL);
6767 if (error != NULL)
6768 goto done;
6769 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6770 if (error)
6771 goto done;
6772 error = list_tags(repo, worktree);
6773 } else {
6774 error = get_gitconfig_path(&gitconfig_path);
6775 if (error)
6776 goto done;
6777 error = got_repo_open(&repo, repo_path, gitconfig_path);
6778 if (error != NULL)
6779 goto done;
6781 if (tagmsg) {
6782 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6783 if (error)
6784 goto done;
6787 if (commit_id_arg == NULL) {
6788 struct got_reference *head_ref;
6789 struct got_object_id *commit_id;
6790 error = got_ref_open(&head_ref, repo,
6791 worktree ? got_worktree_get_head_ref_name(worktree)
6792 : GOT_REF_HEAD, 0);
6793 if (error)
6794 goto done;
6795 error = got_ref_resolve(&commit_id, repo, head_ref);
6796 got_ref_close(head_ref);
6797 if (error)
6798 goto done;
6799 error = got_object_id_str(&commit_id_str, commit_id);
6800 free(commit_id);
6801 if (error)
6802 goto done;
6805 error = add_tag(repo, worktree, tag_name,
6806 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6808 done:
6809 if (repo) {
6810 const struct got_error *close_err = got_repo_close(repo);
6811 if (error == NULL)
6812 error = close_err;
6814 if (worktree)
6815 got_worktree_close(worktree);
6816 free(cwd);
6817 free(repo_path);
6818 free(gitconfig_path);
6819 free(commit_id_str);
6820 return error;
6823 __dead static void
6824 usage_add(void)
6826 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6827 getprogname());
6828 exit(1);
6831 static const struct got_error *
6832 add_progress(void *arg, unsigned char status, const char *path)
6834 while (path[0] == '/')
6835 path++;
6836 printf("%c %s\n", status, path);
6837 return NULL;
6840 static const struct got_error *
6841 cmd_add(int argc, char *argv[])
6843 const struct got_error *error = NULL;
6844 struct got_repository *repo = NULL;
6845 struct got_worktree *worktree = NULL;
6846 char *cwd = NULL;
6847 struct got_pathlist_head paths;
6848 struct got_pathlist_entry *pe;
6849 int ch, can_recurse = 0, no_ignores = 0;
6851 TAILQ_INIT(&paths);
6853 while ((ch = getopt(argc, argv, "IR")) != -1) {
6854 switch (ch) {
6855 case 'I':
6856 no_ignores = 1;
6857 break;
6858 case 'R':
6859 can_recurse = 1;
6860 break;
6861 default:
6862 usage_add();
6863 /* NOTREACHED */
6867 argc -= optind;
6868 argv += optind;
6870 #ifndef PROFILE
6871 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6872 NULL) == -1)
6873 err(1, "pledge");
6874 #endif
6875 if (argc < 1)
6876 usage_add();
6878 cwd = getcwd(NULL, 0);
6879 if (cwd == NULL) {
6880 error = got_error_from_errno("getcwd");
6881 goto done;
6884 error = got_worktree_open(&worktree, cwd);
6885 if (error) {
6886 if (error->code == GOT_ERR_NOT_WORKTREE)
6887 error = wrap_not_worktree_error(error, "add", cwd);
6888 goto done;
6891 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6892 NULL);
6893 if (error != NULL)
6894 goto done;
6896 error = apply_unveil(got_repo_get_path(repo), 1,
6897 got_worktree_get_root_path(worktree));
6898 if (error)
6899 goto done;
6901 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6902 if (error)
6903 goto done;
6905 if (!can_recurse) {
6906 char *ondisk_path;
6907 struct stat sb;
6908 TAILQ_FOREACH(pe, &paths, entry) {
6909 if (asprintf(&ondisk_path, "%s/%s",
6910 got_worktree_get_root_path(worktree),
6911 pe->path) == -1) {
6912 error = got_error_from_errno("asprintf");
6913 goto done;
6915 if (lstat(ondisk_path, &sb) == -1) {
6916 if (errno == ENOENT) {
6917 free(ondisk_path);
6918 continue;
6920 error = got_error_from_errno2("lstat",
6921 ondisk_path);
6922 free(ondisk_path);
6923 goto done;
6925 free(ondisk_path);
6926 if (S_ISDIR(sb.st_mode)) {
6927 error = got_error_msg(GOT_ERR_BAD_PATH,
6928 "adding directories requires -R option");
6929 goto done;
6934 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6935 NULL, repo, no_ignores);
6936 done:
6937 if (repo) {
6938 const struct got_error *close_err = got_repo_close(repo);
6939 if (error == NULL)
6940 error = close_err;
6942 if (worktree)
6943 got_worktree_close(worktree);
6944 TAILQ_FOREACH(pe, &paths, entry)
6945 free((char *)pe->path);
6946 got_pathlist_free(&paths);
6947 free(cwd);
6948 return error;
6951 __dead static void
6952 usage_remove(void)
6954 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6955 "path ...\n", getprogname());
6956 exit(1);
6959 static const struct got_error *
6960 print_remove_status(void *arg, unsigned char status,
6961 unsigned char staged_status, const char *path)
6963 while (path[0] == '/')
6964 path++;
6965 if (status == GOT_STATUS_NONEXISTENT)
6966 return NULL;
6967 if (status == staged_status && (status == GOT_STATUS_DELETE))
6968 status = GOT_STATUS_NO_CHANGE;
6969 printf("%c%c %s\n", status, staged_status, path);
6970 return NULL;
6973 static const struct got_error *
6974 cmd_remove(int argc, char *argv[])
6976 const struct got_error *error = NULL;
6977 struct got_worktree *worktree = NULL;
6978 struct got_repository *repo = NULL;
6979 const char *status_codes = NULL;
6980 char *cwd = NULL;
6981 struct got_pathlist_head paths;
6982 struct got_pathlist_entry *pe;
6983 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6985 TAILQ_INIT(&paths);
6987 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6988 switch (ch) {
6989 case 'f':
6990 delete_local_mods = 1;
6991 break;
6992 case 'k':
6993 keep_on_disk = 1;
6994 break;
6995 case 'R':
6996 can_recurse = 1;
6997 break;
6998 case 's':
6999 for (i = 0; i < strlen(optarg); i++) {
7000 switch (optarg[i]) {
7001 case GOT_STATUS_MODIFY:
7002 delete_local_mods = 1;
7003 break;
7004 case GOT_STATUS_MISSING:
7005 break;
7006 default:
7007 errx(1, "invalid status code '%c'",
7008 optarg[i]);
7011 status_codes = optarg;
7012 break;
7013 default:
7014 usage_remove();
7015 /* NOTREACHED */
7019 argc -= optind;
7020 argv += optind;
7022 #ifndef PROFILE
7023 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7024 NULL) == -1)
7025 err(1, "pledge");
7026 #endif
7027 if (argc < 1)
7028 usage_remove();
7030 cwd = getcwd(NULL, 0);
7031 if (cwd == NULL) {
7032 error = got_error_from_errno("getcwd");
7033 goto done;
7035 error = got_worktree_open(&worktree, cwd);
7036 if (error) {
7037 if (error->code == GOT_ERR_NOT_WORKTREE)
7038 error = wrap_not_worktree_error(error, "remove", cwd);
7039 goto done;
7042 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7043 NULL);
7044 if (error)
7045 goto done;
7047 error = apply_unveil(got_repo_get_path(repo), 1,
7048 got_worktree_get_root_path(worktree));
7049 if (error)
7050 goto done;
7052 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7053 if (error)
7054 goto done;
7056 if (!can_recurse) {
7057 char *ondisk_path;
7058 struct stat sb;
7059 TAILQ_FOREACH(pe, &paths, entry) {
7060 if (asprintf(&ondisk_path, "%s/%s",
7061 got_worktree_get_root_path(worktree),
7062 pe->path) == -1) {
7063 error = got_error_from_errno("asprintf");
7064 goto done;
7066 if (lstat(ondisk_path, &sb) == -1) {
7067 if (errno == ENOENT) {
7068 free(ondisk_path);
7069 continue;
7071 error = got_error_from_errno2("lstat",
7072 ondisk_path);
7073 free(ondisk_path);
7074 goto done;
7076 free(ondisk_path);
7077 if (S_ISDIR(sb.st_mode)) {
7078 error = got_error_msg(GOT_ERR_BAD_PATH,
7079 "removing directories requires -R option");
7080 goto done;
7085 error = got_worktree_schedule_delete(worktree, &paths,
7086 delete_local_mods, status_codes, print_remove_status, NULL,
7087 repo, keep_on_disk);
7088 done:
7089 if (repo) {
7090 const struct got_error *close_err = got_repo_close(repo);
7091 if (error == NULL)
7092 error = close_err;
7094 if (worktree)
7095 got_worktree_close(worktree);
7096 TAILQ_FOREACH(pe, &paths, entry)
7097 free((char *)pe->path);
7098 got_pathlist_free(&paths);
7099 free(cwd);
7100 return error;
7103 __dead static void
7104 usage_revert(void)
7106 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7107 "path ...\n", getprogname());
7108 exit(1);
7111 static const struct got_error *
7112 revert_progress(void *arg, unsigned char status, const char *path)
7114 if (status == GOT_STATUS_UNVERSIONED)
7115 return NULL;
7117 while (path[0] == '/')
7118 path++;
7119 printf("%c %s\n", status, path);
7120 return NULL;
7123 struct choose_patch_arg {
7124 FILE *patch_script_file;
7125 const char *action;
7128 static const struct got_error *
7129 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7130 int nchanges, const char *action)
7132 char *line = NULL;
7133 size_t linesize = 0;
7134 ssize_t linelen;
7136 switch (status) {
7137 case GOT_STATUS_ADD:
7138 printf("A %s\n%s this addition? [y/n] ", path, action);
7139 break;
7140 case GOT_STATUS_DELETE:
7141 printf("D %s\n%s this deletion? [y/n] ", path, action);
7142 break;
7143 case GOT_STATUS_MODIFY:
7144 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7145 return got_error_from_errno("fseek");
7146 printf(GOT_COMMIT_SEP_STR);
7147 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7148 printf("%s", line);
7149 if (ferror(patch_file))
7150 return got_error_from_errno("getline");
7151 printf(GOT_COMMIT_SEP_STR);
7152 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7153 path, n, nchanges, action);
7154 break;
7155 default:
7156 return got_error_path(path, GOT_ERR_FILE_STATUS);
7159 return NULL;
7162 static const struct got_error *
7163 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7164 FILE *patch_file, int n, int nchanges)
7166 const struct got_error *err = NULL;
7167 char *line = NULL;
7168 size_t linesize = 0;
7169 ssize_t linelen;
7170 int resp = ' ';
7171 struct choose_patch_arg *a = arg;
7173 *choice = GOT_PATCH_CHOICE_NONE;
7175 if (a->patch_script_file) {
7176 char *nl;
7177 err = show_change(status, path, patch_file, n, nchanges,
7178 a->action);
7179 if (err)
7180 return err;
7181 linelen = getline(&line, &linesize, a->patch_script_file);
7182 if (linelen == -1) {
7183 if (ferror(a->patch_script_file))
7184 return got_error_from_errno("getline");
7185 return NULL;
7187 nl = strchr(line, '\n');
7188 if (nl)
7189 *nl = '\0';
7190 if (strcmp(line, "y") == 0) {
7191 *choice = GOT_PATCH_CHOICE_YES;
7192 printf("y\n");
7193 } else if (strcmp(line, "n") == 0) {
7194 *choice = GOT_PATCH_CHOICE_NO;
7195 printf("n\n");
7196 } else if (strcmp(line, "q") == 0 &&
7197 status == GOT_STATUS_MODIFY) {
7198 *choice = GOT_PATCH_CHOICE_QUIT;
7199 printf("q\n");
7200 } else
7201 printf("invalid response '%s'\n", line);
7202 free(line);
7203 return NULL;
7206 while (resp != 'y' && resp != 'n' && resp != 'q') {
7207 err = show_change(status, path, patch_file, n, nchanges,
7208 a->action);
7209 if (err)
7210 return err;
7211 resp = getchar();
7212 if (resp == '\n')
7213 resp = getchar();
7214 if (status == GOT_STATUS_MODIFY) {
7215 if (resp != 'y' && resp != 'n' && resp != 'q') {
7216 printf("invalid response '%c'\n", resp);
7217 resp = ' ';
7219 } else if (resp != 'y' && resp != 'n') {
7220 printf("invalid response '%c'\n", resp);
7221 resp = ' ';
7225 if (resp == 'y')
7226 *choice = GOT_PATCH_CHOICE_YES;
7227 else if (resp == 'n')
7228 *choice = GOT_PATCH_CHOICE_NO;
7229 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7230 *choice = GOT_PATCH_CHOICE_QUIT;
7232 return NULL;
7236 static const struct got_error *
7237 cmd_revert(int argc, char *argv[])
7239 const struct got_error *error = NULL;
7240 struct got_worktree *worktree = NULL;
7241 struct got_repository *repo = NULL;
7242 char *cwd = NULL, *path = NULL;
7243 struct got_pathlist_head paths;
7244 struct got_pathlist_entry *pe;
7245 int ch, can_recurse = 0, pflag = 0;
7246 FILE *patch_script_file = NULL;
7247 const char *patch_script_path = NULL;
7248 struct choose_patch_arg cpa;
7250 TAILQ_INIT(&paths);
7252 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7253 switch (ch) {
7254 case 'p':
7255 pflag = 1;
7256 break;
7257 case 'F':
7258 patch_script_path = optarg;
7259 break;
7260 case 'R':
7261 can_recurse = 1;
7262 break;
7263 default:
7264 usage_revert();
7265 /* NOTREACHED */
7269 argc -= optind;
7270 argv += optind;
7272 #ifndef PROFILE
7273 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7274 "unveil", NULL) == -1)
7275 err(1, "pledge");
7276 #endif
7277 if (argc < 1)
7278 usage_revert();
7279 if (patch_script_path && !pflag)
7280 errx(1, "-F option can only be used together with -p option");
7282 cwd = getcwd(NULL, 0);
7283 if (cwd == NULL) {
7284 error = got_error_from_errno("getcwd");
7285 goto done;
7287 error = got_worktree_open(&worktree, cwd);
7288 if (error) {
7289 if (error->code == GOT_ERR_NOT_WORKTREE)
7290 error = wrap_not_worktree_error(error, "revert", cwd);
7291 goto done;
7294 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7295 NULL);
7296 if (error != NULL)
7297 goto done;
7299 if (patch_script_path) {
7300 patch_script_file = fopen(patch_script_path, "re");
7301 if (patch_script_file == NULL) {
7302 error = got_error_from_errno2("fopen",
7303 patch_script_path);
7304 goto done;
7307 error = apply_unveil(got_repo_get_path(repo), 1,
7308 got_worktree_get_root_path(worktree));
7309 if (error)
7310 goto done;
7312 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7313 if (error)
7314 goto done;
7316 if (!can_recurse) {
7317 char *ondisk_path;
7318 struct stat sb;
7319 TAILQ_FOREACH(pe, &paths, entry) {
7320 if (asprintf(&ondisk_path, "%s/%s",
7321 got_worktree_get_root_path(worktree),
7322 pe->path) == -1) {
7323 error = got_error_from_errno("asprintf");
7324 goto done;
7326 if (lstat(ondisk_path, &sb) == -1) {
7327 if (errno == ENOENT) {
7328 free(ondisk_path);
7329 continue;
7331 error = got_error_from_errno2("lstat",
7332 ondisk_path);
7333 free(ondisk_path);
7334 goto done;
7336 free(ondisk_path);
7337 if (S_ISDIR(sb.st_mode)) {
7338 error = got_error_msg(GOT_ERR_BAD_PATH,
7339 "reverting directories requires -R option");
7340 goto done;
7345 cpa.patch_script_file = patch_script_file;
7346 cpa.action = "revert";
7347 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7348 pflag ? choose_patch : NULL, &cpa, repo);
7349 done:
7350 if (patch_script_file && fclose(patch_script_file) == EOF &&
7351 error == NULL)
7352 error = got_error_from_errno2("fclose", patch_script_path);
7353 if (repo) {
7354 const struct got_error *close_err = got_repo_close(repo);
7355 if (error == NULL)
7356 error = close_err;
7358 if (worktree)
7359 got_worktree_close(worktree);
7360 free(path);
7361 free(cwd);
7362 return error;
7365 __dead static void
7366 usage_commit(void)
7368 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7369 "[path ...]\n", getprogname());
7370 exit(1);
7373 struct collect_commit_logmsg_arg {
7374 const char *cmdline_log;
7375 const char *prepared_log;
7376 int non_interactive;
7377 const char *editor;
7378 const char *worktree_path;
7379 const char *branch_name;
7380 const char *repo_path;
7381 char *logmsg_path;
7385 static const struct got_error *
7386 read_prepared_logmsg(char **logmsg, const char *path)
7388 const struct got_error *err = NULL;
7389 FILE *f = NULL;
7390 struct stat sb;
7391 size_t r;
7393 *logmsg = NULL;
7394 memset(&sb, 0, sizeof(sb));
7396 f = fopen(path, "re");
7397 if (f == NULL)
7398 return got_error_from_errno2("fopen", path);
7400 if (fstat(fileno(f), &sb) == -1) {
7401 err = got_error_from_errno2("fstat", path);
7402 goto done;
7404 if (sb.st_size == 0) {
7405 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7406 goto done;
7409 *logmsg = malloc(sb.st_size + 1);
7410 if (*logmsg == NULL) {
7411 err = got_error_from_errno("malloc");
7412 goto done;
7415 r = fread(*logmsg, 1, sb.st_size, f);
7416 if (r != sb.st_size) {
7417 if (ferror(f))
7418 err = got_error_from_errno2("fread", path);
7419 else
7420 err = got_error(GOT_ERR_IO);
7421 goto done;
7423 (*logmsg)[sb.st_size] = '\0';
7424 done:
7425 if (fclose(f) == EOF && err == NULL)
7426 err = got_error_from_errno2("fclose", path);
7427 if (err) {
7428 free(*logmsg);
7429 *logmsg = NULL;
7431 return err;
7435 static const struct got_error *
7436 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7437 void *arg)
7439 char *initial_content = NULL;
7440 struct got_pathlist_entry *pe;
7441 const struct got_error *err = NULL;
7442 char *template = NULL;
7443 struct collect_commit_logmsg_arg *a = arg;
7444 int initial_content_len;
7445 int fd = -1;
7446 size_t len;
7448 /* if a message was specified on the command line, just use it */
7449 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7450 len = strlen(a->cmdline_log) + 1;
7451 *logmsg = malloc(len + 1);
7452 if (*logmsg == NULL)
7453 return got_error_from_errno("malloc");
7454 strlcpy(*logmsg, a->cmdline_log, len);
7455 return NULL;
7456 } else if (a->prepared_log != NULL && a->non_interactive)
7457 return read_prepared_logmsg(logmsg, a->prepared_log);
7459 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7460 return got_error_from_errno("asprintf");
7462 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7463 if (err)
7464 goto done;
7466 if (a->prepared_log) {
7467 char *msg;
7468 err = read_prepared_logmsg(&msg, a->prepared_log);
7469 if (err)
7470 goto done;
7471 if (write(fd, msg, strlen(msg)) == -1) {
7472 err = got_error_from_errno2("write", a->logmsg_path);
7473 free(msg);
7474 goto done;
7476 free(msg);
7479 initial_content_len = asprintf(&initial_content,
7480 "\n# changes to be committed on branch %s:\n",
7481 a->branch_name);
7482 if (initial_content_len == -1) {
7483 err = got_error_from_errno("asprintf");
7484 goto done;
7487 if (write(fd, initial_content, initial_content_len) == -1) {
7488 err = got_error_from_errno2("write", a->logmsg_path);
7489 goto done;
7492 TAILQ_FOREACH(pe, commitable_paths, entry) {
7493 struct got_commitable *ct = pe->data;
7494 dprintf(fd, "# %c %s\n",
7495 got_commitable_get_status(ct),
7496 got_commitable_get_path(ct));
7499 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7500 initial_content_len, a->prepared_log ? 0 : 1);
7501 done:
7502 free(initial_content);
7503 free(template);
7505 if (fd != -1 && close(fd) == -1 && err == NULL)
7506 err = got_error_from_errno2("close", a->logmsg_path);
7508 /* Editor is done; we can now apply unveil(2) */
7509 if (err == NULL)
7510 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7511 if (err) {
7512 free(*logmsg);
7513 *logmsg = NULL;
7515 return err;
7518 static const struct got_error *
7519 cmd_commit(int argc, char *argv[])
7521 const struct got_error *error = NULL;
7522 struct got_worktree *worktree = NULL;
7523 struct got_repository *repo = NULL;
7524 char *cwd = NULL, *id_str = NULL;
7525 struct got_object_id *id = NULL;
7526 const char *logmsg = NULL;
7527 char *prepared_logmsg = NULL;
7528 struct collect_commit_logmsg_arg cl_arg;
7529 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7530 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7531 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7532 struct got_pathlist_head paths;
7534 TAILQ_INIT(&paths);
7535 cl_arg.logmsg_path = NULL;
7537 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7538 switch (ch) {
7539 case 'F':
7540 if (logmsg != NULL)
7541 option_conflict('F', 'm');
7542 prepared_logmsg = realpath(optarg, NULL);
7543 if (prepared_logmsg == NULL)
7544 return got_error_from_errno2("realpath",
7545 optarg);
7546 break;
7547 case 'm':
7548 if (prepared_logmsg)
7549 option_conflict('m', 'F');
7550 logmsg = optarg;
7551 break;
7552 case 'N':
7553 non_interactive = 1;
7554 break;
7555 case 'S':
7556 allow_bad_symlinks = 1;
7557 break;
7558 default:
7559 usage_commit();
7560 /* NOTREACHED */
7564 argc -= optind;
7565 argv += optind;
7567 #ifndef PROFILE
7568 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7569 "unveil", NULL) == -1)
7570 err(1, "pledge");
7571 #endif
7572 cwd = getcwd(NULL, 0);
7573 if (cwd == NULL) {
7574 error = got_error_from_errno("getcwd");
7575 goto done;
7577 error = got_worktree_open(&worktree, cwd);
7578 if (error) {
7579 if (error->code == GOT_ERR_NOT_WORKTREE)
7580 error = wrap_not_worktree_error(error, "commit", cwd);
7581 goto done;
7584 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7585 if (error)
7586 goto done;
7587 if (rebase_in_progress) {
7588 error = got_error(GOT_ERR_REBASING);
7589 goto done;
7592 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7593 worktree);
7594 if (error)
7595 goto done;
7597 error = get_gitconfig_path(&gitconfig_path);
7598 if (error)
7599 goto done;
7600 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7601 gitconfig_path);
7602 if (error != NULL)
7603 goto done;
7605 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7606 if (error)
7607 goto done;
7608 if (merge_in_progress) {
7609 error = got_error(GOT_ERR_MERGE_BUSY);
7610 goto done;
7613 error = get_author(&author, repo, worktree);
7614 if (error)
7615 return error;
7618 * unveil(2) traverses exec(2); if an editor is used we have
7619 * to apply unveil after the log message has been written.
7621 if (logmsg == NULL || strlen(logmsg) == 0)
7622 error = get_editor(&editor);
7623 else
7624 error = apply_unveil(got_repo_get_path(repo), 0,
7625 got_worktree_get_root_path(worktree));
7626 if (error)
7627 goto done;
7629 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7630 if (error)
7631 goto done;
7633 cl_arg.editor = editor;
7634 cl_arg.cmdline_log = logmsg;
7635 cl_arg.prepared_log = prepared_logmsg;
7636 cl_arg.non_interactive = non_interactive;
7637 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7638 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7639 if (!histedit_in_progress) {
7640 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7641 error = got_error(GOT_ERR_COMMIT_BRANCH);
7642 goto done;
7644 cl_arg.branch_name += 11;
7646 cl_arg.repo_path = got_repo_get_path(repo);
7647 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7648 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7649 print_status, NULL, repo);
7650 if (error) {
7651 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7652 cl_arg.logmsg_path != NULL)
7653 preserve_logmsg = 1;
7654 goto done;
7657 error = got_object_id_str(&id_str, id);
7658 if (error)
7659 goto done;
7660 printf("Created commit %s\n", id_str);
7661 done:
7662 if (preserve_logmsg) {
7663 fprintf(stderr, "%s: log message preserved in %s\n",
7664 getprogname(), cl_arg.logmsg_path);
7665 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7666 error == NULL)
7667 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7668 free(cl_arg.logmsg_path);
7669 if (repo) {
7670 const struct got_error *close_err = got_repo_close(repo);
7671 if (error == NULL)
7672 error = close_err;
7674 if (worktree)
7675 got_worktree_close(worktree);
7676 free(cwd);
7677 free(id_str);
7678 free(gitconfig_path);
7679 free(editor);
7680 free(author);
7681 free(prepared_logmsg);
7682 return error;
7685 __dead static void
7686 usage_send(void)
7688 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7689 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7690 "[remote-repository]\n", getprogname());
7691 exit(1);
7694 struct got_send_progress_arg {
7695 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7696 int verbosity;
7697 int last_ncommits;
7698 int last_nobj_total;
7699 int last_p_deltify;
7700 int last_p_written;
7701 int last_p_sent;
7702 int printed_something;
7703 int sent_something;
7704 struct got_pathlist_head *delete_branches;
7707 static const struct got_error *
7708 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7709 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7710 int success)
7712 struct got_send_progress_arg *a = arg;
7713 char scaled_packsize[FMT_SCALED_STRSIZE];
7714 char scaled_sent[FMT_SCALED_STRSIZE];
7715 int p_deltify = 0, p_written = 0, p_sent = 0;
7716 int print_searching = 0, print_total = 0;
7717 int print_deltify = 0, print_written = 0, print_sent = 0;
7719 if (a->verbosity < 0)
7720 return NULL;
7722 if (refname) {
7723 const char *status = success ? "accepted" : "rejected";
7725 if (success) {
7726 struct got_pathlist_entry *pe;
7727 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7728 const char *branchname = pe->path;
7729 if (got_path_cmp(branchname, refname,
7730 strlen(branchname), strlen(refname)) == 0) {
7731 status = "deleted";
7732 a->sent_something = 1;
7733 break;
7738 if (a->printed_something)
7739 putchar('\n');
7740 printf("Server has %s %s", status, refname);
7741 a->printed_something = 1;
7742 return NULL;
7745 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7746 return got_error_from_errno("fmt_scaled");
7747 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7748 return got_error_from_errno("fmt_scaled");
7750 if (a->last_ncommits != ncommits) {
7751 print_searching = 1;
7752 a->last_ncommits = ncommits;
7755 if (a->last_nobj_total != nobj_total) {
7756 print_searching = 1;
7757 print_total = 1;
7758 a->last_nobj_total = nobj_total;
7761 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7762 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7763 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7764 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7765 return got_error(GOT_ERR_NO_SPACE);
7768 if (nobj_deltify > 0 || nobj_written > 0) {
7769 if (nobj_deltify > 0) {
7770 p_deltify = (nobj_deltify * 100) / nobj_total;
7771 if (p_deltify != a->last_p_deltify) {
7772 a->last_p_deltify = p_deltify;
7773 print_searching = 1;
7774 print_total = 1;
7775 print_deltify = 1;
7778 if (nobj_written > 0) {
7779 p_written = (nobj_written * 100) / nobj_total;
7780 if (p_written != a->last_p_written) {
7781 a->last_p_written = p_written;
7782 print_searching = 1;
7783 print_total = 1;
7784 print_deltify = 1;
7785 print_written = 1;
7790 if (bytes_sent > 0) {
7791 p_sent = (bytes_sent * 100) / packfile_size;
7792 if (p_sent != a->last_p_sent) {
7793 a->last_p_sent = p_sent;
7794 print_searching = 1;
7795 print_total = 1;
7796 print_deltify = 1;
7797 print_written = 1;
7798 print_sent = 1;
7800 a->sent_something = 1;
7803 if (print_searching || print_total || print_deltify || print_written ||
7804 print_sent)
7805 printf("\r");
7806 if (print_searching)
7807 printf("packing %d reference%s", ncommits,
7808 ncommits == 1 ? "" : "s");
7809 if (print_total)
7810 printf("; %d object%s", nobj_total,
7811 nobj_total == 1 ? "" : "s");
7812 if (print_deltify)
7813 printf("; deltify: %d%%", p_deltify);
7814 if (print_sent)
7815 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7816 scaled_packsize, p_sent);
7817 else if (print_written)
7818 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7819 scaled_packsize, p_written);
7820 if (print_searching || print_total || print_deltify ||
7821 print_written || print_sent) {
7822 a->printed_something = 1;
7823 fflush(stdout);
7825 return NULL;
7828 static const struct got_error *
7829 cmd_send(int argc, char *argv[])
7831 const struct got_error *error = NULL;
7832 char *cwd = NULL, *repo_path = NULL;
7833 const char *remote_name;
7834 char *proto = NULL, *host = NULL, *port = NULL;
7835 char *repo_name = NULL, *server_path = NULL;
7836 const struct got_remote_repo *remotes, *remote = NULL;
7837 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7838 struct got_repository *repo = NULL;
7839 struct got_worktree *worktree = NULL;
7840 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7841 struct got_pathlist_head branches;
7842 struct got_pathlist_head tags;
7843 struct got_reflist_head all_branches;
7844 struct got_reflist_head all_tags;
7845 struct got_pathlist_head delete_args;
7846 struct got_pathlist_head delete_branches;
7847 struct got_reflist_entry *re;
7848 struct got_pathlist_entry *pe;
7849 int i, ch, sendfd = -1, sendstatus;
7850 pid_t sendpid = -1;
7851 struct got_send_progress_arg spa;
7852 int verbosity = 0, overwrite_refs = 0;
7853 int send_all_branches = 0, send_all_tags = 0;
7854 struct got_reference *ref = NULL;
7856 TAILQ_INIT(&branches);
7857 TAILQ_INIT(&tags);
7858 TAILQ_INIT(&all_branches);
7859 TAILQ_INIT(&all_tags);
7860 TAILQ_INIT(&delete_args);
7861 TAILQ_INIT(&delete_branches);
7863 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7864 switch (ch) {
7865 case 'a':
7866 send_all_branches = 1;
7867 break;
7868 case 'b':
7869 error = got_pathlist_append(&branches, optarg, NULL);
7870 if (error)
7871 return error;
7872 nbranches++;
7873 break;
7874 case 'd':
7875 error = got_pathlist_append(&delete_args, optarg, NULL);
7876 if (error)
7877 return error;
7878 break;
7879 case 'f':
7880 overwrite_refs = 1;
7881 break;
7882 case 'r':
7883 repo_path = realpath(optarg, NULL);
7884 if (repo_path == NULL)
7885 return got_error_from_errno2("realpath",
7886 optarg);
7887 got_path_strip_trailing_slashes(repo_path);
7888 break;
7889 case 't':
7890 error = got_pathlist_append(&tags, optarg, NULL);
7891 if (error)
7892 return error;
7893 ntags++;
7894 break;
7895 case 'T':
7896 send_all_tags = 1;
7897 break;
7898 case 'v':
7899 if (verbosity < 0)
7900 verbosity = 0;
7901 else if (verbosity < 3)
7902 verbosity++;
7903 break;
7904 case 'q':
7905 verbosity = -1;
7906 break;
7907 default:
7908 usage_send();
7909 /* NOTREACHED */
7912 argc -= optind;
7913 argv += optind;
7915 if (send_all_branches && !TAILQ_EMPTY(&branches))
7916 option_conflict('a', 'b');
7917 if (send_all_tags && !TAILQ_EMPTY(&tags))
7918 option_conflict('T', 't');
7921 if (argc == 0)
7922 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7923 else if (argc == 1)
7924 remote_name = argv[0];
7925 else
7926 usage_send();
7928 cwd = getcwd(NULL, 0);
7929 if (cwd == NULL) {
7930 error = got_error_from_errno("getcwd");
7931 goto done;
7934 if (repo_path == NULL) {
7935 error = got_worktree_open(&worktree, cwd);
7936 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7937 goto done;
7938 else
7939 error = NULL;
7940 if (worktree) {
7941 repo_path =
7942 strdup(got_worktree_get_repo_path(worktree));
7943 if (repo_path == NULL)
7944 error = got_error_from_errno("strdup");
7945 if (error)
7946 goto done;
7947 } else {
7948 repo_path = strdup(cwd);
7949 if (repo_path == NULL) {
7950 error = got_error_from_errno("strdup");
7951 goto done;
7956 error = got_repo_open(&repo, repo_path, NULL);
7957 if (error)
7958 goto done;
7960 if (worktree) {
7961 worktree_conf = got_worktree_get_gotconfig(worktree);
7962 if (worktree_conf) {
7963 got_gotconfig_get_remotes(&nremotes, &remotes,
7964 worktree_conf);
7965 for (i = 0; i < nremotes; i++) {
7966 if (strcmp(remotes[i].name, remote_name) == 0) {
7967 remote = &remotes[i];
7968 break;
7973 if (remote == NULL) {
7974 repo_conf = got_repo_get_gotconfig(repo);
7975 if (repo_conf) {
7976 got_gotconfig_get_remotes(&nremotes, &remotes,
7977 repo_conf);
7978 for (i = 0; i < nremotes; i++) {
7979 if (strcmp(remotes[i].name, remote_name) == 0) {
7980 remote = &remotes[i];
7981 break;
7986 if (remote == NULL) {
7987 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7988 for (i = 0; i < nremotes; i++) {
7989 if (strcmp(remotes[i].name, remote_name) == 0) {
7990 remote = &remotes[i];
7991 break;
7995 if (remote == NULL) {
7996 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7997 goto done;
8000 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8001 &repo_name, remote->send_url);
8002 if (error)
8003 goto done;
8005 if (strcmp(proto, "git") == 0) {
8006 #ifndef PROFILE
8007 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8008 "sendfd dns inet unveil", NULL) == -1)
8009 err(1, "pledge");
8010 #endif
8011 } else if (strcmp(proto, "git+ssh") == 0 ||
8012 strcmp(proto, "ssh") == 0) {
8013 #ifndef PROFILE
8014 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8015 "sendfd unveil", NULL) == -1)
8016 err(1, "pledge");
8017 #endif
8018 } else if (strcmp(proto, "http") == 0 ||
8019 strcmp(proto, "git+http") == 0) {
8020 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8021 goto done;
8022 } else {
8023 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8024 goto done;
8027 error = got_dial_apply_unveil(proto);
8028 if (error)
8029 goto done;
8031 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8032 if (error)
8033 goto done;
8035 if (send_all_branches) {
8036 error = got_ref_list(&all_branches, repo, "refs/heads",
8037 got_ref_cmp_by_name, NULL);
8038 if (error)
8039 goto done;
8040 TAILQ_FOREACH(re, &all_branches, entry) {
8041 const char *branchname = got_ref_get_name(re->ref);
8042 error = got_pathlist_append(&branches,
8043 branchname, NULL);
8044 if (error)
8045 goto done;
8046 nbranches++;
8048 } else if (nbranches == 0) {
8049 for (i = 0; i < remote->nsend_branches; i++) {
8050 got_pathlist_append(&branches,
8051 remote->send_branches[i], NULL);
8055 if (send_all_tags) {
8056 error = got_ref_list(&all_tags, repo, "refs/tags",
8057 got_ref_cmp_by_name, NULL);
8058 if (error)
8059 goto done;
8060 TAILQ_FOREACH(re, &all_tags, entry) {
8061 const char *tagname = got_ref_get_name(re->ref);
8062 error = got_pathlist_append(&tags,
8063 tagname, NULL);
8064 if (error)
8065 goto done;
8066 ntags++;
8071 * To prevent accidents only branches in refs/heads/ can be deleted
8072 * with 'got send -d'.
8073 * Deleting anything else requires local repository access or Git.
8075 TAILQ_FOREACH(pe, &delete_args, entry) {
8076 const char *branchname = pe->path;
8077 char *s;
8078 struct got_pathlist_entry *new;
8079 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8080 s = strdup(branchname);
8081 if (s == NULL) {
8082 error = got_error_from_errno("strdup");
8083 goto done;
8085 } else {
8086 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8087 error = got_error_from_errno("asprintf");
8088 goto done;
8091 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8092 if (error || new == NULL /* duplicate */)
8093 free(s);
8094 if (error)
8095 goto done;
8096 ndelete_branches++;
8099 if (nbranches == 0 && ndelete_branches == 0) {
8100 struct got_reference *head_ref;
8101 if (worktree)
8102 error = got_ref_open(&head_ref, repo,
8103 got_worktree_get_head_ref_name(worktree), 0);
8104 else
8105 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8106 if (error)
8107 goto done;
8108 if (got_ref_is_symbolic(head_ref)) {
8109 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8110 got_ref_close(head_ref);
8111 if (error)
8112 goto done;
8113 } else
8114 ref = head_ref;
8115 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8116 NULL);
8117 if (error)
8118 goto done;
8119 nbranches++;
8122 if (verbosity >= 0)
8123 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8124 port ? ":" : "", port ? port : "");
8126 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8127 server_path, verbosity);
8128 if (error)
8129 goto done;
8131 memset(&spa, 0, sizeof(spa));
8132 spa.last_scaled_packsize[0] = '\0';
8133 spa.last_p_deltify = -1;
8134 spa.last_p_written = -1;
8135 spa.verbosity = verbosity;
8136 spa.delete_branches = &delete_branches;
8137 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8138 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8139 check_cancelled, NULL);
8140 if (spa.printed_something)
8141 putchar('\n');
8142 if (error)
8143 goto done;
8144 if (!spa.sent_something && verbosity >= 0)
8145 printf("Already up-to-date\n");
8146 done:
8147 if (sendpid > 0) {
8148 if (kill(sendpid, SIGTERM) == -1)
8149 error = got_error_from_errno("kill");
8150 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8151 error = got_error_from_errno("waitpid");
8153 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8154 error = got_error_from_errno("close");
8155 if (repo) {
8156 const struct got_error *close_err = got_repo_close(repo);
8157 if (error == NULL)
8158 error = close_err;
8160 if (worktree)
8161 got_worktree_close(worktree);
8162 if (ref)
8163 got_ref_close(ref);
8164 got_pathlist_free(&branches);
8165 got_pathlist_free(&tags);
8166 got_ref_list_free(&all_branches);
8167 got_ref_list_free(&all_tags);
8168 got_pathlist_free(&delete_args);
8169 TAILQ_FOREACH(pe, &delete_branches, entry)
8170 free((char *)pe->path);
8171 got_pathlist_free(&delete_branches);
8172 free(cwd);
8173 free(repo_path);
8174 free(proto);
8175 free(host);
8176 free(port);
8177 free(server_path);
8178 free(repo_name);
8179 return error;
8182 __dead static void
8183 usage_cherrypick(void)
8185 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8186 exit(1);
8189 static const struct got_error *
8190 cmd_cherrypick(int argc, char *argv[])
8192 const struct got_error *error = NULL;
8193 struct got_worktree *worktree = NULL;
8194 struct got_repository *repo = NULL;
8195 char *cwd = NULL, *commit_id_str = NULL;
8196 struct got_object_id *commit_id = NULL;
8197 struct got_commit_object *commit = NULL;
8198 struct got_object_qid *pid;
8199 int ch;
8200 struct got_update_progress_arg upa;
8202 while ((ch = getopt(argc, argv, "")) != -1) {
8203 switch (ch) {
8204 default:
8205 usage_cherrypick();
8206 /* NOTREACHED */
8210 argc -= optind;
8211 argv += optind;
8213 #ifndef PROFILE
8214 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8215 "unveil", NULL) == -1)
8216 err(1, "pledge");
8217 #endif
8218 if (argc != 1)
8219 usage_cherrypick();
8221 cwd = getcwd(NULL, 0);
8222 if (cwd == NULL) {
8223 error = got_error_from_errno("getcwd");
8224 goto done;
8226 error = got_worktree_open(&worktree, cwd);
8227 if (error) {
8228 if (error->code == GOT_ERR_NOT_WORKTREE)
8229 error = wrap_not_worktree_error(error, "cherrypick",
8230 cwd);
8231 goto done;
8234 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8235 NULL);
8236 if (error != NULL)
8237 goto done;
8239 error = apply_unveil(got_repo_get_path(repo), 0,
8240 got_worktree_get_root_path(worktree));
8241 if (error)
8242 goto done;
8244 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8245 GOT_OBJ_TYPE_COMMIT, repo);
8246 if (error != NULL) {
8247 struct got_reference *ref;
8248 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8249 goto done;
8250 error = got_ref_open(&ref, repo, argv[0], 0);
8251 if (error != NULL)
8252 goto done;
8253 error = got_ref_resolve(&commit_id, repo, ref);
8254 got_ref_close(ref);
8255 if (error != NULL)
8256 goto done;
8258 error = got_object_id_str(&commit_id_str, commit_id);
8259 if (error)
8260 goto done;
8262 error = got_object_open_as_commit(&commit, repo, commit_id);
8263 if (error)
8264 goto done;
8265 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8266 memset(&upa, 0, sizeof(upa));
8267 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8268 commit_id, repo, update_progress, &upa, check_cancelled,
8269 NULL);
8270 if (error != NULL)
8271 goto done;
8273 if (upa.did_something)
8274 printf("Merged commit %s\n", commit_id_str);
8275 print_merge_progress_stats(&upa);
8276 done:
8277 if (commit)
8278 got_object_commit_close(commit);
8279 free(commit_id_str);
8280 if (worktree)
8281 got_worktree_close(worktree);
8282 if (repo) {
8283 const struct got_error *close_err = got_repo_close(repo);
8284 if (error == NULL)
8285 error = close_err;
8287 return error;
8290 __dead static void
8291 usage_backout(void)
8293 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8294 exit(1);
8297 static const struct got_error *
8298 cmd_backout(int argc, char *argv[])
8300 const struct got_error *error = NULL;
8301 struct got_worktree *worktree = NULL;
8302 struct got_repository *repo = NULL;
8303 char *cwd = NULL, *commit_id_str = NULL;
8304 struct got_object_id *commit_id = NULL;
8305 struct got_commit_object *commit = NULL;
8306 struct got_object_qid *pid;
8307 int ch;
8308 struct got_update_progress_arg upa;
8310 while ((ch = getopt(argc, argv, "")) != -1) {
8311 switch (ch) {
8312 default:
8313 usage_backout();
8314 /* NOTREACHED */
8318 argc -= optind;
8319 argv += optind;
8321 #ifndef PROFILE
8322 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8323 "unveil", NULL) == -1)
8324 err(1, "pledge");
8325 #endif
8326 if (argc != 1)
8327 usage_backout();
8329 cwd = getcwd(NULL, 0);
8330 if (cwd == NULL) {
8331 error = got_error_from_errno("getcwd");
8332 goto done;
8334 error = got_worktree_open(&worktree, cwd);
8335 if (error) {
8336 if (error->code == GOT_ERR_NOT_WORKTREE)
8337 error = wrap_not_worktree_error(error, "backout", cwd);
8338 goto done;
8341 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8342 NULL);
8343 if (error != NULL)
8344 goto done;
8346 error = apply_unveil(got_repo_get_path(repo), 0,
8347 got_worktree_get_root_path(worktree));
8348 if (error)
8349 goto done;
8351 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8352 GOT_OBJ_TYPE_COMMIT, repo);
8353 if (error != NULL) {
8354 struct got_reference *ref;
8355 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8356 goto done;
8357 error = got_ref_open(&ref, repo, argv[0], 0);
8358 if (error != NULL)
8359 goto done;
8360 error = got_ref_resolve(&commit_id, repo, ref);
8361 got_ref_close(ref);
8362 if (error != NULL)
8363 goto done;
8365 error = got_object_id_str(&commit_id_str, commit_id);
8366 if (error)
8367 goto done;
8369 error = got_object_open_as_commit(&commit, repo, commit_id);
8370 if (error)
8371 goto done;
8372 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8373 if (pid == NULL) {
8374 error = got_error(GOT_ERR_ROOT_COMMIT);
8375 goto done;
8378 memset(&upa, 0, sizeof(upa));
8379 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8380 repo, update_progress, &upa, check_cancelled, NULL);
8381 if (error != NULL)
8382 goto done;
8384 if (upa.did_something)
8385 printf("Backed out commit %s\n", commit_id_str);
8386 print_merge_progress_stats(&upa);
8387 done:
8388 if (commit)
8389 got_object_commit_close(commit);
8390 free(commit_id_str);
8391 if (worktree)
8392 got_worktree_close(worktree);
8393 if (repo) {
8394 const struct got_error *close_err = got_repo_close(repo);
8395 if (error == NULL)
8396 error = close_err;
8398 return error;
8401 __dead static void
8402 usage_rebase(void)
8404 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8405 getprogname());
8406 exit(1);
8409 void
8410 trim_logmsg(char *logmsg, int limit)
8412 char *nl;
8413 size_t len;
8415 len = strlen(logmsg);
8416 if (len > limit)
8417 len = limit;
8418 logmsg[len] = '\0';
8419 nl = strchr(logmsg, '\n');
8420 if (nl)
8421 *nl = '\0';
8424 static const struct got_error *
8425 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8427 const struct got_error *err;
8428 char *logmsg0 = NULL;
8429 const char *s;
8431 err = got_object_commit_get_logmsg(&logmsg0, commit);
8432 if (err)
8433 return err;
8435 s = logmsg0;
8436 while (isspace((unsigned char)s[0]))
8437 s++;
8439 *logmsg = strdup(s);
8440 if (*logmsg == NULL) {
8441 err = got_error_from_errno("strdup");
8442 goto done;
8445 trim_logmsg(*logmsg, limit);
8446 done:
8447 free(logmsg0);
8448 return err;
8451 static const struct got_error *
8452 show_rebase_merge_conflict(struct got_object_id *id,
8453 struct got_repository *repo)
8455 const struct got_error *err;
8456 struct got_commit_object *commit = NULL;
8457 char *id_str = NULL, *logmsg = NULL;
8459 err = got_object_open_as_commit(&commit, repo, id);
8460 if (err)
8461 return err;
8463 err = got_object_id_str(&id_str, id);
8464 if (err)
8465 goto done;
8467 id_str[12] = '\0';
8469 err = get_short_logmsg(&logmsg, 42, commit);
8470 if (err)
8471 goto done;
8473 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8474 done:
8475 free(id_str);
8476 got_object_commit_close(commit);
8477 free(logmsg);
8478 return err;
8481 static const struct got_error *
8482 show_rebase_progress(struct got_commit_object *commit,
8483 struct got_object_id *old_id, struct got_object_id *new_id)
8485 const struct got_error *err;
8486 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8488 err = got_object_id_str(&old_id_str, old_id);
8489 if (err)
8490 goto done;
8492 if (new_id) {
8493 err = got_object_id_str(&new_id_str, new_id);
8494 if (err)
8495 goto done;
8498 old_id_str[12] = '\0';
8499 if (new_id_str)
8500 new_id_str[12] = '\0';
8502 err = get_short_logmsg(&logmsg, 42, commit);
8503 if (err)
8504 goto done;
8506 printf("%s -> %s: %s\n", old_id_str,
8507 new_id_str ? new_id_str : "no-op change", logmsg);
8508 done:
8509 free(old_id_str);
8510 free(new_id_str);
8511 free(logmsg);
8512 return err;
8515 static const struct got_error *
8516 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8517 struct got_reference *branch, struct got_reference *new_base_branch,
8518 struct got_reference *tmp_branch, struct got_repository *repo,
8519 int create_backup)
8521 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8522 return got_worktree_rebase_complete(worktree, fileindex,
8523 new_base_branch, tmp_branch, branch, repo, create_backup);
8526 static const struct got_error *
8527 rebase_commit(struct got_pathlist_head *merged_paths,
8528 struct got_worktree *worktree, struct got_fileindex *fileindex,
8529 struct got_reference *tmp_branch,
8530 struct got_object_id *commit_id, struct got_repository *repo)
8532 const struct got_error *error;
8533 struct got_commit_object *commit;
8534 struct got_object_id *new_commit_id;
8536 error = got_object_open_as_commit(&commit, repo, commit_id);
8537 if (error)
8538 return error;
8540 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8541 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8542 if (error) {
8543 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8544 goto done;
8545 error = show_rebase_progress(commit, commit_id, NULL);
8546 } else {
8547 error = show_rebase_progress(commit, commit_id, new_commit_id);
8548 free(new_commit_id);
8550 done:
8551 got_object_commit_close(commit);
8552 return error;
8555 struct check_path_prefix_arg {
8556 const char *path_prefix;
8557 size_t len;
8558 int errcode;
8561 static const struct got_error *
8562 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8563 struct got_blob_object *blob2, struct got_object_id *id1,
8564 struct got_object_id *id2, const char *path1, const char *path2,
8565 mode_t mode1, mode_t mode2, struct got_repository *repo)
8567 struct check_path_prefix_arg *a = arg;
8569 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8570 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8571 return got_error(a->errcode);
8573 return NULL;
8576 static const struct got_error *
8577 check_path_prefix(struct got_object_id *parent_id,
8578 struct got_object_id *commit_id, const char *path_prefix,
8579 int errcode, struct got_repository *repo)
8581 const struct got_error *err;
8582 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8583 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8584 struct check_path_prefix_arg cpp_arg;
8586 if (got_path_is_root_dir(path_prefix))
8587 return NULL;
8589 err = got_object_open_as_commit(&commit, repo, commit_id);
8590 if (err)
8591 goto done;
8593 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8594 if (err)
8595 goto done;
8597 err = got_object_open_as_tree(&tree1, repo,
8598 got_object_commit_get_tree_id(parent_commit));
8599 if (err)
8600 goto done;
8602 err = got_object_open_as_tree(&tree2, repo,
8603 got_object_commit_get_tree_id(commit));
8604 if (err)
8605 goto done;
8607 cpp_arg.path_prefix = path_prefix;
8608 while (cpp_arg.path_prefix[0] == '/')
8609 cpp_arg.path_prefix++;
8610 cpp_arg.len = strlen(cpp_arg.path_prefix);
8611 cpp_arg.errcode = errcode;
8612 err = got_diff_tree(tree1, tree2, "", "", repo,
8613 check_path_prefix_in_diff, &cpp_arg, 0);
8614 done:
8615 if (tree1)
8616 got_object_tree_close(tree1);
8617 if (tree2)
8618 got_object_tree_close(tree2);
8619 if (commit)
8620 got_object_commit_close(commit);
8621 if (parent_commit)
8622 got_object_commit_close(parent_commit);
8623 return err;
8626 static const struct got_error *
8627 collect_commits(struct got_object_id_queue *commits,
8628 struct got_object_id *initial_commit_id,
8629 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8630 const char *path_prefix, int path_prefix_errcode,
8631 struct got_repository *repo)
8633 const struct got_error *err = NULL;
8634 struct got_commit_graph *graph = NULL;
8635 struct got_object_id *parent_id = NULL;
8636 struct got_object_qid *qid;
8637 struct got_object_id *commit_id = initial_commit_id;
8639 err = got_commit_graph_open(&graph, "/", 1);
8640 if (err)
8641 return err;
8643 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8644 check_cancelled, NULL);
8645 if (err)
8646 goto done;
8647 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8648 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8649 check_cancelled, NULL);
8650 if (err) {
8651 if (err->code == GOT_ERR_ITER_COMPLETED) {
8652 err = got_error_msg(GOT_ERR_ANCESTRY,
8653 "ran out of commits to rebase before "
8654 "youngest common ancestor commit has "
8655 "been reached?!?");
8657 goto done;
8658 } else {
8659 err = check_path_prefix(parent_id, commit_id,
8660 path_prefix, path_prefix_errcode, repo);
8661 if (err)
8662 goto done;
8664 err = got_object_qid_alloc(&qid, commit_id);
8665 if (err)
8666 goto done;
8667 STAILQ_INSERT_HEAD(commits, qid, entry);
8668 commit_id = parent_id;
8671 done:
8672 got_commit_graph_close(graph);
8673 return err;
8676 static const struct got_error *
8677 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8679 const struct got_error *err = NULL;
8680 time_t committer_time;
8681 struct tm tm;
8682 char datebuf[11]; /* YYYY-MM-DD + NUL */
8683 char *author0 = NULL, *author, *smallerthan;
8684 char *logmsg0 = NULL, *logmsg, *newline;
8686 committer_time = got_object_commit_get_committer_time(commit);
8687 if (gmtime_r(&committer_time, &tm) == NULL)
8688 return got_error_from_errno("gmtime_r");
8689 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8690 return got_error(GOT_ERR_NO_SPACE);
8692 author0 = strdup(got_object_commit_get_author(commit));
8693 if (author0 == NULL)
8694 return got_error_from_errno("strdup");
8695 author = author0;
8696 smallerthan = strchr(author, '<');
8697 if (smallerthan && smallerthan[1] != '\0')
8698 author = smallerthan + 1;
8699 author[strcspn(author, "@>")] = '\0';
8701 err = got_object_commit_get_logmsg(&logmsg0, commit);
8702 if (err)
8703 goto done;
8704 logmsg = logmsg0;
8705 while (*logmsg == '\n')
8706 logmsg++;
8707 newline = strchr(logmsg, '\n');
8708 if (newline)
8709 *newline = '\0';
8711 if (asprintf(brief_str, "%s %s %s",
8712 datebuf, author, logmsg) == -1)
8713 err = got_error_from_errno("asprintf");
8714 done:
8715 free(author0);
8716 free(logmsg0);
8717 return err;
8720 static const struct got_error *
8721 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8722 struct got_repository *repo)
8724 const struct got_error *err;
8725 char *id_str;
8727 err = got_object_id_str(&id_str, id);
8728 if (err)
8729 return err;
8731 err = got_ref_delete(ref, repo);
8732 if (err)
8733 goto done;
8735 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8736 done:
8737 free(id_str);
8738 return err;
8741 static const struct got_error *
8742 print_backup_ref(const char *branch_name, const char *new_id_str,
8743 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8744 struct got_reflist_object_id_map *refs_idmap,
8745 struct got_repository *repo)
8747 const struct got_error *err = NULL;
8748 struct got_reflist_head *refs;
8749 char *refs_str = NULL;
8750 struct got_object_id *new_commit_id = NULL;
8751 struct got_commit_object *new_commit = NULL;
8752 char *new_commit_brief_str = NULL;
8753 struct got_object_id *yca_id = NULL;
8754 struct got_commit_object *yca_commit = NULL;
8755 char *yca_id_str = NULL, *yca_brief_str = NULL;
8756 char *custom_refs_str;
8758 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8759 return got_error_from_errno("asprintf");
8761 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8762 0, 0, refs_idmap, custom_refs_str);
8763 if (err)
8764 goto done;
8766 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8767 if (err)
8768 goto done;
8770 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8771 if (refs) {
8772 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8773 if (err)
8774 goto done;
8777 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8778 if (err)
8779 goto done;
8781 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8782 if (err)
8783 goto done;
8785 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8786 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8787 if (err)
8788 goto done;
8790 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8791 refs_str ? " (" : "", refs_str ? refs_str : "",
8792 refs_str ? ")" : "", new_commit_brief_str);
8793 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8794 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8795 free(refs_str);
8796 refs_str = NULL;
8798 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8799 if (err)
8800 goto done;
8802 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8803 if (err)
8804 goto done;
8806 err = got_object_id_str(&yca_id_str, yca_id);
8807 if (err)
8808 goto done;
8810 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8811 if (refs) {
8812 err = build_refs_str(&refs_str, refs, yca_id, repo);
8813 if (err)
8814 goto done;
8816 printf("history forked at %s%s%s%s\n %s\n",
8817 yca_id_str,
8818 refs_str ? " (" : "", refs_str ? refs_str : "",
8819 refs_str ? ")" : "", yca_brief_str);
8821 done:
8822 free(custom_refs_str);
8823 free(new_commit_id);
8824 free(refs_str);
8825 free(yca_id);
8826 free(yca_id_str);
8827 free(yca_brief_str);
8828 if (new_commit)
8829 got_object_commit_close(new_commit);
8830 if (yca_commit)
8831 got_object_commit_close(yca_commit);
8833 return NULL;
8836 static const struct got_error *
8837 process_backup_refs(const char *backup_ref_prefix,
8838 const char *wanted_branch_name,
8839 int delete, struct got_repository *repo)
8841 const struct got_error *err;
8842 struct got_reflist_head refs, backup_refs;
8843 struct got_reflist_entry *re;
8844 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8845 struct got_object_id *old_commit_id = NULL;
8846 char *branch_name = NULL;
8847 struct got_commit_object *old_commit = NULL;
8848 struct got_reflist_object_id_map *refs_idmap = NULL;
8849 int wanted_branch_found = 0;
8851 TAILQ_INIT(&refs);
8852 TAILQ_INIT(&backup_refs);
8854 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8855 if (err)
8856 return err;
8858 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8859 if (err)
8860 goto done;
8862 if (wanted_branch_name) {
8863 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8864 wanted_branch_name += 11;
8867 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8868 got_ref_cmp_by_commit_timestamp_descending, repo);
8869 if (err)
8870 goto done;
8872 TAILQ_FOREACH(re, &backup_refs, entry) {
8873 const char *refname = got_ref_get_name(re->ref);
8874 char *slash;
8876 err = check_cancelled(NULL);
8877 if (err)
8878 break;
8880 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8881 if (err)
8882 break;
8884 err = got_object_open_as_commit(&old_commit, repo,
8885 old_commit_id);
8886 if (err)
8887 break;
8889 if (strncmp(backup_ref_prefix, refname,
8890 backup_ref_prefix_len) == 0)
8891 refname += backup_ref_prefix_len;
8893 while (refname[0] == '/')
8894 refname++;
8896 branch_name = strdup(refname);
8897 if (branch_name == NULL) {
8898 err = got_error_from_errno("strdup");
8899 break;
8901 slash = strrchr(branch_name, '/');
8902 if (slash) {
8903 *slash = '\0';
8904 refname += strlen(branch_name) + 1;
8907 if (wanted_branch_name == NULL ||
8908 strcmp(wanted_branch_name, branch_name) == 0) {
8909 wanted_branch_found = 1;
8910 if (delete) {
8911 err = delete_backup_ref(re->ref,
8912 old_commit_id, repo);
8913 } else {
8914 err = print_backup_ref(branch_name, refname,
8915 old_commit_id, old_commit, refs_idmap,
8916 repo);
8918 if (err)
8919 break;
8922 free(old_commit_id);
8923 old_commit_id = NULL;
8924 free(branch_name);
8925 branch_name = NULL;
8926 got_object_commit_close(old_commit);
8927 old_commit = NULL;
8930 if (wanted_branch_name && !wanted_branch_found) {
8931 err = got_error_fmt(GOT_ERR_NOT_REF,
8932 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8934 done:
8935 if (refs_idmap)
8936 got_reflist_object_id_map_free(refs_idmap);
8937 got_ref_list_free(&refs);
8938 got_ref_list_free(&backup_refs);
8939 free(old_commit_id);
8940 free(branch_name);
8941 if (old_commit)
8942 got_object_commit_close(old_commit);
8943 return err;
8946 static const struct got_error *
8947 abort_progress(void *arg, unsigned char status, const char *path)
8950 * Unversioned files should not clutter progress output when
8951 * an operation is aborted.
8953 if (status == GOT_STATUS_UNVERSIONED)
8954 return NULL;
8956 return update_progress(arg, status, path);
8959 static const struct got_error *
8960 cmd_rebase(int argc, char *argv[])
8962 const struct got_error *error = NULL;
8963 struct got_worktree *worktree = NULL;
8964 struct got_repository *repo = NULL;
8965 struct got_fileindex *fileindex = NULL;
8966 char *cwd = NULL;
8967 struct got_reference *branch = NULL;
8968 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8969 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8970 struct got_object_id *resume_commit_id = NULL;
8971 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8972 struct got_commit_object *commit = NULL;
8973 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8974 int histedit_in_progress = 0, merge_in_progress = 0;
8975 int create_backup = 1, list_backups = 0, delete_backups = 0;
8976 struct got_object_id_queue commits;
8977 struct got_pathlist_head merged_paths;
8978 const struct got_object_id_queue *parent_ids;
8979 struct got_object_qid *qid, *pid;
8980 struct got_update_progress_arg upa;
8982 STAILQ_INIT(&commits);
8983 TAILQ_INIT(&merged_paths);
8984 memset(&upa, 0, sizeof(upa));
8986 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8987 switch (ch) {
8988 case 'a':
8989 abort_rebase = 1;
8990 break;
8991 case 'c':
8992 continue_rebase = 1;
8993 break;
8994 case 'l':
8995 list_backups = 1;
8996 break;
8997 case 'X':
8998 delete_backups = 1;
8999 break;
9000 default:
9001 usage_rebase();
9002 /* NOTREACHED */
9006 argc -= optind;
9007 argv += optind;
9009 #ifndef PROFILE
9010 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9011 "unveil", NULL) == -1)
9012 err(1, "pledge");
9013 #endif
9014 if (list_backups) {
9015 if (abort_rebase)
9016 option_conflict('l', 'a');
9017 if (continue_rebase)
9018 option_conflict('l', 'c');
9019 if (delete_backups)
9020 option_conflict('l', 'X');
9021 if (argc != 0 && argc != 1)
9022 usage_rebase();
9023 } else if (delete_backups) {
9024 if (abort_rebase)
9025 option_conflict('X', 'a');
9026 if (continue_rebase)
9027 option_conflict('X', 'c');
9028 if (list_backups)
9029 option_conflict('l', 'X');
9030 if (argc != 0 && argc != 1)
9031 usage_rebase();
9032 } else {
9033 if (abort_rebase && continue_rebase)
9034 usage_rebase();
9035 else if (abort_rebase || continue_rebase) {
9036 if (argc != 0)
9037 usage_rebase();
9038 } else if (argc != 1)
9039 usage_rebase();
9042 cwd = getcwd(NULL, 0);
9043 if (cwd == NULL) {
9044 error = got_error_from_errno("getcwd");
9045 goto done;
9047 error = got_worktree_open(&worktree, cwd);
9048 if (error) {
9049 if (list_backups || delete_backups) {
9050 if (error->code != GOT_ERR_NOT_WORKTREE)
9051 goto done;
9052 } else {
9053 if (error->code == GOT_ERR_NOT_WORKTREE)
9054 error = wrap_not_worktree_error(error,
9055 "rebase", cwd);
9056 goto done;
9060 error = got_repo_open(&repo,
9061 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9062 if (error != NULL)
9063 goto done;
9065 error = apply_unveil(got_repo_get_path(repo), 0,
9066 worktree ? got_worktree_get_root_path(worktree) : NULL);
9067 if (error)
9068 goto done;
9070 if (list_backups || delete_backups) {
9071 error = process_backup_refs(
9072 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9073 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9074 goto done; /* nothing else to do */
9077 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9078 worktree);
9079 if (error)
9080 goto done;
9081 if (histedit_in_progress) {
9082 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9083 goto done;
9086 error = got_worktree_merge_in_progress(&merge_in_progress,
9087 worktree, repo);
9088 if (error)
9089 goto done;
9090 if (merge_in_progress) {
9091 error = got_error(GOT_ERR_MERGE_BUSY);
9092 goto done;
9095 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9096 if (error)
9097 goto done;
9099 if (abort_rebase) {
9100 if (!rebase_in_progress) {
9101 error = got_error(GOT_ERR_NOT_REBASING);
9102 goto done;
9104 error = got_worktree_rebase_continue(&resume_commit_id,
9105 &new_base_branch, &tmp_branch, &branch, &fileindex,
9106 worktree, repo);
9107 if (error)
9108 goto done;
9109 printf("Switching work tree to %s\n",
9110 got_ref_get_symref_target(new_base_branch));
9111 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9112 new_base_branch, abort_progress, &upa);
9113 if (error)
9114 goto done;
9115 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9116 print_merge_progress_stats(&upa);
9117 goto done; /* nothing else to do */
9120 if (continue_rebase) {
9121 if (!rebase_in_progress) {
9122 error = got_error(GOT_ERR_NOT_REBASING);
9123 goto done;
9125 error = got_worktree_rebase_continue(&resume_commit_id,
9126 &new_base_branch, &tmp_branch, &branch, &fileindex,
9127 worktree, repo);
9128 if (error)
9129 goto done;
9131 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9132 resume_commit_id, repo);
9133 if (error)
9134 goto done;
9136 yca_id = got_object_id_dup(resume_commit_id);
9137 if (yca_id == NULL) {
9138 error = got_error_from_errno("got_object_id_dup");
9139 goto done;
9141 } else {
9142 error = got_ref_open(&branch, repo, argv[0], 0);
9143 if (error != NULL)
9144 goto done;
9147 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9148 if (error)
9149 goto done;
9151 if (!continue_rebase) {
9152 struct got_object_id *base_commit_id;
9154 base_commit_id = got_worktree_get_base_commit_id(worktree);
9155 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9156 base_commit_id, branch_head_commit_id, 1, repo,
9157 check_cancelled, NULL);
9158 if (error)
9159 goto done;
9160 if (yca_id == NULL) {
9161 error = got_error_msg(GOT_ERR_ANCESTRY,
9162 "specified branch shares no common ancestry "
9163 "with work tree's branch");
9164 goto done;
9167 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9168 if (error) {
9169 if (error->code != GOT_ERR_ANCESTRY)
9170 goto done;
9171 error = NULL;
9172 } else {
9173 struct got_pathlist_head paths;
9174 printf("%s is already based on %s\n",
9175 got_ref_get_name(branch),
9176 got_worktree_get_head_ref_name(worktree));
9177 error = switch_head_ref(branch, branch_head_commit_id,
9178 worktree, repo);
9179 if (error)
9180 goto done;
9181 error = got_worktree_set_base_commit_id(worktree, repo,
9182 branch_head_commit_id);
9183 if (error)
9184 goto done;
9185 TAILQ_INIT(&paths);
9186 error = got_pathlist_append(&paths, "", NULL);
9187 if (error)
9188 goto done;
9189 error = got_worktree_checkout_files(worktree,
9190 &paths, repo, update_progress, &upa,
9191 check_cancelled, NULL);
9192 got_pathlist_free(&paths);
9193 if (error)
9194 goto done;
9195 if (upa.did_something) {
9196 char *id_str;
9197 error = got_object_id_str(&id_str,
9198 branch_head_commit_id);
9199 if (error)
9200 goto done;
9201 printf("Updated to %s: %s\n",
9202 got_worktree_get_head_ref_name(worktree),
9203 id_str);
9204 free(id_str);
9205 } else
9206 printf("Already up-to-date\n");
9207 print_update_progress_stats(&upa);
9208 goto done;
9210 error = got_worktree_rebase_prepare(&new_base_branch,
9211 &tmp_branch, &fileindex, worktree, branch, repo);
9212 if (error)
9213 goto done;
9216 commit_id = branch_head_commit_id;
9217 error = got_object_open_as_commit(&commit, repo, commit_id);
9218 if (error)
9219 goto done;
9221 parent_ids = got_object_commit_get_parent_ids(commit);
9222 pid = STAILQ_FIRST(parent_ids);
9223 if (pid == NULL) {
9224 if (!continue_rebase) {
9225 error = got_worktree_rebase_abort(worktree, fileindex,
9226 repo, new_base_branch, abort_progress, &upa);
9227 if (error)
9228 goto done;
9229 printf("Rebase of %s aborted\n",
9230 got_ref_get_name(branch));
9231 print_merge_progress_stats(&upa);
9234 error = got_error(GOT_ERR_EMPTY_REBASE);
9235 goto done;
9237 error = collect_commits(&commits, commit_id, pid->id,
9238 yca_id, got_worktree_get_path_prefix(worktree),
9239 GOT_ERR_REBASE_PATH, repo);
9240 got_object_commit_close(commit);
9241 commit = NULL;
9242 if (error)
9243 goto done;
9245 if (STAILQ_EMPTY(&commits)) {
9246 if (continue_rebase) {
9247 error = rebase_complete(worktree, fileindex,
9248 branch, new_base_branch, tmp_branch, repo,
9249 create_backup);
9250 goto done;
9251 } else {
9252 /* Fast-forward the reference of the branch. */
9253 struct got_object_id *new_head_commit_id;
9254 char *id_str;
9255 error = got_ref_resolve(&new_head_commit_id, repo,
9256 new_base_branch);
9257 if (error)
9258 goto done;
9259 error = got_object_id_str(&id_str, new_head_commit_id);
9260 printf("Forwarding %s to commit %s\n",
9261 got_ref_get_name(branch), id_str);
9262 free(id_str);
9263 error = got_ref_change_ref(branch,
9264 new_head_commit_id);
9265 if (error)
9266 goto done;
9267 /* No backup needed since objects did not change. */
9268 create_backup = 0;
9272 pid = NULL;
9273 STAILQ_FOREACH(qid, &commits, entry) {
9275 commit_id = qid->id;
9276 parent_id = pid ? pid->id : yca_id;
9277 pid = qid;
9279 memset(&upa, 0, sizeof(upa));
9280 error = got_worktree_rebase_merge_files(&merged_paths,
9281 worktree, fileindex, parent_id, commit_id, repo,
9282 update_progress, &upa, check_cancelled, NULL);
9283 if (error)
9284 goto done;
9286 print_merge_progress_stats(&upa);
9287 if (upa.conflicts > 0 || upa.missing > 0 ||
9288 upa.not_deleted > 0 || upa.unversioned > 0) {
9289 if (upa.conflicts > 0) {
9290 error = show_rebase_merge_conflict(qid->id,
9291 repo);
9292 if (error)
9293 goto done;
9295 got_worktree_rebase_pathlist_free(&merged_paths);
9296 break;
9299 error = rebase_commit(&merged_paths, worktree, fileindex,
9300 tmp_branch, commit_id, repo);
9301 got_worktree_rebase_pathlist_free(&merged_paths);
9302 if (error)
9303 goto done;
9306 if (upa.conflicts > 0 || upa.missing > 0 ||
9307 upa.not_deleted > 0 || upa.unversioned > 0) {
9308 error = got_worktree_rebase_postpone(worktree, fileindex);
9309 if (error)
9310 goto done;
9311 if (upa.conflicts > 0 && upa.missing == 0 &&
9312 upa.not_deleted == 0 && upa.unversioned == 0) {
9313 error = got_error_msg(GOT_ERR_CONFLICTS,
9314 "conflicts must be resolved before rebasing "
9315 "can continue");
9316 } else if (upa.conflicts > 0) {
9317 error = got_error_msg(GOT_ERR_CONFLICTS,
9318 "conflicts must be resolved before rebasing "
9319 "can continue; changes destined for some "
9320 "files were not yet merged and should be "
9321 "merged manually if required before the "
9322 "rebase operation is continued");
9323 } else {
9324 error = got_error_msg(GOT_ERR_CONFLICTS,
9325 "changes destined for some files were not "
9326 "yet merged and should be merged manually "
9327 "if required before the rebase operation "
9328 "is continued");
9330 } else
9331 error = rebase_complete(worktree, fileindex, branch,
9332 new_base_branch, tmp_branch, repo, create_backup);
9333 done:
9334 got_object_id_queue_free(&commits);
9335 free(branch_head_commit_id);
9336 free(resume_commit_id);
9337 free(yca_id);
9338 if (commit)
9339 got_object_commit_close(commit);
9340 if (branch)
9341 got_ref_close(branch);
9342 if (new_base_branch)
9343 got_ref_close(new_base_branch);
9344 if (tmp_branch)
9345 got_ref_close(tmp_branch);
9346 if (worktree)
9347 got_worktree_close(worktree);
9348 if (repo) {
9349 const struct got_error *close_err = got_repo_close(repo);
9350 if (error == NULL)
9351 error = close_err;
9353 return error;
9356 __dead static void
9357 usage_histedit(void)
9359 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9360 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9361 getprogname());
9362 exit(1);
9365 #define GOT_HISTEDIT_PICK 'p'
9366 #define GOT_HISTEDIT_EDIT 'e'
9367 #define GOT_HISTEDIT_FOLD 'f'
9368 #define GOT_HISTEDIT_DROP 'd'
9369 #define GOT_HISTEDIT_MESG 'm'
9371 static struct got_histedit_cmd {
9372 unsigned char code;
9373 const char *name;
9374 const char *desc;
9375 } got_histedit_cmds[] = {
9376 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9377 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9378 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9379 "be used" },
9380 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9381 { GOT_HISTEDIT_MESG, "mesg",
9382 "single-line log message for commit above (open editor if empty)" },
9385 struct got_histedit_list_entry {
9386 TAILQ_ENTRY(got_histedit_list_entry) entry;
9387 struct got_object_id *commit_id;
9388 const struct got_histedit_cmd *cmd;
9389 char *logmsg;
9391 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9393 static const struct got_error *
9394 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9395 FILE *f, struct got_repository *repo)
9397 const struct got_error *err = NULL;
9398 char *logmsg = NULL, *id_str = NULL;
9399 struct got_commit_object *commit = NULL;
9400 int n;
9402 err = got_object_open_as_commit(&commit, repo, commit_id);
9403 if (err)
9404 goto done;
9406 err = get_short_logmsg(&logmsg, 34, commit);
9407 if (err)
9408 goto done;
9410 err = got_object_id_str(&id_str, commit_id);
9411 if (err)
9412 goto done;
9414 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9415 if (n < 0)
9416 err = got_ferror(f, GOT_ERR_IO);
9417 done:
9418 if (commit)
9419 got_object_commit_close(commit);
9420 free(id_str);
9421 free(logmsg);
9422 return err;
9425 static const struct got_error *
9426 histedit_write_commit_list(struct got_object_id_queue *commits,
9427 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9428 struct got_repository *repo)
9430 const struct got_error *err = NULL;
9431 struct got_object_qid *qid;
9432 const char *histedit_cmd = NULL;
9434 if (STAILQ_EMPTY(commits))
9435 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9437 STAILQ_FOREACH(qid, commits, entry) {
9438 histedit_cmd = got_histedit_cmds[0].name;
9439 if (edit_only)
9440 histedit_cmd = "edit";
9441 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9442 histedit_cmd = "fold";
9443 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9444 if (err)
9445 break;
9446 if (edit_logmsg_only) {
9447 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9448 if (n < 0) {
9449 err = got_ferror(f, GOT_ERR_IO);
9450 break;
9455 return err;
9458 static const struct got_error *
9459 write_cmd_list(FILE *f, const char *branch_name,
9460 struct got_object_id_queue *commits)
9462 const struct got_error *err = NULL;
9463 size_t i;
9464 int n;
9465 char *id_str;
9466 struct got_object_qid *qid;
9468 qid = STAILQ_FIRST(commits);
9469 err = got_object_id_str(&id_str, qid->id);
9470 if (err)
9471 return err;
9473 n = fprintf(f,
9474 "# Editing the history of branch '%s' starting at\n"
9475 "# commit %s\n"
9476 "# Commits will be processed in order from top to "
9477 "bottom of this file.\n", branch_name, id_str);
9478 if (n < 0) {
9479 err = got_ferror(f, GOT_ERR_IO);
9480 goto done;
9483 n = fprintf(f, "# Available histedit commands:\n");
9484 if (n < 0) {
9485 err = got_ferror(f, GOT_ERR_IO);
9486 goto done;
9489 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9490 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9491 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9492 cmd->desc);
9493 if (n < 0) {
9494 err = got_ferror(f, GOT_ERR_IO);
9495 break;
9498 done:
9499 free(id_str);
9500 return err;
9503 static const struct got_error *
9504 histedit_syntax_error(int lineno)
9506 static char msg[42];
9507 int ret;
9509 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9510 lineno);
9511 if (ret == -1 || ret >= sizeof(msg))
9512 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9514 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9517 static const struct got_error *
9518 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9519 char *logmsg, struct got_repository *repo)
9521 const struct got_error *err;
9522 struct got_commit_object *folded_commit = NULL;
9523 char *id_str, *folded_logmsg = NULL;
9525 err = got_object_id_str(&id_str, hle->commit_id);
9526 if (err)
9527 return err;
9529 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9530 if (err)
9531 goto done;
9533 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9534 if (err)
9535 goto done;
9536 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9537 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9538 folded_logmsg) == -1) {
9539 err = got_error_from_errno("asprintf");
9541 done:
9542 if (folded_commit)
9543 got_object_commit_close(folded_commit);
9544 free(id_str);
9545 free(folded_logmsg);
9546 return err;
9549 static struct got_histedit_list_entry *
9550 get_folded_commits(struct got_histedit_list_entry *hle)
9552 struct got_histedit_list_entry *prev, *folded = NULL;
9554 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9555 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9556 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9557 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9558 folded = prev;
9559 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9562 return folded;
9565 static const struct got_error *
9566 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9567 struct got_repository *repo)
9569 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9570 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9571 const struct got_error *err = NULL;
9572 struct got_commit_object *commit = NULL;
9573 int logmsg_len;
9574 int fd;
9575 struct got_histedit_list_entry *folded = NULL;
9577 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9578 if (err)
9579 return err;
9581 folded = get_folded_commits(hle);
9582 if (folded) {
9583 while (folded != hle) {
9584 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9585 folded = TAILQ_NEXT(folded, entry);
9586 continue;
9588 err = append_folded_commit_msg(&new_msg, folded,
9589 logmsg, repo);
9590 if (err)
9591 goto done;
9592 free(logmsg);
9593 logmsg = new_msg;
9594 folded = TAILQ_NEXT(folded, entry);
9598 err = got_object_id_str(&id_str, hle->commit_id);
9599 if (err)
9600 goto done;
9601 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9602 if (err)
9603 goto done;
9604 logmsg_len = asprintf(&new_msg,
9605 "%s\n# original log message of commit %s: %s",
9606 logmsg ? logmsg : "", id_str, orig_logmsg);
9607 if (logmsg_len == -1) {
9608 err = got_error_from_errno("asprintf");
9609 goto done;
9611 free(logmsg);
9612 logmsg = new_msg;
9614 err = got_object_id_str(&id_str, hle->commit_id);
9615 if (err)
9616 goto done;
9618 err = got_opentemp_named_fd(&logmsg_path, &fd,
9619 GOT_TMPDIR_STR "/got-logmsg");
9620 if (err)
9621 goto done;
9623 write(fd, logmsg, logmsg_len);
9624 close(fd);
9626 err = get_editor(&editor);
9627 if (err)
9628 goto done;
9630 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9631 logmsg_len, 0);
9632 if (err) {
9633 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9634 goto done;
9635 err = NULL;
9636 hle->logmsg = strdup(new_msg);
9637 if (hle->logmsg == NULL)
9638 err = got_error_from_errno("strdup");
9640 done:
9641 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9642 err = got_error_from_errno2("unlink", logmsg_path);
9643 free(logmsg_path);
9644 free(logmsg);
9645 free(orig_logmsg);
9646 free(editor);
9647 if (commit)
9648 got_object_commit_close(commit);
9649 return err;
9652 static const struct got_error *
9653 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9654 FILE *f, struct got_repository *repo)
9656 const struct got_error *err = NULL;
9657 char *line = NULL, *p, *end;
9658 size_t i, size;
9659 ssize_t len;
9660 int lineno = 0;
9661 const struct got_histedit_cmd *cmd;
9662 struct got_object_id *commit_id = NULL;
9663 struct got_histedit_list_entry *hle = NULL;
9665 for (;;) {
9666 len = getline(&line, &size, f);
9667 if (len == -1) {
9668 const struct got_error *getline_err;
9669 if (feof(f))
9670 break;
9671 getline_err = got_error_from_errno("getline");
9672 err = got_ferror(f, getline_err->code);
9673 break;
9675 lineno++;
9676 p = line;
9677 while (isspace((unsigned char)p[0]))
9678 p++;
9679 if (p[0] == '#' || p[0] == '\0') {
9680 free(line);
9681 line = NULL;
9682 continue;
9684 cmd = NULL;
9685 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9686 cmd = &got_histedit_cmds[i];
9687 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9688 isspace((unsigned char)p[strlen(cmd->name)])) {
9689 p += strlen(cmd->name);
9690 break;
9692 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9693 p++;
9694 break;
9697 if (i == nitems(got_histedit_cmds)) {
9698 err = histedit_syntax_error(lineno);
9699 break;
9701 while (isspace((unsigned char)p[0]))
9702 p++;
9703 if (cmd->code == GOT_HISTEDIT_MESG) {
9704 if (hle == NULL || hle->logmsg != NULL) {
9705 err = got_error(GOT_ERR_HISTEDIT_CMD);
9706 break;
9708 if (p[0] == '\0') {
9709 err = histedit_edit_logmsg(hle, repo);
9710 if (err)
9711 break;
9712 } else {
9713 hle->logmsg = strdup(p);
9714 if (hle->logmsg == NULL) {
9715 err = got_error_from_errno("strdup");
9716 break;
9719 free(line);
9720 line = NULL;
9721 continue;
9722 } else {
9723 end = p;
9724 while (end[0] && !isspace((unsigned char)end[0]))
9725 end++;
9726 *end = '\0';
9728 err = got_object_resolve_id_str(&commit_id, repo, p);
9729 if (err) {
9730 /* override error code */
9731 err = histedit_syntax_error(lineno);
9732 break;
9735 hle = malloc(sizeof(*hle));
9736 if (hle == NULL) {
9737 err = got_error_from_errno("malloc");
9738 break;
9740 hle->cmd = cmd;
9741 hle->commit_id = commit_id;
9742 hle->logmsg = NULL;
9743 commit_id = NULL;
9744 free(line);
9745 line = NULL;
9746 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9749 free(line);
9750 free(commit_id);
9751 return err;
9754 static const struct got_error *
9755 histedit_check_script(struct got_histedit_list *histedit_cmds,
9756 struct got_object_id_queue *commits, struct got_repository *repo)
9758 const struct got_error *err = NULL;
9759 struct got_object_qid *qid;
9760 struct got_histedit_list_entry *hle;
9761 static char msg[92];
9762 char *id_str;
9764 if (TAILQ_EMPTY(histedit_cmds))
9765 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9766 "histedit script contains no commands");
9767 if (STAILQ_EMPTY(commits))
9768 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9770 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9771 struct got_histedit_list_entry *hle2;
9772 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9773 if (hle == hle2)
9774 continue;
9775 if (got_object_id_cmp(hle->commit_id,
9776 hle2->commit_id) != 0)
9777 continue;
9778 err = got_object_id_str(&id_str, hle->commit_id);
9779 if (err)
9780 return err;
9781 snprintf(msg, sizeof(msg), "commit %s is listed "
9782 "more than once in histedit script", id_str);
9783 free(id_str);
9784 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9788 STAILQ_FOREACH(qid, commits, entry) {
9789 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9790 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9791 break;
9793 if (hle == NULL) {
9794 err = got_object_id_str(&id_str, qid->id);
9795 if (err)
9796 return err;
9797 snprintf(msg, sizeof(msg),
9798 "commit %s missing from histedit script", id_str);
9799 free(id_str);
9800 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9804 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9805 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9806 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9807 "last commit in histedit script cannot be folded");
9809 return NULL;
9812 static const struct got_error *
9813 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9814 const char *path, struct got_object_id_queue *commits,
9815 struct got_repository *repo)
9817 const struct got_error *err = NULL;
9818 char *editor;
9819 FILE *f = NULL;
9821 err = get_editor(&editor);
9822 if (err)
9823 return err;
9825 if (spawn_editor(editor, path) == -1) {
9826 err = got_error_from_errno("failed spawning editor");
9827 goto done;
9830 f = fopen(path, "re");
9831 if (f == NULL) {
9832 err = got_error_from_errno("fopen");
9833 goto done;
9835 err = histedit_parse_list(histedit_cmds, f, repo);
9836 if (err)
9837 goto done;
9839 err = histedit_check_script(histedit_cmds, commits, repo);
9840 done:
9841 if (f && fclose(f) == EOF && err == NULL)
9842 err = got_error_from_errno("fclose");
9843 free(editor);
9844 return err;
9847 static const struct got_error *
9848 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9849 struct got_object_id_queue *, const char *, const char *,
9850 struct got_repository *);
9852 static const struct got_error *
9853 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9854 struct got_object_id_queue *commits, const char *branch_name,
9855 int edit_logmsg_only, int fold_only, int edit_only,
9856 struct got_repository *repo)
9858 const struct got_error *err;
9859 FILE *f = NULL;
9860 char *path = NULL;
9862 err = got_opentemp_named(&path, &f, "got-histedit");
9863 if (err)
9864 return err;
9866 err = write_cmd_list(f, branch_name, commits);
9867 if (err)
9868 goto done;
9870 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9871 fold_only, edit_only, repo);
9872 if (err)
9873 goto done;
9875 if (edit_logmsg_only || fold_only || edit_only) {
9876 rewind(f);
9877 err = histedit_parse_list(histedit_cmds, f, repo);
9878 } else {
9879 if (fclose(f) == EOF) {
9880 err = got_error_from_errno("fclose");
9881 goto done;
9883 f = NULL;
9884 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9885 if (err) {
9886 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9887 err->code != GOT_ERR_HISTEDIT_CMD)
9888 goto done;
9889 err = histedit_edit_list_retry(histedit_cmds, err,
9890 commits, path, branch_name, repo);
9893 done:
9894 if (f && fclose(f) == EOF && err == NULL)
9895 err = got_error_from_errno("fclose");
9896 if (path && unlink(path) != 0 && err == NULL)
9897 err = got_error_from_errno2("unlink", path);
9898 free(path);
9899 return err;
9902 static const struct got_error *
9903 histedit_save_list(struct got_histedit_list *histedit_cmds,
9904 struct got_worktree *worktree, struct got_repository *repo)
9906 const struct got_error *err = NULL;
9907 char *path = NULL;
9908 FILE *f = NULL;
9909 struct got_histedit_list_entry *hle;
9910 struct got_commit_object *commit = NULL;
9912 err = got_worktree_get_histedit_script_path(&path, worktree);
9913 if (err)
9914 return err;
9916 f = fopen(path, "we");
9917 if (f == NULL) {
9918 err = got_error_from_errno2("fopen", path);
9919 goto done;
9921 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9922 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9923 repo);
9924 if (err)
9925 break;
9927 if (hle->logmsg) {
9928 int n = fprintf(f, "%c %s\n",
9929 GOT_HISTEDIT_MESG, hle->logmsg);
9930 if (n < 0) {
9931 err = got_ferror(f, GOT_ERR_IO);
9932 break;
9936 done:
9937 if (f && fclose(f) == EOF && err == NULL)
9938 err = got_error_from_errno("fclose");
9939 free(path);
9940 if (commit)
9941 got_object_commit_close(commit);
9942 return err;
9945 void
9946 histedit_free_list(struct got_histedit_list *histedit_cmds)
9948 struct got_histedit_list_entry *hle;
9950 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9951 TAILQ_REMOVE(histedit_cmds, hle, entry);
9952 free(hle);
9956 static const struct got_error *
9957 histedit_load_list(struct got_histedit_list *histedit_cmds,
9958 const char *path, struct got_repository *repo)
9960 const struct got_error *err = NULL;
9961 FILE *f = NULL;
9963 f = fopen(path, "re");
9964 if (f == NULL) {
9965 err = got_error_from_errno2("fopen", path);
9966 goto done;
9969 err = histedit_parse_list(histedit_cmds, f, repo);
9970 done:
9971 if (f && fclose(f) == EOF && err == NULL)
9972 err = got_error_from_errno("fclose");
9973 return err;
9976 static const struct got_error *
9977 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9978 const struct got_error *edit_err, struct got_object_id_queue *commits,
9979 const char *path, const char *branch_name, struct got_repository *repo)
9981 const struct got_error *err = NULL, *prev_err = edit_err;
9982 int resp = ' ';
9984 while (resp != 'c' && resp != 'r' && resp != 'a') {
9985 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9986 "or (a)bort: ", getprogname(), prev_err->msg);
9987 resp = getchar();
9988 if (resp == '\n')
9989 resp = getchar();
9990 if (resp == 'c') {
9991 histedit_free_list(histedit_cmds);
9992 err = histedit_run_editor(histedit_cmds, path, commits,
9993 repo);
9994 if (err) {
9995 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9996 err->code != GOT_ERR_HISTEDIT_CMD)
9997 break;
9998 prev_err = err;
9999 resp = ' ';
10000 continue;
10002 break;
10003 } else if (resp == 'r') {
10004 histedit_free_list(histedit_cmds);
10005 err = histedit_edit_script(histedit_cmds,
10006 commits, branch_name, 0, 0, 0, repo);
10007 if (err) {
10008 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10009 err->code != GOT_ERR_HISTEDIT_CMD)
10010 break;
10011 prev_err = err;
10012 resp = ' ';
10013 continue;
10015 break;
10016 } else if (resp == 'a') {
10017 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10018 break;
10019 } else
10020 printf("invalid response '%c'\n", resp);
10023 return err;
10026 static const struct got_error *
10027 histedit_complete(struct got_worktree *worktree,
10028 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10029 struct got_reference *branch, struct got_repository *repo)
10031 printf("Switching work tree to %s\n",
10032 got_ref_get_symref_target(branch));
10033 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10034 branch, repo);
10037 static const struct got_error *
10038 show_histedit_progress(struct got_commit_object *commit,
10039 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10041 const struct got_error *err;
10042 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10044 err = got_object_id_str(&old_id_str, hle->commit_id);
10045 if (err)
10046 goto done;
10048 if (new_id) {
10049 err = got_object_id_str(&new_id_str, new_id);
10050 if (err)
10051 goto done;
10054 old_id_str[12] = '\0';
10055 if (new_id_str)
10056 new_id_str[12] = '\0';
10058 if (hle->logmsg) {
10059 logmsg = strdup(hle->logmsg);
10060 if (logmsg == NULL) {
10061 err = got_error_from_errno("strdup");
10062 goto done;
10064 trim_logmsg(logmsg, 42);
10065 } else {
10066 err = get_short_logmsg(&logmsg, 42, commit);
10067 if (err)
10068 goto done;
10071 switch (hle->cmd->code) {
10072 case GOT_HISTEDIT_PICK:
10073 case GOT_HISTEDIT_EDIT:
10074 printf("%s -> %s: %s\n", old_id_str,
10075 new_id_str ? new_id_str : "no-op change", logmsg);
10076 break;
10077 case GOT_HISTEDIT_DROP:
10078 case GOT_HISTEDIT_FOLD:
10079 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10080 logmsg);
10081 break;
10082 default:
10083 break;
10085 done:
10086 free(old_id_str);
10087 free(new_id_str);
10088 return err;
10091 static const struct got_error *
10092 histedit_commit(struct got_pathlist_head *merged_paths,
10093 struct got_worktree *worktree, struct got_fileindex *fileindex,
10094 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10095 struct got_repository *repo)
10097 const struct got_error *err;
10098 struct got_commit_object *commit;
10099 struct got_object_id *new_commit_id;
10101 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10102 && hle->logmsg == NULL) {
10103 err = histedit_edit_logmsg(hle, repo);
10104 if (err)
10105 return err;
10108 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10109 if (err)
10110 return err;
10112 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10113 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10114 hle->logmsg, repo);
10115 if (err) {
10116 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10117 goto done;
10118 err = show_histedit_progress(commit, hle, NULL);
10119 } else {
10120 err = show_histedit_progress(commit, hle, new_commit_id);
10121 free(new_commit_id);
10123 done:
10124 got_object_commit_close(commit);
10125 return err;
10128 static const struct got_error *
10129 histedit_skip_commit(struct got_histedit_list_entry *hle,
10130 struct got_worktree *worktree, struct got_repository *repo)
10132 const struct got_error *error;
10133 struct got_commit_object *commit;
10135 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10136 repo);
10137 if (error)
10138 return error;
10140 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10141 if (error)
10142 return error;
10144 error = show_histedit_progress(commit, hle, NULL);
10145 got_object_commit_close(commit);
10146 return error;
10149 static const struct got_error *
10150 check_local_changes(void *arg, unsigned char status,
10151 unsigned char staged_status, const char *path,
10152 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10153 struct got_object_id *commit_id, int dirfd, const char *de_name)
10155 int *have_local_changes = arg;
10157 switch (status) {
10158 case GOT_STATUS_ADD:
10159 case GOT_STATUS_DELETE:
10160 case GOT_STATUS_MODIFY:
10161 case GOT_STATUS_CONFLICT:
10162 *have_local_changes = 1;
10163 return got_error(GOT_ERR_CANCELLED);
10164 default:
10165 break;
10168 switch (staged_status) {
10169 case GOT_STATUS_ADD:
10170 case GOT_STATUS_DELETE:
10171 case GOT_STATUS_MODIFY:
10172 *have_local_changes = 1;
10173 return got_error(GOT_ERR_CANCELLED);
10174 default:
10175 break;
10178 return NULL;
10181 static const struct got_error *
10182 cmd_histedit(int argc, char *argv[])
10184 const struct got_error *error = NULL;
10185 struct got_worktree *worktree = NULL;
10186 struct got_fileindex *fileindex = NULL;
10187 struct got_repository *repo = NULL;
10188 char *cwd = NULL;
10189 struct got_reference *branch = NULL;
10190 struct got_reference *tmp_branch = NULL;
10191 struct got_object_id *resume_commit_id = NULL;
10192 struct got_object_id *base_commit_id = NULL;
10193 struct got_object_id *head_commit_id = NULL;
10194 struct got_commit_object *commit = NULL;
10195 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10196 struct got_update_progress_arg upa;
10197 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10198 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10199 int list_backups = 0, delete_backups = 0;
10200 const char *edit_script_path = NULL;
10201 struct got_object_id_queue commits;
10202 struct got_pathlist_head merged_paths;
10203 const struct got_object_id_queue *parent_ids;
10204 struct got_object_qid *pid;
10205 struct got_histedit_list histedit_cmds;
10206 struct got_histedit_list_entry *hle;
10208 STAILQ_INIT(&commits);
10209 TAILQ_INIT(&histedit_cmds);
10210 TAILQ_INIT(&merged_paths);
10211 memset(&upa, 0, sizeof(upa));
10213 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10214 switch (ch) {
10215 case 'a':
10216 abort_edit = 1;
10217 break;
10218 case 'c':
10219 continue_edit = 1;
10220 break;
10221 case 'e':
10222 edit_only = 1;
10223 break;
10224 case 'f':
10225 fold_only = 1;
10226 break;
10227 case 'F':
10228 edit_script_path = optarg;
10229 break;
10230 case 'm':
10231 edit_logmsg_only = 1;
10232 break;
10233 case 'l':
10234 list_backups = 1;
10235 break;
10236 case 'X':
10237 delete_backups = 1;
10238 break;
10239 default:
10240 usage_histedit();
10241 /* NOTREACHED */
10245 argc -= optind;
10246 argv += optind;
10248 #ifndef PROFILE
10249 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10250 "unveil", NULL) == -1)
10251 err(1, "pledge");
10252 #endif
10253 if (abort_edit && continue_edit)
10254 option_conflict('a', 'c');
10255 if (edit_script_path && edit_logmsg_only)
10256 option_conflict('F', 'm');
10257 if (abort_edit && edit_logmsg_only)
10258 option_conflict('a', 'm');
10259 if (continue_edit && edit_logmsg_only)
10260 option_conflict('c', 'm');
10261 if (abort_edit && fold_only)
10262 option_conflict('a', 'f');
10263 if (continue_edit && fold_only)
10264 option_conflict('c', 'f');
10265 if (fold_only && edit_logmsg_only)
10266 option_conflict('f', 'm');
10267 if (edit_script_path && fold_only)
10268 option_conflict('F', 'f');
10269 if (abort_edit && edit_only)
10270 option_conflict('a', 'e');
10271 if (continue_edit && edit_only)
10272 option_conflict('c', 'e');
10273 if (edit_only && edit_logmsg_only)
10274 option_conflict('e', 'm');
10275 if (edit_script_path && edit_only)
10276 option_conflict('F', 'e');
10277 if (list_backups) {
10278 if (abort_edit)
10279 option_conflict('l', 'a');
10280 if (continue_edit)
10281 option_conflict('l', 'c');
10282 if (edit_script_path)
10283 option_conflict('l', 'F');
10284 if (edit_logmsg_only)
10285 option_conflict('l', 'm');
10286 if (fold_only)
10287 option_conflict('l', 'f');
10288 if (edit_only)
10289 option_conflict('l', 'e');
10290 if (delete_backups)
10291 option_conflict('l', 'X');
10292 if (argc != 0 && argc != 1)
10293 usage_histedit();
10294 } else if (delete_backups) {
10295 if (abort_edit)
10296 option_conflict('X', 'a');
10297 if (continue_edit)
10298 option_conflict('X', 'c');
10299 if (edit_script_path)
10300 option_conflict('X', 'F');
10301 if (edit_logmsg_only)
10302 option_conflict('X', 'm');
10303 if (fold_only)
10304 option_conflict('X', 'f');
10305 if (edit_only)
10306 option_conflict('X', 'e');
10307 if (list_backups)
10308 option_conflict('X', 'l');
10309 if (argc != 0 && argc != 1)
10310 usage_histedit();
10311 } else if (argc != 0)
10312 usage_histedit();
10315 * This command cannot apply unveil(2) in all cases because the
10316 * user may choose to run an editor to edit the histedit script
10317 * and to edit individual commit log messages.
10318 * unveil(2) traverses exec(2); if an editor is used we have to
10319 * apply unveil after edit script and log messages have been written.
10320 * XXX TODO: Make use of unveil(2) where possible.
10323 cwd = getcwd(NULL, 0);
10324 if (cwd == NULL) {
10325 error = got_error_from_errno("getcwd");
10326 goto done;
10328 error = got_worktree_open(&worktree, cwd);
10329 if (error) {
10330 if (list_backups || delete_backups) {
10331 if (error->code != GOT_ERR_NOT_WORKTREE)
10332 goto done;
10333 } else {
10334 if (error->code == GOT_ERR_NOT_WORKTREE)
10335 error = wrap_not_worktree_error(error,
10336 "histedit", cwd);
10337 goto done;
10341 if (list_backups || delete_backups) {
10342 error = got_repo_open(&repo,
10343 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10344 NULL);
10345 if (error != NULL)
10346 goto done;
10347 error = apply_unveil(got_repo_get_path(repo), 0,
10348 worktree ? got_worktree_get_root_path(worktree) : NULL);
10349 if (error)
10350 goto done;
10351 error = process_backup_refs(
10352 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10353 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10354 goto done; /* nothing else to do */
10357 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10358 NULL);
10359 if (error != NULL)
10360 goto done;
10362 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10363 if (error)
10364 goto done;
10365 if (rebase_in_progress) {
10366 error = got_error(GOT_ERR_REBASING);
10367 goto done;
10370 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10371 repo);
10372 if (error)
10373 goto done;
10374 if (merge_in_progress) {
10375 error = got_error(GOT_ERR_MERGE_BUSY);
10376 goto done;
10379 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10380 if (error)
10381 goto done;
10383 if (edit_in_progress && edit_logmsg_only) {
10384 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10385 "histedit operation is in progress in this "
10386 "work tree and must be continued or aborted "
10387 "before the -m option can be used");
10388 goto done;
10390 if (edit_in_progress && fold_only) {
10391 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10392 "histedit operation is in progress in this "
10393 "work tree and must be continued or aborted "
10394 "before the -f option can be used");
10395 goto done;
10397 if (edit_in_progress && edit_only) {
10398 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10399 "histedit operation is in progress in this "
10400 "work tree and must be continued or aborted "
10401 "before the -e option can be used");
10402 goto done;
10405 if (edit_in_progress && abort_edit) {
10406 error = got_worktree_histedit_continue(&resume_commit_id,
10407 &tmp_branch, &branch, &base_commit_id, &fileindex,
10408 worktree, repo);
10409 if (error)
10410 goto done;
10411 printf("Switching work tree to %s\n",
10412 got_ref_get_symref_target(branch));
10413 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10414 branch, base_commit_id, abort_progress, &upa);
10415 if (error)
10416 goto done;
10417 printf("Histedit of %s aborted\n",
10418 got_ref_get_symref_target(branch));
10419 print_merge_progress_stats(&upa);
10420 goto done; /* nothing else to do */
10421 } else if (abort_edit) {
10422 error = got_error(GOT_ERR_NOT_HISTEDIT);
10423 goto done;
10426 if (continue_edit) {
10427 char *path;
10429 if (!edit_in_progress) {
10430 error = got_error(GOT_ERR_NOT_HISTEDIT);
10431 goto done;
10434 error = got_worktree_get_histedit_script_path(&path, worktree);
10435 if (error)
10436 goto done;
10438 error = histedit_load_list(&histedit_cmds, path, repo);
10439 free(path);
10440 if (error)
10441 goto done;
10443 error = got_worktree_histedit_continue(&resume_commit_id,
10444 &tmp_branch, &branch, &base_commit_id, &fileindex,
10445 worktree, repo);
10446 if (error)
10447 goto done;
10449 error = got_ref_resolve(&head_commit_id, repo, branch);
10450 if (error)
10451 goto done;
10453 error = got_object_open_as_commit(&commit, repo,
10454 head_commit_id);
10455 if (error)
10456 goto done;
10457 parent_ids = got_object_commit_get_parent_ids(commit);
10458 pid = STAILQ_FIRST(parent_ids);
10459 if (pid == NULL) {
10460 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10461 goto done;
10463 error = collect_commits(&commits, head_commit_id, pid->id,
10464 base_commit_id, got_worktree_get_path_prefix(worktree),
10465 GOT_ERR_HISTEDIT_PATH, repo);
10466 got_object_commit_close(commit);
10467 commit = NULL;
10468 if (error)
10469 goto done;
10470 } else {
10471 if (edit_in_progress) {
10472 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10473 goto done;
10476 error = got_ref_open(&branch, repo,
10477 got_worktree_get_head_ref_name(worktree), 0);
10478 if (error != NULL)
10479 goto done;
10481 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10482 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10483 "will not edit commit history of a branch outside "
10484 "the \"refs/heads/\" reference namespace");
10485 goto done;
10488 error = got_ref_resolve(&head_commit_id, repo, branch);
10489 got_ref_close(branch);
10490 branch = NULL;
10491 if (error)
10492 goto done;
10494 error = got_object_open_as_commit(&commit, repo,
10495 head_commit_id);
10496 if (error)
10497 goto done;
10498 parent_ids = got_object_commit_get_parent_ids(commit);
10499 pid = STAILQ_FIRST(parent_ids);
10500 if (pid == NULL) {
10501 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10502 goto done;
10504 error = collect_commits(&commits, head_commit_id, pid->id,
10505 got_worktree_get_base_commit_id(worktree),
10506 got_worktree_get_path_prefix(worktree),
10507 GOT_ERR_HISTEDIT_PATH, repo);
10508 got_object_commit_close(commit);
10509 commit = NULL;
10510 if (error)
10511 goto done;
10513 if (STAILQ_EMPTY(&commits)) {
10514 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10515 goto done;
10518 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10519 &base_commit_id, &fileindex, worktree, repo);
10520 if (error)
10521 goto done;
10523 if (edit_script_path) {
10524 error = histedit_load_list(&histedit_cmds,
10525 edit_script_path, repo);
10526 if (error) {
10527 got_worktree_histedit_abort(worktree, fileindex,
10528 repo, branch, base_commit_id,
10529 abort_progress, &upa);
10530 print_merge_progress_stats(&upa);
10531 goto done;
10533 } else {
10534 const char *branch_name;
10535 branch_name = got_ref_get_symref_target(branch);
10536 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10537 branch_name += 11;
10538 error = histedit_edit_script(&histedit_cmds, &commits,
10539 branch_name, edit_logmsg_only, fold_only,
10540 edit_only, repo);
10541 if (error) {
10542 got_worktree_histedit_abort(worktree, fileindex,
10543 repo, branch, base_commit_id,
10544 abort_progress, &upa);
10545 print_merge_progress_stats(&upa);
10546 goto done;
10551 error = histedit_save_list(&histedit_cmds, worktree,
10552 repo);
10553 if (error) {
10554 got_worktree_histedit_abort(worktree, fileindex,
10555 repo, branch, base_commit_id,
10556 abort_progress, &upa);
10557 print_merge_progress_stats(&upa);
10558 goto done;
10563 error = histedit_check_script(&histedit_cmds, &commits, repo);
10564 if (error)
10565 goto done;
10567 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10568 if (resume_commit_id) {
10569 if (got_object_id_cmp(hle->commit_id,
10570 resume_commit_id) != 0)
10571 continue;
10573 resume_commit_id = NULL;
10574 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10575 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10576 error = histedit_skip_commit(hle, worktree,
10577 repo);
10578 if (error)
10579 goto done;
10580 } else {
10581 struct got_pathlist_head paths;
10582 int have_changes = 0;
10584 TAILQ_INIT(&paths);
10585 error = got_pathlist_append(&paths, "", NULL);
10586 if (error)
10587 goto done;
10588 error = got_worktree_status(worktree, &paths,
10589 repo, 0, check_local_changes, &have_changes,
10590 check_cancelled, NULL);
10591 got_pathlist_free(&paths);
10592 if (error) {
10593 if (error->code != GOT_ERR_CANCELLED)
10594 goto done;
10595 if (sigint_received || sigpipe_received)
10596 goto done;
10598 if (have_changes) {
10599 error = histedit_commit(NULL, worktree,
10600 fileindex, tmp_branch, hle, repo);
10601 if (error)
10602 goto done;
10603 } else {
10604 error = got_object_open_as_commit(
10605 &commit, repo, hle->commit_id);
10606 if (error)
10607 goto done;
10608 error = show_histedit_progress(commit,
10609 hle, NULL);
10610 got_object_commit_close(commit);
10611 commit = NULL;
10612 if (error)
10613 goto done;
10616 continue;
10619 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10620 error = histedit_skip_commit(hle, worktree, repo);
10621 if (error)
10622 goto done;
10623 continue;
10626 error = got_object_open_as_commit(&commit, repo,
10627 hle->commit_id);
10628 if (error)
10629 goto done;
10630 parent_ids = got_object_commit_get_parent_ids(commit);
10631 pid = STAILQ_FIRST(parent_ids);
10633 error = got_worktree_histedit_merge_files(&merged_paths,
10634 worktree, fileindex, pid->id, hle->commit_id, repo,
10635 update_progress, &upa, check_cancelled, NULL);
10636 if (error)
10637 goto done;
10638 got_object_commit_close(commit);
10639 commit = NULL;
10641 print_merge_progress_stats(&upa);
10642 if (upa.conflicts > 0 || upa.missing > 0 ||
10643 upa.not_deleted > 0 || upa.unversioned > 0) {
10644 if (upa.conflicts > 0) {
10645 error = show_rebase_merge_conflict(
10646 hle->commit_id, repo);
10647 if (error)
10648 goto done;
10650 got_worktree_rebase_pathlist_free(&merged_paths);
10651 break;
10654 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10655 char *id_str;
10656 error = got_object_id_str(&id_str, hle->commit_id);
10657 if (error)
10658 goto done;
10659 printf("Stopping histedit for amending commit %s\n",
10660 id_str);
10661 free(id_str);
10662 got_worktree_rebase_pathlist_free(&merged_paths);
10663 error = got_worktree_histedit_postpone(worktree,
10664 fileindex);
10665 goto done;
10668 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10669 error = histedit_skip_commit(hle, worktree, repo);
10670 if (error)
10671 goto done;
10672 continue;
10675 error = histedit_commit(&merged_paths, worktree, fileindex,
10676 tmp_branch, hle, repo);
10677 got_worktree_rebase_pathlist_free(&merged_paths);
10678 if (error)
10679 goto done;
10682 if (upa.conflicts > 0 || upa.missing > 0 ||
10683 upa.not_deleted > 0 || upa.unversioned > 0) {
10684 error = got_worktree_histedit_postpone(worktree, fileindex);
10685 if (error)
10686 goto done;
10687 if (upa.conflicts > 0 && upa.missing == 0 &&
10688 upa.not_deleted == 0 && upa.unversioned == 0) {
10689 error = got_error_msg(GOT_ERR_CONFLICTS,
10690 "conflicts must be resolved before histedit "
10691 "can continue");
10692 } else if (upa.conflicts > 0) {
10693 error = got_error_msg(GOT_ERR_CONFLICTS,
10694 "conflicts must be resolved before histedit "
10695 "can continue; changes destined for some "
10696 "files were not yet merged and should be "
10697 "merged manually if required before the "
10698 "histedit operation is continued");
10699 } else {
10700 error = got_error_msg(GOT_ERR_CONFLICTS,
10701 "changes destined for some files were not "
10702 "yet merged and should be merged manually "
10703 "if required before the histedit operation "
10704 "is continued");
10706 } else
10707 error = histedit_complete(worktree, fileindex, tmp_branch,
10708 branch, repo);
10709 done:
10710 got_object_id_queue_free(&commits);
10711 histedit_free_list(&histedit_cmds);
10712 free(head_commit_id);
10713 free(base_commit_id);
10714 free(resume_commit_id);
10715 if (commit)
10716 got_object_commit_close(commit);
10717 if (branch)
10718 got_ref_close(branch);
10719 if (tmp_branch)
10720 got_ref_close(tmp_branch);
10721 if (worktree)
10722 got_worktree_close(worktree);
10723 if (repo) {
10724 const struct got_error *close_err = got_repo_close(repo);
10725 if (error == NULL)
10726 error = close_err;
10728 return error;
10731 __dead static void
10732 usage_integrate(void)
10734 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10735 exit(1);
10738 static const struct got_error *
10739 cmd_integrate(int argc, char *argv[])
10741 const struct got_error *error = NULL;
10742 struct got_repository *repo = NULL;
10743 struct got_worktree *worktree = NULL;
10744 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10745 const char *branch_arg = NULL;
10746 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10747 struct got_fileindex *fileindex = NULL;
10748 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10749 int ch;
10750 struct got_update_progress_arg upa;
10752 while ((ch = getopt(argc, argv, "")) != -1) {
10753 switch (ch) {
10754 default:
10755 usage_integrate();
10756 /* NOTREACHED */
10760 argc -= optind;
10761 argv += optind;
10763 if (argc != 1)
10764 usage_integrate();
10765 branch_arg = argv[0];
10766 #ifndef PROFILE
10767 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10768 "unveil", NULL) == -1)
10769 err(1, "pledge");
10770 #endif
10771 cwd = getcwd(NULL, 0);
10772 if (cwd == NULL) {
10773 error = got_error_from_errno("getcwd");
10774 goto done;
10777 error = got_worktree_open(&worktree, cwd);
10778 if (error) {
10779 if (error->code == GOT_ERR_NOT_WORKTREE)
10780 error = wrap_not_worktree_error(error, "integrate",
10781 cwd);
10782 goto done;
10785 error = check_rebase_or_histedit_in_progress(worktree);
10786 if (error)
10787 goto done;
10789 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10790 NULL);
10791 if (error != NULL)
10792 goto done;
10794 error = apply_unveil(got_repo_get_path(repo), 0,
10795 got_worktree_get_root_path(worktree));
10796 if (error)
10797 goto done;
10799 error = check_merge_in_progress(worktree, repo);
10800 if (error)
10801 goto done;
10803 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10804 error = got_error_from_errno("asprintf");
10805 goto done;
10808 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10809 &base_branch_ref, worktree, refname, repo);
10810 if (error)
10811 goto done;
10813 refname = strdup(got_ref_get_name(branch_ref));
10814 if (refname == NULL) {
10815 error = got_error_from_errno("strdup");
10816 got_worktree_integrate_abort(worktree, fileindex, repo,
10817 branch_ref, base_branch_ref);
10818 goto done;
10820 base_refname = strdup(got_ref_get_name(base_branch_ref));
10821 if (base_refname == NULL) {
10822 error = got_error_from_errno("strdup");
10823 got_worktree_integrate_abort(worktree, fileindex, repo,
10824 branch_ref, base_branch_ref);
10825 goto done;
10828 error = got_ref_resolve(&commit_id, repo, branch_ref);
10829 if (error)
10830 goto done;
10832 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10833 if (error)
10834 goto done;
10836 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10837 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10838 "specified branch has already been integrated");
10839 got_worktree_integrate_abort(worktree, fileindex, repo,
10840 branch_ref, base_branch_ref);
10841 goto done;
10844 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10845 if (error) {
10846 if (error->code == GOT_ERR_ANCESTRY)
10847 error = got_error(GOT_ERR_REBASE_REQUIRED);
10848 got_worktree_integrate_abort(worktree, fileindex, repo,
10849 branch_ref, base_branch_ref);
10850 goto done;
10853 memset(&upa, 0, sizeof(upa));
10854 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10855 branch_ref, base_branch_ref, update_progress, &upa,
10856 check_cancelled, NULL);
10857 if (error)
10858 goto done;
10860 printf("Integrated %s into %s\n", refname, base_refname);
10861 print_update_progress_stats(&upa);
10862 done:
10863 if (repo) {
10864 const struct got_error *close_err = got_repo_close(repo);
10865 if (error == NULL)
10866 error = close_err;
10868 if (worktree)
10869 got_worktree_close(worktree);
10870 free(cwd);
10871 free(base_commit_id);
10872 free(commit_id);
10873 free(refname);
10874 free(base_refname);
10875 return error;
10878 __dead static void
10879 usage_merge(void)
10881 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
10882 getprogname());
10883 exit(1);
10886 static const struct got_error *
10887 cmd_merge(int argc, char *argv[])
10889 const struct got_error *error = NULL;
10890 struct got_worktree *worktree = NULL;
10891 struct got_repository *repo = NULL;
10892 struct got_fileindex *fileindex = NULL;
10893 char *cwd = NULL, *id_str = NULL, *author = NULL;
10894 struct got_reference *branch = NULL, *wt_branch = NULL;
10895 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
10896 struct got_object_id *wt_branch_tip = NULL;
10897 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
10898 int interrupt_merge = 0;
10899 struct got_update_progress_arg upa;
10900 struct got_object_id *merge_commit_id = NULL;
10901 char *branch_name = NULL;
10903 memset(&upa, 0, sizeof(upa));
10905 while ((ch = getopt(argc, argv, "acn")) != -1) {
10906 switch (ch) {
10907 case 'a':
10908 abort_merge = 1;
10909 break;
10910 case 'c':
10911 continue_merge = 1;
10912 break;
10913 case 'n':
10914 interrupt_merge = 1;
10915 break;
10916 default:
10917 usage_rebase();
10918 /* NOTREACHED */
10922 argc -= optind;
10923 argv += optind;
10925 #ifndef PROFILE
10926 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10927 "unveil", NULL) == -1)
10928 err(1, "pledge");
10929 #endif
10931 if (abort_merge && continue_merge)
10932 option_conflict('a', 'c');
10933 if (abort_merge || continue_merge) {
10934 if (argc != 0)
10935 usage_merge();
10936 } else if (argc != 1)
10937 usage_merge();
10939 cwd = getcwd(NULL, 0);
10940 if (cwd == NULL) {
10941 error = got_error_from_errno("getcwd");
10942 goto done;
10945 error = got_worktree_open(&worktree, cwd);
10946 if (error) {
10947 if (error->code == GOT_ERR_NOT_WORKTREE)
10948 error = wrap_not_worktree_error(error,
10949 "merge", cwd);
10950 goto done;
10953 error = got_repo_open(&repo,
10954 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
10955 if (error != NULL)
10956 goto done;
10958 error = apply_unveil(got_repo_get_path(repo), 0,
10959 worktree ? got_worktree_get_root_path(worktree) : NULL);
10960 if (error)
10961 goto done;
10963 error = check_rebase_or_histedit_in_progress(worktree);
10964 if (error)
10965 goto done;
10967 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10968 repo);
10969 if (error)
10970 goto done;
10972 if (abort_merge) {
10973 if (!merge_in_progress) {
10974 error = got_error(GOT_ERR_NOT_MERGING);
10975 goto done;
10977 error = got_worktree_merge_continue(&branch_name,
10978 &branch_tip, &fileindex, worktree, repo);
10979 if (error)
10980 goto done;
10981 error = got_worktree_merge_abort(worktree, fileindex, repo,
10982 abort_progress, &upa);
10983 if (error)
10984 goto done;
10985 printf("Merge of %s aborted\n", branch_name);
10986 goto done; /* nothing else to do */
10989 error = get_author(&author, repo, worktree);
10990 if (error)
10991 goto done;
10993 if (continue_merge) {
10994 if (!merge_in_progress) {
10995 error = got_error(GOT_ERR_NOT_MERGING);
10996 goto done;
10998 error = got_worktree_merge_continue(&branch_name,
10999 &branch_tip, &fileindex, worktree, repo);
11000 if (error)
11001 goto done;
11002 } else {
11003 error = got_ref_open(&branch, repo, argv[0], 0);
11004 if (error != NULL)
11005 goto done;
11006 branch_name = strdup(got_ref_get_name(branch));
11007 if (branch_name == NULL) {
11008 error = got_error_from_errno("strdup");
11009 goto done;
11011 error = got_ref_resolve(&branch_tip, repo, branch);
11012 if (error)
11013 goto done;
11016 error = got_ref_open(&wt_branch, repo,
11017 got_worktree_get_head_ref_name(worktree), 0);
11018 if (error)
11019 goto done;
11020 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11021 if (error)
11022 goto done;
11023 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11024 wt_branch_tip, branch_tip, 0, repo,
11025 check_cancelled, NULL);
11026 if (error && error->code != GOT_ERR_ANCESTRY)
11027 goto done;
11029 if (!continue_merge) {
11030 error = check_path_prefix(wt_branch_tip, branch_tip,
11031 got_worktree_get_path_prefix(worktree),
11032 GOT_ERR_MERGE_PATH, repo);
11033 if (error)
11034 goto done;
11035 if (yca_id) {
11036 error = check_same_branch(wt_branch_tip, branch,
11037 yca_id, repo);
11038 if (error) {
11039 if (error->code != GOT_ERR_ANCESTRY)
11040 goto done;
11041 error = NULL;
11042 } else {
11043 static char msg[512];
11044 snprintf(msg, sizeof(msg),
11045 "cannot create a merge commit because "
11046 "%s is based on %s; %s can be integrated "
11047 "with 'got integrate' instead", branch_name,
11048 got_worktree_get_head_ref_name(worktree),
11049 branch_name);
11050 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11051 goto done;
11054 error = got_worktree_merge_prepare(&fileindex, worktree,
11055 branch, repo);
11056 if (error)
11057 goto done;
11059 error = got_worktree_merge_branch(worktree, fileindex,
11060 yca_id, branch_tip, repo, update_progress, &upa,
11061 check_cancelled, NULL);
11062 if (error)
11063 goto done;
11064 print_merge_progress_stats(&upa);
11065 if (!upa.did_something) {
11066 error = got_worktree_merge_abort(worktree, fileindex,
11067 repo, abort_progress, &upa);
11068 if (error)
11069 goto done;
11070 printf("Already up-to-date\n");
11071 goto done;
11075 if (interrupt_merge) {
11076 error = got_worktree_merge_postpone(worktree, fileindex);
11077 if (error)
11078 goto done;
11079 printf("Merge of %s interrupted on request\n", branch_name);
11080 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11081 upa.not_deleted > 0 || upa.unversioned > 0) {
11082 error = got_worktree_merge_postpone(worktree, fileindex);
11083 if (error)
11084 goto done;
11085 if (upa.conflicts > 0 && upa.missing == 0 &&
11086 upa.not_deleted == 0 && upa.unversioned == 0) {
11087 error = got_error_msg(GOT_ERR_CONFLICTS,
11088 "conflicts must be resolved before merging "
11089 "can continue");
11090 } else if (upa.conflicts > 0) {
11091 error = got_error_msg(GOT_ERR_CONFLICTS,
11092 "conflicts must be resolved before merging "
11093 "can continue; changes destined for some "
11094 "files were not yet merged and "
11095 "should be merged manually if required before the "
11096 "merge operation is continued");
11097 } else {
11098 error = got_error_msg(GOT_ERR_CONFLICTS,
11099 "changes destined for some "
11100 "files were not yet merged and should be "
11101 "merged manually if required before the "
11102 "merge operation is continued");
11104 goto done;
11105 } else {
11106 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11107 fileindex, author, NULL, 1, branch_tip, branch_name,
11108 repo, continue_merge ? print_status : NULL, NULL);
11109 if (error)
11110 goto done;
11111 error = got_worktree_merge_complete(worktree, fileindex, repo);
11112 if (error)
11113 goto done;
11114 error = got_object_id_str(&id_str, merge_commit_id);
11115 if (error)
11116 goto done;
11117 printf("Merged %s into %s: %s\n", branch_name,
11118 got_worktree_get_head_ref_name(worktree),
11119 id_str);
11122 done:
11123 free(id_str);
11124 free(merge_commit_id);
11125 free(author);
11126 free(branch_tip);
11127 free(branch_name);
11128 free(yca_id);
11129 if (branch)
11130 got_ref_close(branch);
11131 if (wt_branch)
11132 got_ref_close(wt_branch);
11133 if (worktree)
11134 got_worktree_close(worktree);
11135 if (repo) {
11136 const struct got_error *close_err = got_repo_close(repo);
11137 if (error == NULL)
11138 error = close_err;
11140 return error;
11143 __dead static void
11144 usage_stage(void)
11146 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11147 "[-S] [file-path ...]\n",
11148 getprogname());
11149 exit(1);
11152 static const struct got_error *
11153 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11154 const char *path, struct got_object_id *blob_id,
11155 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11156 int dirfd, const char *de_name)
11158 const struct got_error *err = NULL;
11159 char *id_str = NULL;
11161 if (staged_status != GOT_STATUS_ADD &&
11162 staged_status != GOT_STATUS_MODIFY &&
11163 staged_status != GOT_STATUS_DELETE)
11164 return NULL;
11166 if (staged_status == GOT_STATUS_ADD ||
11167 staged_status == GOT_STATUS_MODIFY)
11168 err = got_object_id_str(&id_str, staged_blob_id);
11169 else
11170 err = got_object_id_str(&id_str, blob_id);
11171 if (err)
11172 return err;
11174 printf("%s %c %s\n", id_str, staged_status, path);
11175 free(id_str);
11176 return NULL;
11179 static const struct got_error *
11180 cmd_stage(int argc, char *argv[])
11182 const struct got_error *error = NULL;
11183 struct got_repository *repo = NULL;
11184 struct got_worktree *worktree = NULL;
11185 char *cwd = NULL;
11186 struct got_pathlist_head paths;
11187 struct got_pathlist_entry *pe;
11188 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11189 FILE *patch_script_file = NULL;
11190 const char *patch_script_path = NULL;
11191 struct choose_patch_arg cpa;
11193 TAILQ_INIT(&paths);
11195 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11196 switch (ch) {
11197 case 'l':
11198 list_stage = 1;
11199 break;
11200 case 'p':
11201 pflag = 1;
11202 break;
11203 case 'F':
11204 patch_script_path = optarg;
11205 break;
11206 case 'S':
11207 allow_bad_symlinks = 1;
11208 break;
11209 default:
11210 usage_stage();
11211 /* NOTREACHED */
11215 argc -= optind;
11216 argv += optind;
11218 #ifndef PROFILE
11219 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11220 "unveil", NULL) == -1)
11221 err(1, "pledge");
11222 #endif
11223 if (list_stage && (pflag || patch_script_path))
11224 errx(1, "-l option cannot be used with other options");
11225 if (patch_script_path && !pflag)
11226 errx(1, "-F option can only be used together with -p option");
11228 cwd = getcwd(NULL, 0);
11229 if (cwd == NULL) {
11230 error = got_error_from_errno("getcwd");
11231 goto done;
11234 error = got_worktree_open(&worktree, cwd);
11235 if (error) {
11236 if (error->code == GOT_ERR_NOT_WORKTREE)
11237 error = wrap_not_worktree_error(error, "stage", cwd);
11238 goto done;
11241 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11242 NULL);
11243 if (error != NULL)
11244 goto done;
11246 if (patch_script_path) {
11247 patch_script_file = fopen(patch_script_path, "re");
11248 if (patch_script_file == NULL) {
11249 error = got_error_from_errno2("fopen",
11250 patch_script_path);
11251 goto done;
11254 error = apply_unveil(got_repo_get_path(repo), 0,
11255 got_worktree_get_root_path(worktree));
11256 if (error)
11257 goto done;
11259 error = check_merge_in_progress(worktree, repo);
11260 if (error)
11261 goto done;
11263 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11264 if (error)
11265 goto done;
11267 if (list_stage)
11268 error = got_worktree_status(worktree, &paths, repo, 0,
11269 print_stage, NULL, check_cancelled, NULL);
11270 else {
11271 cpa.patch_script_file = patch_script_file;
11272 cpa.action = "stage";
11273 error = got_worktree_stage(worktree, &paths,
11274 pflag ? NULL : print_status, NULL,
11275 pflag ? choose_patch : NULL, &cpa,
11276 allow_bad_symlinks, repo);
11278 done:
11279 if (patch_script_file && fclose(patch_script_file) == EOF &&
11280 error == NULL)
11281 error = got_error_from_errno2("fclose", patch_script_path);
11282 if (repo) {
11283 const struct got_error *close_err = got_repo_close(repo);
11284 if (error == NULL)
11285 error = close_err;
11287 if (worktree)
11288 got_worktree_close(worktree);
11289 TAILQ_FOREACH(pe, &paths, entry)
11290 free((char *)pe->path);
11291 got_pathlist_free(&paths);
11292 free(cwd);
11293 return error;
11296 __dead static void
11297 usage_unstage(void)
11299 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11300 "[file-path ...]\n",
11301 getprogname());
11302 exit(1);
11306 static const struct got_error *
11307 cmd_unstage(int argc, char *argv[])
11309 const struct got_error *error = NULL;
11310 struct got_repository *repo = NULL;
11311 struct got_worktree *worktree = NULL;
11312 char *cwd = NULL;
11313 struct got_pathlist_head paths;
11314 struct got_pathlist_entry *pe;
11315 int ch, pflag = 0;
11316 struct got_update_progress_arg upa;
11317 FILE *patch_script_file = NULL;
11318 const char *patch_script_path = NULL;
11319 struct choose_patch_arg cpa;
11321 TAILQ_INIT(&paths);
11323 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11324 switch (ch) {
11325 case 'p':
11326 pflag = 1;
11327 break;
11328 case 'F':
11329 patch_script_path = optarg;
11330 break;
11331 default:
11332 usage_unstage();
11333 /* NOTREACHED */
11337 argc -= optind;
11338 argv += optind;
11340 #ifndef PROFILE
11341 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11342 "unveil", NULL) == -1)
11343 err(1, "pledge");
11344 #endif
11345 if (patch_script_path && !pflag)
11346 errx(1, "-F option can only be used together with -p option");
11348 cwd = getcwd(NULL, 0);
11349 if (cwd == NULL) {
11350 error = got_error_from_errno("getcwd");
11351 goto done;
11354 error = got_worktree_open(&worktree, cwd);
11355 if (error) {
11356 if (error->code == GOT_ERR_NOT_WORKTREE)
11357 error = wrap_not_worktree_error(error, "unstage", cwd);
11358 goto done;
11361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11362 NULL);
11363 if (error != NULL)
11364 goto done;
11366 if (patch_script_path) {
11367 patch_script_file = fopen(patch_script_path, "re");
11368 if (patch_script_file == NULL) {
11369 error = got_error_from_errno2("fopen",
11370 patch_script_path);
11371 goto done;
11375 error = apply_unveil(got_repo_get_path(repo), 0,
11376 got_worktree_get_root_path(worktree));
11377 if (error)
11378 goto done;
11380 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11381 if (error)
11382 goto done;
11384 cpa.patch_script_file = patch_script_file;
11385 cpa.action = "unstage";
11386 memset(&upa, 0, sizeof(upa));
11387 error = got_worktree_unstage(worktree, &paths, update_progress,
11388 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11389 if (!error)
11390 print_merge_progress_stats(&upa);
11391 done:
11392 if (patch_script_file && fclose(patch_script_file) == EOF &&
11393 error == NULL)
11394 error = got_error_from_errno2("fclose", patch_script_path);
11395 if (repo) {
11396 const struct got_error *close_err = got_repo_close(repo);
11397 if (error == NULL)
11398 error = close_err;
11400 if (worktree)
11401 got_worktree_close(worktree);
11402 TAILQ_FOREACH(pe, &paths, entry)
11403 free((char *)pe->path);
11404 got_pathlist_free(&paths);
11405 free(cwd);
11406 return error;
11409 __dead static void
11410 usage_cat(void)
11412 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11413 "arg1 [arg2 ...]\n", getprogname());
11414 exit(1);
11417 static const struct got_error *
11418 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11420 const struct got_error *err;
11421 struct got_blob_object *blob;
11423 err = got_object_open_as_blob(&blob, repo, id, 8192);
11424 if (err)
11425 return err;
11427 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11428 got_object_blob_close(blob);
11429 return err;
11432 static const struct got_error *
11433 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11435 const struct got_error *err;
11436 struct got_tree_object *tree;
11437 int nentries, i;
11439 err = got_object_open_as_tree(&tree, repo, id);
11440 if (err)
11441 return err;
11443 nentries = got_object_tree_get_nentries(tree);
11444 for (i = 0; i < nentries; i++) {
11445 struct got_tree_entry *te;
11446 char *id_str;
11447 if (sigint_received || sigpipe_received)
11448 break;
11449 te = got_object_tree_get_entry(tree, i);
11450 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11451 if (err)
11452 break;
11453 fprintf(outfile, "%s %.7o %s\n", id_str,
11454 got_tree_entry_get_mode(te),
11455 got_tree_entry_get_name(te));
11456 free(id_str);
11459 got_object_tree_close(tree);
11460 return err;
11463 static const struct got_error *
11464 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11466 const struct got_error *err;
11467 struct got_commit_object *commit;
11468 const struct got_object_id_queue *parent_ids;
11469 struct got_object_qid *pid;
11470 char *id_str = NULL;
11471 const char *logmsg = NULL;
11473 err = got_object_open_as_commit(&commit, repo, id);
11474 if (err)
11475 return err;
11477 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11478 if (err)
11479 goto done;
11481 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11482 parent_ids = got_object_commit_get_parent_ids(commit);
11483 fprintf(outfile, "numparents %d\n",
11484 got_object_commit_get_nparents(commit));
11485 STAILQ_FOREACH(pid, parent_ids, entry) {
11486 char *pid_str;
11487 err = got_object_id_str(&pid_str, pid->id);
11488 if (err)
11489 goto done;
11490 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11491 free(pid_str);
11493 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
11494 got_object_commit_get_author(commit),
11495 (long long)got_object_commit_get_author_time(commit));
11497 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
11498 got_object_commit_get_author(commit),
11499 (long long)got_object_commit_get_committer_time(commit));
11501 logmsg = got_object_commit_get_logmsg_raw(commit);
11502 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11503 fprintf(outfile, "%s", logmsg);
11504 done:
11505 free(id_str);
11506 got_object_commit_close(commit);
11507 return err;
11510 static const struct got_error *
11511 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11513 const struct got_error *err;
11514 struct got_tag_object *tag;
11515 char *id_str = NULL;
11516 const char *tagmsg = NULL;
11518 err = got_object_open_as_tag(&tag, repo, id);
11519 if (err)
11520 return err;
11522 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11523 if (err)
11524 goto done;
11526 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11528 switch (got_object_tag_get_object_type(tag)) {
11529 case GOT_OBJ_TYPE_BLOB:
11530 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11531 GOT_OBJ_LABEL_BLOB);
11532 break;
11533 case GOT_OBJ_TYPE_TREE:
11534 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11535 GOT_OBJ_LABEL_TREE);
11536 break;
11537 case GOT_OBJ_TYPE_COMMIT:
11538 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11539 GOT_OBJ_LABEL_COMMIT);
11540 break;
11541 case GOT_OBJ_TYPE_TAG:
11542 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11543 GOT_OBJ_LABEL_TAG);
11544 break;
11545 default:
11546 break;
11549 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11550 got_object_tag_get_name(tag));
11552 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
11553 got_object_tag_get_tagger(tag),
11554 (long long)got_object_tag_get_tagger_time(tag));
11556 tagmsg = got_object_tag_get_message(tag);
11557 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11558 fprintf(outfile, "%s", tagmsg);
11559 done:
11560 free(id_str);
11561 got_object_tag_close(tag);
11562 return err;
11565 static const struct got_error *
11566 cmd_cat(int argc, char *argv[])
11568 const struct got_error *error;
11569 struct got_repository *repo = NULL;
11570 struct got_worktree *worktree = NULL;
11571 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11572 const char *commit_id_str = NULL;
11573 struct got_object_id *id = NULL, *commit_id = NULL;
11574 int ch, obj_type, i, force_path = 0;
11575 struct got_reflist_head refs;
11577 TAILQ_INIT(&refs);
11579 #ifndef PROFILE
11580 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11581 NULL) == -1)
11582 err(1, "pledge");
11583 #endif
11585 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11586 switch (ch) {
11587 case 'c':
11588 commit_id_str = optarg;
11589 break;
11590 case 'r':
11591 repo_path = realpath(optarg, NULL);
11592 if (repo_path == NULL)
11593 return got_error_from_errno2("realpath",
11594 optarg);
11595 got_path_strip_trailing_slashes(repo_path);
11596 break;
11597 case 'P':
11598 force_path = 1;
11599 break;
11600 default:
11601 usage_cat();
11602 /* NOTREACHED */
11606 argc -= optind;
11607 argv += optind;
11609 cwd = getcwd(NULL, 0);
11610 if (cwd == NULL) {
11611 error = got_error_from_errno("getcwd");
11612 goto done;
11614 error = got_worktree_open(&worktree, cwd);
11615 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11616 goto done;
11617 if (worktree) {
11618 if (repo_path == NULL) {
11619 repo_path = strdup(
11620 got_worktree_get_repo_path(worktree));
11621 if (repo_path == NULL) {
11622 error = got_error_from_errno("strdup");
11623 goto done;
11628 if (repo_path == NULL) {
11629 repo_path = getcwd(NULL, 0);
11630 if (repo_path == NULL)
11631 return got_error_from_errno("getcwd");
11634 error = got_repo_open(&repo, repo_path, NULL);
11635 free(repo_path);
11636 if (error != NULL)
11637 goto done;
11639 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11640 if (error)
11641 goto done;
11643 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11644 if (error)
11645 goto done;
11647 if (commit_id_str == NULL)
11648 commit_id_str = GOT_REF_HEAD;
11649 error = got_repo_match_object_id(&commit_id, NULL,
11650 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11651 if (error)
11652 goto done;
11654 for (i = 0; i < argc; i++) {
11655 if (force_path) {
11656 error = got_object_id_by_path(&id, repo, commit_id,
11657 argv[i]);
11658 if (error)
11659 break;
11660 } else {
11661 error = got_repo_match_object_id(&id, &label, argv[i],
11662 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11663 repo);
11664 if (error) {
11665 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11666 error->code != GOT_ERR_NOT_REF)
11667 break;
11668 error = got_object_id_by_path(&id, repo,
11669 commit_id, argv[i]);
11670 if (error)
11671 break;
11675 error = got_object_get_type(&obj_type, repo, id);
11676 if (error)
11677 break;
11679 switch (obj_type) {
11680 case GOT_OBJ_TYPE_BLOB:
11681 error = cat_blob(id, repo, stdout);
11682 break;
11683 case GOT_OBJ_TYPE_TREE:
11684 error = cat_tree(id, repo, stdout);
11685 break;
11686 case GOT_OBJ_TYPE_COMMIT:
11687 error = cat_commit(id, repo, stdout);
11688 break;
11689 case GOT_OBJ_TYPE_TAG:
11690 error = cat_tag(id, repo, stdout);
11691 break;
11692 default:
11693 error = got_error(GOT_ERR_OBJ_TYPE);
11694 break;
11696 if (error)
11697 break;
11698 free(label);
11699 label = NULL;
11700 free(id);
11701 id = NULL;
11703 done:
11704 free(label);
11705 free(id);
11706 free(commit_id);
11707 if (worktree)
11708 got_worktree_close(worktree);
11709 if (repo) {
11710 const struct got_error *close_err = got_repo_close(repo);
11711 if (error == NULL)
11712 error = close_err;
11714 got_ref_list_free(&refs);
11715 return error;
11718 __dead static void
11719 usage_info(void)
11721 fprintf(stderr, "usage: %s info [path ...]\n",
11722 getprogname());
11723 exit(1);
11726 static const struct got_error *
11727 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11728 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11729 struct got_object_id *commit_id)
11731 const struct got_error *err = NULL;
11732 char *id_str = NULL;
11733 char datebuf[128];
11734 struct tm mytm, *tm;
11735 struct got_pathlist_head *paths = arg;
11736 struct got_pathlist_entry *pe;
11739 * Clear error indication from any of the path arguments which
11740 * would cause this file index entry to be displayed.
11742 TAILQ_FOREACH(pe, paths, entry) {
11743 if (got_path_cmp(path, pe->path, strlen(path),
11744 pe->path_len) == 0 ||
11745 got_path_is_child(path, pe->path, pe->path_len))
11746 pe->data = NULL; /* no error */
11749 printf(GOT_COMMIT_SEP_STR);
11750 if (S_ISLNK(mode))
11751 printf("symlink: %s\n", path);
11752 else if (S_ISREG(mode)) {
11753 printf("file: %s\n", path);
11754 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11755 } else if (S_ISDIR(mode))
11756 printf("directory: %s\n", path);
11757 else
11758 printf("something: %s\n", path);
11760 tm = localtime_r(&mtime, &mytm);
11761 if (tm == NULL)
11762 return NULL;
11763 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11764 return got_error(GOT_ERR_NO_SPACE);
11765 printf("timestamp: %s\n", datebuf);
11767 if (blob_id) {
11768 err = got_object_id_str(&id_str, blob_id);
11769 if (err)
11770 return err;
11771 printf("based on blob: %s\n", id_str);
11772 free(id_str);
11775 if (staged_blob_id) {
11776 err = got_object_id_str(&id_str, staged_blob_id);
11777 if (err)
11778 return err;
11779 printf("based on staged blob: %s\n", id_str);
11780 free(id_str);
11783 if (commit_id) {
11784 err = got_object_id_str(&id_str, commit_id);
11785 if (err)
11786 return err;
11787 printf("based on commit: %s\n", id_str);
11788 free(id_str);
11791 return NULL;
11794 static const struct got_error *
11795 cmd_info(int argc, char *argv[])
11797 const struct got_error *error = NULL;
11798 struct got_worktree *worktree = NULL;
11799 char *cwd = NULL, *id_str = NULL;
11800 struct got_pathlist_head paths;
11801 struct got_pathlist_entry *pe;
11802 char *uuidstr = NULL;
11803 int ch, show_files = 0;
11805 TAILQ_INIT(&paths);
11807 while ((ch = getopt(argc, argv, "")) != -1) {
11808 switch (ch) {
11809 default:
11810 usage_info();
11811 /* NOTREACHED */
11815 argc -= optind;
11816 argv += optind;
11818 #ifndef PROFILE
11819 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11820 NULL) == -1)
11821 err(1, "pledge");
11822 #endif
11823 cwd = getcwd(NULL, 0);
11824 if (cwd == NULL) {
11825 error = got_error_from_errno("getcwd");
11826 goto done;
11829 error = got_worktree_open(&worktree, cwd);
11830 if (error) {
11831 if (error->code == GOT_ERR_NOT_WORKTREE)
11832 error = wrap_not_worktree_error(error, "info", cwd);
11833 goto done;
11836 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11837 if (error)
11838 goto done;
11840 if (argc >= 1) {
11841 error = get_worktree_paths_from_argv(&paths, argc, argv,
11842 worktree);
11843 if (error)
11844 goto done;
11845 show_files = 1;
11848 error = got_object_id_str(&id_str,
11849 got_worktree_get_base_commit_id(worktree));
11850 if (error)
11851 goto done;
11853 error = got_worktree_get_uuid(&uuidstr, worktree);
11854 if (error)
11855 goto done;
11857 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11858 printf("work tree base commit: %s\n", id_str);
11859 printf("work tree path prefix: %s\n",
11860 got_worktree_get_path_prefix(worktree));
11861 printf("work tree branch reference: %s\n",
11862 got_worktree_get_head_ref_name(worktree));
11863 printf("work tree UUID: %s\n", uuidstr);
11864 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11866 if (show_files) {
11867 struct got_pathlist_entry *pe;
11868 TAILQ_FOREACH(pe, &paths, entry) {
11869 if (pe->path_len == 0)
11870 continue;
11872 * Assume this path will fail. This will be corrected
11873 * in print_path_info() in case the path does suceeed.
11875 pe->data = (void *)got_error_path(pe->path,
11876 GOT_ERR_BAD_PATH);
11878 error = got_worktree_path_info(worktree, &paths,
11879 print_path_info, &paths, check_cancelled, NULL);
11880 if (error)
11881 goto done;
11882 TAILQ_FOREACH(pe, &paths, entry) {
11883 if (pe->data != NULL) {
11884 error = pe->data; /* bad path */
11885 break;
11889 done:
11890 TAILQ_FOREACH(pe, &paths, entry)
11891 free((char *)pe->path);
11892 got_pathlist_free(&paths);
11893 free(cwd);
11894 free(id_str);
11895 free(uuidstr);
11896 return error;