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, "r");
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, "a");
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, "a");
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 error = got_object_id_str(&id_str, pack_hash);
1662 if (error)
1663 goto done;
1664 if (verbosity >= 0)
1665 printf("\nFetched %s.pack\n", id_str);
1666 free(id_str);
1668 /* Set up references provided with the pack file. */
1669 TAILQ_FOREACH(pe, &refs, entry) {
1670 const char *refname = pe->path;
1671 struct got_object_id *id = pe->data;
1672 char *remote_refname;
1674 if (is_wanted_ref(&wanted_refs, refname) &&
1675 !mirror_references) {
1676 error = create_wanted_ref(refname, id,
1677 GOT_FETCH_DEFAULT_REMOTE_NAME,
1678 verbosity - 1, repo);
1679 if (error)
1680 goto done;
1681 continue;
1684 error = create_ref(refname, id, verbosity - 1, repo);
1685 if (error)
1686 goto done;
1688 if (mirror_references)
1689 continue;
1691 if (strncmp("refs/heads/", refname, 11) != 0)
1692 continue;
1694 if (asprintf(&remote_refname,
1695 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1696 refname + 11) == -1) {
1697 error = got_error_from_errno("asprintf");
1698 goto done;
1700 error = create_ref(remote_refname, id, verbosity - 1, repo);
1701 free(remote_refname);
1702 if (error)
1703 goto done;
1706 /* Set the HEAD reference if the server provided one. */
1707 TAILQ_FOREACH(pe, &symrefs, entry) {
1708 struct got_reference *target_ref;
1709 const char *refname = pe->path;
1710 const char *target = pe->data;
1711 char *remote_refname = NULL, *remote_target = NULL;
1713 if (strcmp(refname, GOT_REF_HEAD) != 0)
1714 continue;
1716 error = got_ref_open(&target_ref, repo, target, 0);
1717 if (error) {
1718 if (error->code == GOT_ERR_NOT_REF) {
1719 error = NULL;
1720 continue;
1722 goto done;
1725 error = create_symref(refname, target_ref, verbosity, repo);
1726 got_ref_close(target_ref);
1727 if (error)
1728 goto done;
1730 if (mirror_references)
1731 continue;
1733 if (strncmp("refs/heads/", target, 11) != 0)
1734 continue;
1736 if (asprintf(&remote_refname,
1737 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1738 refname) == -1) {
1739 error = got_error_from_errno("asprintf");
1740 goto done;
1742 if (asprintf(&remote_target,
1743 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1744 target + 11) == -1) {
1745 error = got_error_from_errno("asprintf");
1746 free(remote_refname);
1747 goto done;
1749 error = got_ref_open(&target_ref, repo, remote_target, 0);
1750 if (error) {
1751 free(remote_refname);
1752 free(remote_target);
1753 if (error->code == GOT_ERR_NOT_REF) {
1754 error = NULL;
1755 continue;
1757 goto done;
1759 error = create_symref(remote_refname, target_ref,
1760 verbosity - 1, repo);
1761 free(remote_refname);
1762 free(remote_target);
1763 got_ref_close(target_ref);
1764 if (error)
1765 goto done;
1767 if (pe == NULL) {
1769 * We failed to set the HEAD reference. If we asked for
1770 * a set of wanted branches use the first of one of those
1771 * which could be fetched instead.
1773 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1774 const char *target = pe->path;
1775 struct got_reference *target_ref;
1777 error = got_ref_open(&target_ref, repo, target, 0);
1778 if (error) {
1779 if (error->code == GOT_ERR_NOT_REF) {
1780 error = NULL;
1781 continue;
1783 goto done;
1786 error = create_symref(GOT_REF_HEAD, target_ref,
1787 verbosity, repo);
1788 got_ref_close(target_ref);
1789 if (error)
1790 goto done;
1791 break;
1795 if (verbosity >= 0)
1796 printf("Created %s repository '%s'\n",
1797 mirror_references ? "mirrored" : "cloned", repo_path);
1798 done:
1799 if (fetchpid > 0) {
1800 if (kill(fetchpid, SIGTERM) == -1)
1801 error = got_error_from_errno("kill");
1802 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1803 error = got_error_from_errno("waitpid");
1805 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1806 error = got_error_from_errno("close");
1807 if (repo) {
1808 const struct got_error *close_err = got_repo_close(repo);
1809 if (error == NULL)
1810 error = close_err;
1812 TAILQ_FOREACH(pe, &refs, entry) {
1813 free((void *)pe->path);
1814 free(pe->data);
1816 got_pathlist_free(&refs);
1817 TAILQ_FOREACH(pe, &symrefs, entry) {
1818 free((void *)pe->path);
1819 free(pe->data);
1821 got_pathlist_free(&symrefs);
1822 got_pathlist_free(&wanted_branches);
1823 got_pathlist_free(&wanted_refs);
1824 free(pack_hash);
1825 free(proto);
1826 free(host);
1827 free(port);
1828 free(server_path);
1829 free(repo_name);
1830 free(default_destdir);
1831 free(git_url);
1832 return error;
1835 static const struct got_error *
1836 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1837 int replace_tags, int verbosity, struct got_repository *repo)
1839 const struct got_error *err = NULL;
1840 char *new_id_str = NULL;
1841 struct got_object_id *old_id = NULL;
1843 err = got_object_id_str(&new_id_str, new_id);
1844 if (err)
1845 goto done;
1847 if (!replace_tags &&
1848 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1849 err = got_ref_resolve(&old_id, repo, ref);
1850 if (err)
1851 goto done;
1852 if (got_object_id_cmp(old_id, new_id) == 0)
1853 goto done;
1854 if (verbosity >= 0) {
1855 printf("Rejecting update of existing tag %s: %s\n",
1856 got_ref_get_name(ref), new_id_str);
1858 goto done;
1861 if (got_ref_is_symbolic(ref)) {
1862 if (verbosity >= 0) {
1863 printf("Replacing reference %s: %s\n",
1864 got_ref_get_name(ref),
1865 got_ref_get_symref_target(ref));
1867 err = got_ref_change_symref_to_ref(ref, new_id);
1868 if (err)
1869 goto done;
1870 err = got_ref_write(ref, repo);
1871 if (err)
1872 goto done;
1873 } else {
1874 err = got_ref_resolve(&old_id, repo, ref);
1875 if (err)
1876 goto done;
1877 if (got_object_id_cmp(old_id, new_id) == 0)
1878 goto done;
1880 err = got_ref_change_ref(ref, new_id);
1881 if (err)
1882 goto done;
1883 err = got_ref_write(ref, repo);
1884 if (err)
1885 goto done;
1888 if (verbosity >= 0)
1889 printf("Updated %s: %s\n", got_ref_get_name(ref),
1890 new_id_str);
1891 done:
1892 free(old_id);
1893 free(new_id_str);
1894 return err;
1897 static const struct got_error *
1898 update_symref(const char *refname, struct got_reference *target_ref,
1899 int verbosity, struct got_repository *repo)
1901 const struct got_error *err = NULL, *unlock_err;
1902 struct got_reference *symref;
1903 int symref_is_locked = 0;
1905 err = got_ref_open(&symref, repo, refname, 1);
1906 if (err) {
1907 if (err->code != GOT_ERR_NOT_REF)
1908 return err;
1909 err = got_ref_alloc_symref(&symref, refname, target_ref);
1910 if (err)
1911 goto done;
1913 err = got_ref_write(symref, repo);
1914 if (err)
1915 goto done;
1917 if (verbosity >= 0)
1918 printf("Created reference %s: %s\n",
1919 got_ref_get_name(symref),
1920 got_ref_get_symref_target(symref));
1921 } else {
1922 symref_is_locked = 1;
1924 if (strcmp(got_ref_get_symref_target(symref),
1925 got_ref_get_name(target_ref)) == 0)
1926 goto done;
1928 err = got_ref_change_symref(symref,
1929 got_ref_get_name(target_ref));
1930 if (err)
1931 goto done;
1933 err = got_ref_write(symref, repo);
1934 if (err)
1935 goto done;
1937 if (verbosity >= 0)
1938 printf("Updated %s: %s\n", got_ref_get_name(symref),
1939 got_ref_get_symref_target(symref));
1942 done:
1943 if (symref_is_locked) {
1944 unlock_err = got_ref_unlock(symref);
1945 if (unlock_err && err == NULL)
1946 err = unlock_err;
1948 got_ref_close(symref);
1949 return err;
1952 __dead static void
1953 usage_fetch(void)
1955 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1956 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1957 "[remote-repository-name]\n",
1958 getprogname());
1959 exit(1);
1962 static const struct got_error *
1963 delete_missing_ref(struct got_reference *ref,
1964 int verbosity, struct got_repository *repo)
1966 const struct got_error *err = NULL;
1967 struct got_object_id *id = NULL;
1968 char *id_str = NULL;
1970 if (got_ref_is_symbolic(ref)) {
1971 err = got_ref_delete(ref, repo);
1972 if (err)
1973 return err;
1974 if (verbosity >= 0) {
1975 printf("Deleted %s: %s\n",
1976 got_ref_get_name(ref),
1977 got_ref_get_symref_target(ref));
1979 } else {
1980 err = got_ref_resolve(&id, repo, ref);
1981 if (err)
1982 return err;
1983 err = got_object_id_str(&id_str, id);
1984 if (err)
1985 goto done;
1987 err = got_ref_delete(ref, repo);
1988 if (err)
1989 goto done;
1990 if (verbosity >= 0) {
1991 printf("Deleted %s: %s\n",
1992 got_ref_get_name(ref), id_str);
1995 done:
1996 free(id);
1997 free(id_str);
1998 return NULL;
2001 static const struct got_error *
2002 delete_missing_refs(struct got_pathlist_head *their_refs,
2003 struct got_pathlist_head *their_symrefs,
2004 const struct got_remote_repo *remote,
2005 int verbosity, struct got_repository *repo)
2007 const struct got_error *err = NULL, *unlock_err;
2008 struct got_reflist_head my_refs;
2009 struct got_reflist_entry *re;
2010 struct got_pathlist_entry *pe;
2011 char *remote_namespace = NULL;
2012 char *local_refname = NULL;
2014 TAILQ_INIT(&my_refs);
2016 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2017 == -1)
2018 return got_error_from_errno("asprintf");
2020 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2021 if (err)
2022 goto done;
2024 TAILQ_FOREACH(re, &my_refs, entry) {
2025 const char *refname = got_ref_get_name(re->ref);
2026 const char *their_refname;
2028 if (remote->mirror_references) {
2029 their_refname = refname;
2030 } else {
2031 if (strncmp(refname, remote_namespace,
2032 strlen(remote_namespace)) == 0) {
2033 if (strcmp(refname + strlen(remote_namespace),
2034 GOT_REF_HEAD) == 0)
2035 continue;
2036 if (asprintf(&local_refname, "refs/heads/%s",
2037 refname + strlen(remote_namespace)) == -1) {
2038 err = got_error_from_errno("asprintf");
2039 goto done;
2041 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2042 continue;
2044 their_refname = local_refname;
2047 TAILQ_FOREACH(pe, their_refs, entry) {
2048 if (strcmp(their_refname, pe->path) == 0)
2049 break;
2051 if (pe != NULL)
2052 continue;
2054 TAILQ_FOREACH(pe, their_symrefs, entry) {
2055 if (strcmp(their_refname, pe->path) == 0)
2056 break;
2058 if (pe != NULL)
2059 continue;
2061 err = delete_missing_ref(re->ref, verbosity, repo);
2062 if (err)
2063 break;
2065 if (local_refname) {
2066 struct got_reference *ref;
2067 err = got_ref_open(&ref, repo, local_refname, 1);
2068 if (err) {
2069 if (err->code != GOT_ERR_NOT_REF)
2070 break;
2071 free(local_refname);
2072 local_refname = NULL;
2073 continue;
2075 err = delete_missing_ref(ref, verbosity, repo);
2076 if (err)
2077 break;
2078 unlock_err = got_ref_unlock(ref);
2079 got_ref_close(ref);
2080 if (unlock_err && err == NULL) {
2081 err = unlock_err;
2082 break;
2085 free(local_refname);
2086 local_refname = NULL;
2089 done:
2090 free(remote_namespace);
2091 free(local_refname);
2092 return err;
2095 static const struct got_error *
2096 update_wanted_ref(const char *refname, struct got_object_id *id,
2097 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2099 const struct got_error *err, *unlock_err;
2100 char *remote_refname;
2101 struct got_reference *ref;
2103 if (strncmp("refs/", refname, 5) == 0)
2104 refname += 5;
2106 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2107 remote_repo_name, refname) == -1)
2108 return got_error_from_errno("asprintf");
2110 err = got_ref_open(&ref, repo, remote_refname, 1);
2111 if (err) {
2112 if (err->code != GOT_ERR_NOT_REF)
2113 goto done;
2114 err = create_ref(remote_refname, id, verbosity, repo);
2115 } else {
2116 err = update_ref(ref, id, 0, verbosity, repo);
2117 unlock_err = got_ref_unlock(ref);
2118 if (unlock_err && err == NULL)
2119 err = unlock_err;
2120 got_ref_close(ref);
2122 done:
2123 free(remote_refname);
2124 return err;
2127 static const struct got_error *
2128 delete_ref(struct got_repository *repo, struct got_reference *ref)
2130 const struct got_error *err = NULL;
2131 struct got_object_id *id = NULL;
2132 char *id_str = NULL;
2133 const char *target;
2135 if (got_ref_is_symbolic(ref)) {
2136 target = got_ref_get_symref_target(ref);
2137 } else {
2138 err = got_ref_resolve(&id, repo, ref);
2139 if (err)
2140 goto done;
2141 err = got_object_id_str(&id_str, id);
2142 if (err)
2143 goto done;
2144 target = id_str;
2147 err = got_ref_delete(ref, repo);
2148 if (err)
2149 goto done;
2151 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2152 done:
2153 free(id);
2154 free(id_str);
2155 return err;
2158 static const struct got_error *
2159 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2161 const struct got_error *err = NULL;
2162 struct got_reflist_head refs;
2163 struct got_reflist_entry *re;
2164 char *prefix;
2166 TAILQ_INIT(&refs);
2168 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2169 err = got_error_from_errno("asprintf");
2170 goto done;
2172 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2173 if (err)
2174 goto done;
2176 TAILQ_FOREACH(re, &refs, entry)
2177 delete_ref(repo, re->ref);
2178 done:
2179 got_ref_list_free(&refs);
2180 return err;
2183 static const struct got_error *
2184 cmd_fetch(int argc, char *argv[])
2186 const struct got_error *error = NULL, *unlock_err;
2187 char *cwd = NULL, *repo_path = NULL;
2188 const char *remote_name;
2189 char *proto = NULL, *host = NULL, *port = NULL;
2190 char *repo_name = NULL, *server_path = NULL;
2191 const struct got_remote_repo *remotes, *remote = NULL;
2192 int nremotes;
2193 char *id_str = NULL;
2194 struct got_repository *repo = NULL;
2195 struct got_worktree *worktree = NULL;
2196 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2197 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2198 struct got_pathlist_entry *pe;
2199 struct got_object_id *pack_hash = NULL;
2200 int i, ch, fetchfd = -1, fetchstatus;
2201 pid_t fetchpid = -1;
2202 struct got_fetch_progress_arg fpa;
2203 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2204 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2206 TAILQ_INIT(&refs);
2207 TAILQ_INIT(&symrefs);
2208 TAILQ_INIT(&wanted_branches);
2209 TAILQ_INIT(&wanted_refs);
2211 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2212 switch (ch) {
2213 case 'a':
2214 fetch_all_branches = 1;
2215 break;
2216 case 'b':
2217 error = got_pathlist_append(&wanted_branches,
2218 optarg, NULL);
2219 if (error)
2220 return error;
2221 break;
2222 case 'd':
2223 delete_refs = 1;
2224 break;
2225 case 'l':
2226 list_refs_only = 1;
2227 break;
2228 case 'r':
2229 repo_path = realpath(optarg, NULL);
2230 if (repo_path == NULL)
2231 return got_error_from_errno2("realpath",
2232 optarg);
2233 got_path_strip_trailing_slashes(repo_path);
2234 break;
2235 case 't':
2236 replace_tags = 1;
2237 break;
2238 case 'v':
2239 if (verbosity < 0)
2240 verbosity = 0;
2241 else if (verbosity < 3)
2242 verbosity++;
2243 break;
2244 case 'q':
2245 verbosity = -1;
2246 break;
2247 case 'R':
2248 error = got_pathlist_append(&wanted_refs,
2249 optarg, NULL);
2250 if (error)
2251 return error;
2252 break;
2253 case 'X':
2254 delete_remote = 1;
2255 break;
2256 default:
2257 usage_fetch();
2258 break;
2261 argc -= optind;
2262 argv += optind;
2264 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2265 option_conflict('a', 'b');
2266 if (list_refs_only) {
2267 if (!TAILQ_EMPTY(&wanted_branches))
2268 option_conflict('l', 'b');
2269 if (fetch_all_branches)
2270 option_conflict('l', 'a');
2271 if (delete_refs)
2272 option_conflict('l', 'd');
2273 if (delete_remote)
2274 option_conflict('l', 'X');
2276 if (delete_remote) {
2277 if (fetch_all_branches)
2278 option_conflict('X', 'a');
2279 if (!TAILQ_EMPTY(&wanted_branches))
2280 option_conflict('X', 'b');
2281 if (delete_refs)
2282 option_conflict('X', 'd');
2283 if (replace_tags)
2284 option_conflict('X', 't');
2285 if (!TAILQ_EMPTY(&wanted_refs))
2286 option_conflict('X', 'R');
2289 if (argc == 0) {
2290 if (delete_remote)
2291 errx(1, "-X option requires a remote name");
2292 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2293 } else if (argc == 1)
2294 remote_name = argv[0];
2295 else
2296 usage_fetch();
2298 cwd = getcwd(NULL, 0);
2299 if (cwd == NULL) {
2300 error = got_error_from_errno("getcwd");
2301 goto done;
2304 if (repo_path == NULL) {
2305 error = got_worktree_open(&worktree, cwd);
2306 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2307 goto done;
2308 else
2309 error = NULL;
2310 if (worktree) {
2311 repo_path =
2312 strdup(got_worktree_get_repo_path(worktree));
2313 if (repo_path == NULL)
2314 error = got_error_from_errno("strdup");
2315 if (error)
2316 goto done;
2317 } else {
2318 repo_path = strdup(cwd);
2319 if (repo_path == NULL) {
2320 error = got_error_from_errno("strdup");
2321 goto done;
2326 error = got_repo_open(&repo, repo_path, NULL);
2327 if (error)
2328 goto done;
2330 if (delete_remote) {
2331 error = delete_refs_for_remote(repo, remote_name);
2332 goto done; /* nothing else to do */
2335 if (worktree) {
2336 worktree_conf = got_worktree_get_gotconfig(worktree);
2337 if (worktree_conf) {
2338 got_gotconfig_get_remotes(&nremotes, &remotes,
2339 worktree_conf);
2340 for (i = 0; i < nremotes; i++) {
2341 if (strcmp(remotes[i].name, remote_name) == 0) {
2342 remote = &remotes[i];
2343 break;
2348 if (remote == NULL) {
2349 repo_conf = got_repo_get_gotconfig(repo);
2350 if (repo_conf) {
2351 got_gotconfig_get_remotes(&nremotes, &remotes,
2352 repo_conf);
2353 for (i = 0; i < nremotes; i++) {
2354 if (strcmp(remotes[i].name, remote_name) == 0) {
2355 remote = &remotes[i];
2356 break;
2361 if (remote == NULL) {
2362 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2363 for (i = 0; i < nremotes; i++) {
2364 if (strcmp(remotes[i].name, remote_name) == 0) {
2365 remote = &remotes[i];
2366 break;
2370 if (remote == NULL) {
2371 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2372 goto done;
2375 if (TAILQ_EMPTY(&wanted_branches)) {
2376 if (!fetch_all_branches)
2377 fetch_all_branches = remote->fetch_all_branches;
2378 for (i = 0; i < remote->nfetch_branches; i++) {
2379 got_pathlist_append(&wanted_branches,
2380 remote->fetch_branches[i], NULL);
2383 if (TAILQ_EMPTY(&wanted_refs)) {
2384 for (i = 0; i < remote->nfetch_refs; i++) {
2385 got_pathlist_append(&wanted_refs,
2386 remote->fetch_refs[i], NULL);
2390 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2391 &repo_name, remote->fetch_url);
2392 if (error)
2393 goto done;
2395 if (strcmp(proto, "git") == 0) {
2396 #ifndef PROFILE
2397 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2398 "sendfd dns inet unveil", NULL) == -1)
2399 err(1, "pledge");
2400 #endif
2401 } else if (strcmp(proto, "git+ssh") == 0 ||
2402 strcmp(proto, "ssh") == 0) {
2403 #ifndef PROFILE
2404 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2405 "sendfd unveil", NULL) == -1)
2406 err(1, "pledge");
2407 #endif
2408 } else if (strcmp(proto, "http") == 0 ||
2409 strcmp(proto, "git+http") == 0) {
2410 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2411 goto done;
2412 } else {
2413 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2414 goto done;
2417 error = got_dial_apply_unveil(proto);
2418 if (error)
2419 goto done;
2421 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2422 if (error)
2423 goto done;
2425 if (verbosity >= 0)
2426 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2427 port ? ":" : "", port ? port : "");
2429 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2430 server_path, verbosity);
2431 if (error)
2432 goto done;
2434 fpa.last_scaled_size[0] = '\0';
2435 fpa.last_p_indexed = -1;
2436 fpa.last_p_resolved = -1;
2437 fpa.verbosity = verbosity;
2438 fpa.repo = repo;
2439 fpa.create_configs = 0;
2440 fpa.configs_created = 0;
2441 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2442 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2443 remote->mirror_references, fetch_all_branches, &wanted_branches,
2444 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2445 fetch_progress, &fpa);
2446 if (error)
2447 goto done;
2449 if (list_refs_only) {
2450 error = list_remote_refs(&symrefs, &refs);
2451 goto done;
2454 if (pack_hash == NULL) {
2455 if (verbosity >= 0)
2456 printf("Already up-to-date\n");
2457 } else if (verbosity >= 0) {
2458 error = got_object_id_str(&id_str, pack_hash);
2459 if (error)
2460 goto done;
2461 printf("\nFetched %s.pack\n", id_str);
2462 free(id_str);
2463 id_str = NULL;
2466 /* Update references provided with the pack file. */
2467 TAILQ_FOREACH(pe, &refs, entry) {
2468 const char *refname = pe->path;
2469 struct got_object_id *id = pe->data;
2470 struct got_reference *ref;
2471 char *remote_refname;
2473 if (is_wanted_ref(&wanted_refs, refname) &&
2474 !remote->mirror_references) {
2475 error = update_wanted_ref(refname, id,
2476 remote->name, verbosity, repo);
2477 if (error)
2478 goto done;
2479 continue;
2482 if (remote->mirror_references ||
2483 strncmp("refs/tags/", refname, 10) == 0) {
2484 error = got_ref_open(&ref, repo, refname, 1);
2485 if (error) {
2486 if (error->code != GOT_ERR_NOT_REF)
2487 goto done;
2488 error = create_ref(refname, id, verbosity,
2489 repo);
2490 if (error)
2491 goto done;
2492 } else {
2493 error = update_ref(ref, id, replace_tags,
2494 verbosity, repo);
2495 unlock_err = got_ref_unlock(ref);
2496 if (unlock_err && error == NULL)
2497 error = unlock_err;
2498 got_ref_close(ref);
2499 if (error)
2500 goto done;
2502 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2503 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2504 remote_name, refname + 11) == -1) {
2505 error = got_error_from_errno("asprintf");
2506 goto done;
2509 error = got_ref_open(&ref, repo, remote_refname, 1);
2510 if (error) {
2511 if (error->code != GOT_ERR_NOT_REF)
2512 goto done;
2513 error = create_ref(remote_refname, id,
2514 verbosity, repo);
2515 if (error)
2516 goto done;
2517 } else {
2518 error = update_ref(ref, id, replace_tags,
2519 verbosity, repo);
2520 unlock_err = got_ref_unlock(ref);
2521 if (unlock_err && error == NULL)
2522 error = unlock_err;
2523 got_ref_close(ref);
2524 if (error)
2525 goto done;
2528 /* Also create a local branch if none exists yet. */
2529 error = got_ref_open(&ref, repo, refname, 1);
2530 if (error) {
2531 if (error->code != GOT_ERR_NOT_REF)
2532 goto done;
2533 error = create_ref(refname, id, verbosity,
2534 repo);
2535 if (error)
2536 goto done;
2537 } else {
2538 unlock_err = got_ref_unlock(ref);
2539 if (unlock_err && error == NULL)
2540 error = unlock_err;
2541 got_ref_close(ref);
2545 if (delete_refs) {
2546 error = delete_missing_refs(&refs, &symrefs, remote,
2547 verbosity, repo);
2548 if (error)
2549 goto done;
2552 if (!remote->mirror_references) {
2553 /* Update remote HEAD reference if the server provided one. */
2554 TAILQ_FOREACH(pe, &symrefs, entry) {
2555 struct got_reference *target_ref;
2556 const char *refname = pe->path;
2557 const char *target = pe->data;
2558 char *remote_refname = NULL, *remote_target = NULL;
2560 if (strcmp(refname, GOT_REF_HEAD) != 0)
2561 continue;
2563 if (strncmp("refs/heads/", target, 11) != 0)
2564 continue;
2566 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2567 remote->name, refname) == -1) {
2568 error = got_error_from_errno("asprintf");
2569 goto done;
2571 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2572 remote->name, target + 11) == -1) {
2573 error = got_error_from_errno("asprintf");
2574 free(remote_refname);
2575 goto done;
2578 error = got_ref_open(&target_ref, repo, remote_target,
2579 0);
2580 if (error) {
2581 free(remote_refname);
2582 free(remote_target);
2583 if (error->code == GOT_ERR_NOT_REF) {
2584 error = NULL;
2585 continue;
2587 goto done;
2589 error = update_symref(remote_refname, target_ref,
2590 verbosity, repo);
2591 free(remote_refname);
2592 free(remote_target);
2593 got_ref_close(target_ref);
2594 if (error)
2595 goto done;
2598 done:
2599 if (fetchpid > 0) {
2600 if (kill(fetchpid, SIGTERM) == -1)
2601 error = got_error_from_errno("kill");
2602 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2603 error = got_error_from_errno("waitpid");
2605 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2606 error = got_error_from_errno("close");
2607 if (repo) {
2608 const struct got_error *close_err = got_repo_close(repo);
2609 if (error == NULL)
2610 error = close_err;
2612 if (worktree)
2613 got_worktree_close(worktree);
2614 TAILQ_FOREACH(pe, &refs, entry) {
2615 free((void *)pe->path);
2616 free(pe->data);
2618 got_pathlist_free(&refs);
2619 TAILQ_FOREACH(pe, &symrefs, entry) {
2620 free((void *)pe->path);
2621 free(pe->data);
2623 got_pathlist_free(&symrefs);
2624 got_pathlist_free(&wanted_branches);
2625 got_pathlist_free(&wanted_refs);
2626 free(id_str);
2627 free(cwd);
2628 free(repo_path);
2629 free(pack_hash);
2630 free(proto);
2631 free(host);
2632 free(port);
2633 free(server_path);
2634 free(repo_name);
2635 return error;
2639 __dead static void
2640 usage_checkout(void)
2642 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2643 "[-p prefix] [-q] repository-path [worktree-path]\n",
2644 getprogname());
2645 exit(1);
2648 static void
2649 show_worktree_base_ref_warning(void)
2651 fprintf(stderr, "%s: warning: could not create a reference "
2652 "to the work tree's base commit; the commit could be "
2653 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2654 "repository writable and running 'got update' will prevent this\n",
2655 getprogname());
2658 struct got_checkout_progress_arg {
2659 const char *worktree_path;
2660 int had_base_commit_ref_error;
2661 int verbosity;
2664 static const struct got_error *
2665 checkout_progress(void *arg, unsigned char status, const char *path)
2667 struct got_checkout_progress_arg *a = arg;
2669 /* Base commit bump happens silently. */
2670 if (status == GOT_STATUS_BUMP_BASE)
2671 return NULL;
2673 if (status == GOT_STATUS_BASE_REF_ERR) {
2674 a->had_base_commit_ref_error = 1;
2675 return NULL;
2678 while (path[0] == '/')
2679 path++;
2681 if (a->verbosity >= 0)
2682 printf("%c %s/%s\n", status, a->worktree_path, path);
2684 return NULL;
2687 static const struct got_error *
2688 check_cancelled(void *arg)
2690 if (sigint_received || sigpipe_received)
2691 return got_error(GOT_ERR_CANCELLED);
2692 return NULL;
2695 static const struct got_error *
2696 check_linear_ancestry(struct got_object_id *commit_id,
2697 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2698 struct got_repository *repo)
2700 const struct got_error *err = NULL;
2701 struct got_object_id *yca_id;
2703 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2704 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2705 if (err)
2706 return err;
2708 if (yca_id == NULL)
2709 return got_error(GOT_ERR_ANCESTRY);
2712 * Require a straight line of history between the target commit
2713 * and the work tree's base commit.
2715 * Non-linear situations such as this require a rebase:
2717 * (commit) D F (base_commit)
2718 * \ /
2719 * C E
2720 * \ /
2721 * B (yca)
2722 * |
2723 * A
2725 * 'got update' only handles linear cases:
2726 * Update forwards in time: A (base/yca) - B - C - D (commit)
2727 * Update backwards in time: D (base) - C - B - A (commit/yca)
2729 if (allow_forwards_in_time_only) {
2730 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2731 return got_error(GOT_ERR_ANCESTRY);
2732 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2733 got_object_id_cmp(base_commit_id, yca_id) != 0)
2734 return got_error(GOT_ERR_ANCESTRY);
2736 free(yca_id);
2737 return NULL;
2740 static const struct got_error *
2741 check_same_branch(struct got_object_id *commit_id,
2742 struct got_reference *head_ref, struct got_object_id *yca_id,
2743 struct got_repository *repo)
2745 const struct got_error *err = NULL;
2746 struct got_commit_graph *graph = NULL;
2747 struct got_object_id *head_commit_id = NULL;
2748 int is_same_branch = 0;
2750 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2751 if (err)
2752 goto done;
2754 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2755 is_same_branch = 1;
2756 goto done;
2758 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2759 is_same_branch = 1;
2760 goto done;
2763 err = got_commit_graph_open(&graph, "/", 1);
2764 if (err)
2765 goto done;
2767 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2768 check_cancelled, NULL);
2769 if (err)
2770 goto done;
2772 for (;;) {
2773 struct got_object_id *id;
2774 err = got_commit_graph_iter_next(&id, graph, repo,
2775 check_cancelled, NULL);
2776 if (err) {
2777 if (err->code == GOT_ERR_ITER_COMPLETED)
2778 err = NULL;
2779 break;
2782 if (id) {
2783 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2784 break;
2785 if (got_object_id_cmp(id, commit_id) == 0) {
2786 is_same_branch = 1;
2787 break;
2791 done:
2792 if (graph)
2793 got_commit_graph_close(graph);
2794 free(head_commit_id);
2795 if (!err && !is_same_branch)
2796 err = got_error(GOT_ERR_ANCESTRY);
2797 return err;
2800 static const struct got_error *
2801 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2803 static char msg[512];
2804 const char *branch_name;
2806 if (got_ref_is_symbolic(ref))
2807 branch_name = got_ref_get_symref_target(ref);
2808 else
2809 branch_name = got_ref_get_name(ref);
2811 if (strncmp("refs/heads/", branch_name, 11) == 0)
2812 branch_name += 11;
2814 snprintf(msg, sizeof(msg),
2815 "target commit is not contained in branch '%s'; "
2816 "the branch to use must be specified with -b; "
2817 "if necessary a new branch can be created for "
2818 "this commit with 'got branch -c %s BRANCH_NAME'",
2819 branch_name, commit_id_str);
2821 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2824 static const struct got_error *
2825 cmd_checkout(int argc, char *argv[])
2827 const struct got_error *error = NULL;
2828 struct got_repository *repo = NULL;
2829 struct got_reference *head_ref = NULL, *ref = NULL;
2830 struct got_worktree *worktree = NULL;
2831 char *repo_path = NULL;
2832 char *worktree_path = NULL;
2833 const char *path_prefix = "";
2834 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2835 char *commit_id_str = NULL;
2836 struct got_object_id *commit_id = NULL;
2837 char *cwd = NULL;
2838 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2839 struct got_pathlist_head paths;
2840 struct got_checkout_progress_arg cpa;
2842 TAILQ_INIT(&paths);
2844 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2845 switch (ch) {
2846 case 'b':
2847 branch_name = optarg;
2848 break;
2849 case 'c':
2850 commit_id_str = strdup(optarg);
2851 if (commit_id_str == NULL)
2852 return got_error_from_errno("strdup");
2853 break;
2854 case 'E':
2855 allow_nonempty = 1;
2856 break;
2857 case 'p':
2858 path_prefix = optarg;
2859 break;
2860 case 'q':
2861 verbosity = -1;
2862 break;
2863 default:
2864 usage_checkout();
2865 /* NOTREACHED */
2869 argc -= optind;
2870 argv += optind;
2872 #ifndef PROFILE
2873 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2874 "unveil", NULL) == -1)
2875 err(1, "pledge");
2876 #endif
2877 if (argc == 1) {
2878 char *base, *dotgit;
2879 const char *path;
2880 repo_path = realpath(argv[0], NULL);
2881 if (repo_path == NULL)
2882 return got_error_from_errno2("realpath", argv[0]);
2883 cwd = getcwd(NULL, 0);
2884 if (cwd == NULL) {
2885 error = got_error_from_errno("getcwd");
2886 goto done;
2888 if (path_prefix[0])
2889 path = path_prefix;
2890 else
2891 path = repo_path;
2892 error = got_path_basename(&base, path);
2893 if (error)
2894 goto done;
2895 dotgit = strstr(base, ".git");
2896 if (dotgit)
2897 *dotgit = '\0';
2898 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2899 error = got_error_from_errno("asprintf");
2900 free(base);
2901 goto done;
2903 free(base);
2904 } else if (argc == 2) {
2905 repo_path = realpath(argv[0], NULL);
2906 if (repo_path == NULL) {
2907 error = got_error_from_errno2("realpath", argv[0]);
2908 goto done;
2910 worktree_path = realpath(argv[1], NULL);
2911 if (worktree_path == NULL) {
2912 if (errno != ENOENT) {
2913 error = got_error_from_errno2("realpath",
2914 argv[1]);
2915 goto done;
2917 worktree_path = strdup(argv[1]);
2918 if (worktree_path == NULL) {
2919 error = got_error_from_errno("strdup");
2920 goto done;
2923 } else
2924 usage_checkout();
2926 got_path_strip_trailing_slashes(repo_path);
2927 got_path_strip_trailing_slashes(worktree_path);
2929 error = got_repo_open(&repo, repo_path, NULL);
2930 if (error != NULL)
2931 goto done;
2933 /* Pre-create work tree path for unveil(2) */
2934 error = got_path_mkdir(worktree_path);
2935 if (error) {
2936 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2937 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2938 goto done;
2939 if (!allow_nonempty &&
2940 !got_path_dir_is_empty(worktree_path)) {
2941 error = got_error_path(worktree_path,
2942 GOT_ERR_DIR_NOT_EMPTY);
2943 goto done;
2947 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2948 if (error)
2949 goto done;
2951 error = got_ref_open(&head_ref, repo, branch_name, 0);
2952 if (error != NULL)
2953 goto done;
2955 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2956 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2957 goto done;
2959 error = got_worktree_open(&worktree, worktree_path);
2960 if (error != NULL)
2961 goto done;
2963 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2964 path_prefix);
2965 if (error != NULL)
2966 goto done;
2967 if (!same_path_prefix) {
2968 error = got_error(GOT_ERR_PATH_PREFIX);
2969 goto done;
2972 if (commit_id_str) {
2973 struct got_reflist_head refs;
2974 TAILQ_INIT(&refs);
2975 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2976 NULL);
2977 if (error)
2978 goto done;
2979 error = got_repo_match_object_id(&commit_id, NULL,
2980 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2981 got_ref_list_free(&refs);
2982 if (error)
2983 goto done;
2984 error = check_linear_ancestry(commit_id,
2985 got_worktree_get_base_commit_id(worktree), 0, repo);
2986 if (error != NULL) {
2987 free(commit_id);
2988 if (error->code == GOT_ERR_ANCESTRY) {
2989 error = checkout_ancestry_error(
2990 head_ref, commit_id_str);
2992 goto done;
2994 error = check_same_branch(commit_id, head_ref, NULL, repo);
2995 if (error) {
2996 if (error->code == GOT_ERR_ANCESTRY) {
2997 error = checkout_ancestry_error(
2998 head_ref, commit_id_str);
3000 goto done;
3002 error = got_worktree_set_base_commit_id(worktree, repo,
3003 commit_id);
3004 if (error)
3005 goto done;
3006 /* Expand potentially abbreviated commit ID string. */
3007 free(commit_id_str);
3008 error = got_object_id_str(&commit_id_str, commit_id);
3009 if (error)
3010 goto done;
3011 } else {
3012 commit_id = got_object_id_dup(
3013 got_worktree_get_base_commit_id(worktree));
3014 if (commit_id == NULL) {
3015 error = got_error_from_errno("got_object_id_dup");
3016 goto done;
3018 error = got_object_id_str(&commit_id_str, commit_id);
3019 if (error)
3020 goto done;
3023 error = got_pathlist_append(&paths, "", NULL);
3024 if (error)
3025 goto done;
3026 cpa.worktree_path = worktree_path;
3027 cpa.had_base_commit_ref_error = 0;
3028 cpa.verbosity = verbosity;
3029 error = got_worktree_checkout_files(worktree, &paths, repo,
3030 checkout_progress, &cpa, check_cancelled, NULL);
3031 if (error != NULL)
3032 goto done;
3034 if (got_ref_is_symbolic(head_ref)) {
3035 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3036 if (error)
3037 goto done;
3038 refname = got_ref_get_name(ref);
3039 } else
3040 refname = got_ref_get_name(head_ref);
3041 printf("Checked out %s: %s\n", refname, commit_id_str);
3042 printf("Now shut up and hack\n");
3043 if (cpa.had_base_commit_ref_error)
3044 show_worktree_base_ref_warning();
3045 done:
3046 if (head_ref)
3047 got_ref_close(head_ref);
3048 if (ref)
3049 got_ref_close(ref);
3050 got_pathlist_free(&paths);
3051 free(commit_id_str);
3052 free(commit_id);
3053 free(repo_path);
3054 free(worktree_path);
3055 free(cwd);
3056 return error;
3059 struct got_update_progress_arg {
3060 int did_something;
3061 int conflicts;
3062 int obstructed;
3063 int not_updated;
3064 int missing;
3065 int not_deleted;
3066 int unversioned;
3067 int verbosity;
3070 void
3071 print_update_progress_stats(struct got_update_progress_arg *upa)
3073 if (!upa->did_something)
3074 return;
3076 if (upa->conflicts > 0)
3077 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3078 if (upa->obstructed > 0)
3079 printf("File paths obstructed by a non-regular file: %d\n",
3080 upa->obstructed);
3081 if (upa->not_updated > 0)
3082 printf("Files not updated because of existing merge "
3083 "conflicts: %d\n", upa->not_updated);
3087 * The meaning of some status codes differs between merge-style operations and
3088 * update operations. For example, the ! status code means "file was missing"
3089 * if changes were merged into the work tree, and "missing file was restored"
3090 * if the work tree was updated. This function should be used by any operation
3091 * which merges changes into the work tree without updating the work tree.
3093 void
3094 print_merge_progress_stats(struct got_update_progress_arg *upa)
3096 if (!upa->did_something)
3097 return;
3099 if (upa->conflicts > 0)
3100 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3101 if (upa->obstructed > 0)
3102 printf("File paths obstructed by a non-regular file: %d\n",
3103 upa->obstructed);
3104 if (upa->missing > 0)
3105 printf("Files which had incoming changes but could not be "
3106 "found in the work tree: %d\n", upa->missing);
3107 if (upa->not_deleted > 0)
3108 printf("Files not deleted due to differences in deleted "
3109 "content: %d\n", upa->not_deleted);
3110 if (upa->unversioned > 0)
3111 printf("Files not merged because an unversioned file was "
3112 "found in the work tree: %d\n", upa->unversioned);
3115 __dead static void
3116 usage_update(void)
3118 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3119 "[path ...]\n",
3120 getprogname());
3121 exit(1);
3124 static const struct got_error *
3125 update_progress(void *arg, unsigned char status, const char *path)
3127 struct got_update_progress_arg *upa = arg;
3129 if (status == GOT_STATUS_EXISTS ||
3130 status == GOT_STATUS_BASE_REF_ERR)
3131 return NULL;
3133 upa->did_something = 1;
3135 /* Base commit bump happens silently. */
3136 if (status == GOT_STATUS_BUMP_BASE)
3137 return NULL;
3139 if (status == GOT_STATUS_CONFLICT)
3140 upa->conflicts++;
3141 if (status == GOT_STATUS_OBSTRUCTED)
3142 upa->obstructed++;
3143 if (status == GOT_STATUS_CANNOT_UPDATE)
3144 upa->not_updated++;
3145 if (status == GOT_STATUS_MISSING)
3146 upa->missing++;
3147 if (status == GOT_STATUS_CANNOT_DELETE)
3148 upa->not_deleted++;
3149 if (status == GOT_STATUS_UNVERSIONED)
3150 upa->unversioned++;
3152 while (path[0] == '/')
3153 path++;
3154 if (upa->verbosity >= 0)
3155 printf("%c %s\n", status, path);
3157 return NULL;
3160 static const struct got_error *
3161 switch_head_ref(struct got_reference *head_ref,
3162 struct got_object_id *commit_id, struct got_worktree *worktree,
3163 struct got_repository *repo)
3165 const struct got_error *err = NULL;
3166 char *base_id_str;
3167 int ref_has_moved = 0;
3169 /* Trivial case: switching between two different references. */
3170 if (strcmp(got_ref_get_name(head_ref),
3171 got_worktree_get_head_ref_name(worktree)) != 0) {
3172 printf("Switching work tree from %s to %s\n",
3173 got_worktree_get_head_ref_name(worktree),
3174 got_ref_get_name(head_ref));
3175 return got_worktree_set_head_ref(worktree, head_ref);
3178 err = check_linear_ancestry(commit_id,
3179 got_worktree_get_base_commit_id(worktree), 0, repo);
3180 if (err) {
3181 if (err->code != GOT_ERR_ANCESTRY)
3182 return err;
3183 ref_has_moved = 1;
3185 if (!ref_has_moved)
3186 return NULL;
3188 /* Switching to a rebased branch with the same reference name. */
3189 err = got_object_id_str(&base_id_str,
3190 got_worktree_get_base_commit_id(worktree));
3191 if (err)
3192 return err;
3193 printf("Reference %s now points at a different branch\n",
3194 got_worktree_get_head_ref_name(worktree));
3195 printf("Switching work tree from %s to %s\n", base_id_str,
3196 got_worktree_get_head_ref_name(worktree));
3197 return NULL;
3200 static const struct got_error *
3201 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3203 const struct got_error *err;
3204 int in_progress;
3206 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3207 if (err)
3208 return err;
3209 if (in_progress)
3210 return got_error(GOT_ERR_REBASING);
3212 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3213 if (err)
3214 return err;
3215 if (in_progress)
3216 return got_error(GOT_ERR_HISTEDIT_BUSY);
3218 return NULL;
3221 static const struct got_error *
3222 check_merge_in_progress(struct got_worktree *worktree,
3223 struct got_repository *repo)
3225 const struct got_error *err;
3226 int in_progress;
3228 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3229 if (err)
3230 return err;
3231 if (in_progress)
3232 return got_error(GOT_ERR_MERGE_BUSY);
3234 return NULL;
3237 static const struct got_error *
3238 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3239 char *argv[], struct got_worktree *worktree)
3241 const struct got_error *err = NULL;
3242 char *path;
3243 int i;
3245 if (argc == 0) {
3246 path = strdup("");
3247 if (path == NULL)
3248 return got_error_from_errno("strdup");
3249 return got_pathlist_append(paths, path, NULL);
3252 for (i = 0; i < argc; i++) {
3253 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3254 if (err)
3255 break;
3256 err = got_pathlist_append(paths, path, NULL);
3257 if (err) {
3258 free(path);
3259 break;
3263 return err;
3266 static const struct got_error *
3267 wrap_not_worktree_error(const struct got_error *orig_err,
3268 const char *cmdname, const char *path)
3270 const struct got_error *err;
3271 struct got_repository *repo;
3272 static char msg[512];
3274 err = got_repo_open(&repo, path, NULL);
3275 if (err)
3276 return orig_err;
3278 snprintf(msg, sizeof(msg),
3279 "'got %s' needs a work tree in addition to a git repository\n"
3280 "Work trees can be checked out from this Git repository with "
3281 "'got checkout'.\n"
3282 "The got(1) manual page contains more information.", cmdname);
3283 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3284 got_repo_close(repo);
3285 return err;
3288 static const struct got_error *
3289 cmd_update(int argc, char *argv[])
3291 const struct got_error *error = NULL;
3292 struct got_repository *repo = NULL;
3293 struct got_worktree *worktree = NULL;
3294 char *worktree_path = NULL;
3295 struct got_object_id *commit_id = NULL;
3296 char *commit_id_str = NULL;
3297 const char *branch_name = NULL;
3298 struct got_reference *head_ref = NULL;
3299 struct got_pathlist_head paths;
3300 struct got_pathlist_entry *pe;
3301 int ch, verbosity = 0;
3302 struct got_update_progress_arg upa;
3304 TAILQ_INIT(&paths);
3306 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3307 switch (ch) {
3308 case 'b':
3309 branch_name = optarg;
3310 break;
3311 case 'c':
3312 commit_id_str = strdup(optarg);
3313 if (commit_id_str == NULL)
3314 return got_error_from_errno("strdup");
3315 break;
3316 case 'q':
3317 verbosity = -1;
3318 break;
3319 default:
3320 usage_update();
3321 /* NOTREACHED */
3325 argc -= optind;
3326 argv += optind;
3328 #ifndef PROFILE
3329 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3330 "unveil", NULL) == -1)
3331 err(1, "pledge");
3332 #endif
3333 worktree_path = getcwd(NULL, 0);
3334 if (worktree_path == NULL) {
3335 error = got_error_from_errno("getcwd");
3336 goto done;
3338 error = got_worktree_open(&worktree, worktree_path);
3339 if (error) {
3340 if (error->code == GOT_ERR_NOT_WORKTREE)
3341 error = wrap_not_worktree_error(error, "update",
3342 worktree_path);
3343 goto done;
3346 error = check_rebase_or_histedit_in_progress(worktree);
3347 if (error)
3348 goto done;
3350 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3351 NULL);
3352 if (error != NULL)
3353 goto done;
3355 error = apply_unveil(got_repo_get_path(repo), 0,
3356 got_worktree_get_root_path(worktree));
3357 if (error)
3358 goto done;
3360 error = check_merge_in_progress(worktree, repo);
3361 if (error)
3362 goto done;
3364 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3365 if (error)
3366 goto done;
3368 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3369 got_worktree_get_head_ref_name(worktree), 0);
3370 if (error != NULL)
3371 goto done;
3372 if (commit_id_str == NULL) {
3373 error = got_ref_resolve(&commit_id, repo, head_ref);
3374 if (error != NULL)
3375 goto done;
3376 error = got_object_id_str(&commit_id_str, commit_id);
3377 if (error != NULL)
3378 goto done;
3379 } else {
3380 struct got_reflist_head refs;
3381 TAILQ_INIT(&refs);
3382 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3383 NULL);
3384 if (error)
3385 goto done;
3386 error = got_repo_match_object_id(&commit_id, NULL,
3387 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3388 got_ref_list_free(&refs);
3389 free(commit_id_str);
3390 commit_id_str = NULL;
3391 if (error)
3392 goto done;
3393 error = got_object_id_str(&commit_id_str, commit_id);
3394 if (error)
3395 goto done;
3398 if (branch_name) {
3399 struct got_object_id *head_commit_id;
3400 TAILQ_FOREACH(pe, &paths, entry) {
3401 if (pe->path_len == 0)
3402 continue;
3403 error = got_error_msg(GOT_ERR_BAD_PATH,
3404 "switching between branches requires that "
3405 "the entire work tree gets updated");
3406 goto done;
3408 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3409 if (error)
3410 goto done;
3411 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3412 repo);
3413 free(head_commit_id);
3414 if (error != NULL)
3415 goto done;
3416 error = check_same_branch(commit_id, head_ref, NULL, repo);
3417 if (error)
3418 goto done;
3419 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3420 if (error)
3421 goto done;
3422 } else {
3423 error = check_linear_ancestry(commit_id,
3424 got_worktree_get_base_commit_id(worktree), 0, repo);
3425 if (error != NULL) {
3426 if (error->code == GOT_ERR_ANCESTRY)
3427 error = got_error(GOT_ERR_BRANCH_MOVED);
3428 goto done;
3430 error = check_same_branch(commit_id, head_ref, NULL, repo);
3431 if (error)
3432 goto done;
3435 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3436 commit_id) != 0) {
3437 error = got_worktree_set_base_commit_id(worktree, repo,
3438 commit_id);
3439 if (error)
3440 goto done;
3443 memset(&upa, 0, sizeof(upa));
3444 upa.verbosity = verbosity;
3445 error = got_worktree_checkout_files(worktree, &paths, repo,
3446 update_progress, &upa, check_cancelled, NULL);
3447 if (error != NULL)
3448 goto done;
3450 if (upa.did_something) {
3451 printf("Updated to %s: %s\n",
3452 got_worktree_get_head_ref_name(worktree), commit_id_str);
3453 } else
3454 printf("Already up-to-date\n");
3455 print_update_progress_stats(&upa);
3456 done:
3457 free(worktree_path);
3458 TAILQ_FOREACH(pe, &paths, entry)
3459 free((char *)pe->path);
3460 got_pathlist_free(&paths);
3461 free(commit_id);
3462 free(commit_id_str);
3463 return error;
3466 static const struct got_error *
3467 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3468 const char *path, int diff_context, int ignore_whitespace,
3469 int force_text_diff, struct got_repository *repo)
3471 const struct got_error *err = NULL;
3472 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3474 if (blob_id1) {
3475 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3476 if (err)
3477 goto done;
3480 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3481 if (err)
3482 goto done;
3484 while (path[0] == '/')
3485 path++;
3486 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3487 diff_context, ignore_whitespace, force_text_diff, stdout);
3488 done:
3489 if (blob1)
3490 got_object_blob_close(blob1);
3491 got_object_blob_close(blob2);
3492 return err;
3495 static const struct got_error *
3496 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3497 const char *path, int diff_context, int ignore_whitespace,
3498 int force_text_diff, struct got_repository *repo)
3500 const struct got_error *err = NULL;
3501 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3502 struct got_diff_blob_output_unidiff_arg arg;
3504 if (tree_id1) {
3505 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3506 if (err)
3507 goto done;
3510 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3511 if (err)
3512 goto done;
3514 arg.diff_context = diff_context;
3515 arg.ignore_whitespace = ignore_whitespace;
3516 arg.force_text_diff = force_text_diff;
3517 arg.outfile = stdout;
3518 arg.line_offsets = NULL;
3519 arg.nlines = 0;
3520 while (path[0] == '/')
3521 path++;
3522 err = got_diff_tree(tree1, tree2, path, path, repo,
3523 got_diff_blob_output_unidiff, &arg, 1);
3524 done:
3525 if (tree1)
3526 got_object_tree_close(tree1);
3527 if (tree2)
3528 got_object_tree_close(tree2);
3529 return err;
3532 static const struct got_error *
3533 get_changed_paths(struct got_pathlist_head *paths,
3534 struct got_commit_object *commit, struct got_repository *repo)
3536 const struct got_error *err = NULL;
3537 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3538 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3539 struct got_object_qid *qid;
3541 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3542 if (qid != NULL) {
3543 struct got_commit_object *pcommit;
3544 err = got_object_open_as_commit(&pcommit, repo,
3545 qid->id);
3546 if (err)
3547 return err;
3549 tree_id1 = got_object_id_dup(
3550 got_object_commit_get_tree_id(pcommit));
3551 if (tree_id1 == NULL) {
3552 got_object_commit_close(pcommit);
3553 return got_error_from_errno("got_object_id_dup");
3555 got_object_commit_close(pcommit);
3559 if (tree_id1) {
3560 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3561 if (err)
3562 goto done;
3565 tree_id2 = got_object_commit_get_tree_id(commit);
3566 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3567 if (err)
3568 goto done;
3570 err = got_diff_tree(tree1, tree2, "", "", repo,
3571 got_diff_tree_collect_changed_paths, paths, 0);
3572 done:
3573 if (tree1)
3574 got_object_tree_close(tree1);
3575 if (tree2)
3576 got_object_tree_close(tree2);
3577 free(tree_id1);
3578 return err;
3581 static const struct got_error *
3582 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3583 const char *path, int diff_context, struct got_repository *repo)
3585 const struct got_error *err = NULL;
3586 struct got_commit_object *pcommit = NULL;
3587 char *id_str1 = NULL, *id_str2 = NULL;
3588 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3589 struct got_object_qid *qid;
3591 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3592 if (qid != NULL) {
3593 err = got_object_open_as_commit(&pcommit, repo,
3594 qid->id);
3595 if (err)
3596 return err;
3599 if (path && path[0] != '\0') {
3600 int obj_type;
3601 err = got_object_id_by_path(&obj_id2, repo, id, path);
3602 if (err)
3603 goto done;
3604 err = got_object_id_str(&id_str2, obj_id2);
3605 if (err) {
3606 free(obj_id2);
3607 goto done;
3609 if (pcommit) {
3610 err = got_object_id_by_path(&obj_id1, repo,
3611 qid->id, path);
3612 if (err) {
3613 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3614 free(obj_id2);
3615 goto done;
3617 } else {
3618 err = got_object_id_str(&id_str1, obj_id1);
3619 if (err) {
3620 free(obj_id2);
3621 goto done;
3625 err = got_object_get_type(&obj_type, repo, obj_id2);
3626 if (err) {
3627 free(obj_id2);
3628 goto done;
3630 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3631 switch (obj_type) {
3632 case GOT_OBJ_TYPE_BLOB:
3633 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3634 0, 0, repo);
3635 break;
3636 case GOT_OBJ_TYPE_TREE:
3637 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3638 0, 0, repo);
3639 break;
3640 default:
3641 err = got_error(GOT_ERR_OBJ_TYPE);
3642 break;
3644 free(obj_id1);
3645 free(obj_id2);
3646 } else {
3647 obj_id2 = got_object_commit_get_tree_id(commit);
3648 err = got_object_id_str(&id_str2, obj_id2);
3649 if (err)
3650 goto done;
3651 if (pcommit) {
3652 obj_id1 = got_object_commit_get_tree_id(pcommit);
3653 err = got_object_id_str(&id_str1, obj_id1);
3654 if (err)
3655 goto done;
3657 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3658 id_str2);
3659 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3660 repo);
3662 done:
3663 free(id_str1);
3664 free(id_str2);
3665 if (pcommit)
3666 got_object_commit_close(pcommit);
3667 return err;
3670 static char *
3671 get_datestr(time_t *time, char *datebuf)
3673 struct tm mytm, *tm;
3674 char *p, *s;
3676 tm = gmtime_r(time, &mytm);
3677 if (tm == NULL)
3678 return NULL;
3679 s = asctime_r(tm, datebuf);
3680 if (s == NULL)
3681 return NULL;
3682 p = strchr(s, '\n');
3683 if (p)
3684 *p = '\0';
3685 return s;
3688 static const struct got_error *
3689 match_logmsg(int *have_match, struct got_object_id *id,
3690 struct got_commit_object *commit, regex_t *regex)
3692 const struct got_error *err = NULL;
3693 regmatch_t regmatch;
3694 char *id_str = NULL, *logmsg = NULL;
3696 *have_match = 0;
3698 err = got_object_id_str(&id_str, id);
3699 if (err)
3700 return err;
3702 err = got_object_commit_get_logmsg(&logmsg, commit);
3703 if (err)
3704 goto done;
3706 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3707 *have_match = 1;
3708 done:
3709 free(id_str);
3710 free(logmsg);
3711 return err;
3714 static void
3715 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3716 regex_t *regex)
3718 regmatch_t regmatch;
3719 struct got_pathlist_entry *pe;
3721 *have_match = 0;
3723 TAILQ_FOREACH(pe, changed_paths, entry) {
3724 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3725 *have_match = 1;
3726 break;
3731 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3733 static const struct got_error*
3734 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3735 struct got_object_id *id, struct got_repository *repo)
3737 static const struct got_error *err = NULL;
3738 struct got_reflist_entry *re;
3739 char *s;
3740 const char *name;
3742 *refs_str = NULL;
3744 TAILQ_FOREACH(re, refs, entry) {
3745 struct got_tag_object *tag = NULL;
3746 struct got_object_id *ref_id;
3747 int cmp;
3749 name = got_ref_get_name(re->ref);
3750 if (strcmp(name, GOT_REF_HEAD) == 0)
3751 continue;
3752 if (strncmp(name, "refs/", 5) == 0)
3753 name += 5;
3754 if (strncmp(name, "got/", 4) == 0)
3755 continue;
3756 if (strncmp(name, "heads/", 6) == 0)
3757 name += 6;
3758 if (strncmp(name, "remotes/", 8) == 0) {
3759 name += 8;
3760 s = strstr(name, "/" GOT_REF_HEAD);
3761 if (s != NULL && s[strlen(s)] == '\0')
3762 continue;
3764 err = got_ref_resolve(&ref_id, repo, re->ref);
3765 if (err)
3766 break;
3767 if (strncmp(name, "tags/", 5) == 0) {
3768 err = got_object_open_as_tag(&tag, repo, ref_id);
3769 if (err) {
3770 if (err->code != GOT_ERR_OBJ_TYPE) {
3771 free(ref_id);
3772 break;
3774 /* Ref points at something other than a tag. */
3775 err = NULL;
3776 tag = NULL;
3779 cmp = got_object_id_cmp(tag ?
3780 got_object_tag_get_object_id(tag) : ref_id, id);
3781 free(ref_id);
3782 if (tag)
3783 got_object_tag_close(tag);
3784 if (cmp != 0)
3785 continue;
3786 s = *refs_str;
3787 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3788 s ? ", " : "", name) == -1) {
3789 err = got_error_from_errno("asprintf");
3790 free(s);
3791 *refs_str = NULL;
3792 break;
3794 free(s);
3797 return err;
3800 static const struct got_error *
3801 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3802 struct got_repository *repo, const char *path,
3803 struct got_pathlist_head *changed_paths, int show_patch,
3804 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3805 const char *custom_refs_str)
3807 const struct got_error *err = NULL;
3808 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3809 char datebuf[26];
3810 time_t committer_time;
3811 const char *author, *committer;
3812 char *refs_str = NULL;
3814 err = got_object_id_str(&id_str, id);
3815 if (err)
3816 return err;
3818 if (custom_refs_str == NULL) {
3819 struct got_reflist_head *refs;
3820 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3821 if (refs) {
3822 err = build_refs_str(&refs_str, refs, id, repo);
3823 if (err)
3824 goto done;
3828 printf(GOT_COMMIT_SEP_STR);
3829 if (custom_refs_str)
3830 printf("commit %s (%s)\n", id_str, custom_refs_str);
3831 else
3832 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3833 refs_str ? refs_str : "", refs_str ? ")" : "");
3834 free(id_str);
3835 id_str = NULL;
3836 free(refs_str);
3837 refs_str = NULL;
3838 printf("from: %s\n", got_object_commit_get_author(commit));
3839 committer_time = got_object_commit_get_committer_time(commit);
3840 datestr = get_datestr(&committer_time, datebuf);
3841 if (datestr)
3842 printf("date: %s UTC\n", datestr);
3843 author = got_object_commit_get_author(commit);
3844 committer = got_object_commit_get_committer(commit);
3845 if (strcmp(author, committer) != 0)
3846 printf("via: %s\n", committer);
3847 if (got_object_commit_get_nparents(commit) > 1) {
3848 const struct got_object_id_queue *parent_ids;
3849 struct got_object_qid *qid;
3850 int n = 1;
3851 parent_ids = got_object_commit_get_parent_ids(commit);
3852 STAILQ_FOREACH(qid, parent_ids, entry) {
3853 err = got_object_id_str(&id_str, qid->id);
3854 if (err)
3855 goto done;
3856 printf("parent %d: %s\n", n++, id_str);
3857 free(id_str);
3858 id_str = NULL;
3862 err = got_object_commit_get_logmsg(&logmsg0, commit);
3863 if (err)
3864 goto done;
3866 logmsg = logmsg0;
3867 do {
3868 line = strsep(&logmsg, "\n");
3869 if (line)
3870 printf(" %s\n", line);
3871 } while (line);
3872 free(logmsg0);
3874 if (changed_paths) {
3875 struct got_pathlist_entry *pe;
3876 TAILQ_FOREACH(pe, changed_paths, entry) {
3877 struct got_diff_changed_path *cp = pe->data;
3878 printf(" %c %s\n", cp->status, pe->path);
3880 printf("\n");
3882 if (show_patch) {
3883 err = print_patch(commit, id, path, diff_context, repo);
3884 if (err == 0)
3885 printf("\n");
3888 if (fflush(stdout) != 0 && err == NULL)
3889 err = got_error_from_errno("fflush");
3890 done:
3891 free(id_str);
3892 free(refs_str);
3893 return err;
3896 static const struct got_error *
3897 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3898 struct got_repository *repo, const char *path, int show_changed_paths,
3899 int show_patch, const char *search_pattern, int diff_context, int limit,
3900 int log_branches, int reverse_display_order,
3901 struct got_reflist_object_id_map *refs_idmap)
3903 const struct got_error *err;
3904 struct got_commit_graph *graph;
3905 regex_t regex;
3906 int have_match;
3907 struct got_object_id_queue reversed_commits;
3908 struct got_object_qid *qid;
3909 struct got_commit_object *commit;
3910 struct got_pathlist_head changed_paths;
3911 struct got_pathlist_entry *pe;
3913 STAILQ_INIT(&reversed_commits);
3914 TAILQ_INIT(&changed_paths);
3916 if (search_pattern && regcomp(&regex, search_pattern,
3917 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3918 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3920 err = got_commit_graph_open(&graph, path, !log_branches);
3921 if (err)
3922 return err;
3923 err = got_commit_graph_iter_start(graph, root_id, repo,
3924 check_cancelled, NULL);
3925 if (err)
3926 goto done;
3927 for (;;) {
3928 struct got_object_id *id;
3930 if (sigint_received || sigpipe_received)
3931 break;
3933 err = got_commit_graph_iter_next(&id, graph, repo,
3934 check_cancelled, NULL);
3935 if (err) {
3936 if (err->code == GOT_ERR_ITER_COMPLETED)
3937 err = NULL;
3938 break;
3940 if (id == NULL)
3941 break;
3943 err = got_object_open_as_commit(&commit, repo, id);
3944 if (err)
3945 break;
3947 if (show_changed_paths && !reverse_display_order) {
3948 err = get_changed_paths(&changed_paths, commit, repo);
3949 if (err)
3950 break;
3953 if (search_pattern) {
3954 err = match_logmsg(&have_match, id, commit, &regex);
3955 if (err) {
3956 got_object_commit_close(commit);
3957 break;
3959 if (have_match == 0 && show_changed_paths)
3960 match_changed_paths(&have_match,
3961 &changed_paths, &regex);
3962 if (have_match == 0) {
3963 got_object_commit_close(commit);
3964 TAILQ_FOREACH(pe, &changed_paths, entry) {
3965 free((char *)pe->path);
3966 free(pe->data);
3968 got_pathlist_free(&changed_paths);
3969 continue;
3973 if (reverse_display_order) {
3974 err = got_object_qid_alloc(&qid, id);
3975 if (err)
3976 break;
3977 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3978 got_object_commit_close(commit);
3979 } else {
3980 err = print_commit(commit, id, repo, path,
3981 show_changed_paths ? &changed_paths : NULL,
3982 show_patch, diff_context, refs_idmap, NULL);
3983 got_object_commit_close(commit);
3984 if (err)
3985 break;
3987 if ((limit && --limit == 0) ||
3988 (end_id && got_object_id_cmp(id, end_id) == 0))
3989 break;
3991 TAILQ_FOREACH(pe, &changed_paths, entry) {
3992 free((char *)pe->path);
3993 free(pe->data);
3995 got_pathlist_free(&changed_paths);
3997 if (reverse_display_order) {
3998 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3999 err = got_object_open_as_commit(&commit, repo, qid->id);
4000 if (err)
4001 break;
4002 if (show_changed_paths) {
4003 err = get_changed_paths(&changed_paths,
4004 commit, repo);
4005 if (err)
4006 break;
4008 err = print_commit(commit, qid->id, repo, path,
4009 show_changed_paths ? &changed_paths : NULL,
4010 show_patch, diff_context, refs_idmap, NULL);
4011 got_object_commit_close(commit);
4012 if (err)
4013 break;
4014 TAILQ_FOREACH(pe, &changed_paths, entry) {
4015 free((char *)pe->path);
4016 free(pe->data);
4018 got_pathlist_free(&changed_paths);
4021 done:
4022 while (!STAILQ_EMPTY(&reversed_commits)) {
4023 qid = STAILQ_FIRST(&reversed_commits);
4024 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4025 got_object_qid_free(qid);
4027 TAILQ_FOREACH(pe, &changed_paths, entry) {
4028 free((char *)pe->path);
4029 free(pe->data);
4031 got_pathlist_free(&changed_paths);
4032 if (search_pattern)
4033 regfree(&regex);
4034 got_commit_graph_close(graph);
4035 return err;
4038 __dead static void
4039 usage_log(void)
4041 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4042 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4043 "[-R] [path]\n", getprogname());
4044 exit(1);
4047 static int
4048 get_default_log_limit(void)
4050 const char *got_default_log_limit;
4051 long long n;
4052 const char *errstr;
4054 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4055 if (got_default_log_limit == NULL)
4056 return 0;
4057 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4058 if (errstr != NULL)
4059 return 0;
4060 return n;
4063 static const struct got_error *
4064 cmd_log(int argc, char *argv[])
4066 const struct got_error *error;
4067 struct got_repository *repo = NULL;
4068 struct got_worktree *worktree = NULL;
4069 struct got_object_id *start_id = NULL, *end_id = NULL;
4070 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4071 const char *start_commit = NULL, *end_commit = NULL;
4072 const char *search_pattern = NULL;
4073 int diff_context = -1, ch;
4074 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4075 int reverse_display_order = 0;
4076 const char *errstr;
4077 struct got_reflist_head refs;
4078 struct got_reflist_object_id_map *refs_idmap = NULL;
4080 TAILQ_INIT(&refs);
4082 #ifndef PROFILE
4083 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4084 NULL)
4085 == -1)
4086 err(1, "pledge");
4087 #endif
4089 limit = get_default_log_limit();
4091 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4092 switch (ch) {
4093 case 'p':
4094 show_patch = 1;
4095 break;
4096 case 'P':
4097 show_changed_paths = 1;
4098 break;
4099 case 'c':
4100 start_commit = optarg;
4101 break;
4102 case 'C':
4103 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4104 &errstr);
4105 if (errstr != NULL)
4106 err(1, "-C option %s", errstr);
4107 break;
4108 case 'l':
4109 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4110 if (errstr != NULL)
4111 err(1, "-l option %s", errstr);
4112 break;
4113 case 'b':
4114 log_branches = 1;
4115 break;
4116 case 'r':
4117 repo_path = realpath(optarg, NULL);
4118 if (repo_path == NULL)
4119 return got_error_from_errno2("realpath",
4120 optarg);
4121 got_path_strip_trailing_slashes(repo_path);
4122 break;
4123 case 'R':
4124 reverse_display_order = 1;
4125 break;
4126 case 's':
4127 search_pattern = optarg;
4128 break;
4129 case 'x':
4130 end_commit = optarg;
4131 break;
4132 default:
4133 usage_log();
4134 /* NOTREACHED */
4138 argc -= optind;
4139 argv += optind;
4141 if (diff_context == -1)
4142 diff_context = 3;
4143 else if (!show_patch)
4144 errx(1, "-C requires -p");
4146 cwd = getcwd(NULL, 0);
4147 if (cwd == NULL) {
4148 error = got_error_from_errno("getcwd");
4149 goto done;
4152 if (repo_path == NULL) {
4153 error = got_worktree_open(&worktree, cwd);
4154 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4155 goto done;
4156 error = NULL;
4159 if (argc == 1) {
4160 if (worktree) {
4161 error = got_worktree_resolve_path(&path, worktree,
4162 argv[0]);
4163 if (error)
4164 goto done;
4165 } else {
4166 path = strdup(argv[0]);
4167 if (path == NULL) {
4168 error = got_error_from_errno("strdup");
4169 goto done;
4172 } else if (argc != 0)
4173 usage_log();
4175 if (repo_path == NULL) {
4176 repo_path = worktree ?
4177 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4179 if (repo_path == NULL) {
4180 error = got_error_from_errno("strdup");
4181 goto done;
4184 error = got_repo_open(&repo, repo_path, NULL);
4185 if (error != NULL)
4186 goto done;
4188 error = apply_unveil(got_repo_get_path(repo), 1,
4189 worktree ? got_worktree_get_root_path(worktree) : NULL);
4190 if (error)
4191 goto done;
4193 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4194 if (error)
4195 goto done;
4197 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4198 if (error)
4199 goto done;
4201 if (start_commit == NULL) {
4202 struct got_reference *head_ref;
4203 struct got_commit_object *commit = NULL;
4204 error = got_ref_open(&head_ref, repo,
4205 worktree ? got_worktree_get_head_ref_name(worktree)
4206 : GOT_REF_HEAD, 0);
4207 if (error != NULL)
4208 goto done;
4209 error = got_ref_resolve(&start_id, repo, head_ref);
4210 got_ref_close(head_ref);
4211 if (error != NULL)
4212 goto done;
4213 error = got_object_open_as_commit(&commit, repo,
4214 start_id);
4215 if (error != NULL)
4216 goto done;
4217 got_object_commit_close(commit);
4218 } else {
4219 error = got_repo_match_object_id(&start_id, NULL,
4220 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4221 if (error != NULL)
4222 goto done;
4224 if (end_commit != NULL) {
4225 error = got_repo_match_object_id(&end_id, NULL,
4226 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4227 if (error != NULL)
4228 goto done;
4231 if (worktree) {
4233 * If a path was specified on the command line it was resolved
4234 * to a path in the work tree above. Prepend the work tree's
4235 * path prefix to obtain the corresponding in-repository path.
4237 if (path) {
4238 const char *prefix;
4239 prefix = got_worktree_get_path_prefix(worktree);
4240 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4241 (path[0] != '\0') ? "/" : "", path) == -1) {
4242 error = got_error_from_errno("asprintf");
4243 goto done;
4246 } else
4247 error = got_repo_map_path(&in_repo_path, repo,
4248 path ? path : "");
4249 if (error != NULL)
4250 goto done;
4251 if (in_repo_path) {
4252 free(path);
4253 path = in_repo_path;
4256 error = print_commits(start_id, end_id, repo, path ? path : "",
4257 show_changed_paths, show_patch, search_pattern, diff_context,
4258 limit, log_branches, reverse_display_order, refs_idmap);
4259 done:
4260 free(path);
4261 free(repo_path);
4262 free(cwd);
4263 if (worktree)
4264 got_worktree_close(worktree);
4265 if (repo) {
4266 const struct got_error *close_err = got_repo_close(repo);
4267 if (error == NULL)
4268 error = close_err;
4270 if (refs_idmap)
4271 got_reflist_object_id_map_free(refs_idmap);
4272 got_ref_list_free(&refs);
4273 return error;
4276 __dead static void
4277 usage_diff(void)
4279 fprintf(stderr, "usage: %s diff [-a] [-c commit1] [-c commit2] "
4280 "[-C number] [-r repository-path] "
4281 "[-s] [-w] [-P] [object1 object2 | path ...]\n", getprogname());
4282 exit(1);
4285 struct print_diff_arg {
4286 struct got_repository *repo;
4287 struct got_worktree *worktree;
4288 int diff_context;
4289 const char *id_str;
4290 int header_shown;
4291 int diff_staged;
4292 int ignore_whitespace;
4293 int force_text_diff;
4297 * Create a file which contains the target path of a symlink so we can feed
4298 * it as content to the diff engine.
4300 static const struct got_error *
4301 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4302 const char *abspath)
4304 const struct got_error *err = NULL;
4305 char target_path[PATH_MAX];
4306 ssize_t target_len, outlen;
4308 *fd = -1;
4310 if (dirfd != -1) {
4311 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4312 if (target_len == -1)
4313 return got_error_from_errno2("readlinkat", abspath);
4314 } else {
4315 target_len = readlink(abspath, target_path, PATH_MAX);
4316 if (target_len == -1)
4317 return got_error_from_errno2("readlink", abspath);
4320 *fd = got_opentempfd();
4321 if (*fd == -1)
4322 return got_error_from_errno("got_opentempfd");
4324 outlen = write(*fd, target_path, target_len);
4325 if (outlen == -1) {
4326 err = got_error_from_errno("got_opentempfd");
4327 goto done;
4330 if (lseek(*fd, 0, SEEK_SET) == -1) {
4331 err = got_error_from_errno2("lseek", abspath);
4332 goto done;
4334 done:
4335 if (err) {
4336 close(*fd);
4337 *fd = -1;
4339 return err;
4342 static const struct got_error *
4343 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4344 const char *path, struct got_object_id *blob_id,
4345 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4346 int dirfd, const char *de_name)
4348 struct print_diff_arg *a = arg;
4349 const struct got_error *err = NULL;
4350 struct got_blob_object *blob1 = NULL;
4351 int fd = -1;
4352 FILE *f2 = NULL;
4353 char *abspath = NULL, *label1 = NULL;
4354 struct stat sb;
4356 if (a->diff_staged) {
4357 if (staged_status != GOT_STATUS_MODIFY &&
4358 staged_status != GOT_STATUS_ADD &&
4359 staged_status != GOT_STATUS_DELETE)
4360 return NULL;
4361 } else {
4362 if (staged_status == GOT_STATUS_DELETE)
4363 return NULL;
4364 if (status == GOT_STATUS_NONEXISTENT)
4365 return got_error_set_errno(ENOENT, path);
4366 if (status != GOT_STATUS_MODIFY &&
4367 status != GOT_STATUS_ADD &&
4368 status != GOT_STATUS_DELETE &&
4369 status != GOT_STATUS_CONFLICT)
4370 return NULL;
4373 if (!a->header_shown) {
4374 printf("diff %s %s%s\n", a->id_str,
4375 got_worktree_get_root_path(a->worktree),
4376 a->diff_staged ? " (staged changes)" : "");
4377 a->header_shown = 1;
4380 if (a->diff_staged) {
4381 const char *label1 = NULL, *label2 = NULL;
4382 switch (staged_status) {
4383 case GOT_STATUS_MODIFY:
4384 label1 = path;
4385 label2 = path;
4386 break;
4387 case GOT_STATUS_ADD:
4388 label2 = path;
4389 break;
4390 case GOT_STATUS_DELETE:
4391 label1 = path;
4392 break;
4393 default:
4394 return got_error(GOT_ERR_FILE_STATUS);
4396 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4397 staged_blob_id, label1, label2, a->diff_context,
4398 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4401 if (staged_status == GOT_STATUS_ADD ||
4402 staged_status == GOT_STATUS_MODIFY) {
4403 char *id_str;
4404 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4405 8192);
4406 if (err)
4407 goto done;
4408 err = got_object_id_str(&id_str, staged_blob_id);
4409 if (err)
4410 goto done;
4411 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4412 err = got_error_from_errno("asprintf");
4413 free(id_str);
4414 goto done;
4416 free(id_str);
4417 } else if (status != GOT_STATUS_ADD) {
4418 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4419 if (err)
4420 goto done;
4423 if (status != GOT_STATUS_DELETE) {
4424 if (asprintf(&abspath, "%s/%s",
4425 got_worktree_get_root_path(a->worktree), path) == -1) {
4426 err = got_error_from_errno("asprintf");
4427 goto done;
4430 if (dirfd != -1) {
4431 fd = openat(dirfd, de_name, O_RDONLY | O_NOFOLLOW);
4432 if (fd == -1) {
4433 if (!got_err_open_nofollow_on_symlink()) {
4434 err = got_error_from_errno2("openat",
4435 abspath);
4436 goto done;
4438 err = get_symlink_target_file(&fd, dirfd,
4439 de_name, abspath);
4440 if (err)
4441 goto done;
4443 } else {
4444 fd = open(abspath, O_RDONLY | O_NOFOLLOW);
4445 if (fd == -1) {
4446 if (!got_err_open_nofollow_on_symlink()) {
4447 err = got_error_from_errno2("open",
4448 abspath);
4449 goto done;
4451 err = get_symlink_target_file(&fd, dirfd,
4452 de_name, abspath);
4453 if (err)
4454 goto done;
4457 if (fstat(fd, &sb) == -1) {
4458 err = got_error_from_errno2("fstat", abspath);
4459 goto done;
4461 f2 = fdopen(fd, "r");
4462 if (f2 == NULL) {
4463 err = got_error_from_errno2("fdopen", abspath);
4464 goto done;
4466 fd = -1;
4467 } else
4468 sb.st_size = 0;
4470 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4471 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4472 done:
4473 if (blob1)
4474 got_object_blob_close(blob1);
4475 if (f2 && fclose(f2) == EOF && err == NULL)
4476 err = got_error_from_errno("fclose");
4477 if (fd != -1 && close(fd) == -1 && err == NULL)
4478 err = got_error_from_errno("close");
4479 free(abspath);
4480 return err;
4483 static const struct got_error *
4484 cmd_diff(int argc, char *argv[])
4486 const struct got_error *error;
4487 struct got_repository *repo = NULL;
4488 struct got_worktree *worktree = NULL;
4489 char *cwd = NULL, *repo_path = NULL;
4490 const char *commit_args[2] = { NULL, NULL };
4491 int ncommit_args = 0;
4492 struct got_object_id *ids[2] = { NULL, NULL };
4493 char *labels[2] = { NULL, NULL };
4494 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4495 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4496 int force_text_diff = 0, force_path = 0, rflag = 0;
4497 const char *errstr;
4498 struct got_reflist_head refs;
4499 struct got_pathlist_head paths;
4500 struct got_pathlist_entry *pe;
4502 TAILQ_INIT(&refs);
4503 TAILQ_INIT(&paths);
4505 #ifndef PROFILE
4506 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4507 NULL) == -1)
4508 err(1, "pledge");
4509 #endif
4511 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4512 switch (ch) {
4513 case 'a':
4514 force_text_diff = 1;
4515 break;
4516 case 'c':
4517 if (ncommit_args >= 2)
4518 errx(1, "too many -c options used");
4519 commit_args[ncommit_args++] = optarg;
4520 break;
4521 case 'C':
4522 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4523 &errstr);
4524 if (errstr != NULL)
4525 err(1, "-C option %s", errstr);
4526 break;
4527 case 'r':
4528 repo_path = realpath(optarg, NULL);
4529 if (repo_path == NULL)
4530 return got_error_from_errno2("realpath",
4531 optarg);
4532 got_path_strip_trailing_slashes(repo_path);
4533 rflag = 1;
4534 break;
4535 case 's':
4536 diff_staged = 1;
4537 break;
4538 case 'w':
4539 ignore_whitespace = 1;
4540 break;
4541 case 'P':
4542 force_path = 1;
4543 break;
4544 default:
4545 usage_diff();
4546 /* NOTREACHED */
4550 argc -= optind;
4551 argv += optind;
4553 cwd = getcwd(NULL, 0);
4554 if (cwd == NULL) {
4555 error = got_error_from_errno("getcwd");
4556 goto done;
4559 if (repo_path == NULL) {
4560 error = got_worktree_open(&worktree, cwd);
4561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4562 goto done;
4563 else
4564 error = NULL;
4565 if (worktree) {
4566 repo_path =
4567 strdup(got_worktree_get_repo_path(worktree));
4568 if (repo_path == NULL) {
4569 error = got_error_from_errno("strdup");
4570 goto done;
4572 } else {
4573 repo_path = strdup(cwd);
4574 if (repo_path == NULL) {
4575 error = got_error_from_errno("strdup");
4576 goto done;
4581 error = got_repo_open(&repo, repo_path, NULL);
4582 free(repo_path);
4583 if (error != NULL)
4584 goto done;
4586 if (rflag || worktree == NULL || ncommit_args > 0) {
4587 if (force_path) {
4588 error = got_error_msg(GOT_ERR_NOT_IMPL,
4589 "-P option can only be used when diffing "
4590 "a work tree");
4591 goto done;
4593 if (diff_staged) {
4594 error = got_error_msg(GOT_ERR_NOT_IMPL,
4595 "-s option can only be used when diffing "
4596 "a work tree");
4597 goto done;
4601 error = apply_unveil(got_repo_get_path(repo), 1,
4602 worktree ? got_worktree_get_root_path(worktree) : NULL);
4603 if (error)
4604 goto done;
4606 if ((!force_path && argc == 2) || ncommit_args > 0) {
4607 int obj_type = (ncommit_args > 0 ?
4608 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4609 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4610 NULL);
4611 if (error)
4612 goto done;
4613 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4614 const char *arg;
4615 if (ncommit_args > 0)
4616 arg = commit_args[i];
4617 else
4618 arg = argv[i];
4619 error = got_repo_match_object_id(&ids[i], &labels[i],
4620 arg, obj_type, &refs, repo);
4621 if (error) {
4622 if (error->code != GOT_ERR_NOT_REF &&
4623 error->code != GOT_ERR_NO_OBJ)
4624 goto done;
4625 if (ncommit_args > 0)
4626 goto done;
4627 error = NULL;
4628 break;
4633 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4634 struct print_diff_arg arg;
4635 char *id_str;
4637 if (worktree == NULL) {
4638 if (argc == 2 && ids[0] == NULL) {
4639 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4640 goto done;
4641 } else if (argc == 2 && ids[1] == NULL) {
4642 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4643 goto done;
4644 } else if (argc > 0) {
4645 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4646 "%s", "specified paths cannot be resolved");
4647 goto done;
4648 } else {
4649 error = got_error(GOT_ERR_NOT_WORKTREE);
4650 goto done;
4654 error = get_worktree_paths_from_argv(&paths, argc, argv,
4655 worktree);
4656 if (error)
4657 goto done;
4659 error = got_object_id_str(&id_str,
4660 got_worktree_get_base_commit_id(worktree));
4661 if (error)
4662 goto done;
4663 arg.repo = repo;
4664 arg.worktree = worktree;
4665 arg.diff_context = diff_context;
4666 arg.id_str = id_str;
4667 arg.header_shown = 0;
4668 arg.diff_staged = diff_staged;
4669 arg.ignore_whitespace = ignore_whitespace;
4670 arg.force_text_diff = force_text_diff;
4672 error = got_worktree_status(worktree, &paths, repo, 0,
4673 print_diff, &arg, check_cancelled, NULL);
4674 free(id_str);
4675 goto done;
4678 if (ncommit_args == 1) {
4679 struct got_commit_object *commit;
4680 error = got_object_open_as_commit(&commit, repo, ids[0]);
4681 if (error)
4682 goto done;
4684 labels[1] = labels[0];
4685 ids[1] = ids[0];
4686 if (got_object_commit_get_nparents(commit) > 0) {
4687 const struct got_object_id_queue *pids;
4688 struct got_object_qid *pid;
4689 pids = got_object_commit_get_parent_ids(commit);
4690 pid = STAILQ_FIRST(pids);
4691 ids[0] = got_object_id_dup(pid->id);
4692 if (ids[0] == NULL) {
4693 error = got_error_from_errno(
4694 "got_object_id_dup");
4695 got_object_commit_close(commit);
4696 goto done;
4698 error = got_object_id_str(&labels[0], ids[0]);
4699 if (error) {
4700 got_object_commit_close(commit);
4701 goto done;
4703 } else {
4704 ids[0] = NULL;
4705 labels[0] = strdup("/dev/null");
4706 if (labels[0] == NULL) {
4707 error = got_error_from_errno("strdup");
4708 got_object_commit_close(commit);
4709 goto done;
4713 got_object_commit_close(commit);
4716 if (ncommit_args == 0 && argc > 2) {
4717 error = got_error_msg(GOT_ERR_BAD_PATH,
4718 "path arguments cannot be used when diffing two objects");
4719 goto done;
4722 if (ids[0]) {
4723 error = got_object_get_type(&type1, repo, ids[0]);
4724 if (error)
4725 goto done;
4728 error = got_object_get_type(&type2, repo, ids[1]);
4729 if (error)
4730 goto done;
4731 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4732 error = got_error(GOT_ERR_OBJ_TYPE);
4733 goto done;
4735 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4736 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4737 "path arguments cannot be used when diffing blobs");
4738 goto done;
4741 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4742 char *in_repo_path;
4743 struct got_pathlist_entry *new;
4744 if (worktree) {
4745 const char *prefix;
4746 char *p;
4747 error = got_worktree_resolve_path(&p, worktree,
4748 argv[i]);
4749 if (error)
4750 goto done;
4751 prefix = got_worktree_get_path_prefix(worktree);
4752 while (prefix[0] == '/')
4753 prefix++;
4754 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4755 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4756 p) == -1) {
4757 error = got_error_from_errno("asprintf");
4758 free(p);
4759 goto done;
4761 free(p);
4762 } else {
4763 char *mapped_path, *s;
4764 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4765 if (error)
4766 goto done;
4767 s = mapped_path;
4768 while (s[0] == '/')
4769 s++;
4770 in_repo_path = strdup(s);
4771 if (in_repo_path == NULL) {
4772 error = got_error_from_errno("asprintf");
4773 free(mapped_path);
4774 goto done;
4776 free(mapped_path);
4779 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4780 if (error || new == NULL /* duplicate */)
4781 free(in_repo_path);
4782 if (error)
4783 goto done;
4786 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4787 case GOT_OBJ_TYPE_BLOB:
4788 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4789 NULL, NULL, diff_context, ignore_whitespace,
4790 force_text_diff, repo, stdout);
4791 break;
4792 case GOT_OBJ_TYPE_TREE:
4793 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4794 &paths, "", "", diff_context, ignore_whitespace,
4795 force_text_diff, repo, stdout);
4796 break;
4797 case GOT_OBJ_TYPE_COMMIT:
4798 printf("diff %s %s\n", labels[0], labels[1]);
4799 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4800 &paths, diff_context, ignore_whitespace, force_text_diff,
4801 repo, stdout);
4802 break;
4803 default:
4804 error = got_error(GOT_ERR_OBJ_TYPE);
4806 done:
4807 free(labels[0]);
4808 free(labels[1]);
4809 free(ids[0]);
4810 free(ids[1]);
4811 if (worktree)
4812 got_worktree_close(worktree);
4813 if (repo) {
4814 const struct got_error *close_err = got_repo_close(repo);
4815 if (error == NULL)
4816 error = close_err;
4818 TAILQ_FOREACH(pe, &paths, entry)
4819 free((char *)pe->path);
4820 got_pathlist_free(&paths);
4821 got_ref_list_free(&refs);
4822 return error;
4825 __dead static void
4826 usage_blame(void)
4828 fprintf(stderr,
4829 "usage: %s blame [-c commit] [-r repository-path] path\n",
4830 getprogname());
4831 exit(1);
4834 struct blame_line {
4835 int annotated;
4836 char *id_str;
4837 char *committer;
4838 char datebuf[11]; /* YYYY-MM-DD + NUL */
4841 struct blame_cb_args {
4842 struct blame_line *lines;
4843 int nlines;
4844 int nlines_prec;
4845 int lineno_cur;
4846 off_t *line_offsets;
4847 FILE *f;
4848 struct got_repository *repo;
4851 static const struct got_error *
4852 blame_cb(void *arg, int nlines, int lineno, struct got_object_id *id)
4854 const struct got_error *err = NULL;
4855 struct blame_cb_args *a = arg;
4856 struct blame_line *bline;
4857 char *line = NULL;
4858 size_t linesize = 0;
4859 struct got_commit_object *commit = NULL;
4860 off_t offset;
4861 struct tm tm;
4862 time_t committer_time;
4864 if (nlines != a->nlines ||
4865 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4866 return got_error(GOT_ERR_RANGE);
4868 if (sigint_received)
4869 return got_error(GOT_ERR_ITER_COMPLETED);
4871 if (lineno == -1)
4872 return NULL; /* no change in this commit */
4874 /* Annotate this line. */
4875 bline = &a->lines[lineno - 1];
4876 if (bline->annotated)
4877 return NULL;
4878 err = got_object_id_str(&bline->id_str, id);
4879 if (err)
4880 return err;
4882 err = got_object_open_as_commit(&commit, a->repo, id);
4883 if (err)
4884 goto done;
4886 bline->committer = strdup(got_object_commit_get_committer(commit));
4887 if (bline->committer == NULL) {
4888 err = got_error_from_errno("strdup");
4889 goto done;
4892 committer_time = got_object_commit_get_committer_time(commit);
4893 if (gmtime_r(&committer_time, &tm) == NULL)
4894 return got_error_from_errno("gmtime_r");
4895 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4896 &tm) == 0) {
4897 err = got_error(GOT_ERR_NO_SPACE);
4898 goto done;
4900 bline->annotated = 1;
4902 /* Print lines annotated so far. */
4903 bline = &a->lines[a->lineno_cur - 1];
4904 if (!bline->annotated)
4905 goto done;
4907 offset = a->line_offsets[a->lineno_cur - 1];
4908 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4909 err = got_error_from_errno("fseeko");
4910 goto done;
4913 while (bline->annotated) {
4914 char *smallerthan, *at, *nl, *committer;
4915 size_t len;
4917 if (getline(&line, &linesize, a->f) == -1) {
4918 if (ferror(a->f))
4919 err = got_error_from_errno("getline");
4920 break;
4923 committer = bline->committer;
4924 smallerthan = strchr(committer, '<');
4925 if (smallerthan && smallerthan[1] != '\0')
4926 committer = smallerthan + 1;
4927 at = strchr(committer, '@');
4928 if (at)
4929 *at = '\0';
4930 len = strlen(committer);
4931 if (len >= 9)
4932 committer[8] = '\0';
4934 nl = strchr(line, '\n');
4935 if (nl)
4936 *nl = '\0';
4937 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4938 bline->id_str, bline->datebuf, committer, line);
4940 a->lineno_cur++;
4941 bline = &a->lines[a->lineno_cur - 1];
4943 done:
4944 if (commit)
4945 got_object_commit_close(commit);
4946 free(line);
4947 return err;
4950 static const struct got_error *
4951 cmd_blame(int argc, char *argv[])
4953 const struct got_error *error;
4954 struct got_repository *repo = NULL;
4955 struct got_worktree *worktree = NULL;
4956 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4957 char *link_target = NULL;
4958 struct got_object_id *obj_id = NULL;
4959 struct got_object_id *commit_id = NULL;
4960 struct got_blob_object *blob = NULL;
4961 char *commit_id_str = NULL;
4962 struct blame_cb_args bca;
4963 int ch, obj_type, i;
4964 off_t filesize;
4966 memset(&bca, 0, sizeof(bca));
4968 #ifndef PROFILE
4969 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4970 NULL) == -1)
4971 err(1, "pledge");
4972 #endif
4974 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4975 switch (ch) {
4976 case 'c':
4977 commit_id_str = optarg;
4978 break;
4979 case 'r':
4980 repo_path = realpath(optarg, NULL);
4981 if (repo_path == NULL)
4982 return got_error_from_errno2("realpath",
4983 optarg);
4984 got_path_strip_trailing_slashes(repo_path);
4985 break;
4986 default:
4987 usage_blame();
4988 /* NOTREACHED */
4992 argc -= optind;
4993 argv += optind;
4995 if (argc == 1)
4996 path = argv[0];
4997 else
4998 usage_blame();
5000 cwd = getcwd(NULL, 0);
5001 if (cwd == NULL) {
5002 error = got_error_from_errno("getcwd");
5003 goto done;
5005 if (repo_path == NULL) {
5006 error = got_worktree_open(&worktree, cwd);
5007 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5008 goto done;
5009 else
5010 error = NULL;
5011 if (worktree) {
5012 repo_path =
5013 strdup(got_worktree_get_repo_path(worktree));
5014 if (repo_path == NULL) {
5015 error = got_error_from_errno("strdup");
5016 if (error)
5017 goto done;
5019 } else {
5020 repo_path = strdup(cwd);
5021 if (repo_path == NULL) {
5022 error = got_error_from_errno("strdup");
5023 goto done;
5028 error = got_repo_open(&repo, repo_path, NULL);
5029 if (error != NULL)
5030 goto done;
5032 if (worktree) {
5033 const char *prefix = got_worktree_get_path_prefix(worktree);
5034 char *p;
5036 error = got_worktree_resolve_path(&p, worktree, path);
5037 if (error)
5038 goto done;
5039 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5040 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5041 p) == -1) {
5042 error = got_error_from_errno("asprintf");
5043 free(p);
5044 goto done;
5046 free(p);
5047 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5048 } else {
5049 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5050 if (error)
5051 goto done;
5052 error = got_repo_map_path(&in_repo_path, repo, path);
5054 if (error)
5055 goto done;
5057 if (commit_id_str == NULL) {
5058 struct got_reference *head_ref;
5059 error = got_ref_open(&head_ref, repo, worktree ?
5060 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5061 if (error != NULL)
5062 goto done;
5063 error = got_ref_resolve(&commit_id, repo, head_ref);
5064 got_ref_close(head_ref);
5065 if (error != NULL)
5066 goto done;
5067 } else {
5068 struct got_reflist_head refs;
5069 TAILQ_INIT(&refs);
5070 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5071 NULL);
5072 if (error)
5073 goto done;
5074 error = got_repo_match_object_id(&commit_id, NULL,
5075 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5076 got_ref_list_free(&refs);
5077 if (error)
5078 goto done;
5081 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5082 commit_id, repo);
5083 if (error)
5084 goto done;
5086 error = got_object_id_by_path(&obj_id, repo, commit_id,
5087 link_target ? link_target : in_repo_path);
5088 if (error)
5089 goto done;
5091 error = got_object_get_type(&obj_type, repo, obj_id);
5092 if (error)
5093 goto done;
5095 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5096 error = got_error_path(link_target ? link_target : in_repo_path,
5097 GOT_ERR_OBJ_TYPE);
5098 goto done;
5101 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5102 if (error)
5103 goto done;
5104 bca.f = got_opentemp();
5105 if (bca.f == NULL) {
5106 error = got_error_from_errno("got_opentemp");
5107 goto done;
5109 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5110 &bca.line_offsets, bca.f, blob);
5111 if (error || bca.nlines == 0)
5112 goto done;
5114 /* Don't include \n at EOF in the blame line count. */
5115 if (bca.line_offsets[bca.nlines - 1] == filesize)
5116 bca.nlines--;
5118 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5119 if (bca.lines == NULL) {
5120 error = got_error_from_errno("calloc");
5121 goto done;
5123 bca.lineno_cur = 1;
5124 bca.nlines_prec = 0;
5125 i = bca.nlines;
5126 while (i > 0) {
5127 i /= 10;
5128 bca.nlines_prec++;
5130 bca.repo = repo;
5132 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5133 repo, blame_cb, &bca, check_cancelled, NULL);
5134 done:
5135 free(in_repo_path);
5136 free(link_target);
5137 free(repo_path);
5138 free(cwd);
5139 free(commit_id);
5140 free(obj_id);
5141 if (blob)
5142 got_object_blob_close(blob);
5143 if (worktree)
5144 got_worktree_close(worktree);
5145 if (repo) {
5146 const struct got_error *close_err = got_repo_close(repo);
5147 if (error == NULL)
5148 error = close_err;
5150 if (bca.lines) {
5151 for (i = 0; i < bca.nlines; i++) {
5152 struct blame_line *bline = &bca.lines[i];
5153 free(bline->id_str);
5154 free(bline->committer);
5156 free(bca.lines);
5158 free(bca.line_offsets);
5159 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5160 error = got_error_from_errno("fclose");
5161 return error;
5164 __dead static void
5165 usage_tree(void)
5167 fprintf(stderr,
5168 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5169 getprogname());
5170 exit(1);
5173 static const struct got_error *
5174 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5175 const char *root_path, struct got_repository *repo)
5177 const struct got_error *err = NULL;
5178 int is_root_path = (strcmp(path, root_path) == 0);
5179 const char *modestr = "";
5180 mode_t mode = got_tree_entry_get_mode(te);
5181 char *link_target = NULL;
5183 path += strlen(root_path);
5184 while (path[0] == '/')
5185 path++;
5187 if (got_object_tree_entry_is_submodule(te))
5188 modestr = "$";
5189 else if (S_ISLNK(mode)) {
5190 int i;
5192 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5193 if (err)
5194 return err;
5195 for (i = 0; i < strlen(link_target); i++) {
5196 if (!isprint((unsigned char)link_target[i]))
5197 link_target[i] = '?';
5200 modestr = "@";
5202 else if (S_ISDIR(mode))
5203 modestr = "/";
5204 else if (mode & S_IXUSR)
5205 modestr = "*";
5207 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5208 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5209 link_target ? " -> ": "", link_target ? link_target : "");
5211 free(link_target);
5212 return NULL;
5215 static const struct got_error *
5216 print_tree(const char *path, struct got_object_id *commit_id,
5217 int show_ids, int recurse, const char *root_path,
5218 struct got_repository *repo)
5220 const struct got_error *err = NULL;
5221 struct got_object_id *tree_id = NULL;
5222 struct got_tree_object *tree = NULL;
5223 int nentries, i;
5225 err = got_object_id_by_path(&tree_id, repo, commit_id, path);
5226 if (err)
5227 goto done;
5229 err = got_object_open_as_tree(&tree, repo, tree_id);
5230 if (err)
5231 goto done;
5232 nentries = got_object_tree_get_nentries(tree);
5233 for (i = 0; i < nentries; i++) {
5234 struct got_tree_entry *te;
5235 char *id = NULL;
5237 if (sigint_received || sigpipe_received)
5238 break;
5240 te = got_object_tree_get_entry(tree, i);
5241 if (show_ids) {
5242 char *id_str;
5243 err = got_object_id_str(&id_str,
5244 got_tree_entry_get_id(te));
5245 if (err)
5246 goto done;
5247 if (asprintf(&id, "%s ", id_str) == -1) {
5248 err = got_error_from_errno("asprintf");
5249 free(id_str);
5250 goto done;
5252 free(id_str);
5254 err = print_entry(te, id, path, root_path, repo);
5255 free(id);
5256 if (err)
5257 goto done;
5259 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5260 char *child_path;
5261 if (asprintf(&child_path, "%s%s%s", path,
5262 path[0] == '/' && path[1] == '\0' ? "" : "/",
5263 got_tree_entry_get_name(te)) == -1) {
5264 err = got_error_from_errno("asprintf");
5265 goto done;
5267 err = print_tree(child_path, commit_id, show_ids, 1,
5268 root_path, repo);
5269 free(child_path);
5270 if (err)
5271 goto done;
5274 done:
5275 if (tree)
5276 got_object_tree_close(tree);
5277 free(tree_id);
5278 return err;
5281 static const struct got_error *
5282 cmd_tree(int argc, char *argv[])
5284 const struct got_error *error;
5285 struct got_repository *repo = NULL;
5286 struct got_worktree *worktree = NULL;
5287 const char *path, *refname = NULL;
5288 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5289 struct got_object_id *commit_id = NULL;
5290 char *commit_id_str = NULL;
5291 int show_ids = 0, recurse = 0;
5292 int ch;
5294 #ifndef PROFILE
5295 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5296 NULL) == -1)
5297 err(1, "pledge");
5298 #endif
5300 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5301 switch (ch) {
5302 case 'c':
5303 commit_id_str = optarg;
5304 break;
5305 case 'r':
5306 repo_path = realpath(optarg, NULL);
5307 if (repo_path == NULL)
5308 return got_error_from_errno2("realpath",
5309 optarg);
5310 got_path_strip_trailing_slashes(repo_path);
5311 break;
5312 case 'i':
5313 show_ids = 1;
5314 break;
5315 case 'R':
5316 recurse = 1;
5317 break;
5318 default:
5319 usage_tree();
5320 /* NOTREACHED */
5324 argc -= optind;
5325 argv += optind;
5327 if (argc == 1)
5328 path = argv[0];
5329 else if (argc > 1)
5330 usage_tree();
5331 else
5332 path = NULL;
5334 cwd = getcwd(NULL, 0);
5335 if (cwd == NULL) {
5336 error = got_error_from_errno("getcwd");
5337 goto done;
5339 if (repo_path == NULL) {
5340 error = got_worktree_open(&worktree, cwd);
5341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5342 goto done;
5343 else
5344 error = NULL;
5345 if (worktree) {
5346 repo_path =
5347 strdup(got_worktree_get_repo_path(worktree));
5348 if (repo_path == NULL)
5349 error = got_error_from_errno("strdup");
5350 if (error)
5351 goto done;
5352 } else {
5353 repo_path = strdup(cwd);
5354 if (repo_path == NULL) {
5355 error = got_error_from_errno("strdup");
5356 goto done;
5361 error = got_repo_open(&repo, repo_path, NULL);
5362 if (error != NULL)
5363 goto done;
5365 if (worktree) {
5366 const char *prefix = got_worktree_get_path_prefix(worktree);
5367 char *p;
5369 if (path == NULL)
5370 path = "";
5371 error = got_worktree_resolve_path(&p, worktree, path);
5372 if (error)
5373 goto done;
5374 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5375 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5376 p) == -1) {
5377 error = got_error_from_errno("asprintf");
5378 free(p);
5379 goto done;
5381 free(p);
5382 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5383 if (error)
5384 goto done;
5385 } else {
5386 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5387 if (error)
5388 goto done;
5389 if (path == NULL)
5390 path = "/";
5391 error = got_repo_map_path(&in_repo_path, repo, path);
5392 if (error != NULL)
5393 goto done;
5396 if (commit_id_str == NULL) {
5397 struct got_reference *head_ref;
5398 if (worktree)
5399 refname = got_worktree_get_head_ref_name(worktree);
5400 else
5401 refname = GOT_REF_HEAD;
5402 error = got_ref_open(&head_ref, repo, refname, 0);
5403 if (error != NULL)
5404 goto done;
5405 error = got_ref_resolve(&commit_id, repo, head_ref);
5406 got_ref_close(head_ref);
5407 if (error != NULL)
5408 goto done;
5409 } else {
5410 struct got_reflist_head refs;
5411 TAILQ_INIT(&refs);
5412 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5413 NULL);
5414 if (error)
5415 goto done;
5416 error = got_repo_match_object_id(&commit_id, NULL,
5417 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5418 got_ref_list_free(&refs);
5419 if (error)
5420 goto done;
5423 error = print_tree(in_repo_path, commit_id, show_ids, recurse,
5424 in_repo_path, repo);
5425 done:
5426 free(in_repo_path);
5427 free(repo_path);
5428 free(cwd);
5429 free(commit_id);
5430 if (worktree)
5431 got_worktree_close(worktree);
5432 if (repo) {
5433 const struct got_error *close_err = got_repo_close(repo);
5434 if (error == NULL)
5435 error = close_err;
5437 return error;
5440 __dead static void
5441 usage_status(void)
5443 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5444 "[-S status-codes] [path ...]\n", getprogname());
5445 exit(1);
5448 struct got_status_arg {
5449 char *status_codes;
5450 int suppress;
5453 static const struct got_error *
5454 print_status(void *arg, unsigned char status, unsigned char staged_status,
5455 const char *path, struct got_object_id *blob_id,
5456 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5457 int dirfd, const char *de_name)
5459 struct got_status_arg *st = arg;
5461 if (status == staged_status && (status == GOT_STATUS_DELETE))
5462 status = GOT_STATUS_NO_CHANGE;
5463 if (st != NULL && st->status_codes) {
5464 size_t ncodes = strlen(st->status_codes);
5465 int i, j = 0;
5467 for (i = 0; i < ncodes ; i++) {
5468 if (st->suppress) {
5469 if (status == st->status_codes[i] ||
5470 staged_status == st->status_codes[i]) {
5471 j++;
5472 continue;
5474 } else {
5475 if (status == st->status_codes[i] ||
5476 staged_status == st->status_codes[i])
5477 break;
5481 if (st->suppress && j == 0)
5482 goto print;
5484 if (i == ncodes)
5485 return NULL;
5487 print:
5488 printf("%c%c %s\n", status, staged_status, path);
5489 return NULL;
5492 static const struct got_error *
5493 cmd_status(int argc, char *argv[])
5495 const struct got_error *error = NULL;
5496 struct got_repository *repo = NULL;
5497 struct got_worktree *worktree = NULL;
5498 struct got_status_arg st;
5499 char *cwd = NULL;
5500 struct got_pathlist_head paths;
5501 struct got_pathlist_entry *pe;
5502 int ch, i, no_ignores = 0;
5504 TAILQ_INIT(&paths);
5506 memset(&st, 0, sizeof(st));
5507 st.status_codes = NULL;
5508 st.suppress = 0;
5510 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5511 switch (ch) {
5512 case 'I':
5513 no_ignores = 1;
5514 break;
5515 case 'S':
5516 if (st.status_codes != NULL && st.suppress == 0)
5517 option_conflict('S', 's');
5518 st.suppress = 1;
5519 /* fallthrough */
5520 case 's':
5521 for (i = 0; i < strlen(optarg); i++) {
5522 switch (optarg[i]) {
5523 case GOT_STATUS_MODIFY:
5524 case GOT_STATUS_ADD:
5525 case GOT_STATUS_DELETE:
5526 case GOT_STATUS_CONFLICT:
5527 case GOT_STATUS_MISSING:
5528 case GOT_STATUS_OBSTRUCTED:
5529 case GOT_STATUS_UNVERSIONED:
5530 case GOT_STATUS_MODE_CHANGE:
5531 case GOT_STATUS_NONEXISTENT:
5532 break;
5533 default:
5534 errx(1, "invalid status code '%c'",
5535 optarg[i]);
5538 if (ch == 's' && st.suppress)
5539 option_conflict('s', 'S');
5540 st.status_codes = optarg;
5541 break;
5542 default:
5543 usage_status();
5544 /* NOTREACHED */
5548 argc -= optind;
5549 argv += optind;
5551 #ifndef PROFILE
5552 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5553 NULL) == -1)
5554 err(1, "pledge");
5555 #endif
5556 cwd = getcwd(NULL, 0);
5557 if (cwd == NULL) {
5558 error = got_error_from_errno("getcwd");
5559 goto done;
5562 error = got_worktree_open(&worktree, cwd);
5563 if (error) {
5564 if (error->code == GOT_ERR_NOT_WORKTREE)
5565 error = wrap_not_worktree_error(error, "status", cwd);
5566 goto done;
5569 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5570 NULL);
5571 if (error != NULL)
5572 goto done;
5574 error = apply_unveil(got_repo_get_path(repo), 1,
5575 got_worktree_get_root_path(worktree));
5576 if (error)
5577 goto done;
5579 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5580 if (error)
5581 goto done;
5583 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5584 print_status, &st, check_cancelled, NULL);
5585 done:
5586 TAILQ_FOREACH(pe, &paths, entry)
5587 free((char *)pe->path);
5588 got_pathlist_free(&paths);
5589 free(cwd);
5590 return error;
5593 __dead static void
5594 usage_ref(void)
5596 fprintf(stderr,
5597 "usage: %s ref [-r repository] [-l] [-c object] [-s reference] "
5598 "[-d] [name]\n",
5599 getprogname());
5600 exit(1);
5603 static const struct got_error *
5604 list_refs(struct got_repository *repo, const char *refname)
5606 static const struct got_error *err = NULL;
5607 struct got_reflist_head refs;
5608 struct got_reflist_entry *re;
5610 TAILQ_INIT(&refs);
5611 err = got_ref_list(&refs, repo, refname, got_ref_cmp_by_name, NULL);
5612 if (err)
5613 return err;
5615 TAILQ_FOREACH(re, &refs, entry) {
5616 char *refstr;
5617 refstr = got_ref_to_str(re->ref);
5618 if (refstr == NULL)
5619 return got_error_from_errno("got_ref_to_str");
5620 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5621 free(refstr);
5624 got_ref_list_free(&refs);
5625 return NULL;
5628 static const struct got_error *
5629 delete_ref_by_name(struct got_repository *repo, const char *refname)
5631 const struct got_error *err;
5632 struct got_reference *ref;
5634 err = got_ref_open(&ref, repo, refname, 0);
5635 if (err)
5636 return err;
5638 err = delete_ref(repo, ref);
5639 got_ref_close(ref);
5640 return err;
5643 static const struct got_error *
5644 add_ref(struct got_repository *repo, const char *refname, const char *target)
5646 const struct got_error *err = NULL;
5647 struct got_object_id *id;
5648 struct got_reference *ref = NULL;
5651 * Don't let the user create a reference name with a leading '-'.
5652 * While technically a valid reference name, this case is usually
5653 * an unintended typo.
5655 if (refname[0] == '-')
5656 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5658 err = got_repo_match_object_id_prefix(&id, target, GOT_OBJ_TYPE_ANY,
5659 repo);
5660 if (err) {
5661 struct got_reference *target_ref;
5663 if (err->code != GOT_ERR_BAD_OBJ_ID_STR)
5664 return err;
5665 err = got_ref_open(&target_ref, repo, target, 0);
5666 if (err)
5667 return err;
5668 err = got_ref_resolve(&id, repo, target_ref);
5669 got_ref_close(target_ref);
5670 if (err)
5671 return err;
5674 err = got_ref_alloc(&ref, refname, id);
5675 if (err)
5676 goto done;
5678 err = got_ref_write(ref, repo);
5679 done:
5680 if (ref)
5681 got_ref_close(ref);
5682 free(id);
5683 return err;
5686 static const struct got_error *
5687 add_symref(struct got_repository *repo, const char *refname, const char *target)
5689 const struct got_error *err = NULL;
5690 struct got_reference *ref = NULL;
5691 struct got_reference *target_ref = NULL;
5694 * Don't let the user create a reference name with a leading '-'.
5695 * While technically a valid reference name, this case is usually
5696 * an unintended typo.
5698 if (refname[0] == '-')
5699 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5701 err = got_ref_open(&target_ref, repo, target, 0);
5702 if (err)
5703 return err;
5705 err = got_ref_alloc_symref(&ref, refname, target_ref);
5706 if (err)
5707 goto done;
5709 err = got_ref_write(ref, repo);
5710 done:
5711 if (target_ref)
5712 got_ref_close(target_ref);
5713 if (ref)
5714 got_ref_close(ref);
5715 return err;
5718 static const struct got_error *
5719 cmd_ref(int argc, char *argv[])
5721 const struct got_error *error = NULL;
5722 struct got_repository *repo = NULL;
5723 struct got_worktree *worktree = NULL;
5724 char *cwd = NULL, *repo_path = NULL;
5725 int ch, do_list = 0, do_delete = 0;
5726 const char *obj_arg = NULL, *symref_target= NULL;
5727 char *refname = NULL;
5729 while ((ch = getopt(argc, argv, "c:dr:ls:")) != -1) {
5730 switch (ch) {
5731 case 'c':
5732 obj_arg = optarg;
5733 break;
5734 case 'd':
5735 do_delete = 1;
5736 break;
5737 case 'r':
5738 repo_path = realpath(optarg, NULL);
5739 if (repo_path == NULL)
5740 return got_error_from_errno2("realpath",
5741 optarg);
5742 got_path_strip_trailing_slashes(repo_path);
5743 break;
5744 case 'l':
5745 do_list = 1;
5746 break;
5747 case 's':
5748 symref_target = optarg;
5749 break;
5750 default:
5751 usage_ref();
5752 /* NOTREACHED */
5756 if (obj_arg && do_list)
5757 option_conflict('c', 'l');
5758 if (obj_arg && do_delete)
5759 option_conflict('c', 'd');
5760 if (obj_arg && symref_target)
5761 option_conflict('c', 's');
5762 if (symref_target && do_delete)
5763 option_conflict('s', 'd');
5764 if (symref_target && do_list)
5765 option_conflict('s', 'l');
5766 if (do_delete && do_list)
5767 option_conflict('d', 'l');
5769 argc -= optind;
5770 argv += optind;
5772 if (do_list) {
5773 if (argc != 0 && argc != 1)
5774 usage_ref();
5775 if (argc == 1) {
5776 refname = strdup(argv[0]);
5777 if (refname == NULL) {
5778 error = got_error_from_errno("strdup");
5779 goto done;
5782 } else {
5783 if (argc != 1)
5784 usage_ref();
5785 refname = strdup(argv[0]);
5786 if (refname == NULL) {
5787 error = got_error_from_errno("strdup");
5788 goto done;
5792 if (refname)
5793 got_path_strip_trailing_slashes(refname);
5795 #ifndef PROFILE
5796 if (do_list) {
5797 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5798 NULL) == -1)
5799 err(1, "pledge");
5800 } else {
5801 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5802 "sendfd unveil", NULL) == -1)
5803 err(1, "pledge");
5805 #endif
5806 cwd = getcwd(NULL, 0);
5807 if (cwd == NULL) {
5808 error = got_error_from_errno("getcwd");
5809 goto done;
5812 if (repo_path == NULL) {
5813 error = got_worktree_open(&worktree, cwd);
5814 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5815 goto done;
5816 else
5817 error = NULL;
5818 if (worktree) {
5819 repo_path =
5820 strdup(got_worktree_get_repo_path(worktree));
5821 if (repo_path == NULL)
5822 error = got_error_from_errno("strdup");
5823 if (error)
5824 goto done;
5825 } else {
5826 repo_path = strdup(cwd);
5827 if (repo_path == NULL) {
5828 error = got_error_from_errno("strdup");
5829 goto done;
5834 error = got_repo_open(&repo, repo_path, NULL);
5835 if (error != NULL)
5836 goto done;
5838 error = apply_unveil(got_repo_get_path(repo), do_list,
5839 worktree ? got_worktree_get_root_path(worktree) : NULL);
5840 if (error)
5841 goto done;
5843 if (do_list)
5844 error = list_refs(repo, refname);
5845 else if (do_delete)
5846 error = delete_ref_by_name(repo, refname);
5847 else if (symref_target)
5848 error = add_symref(repo, refname, symref_target);
5849 else {
5850 if (obj_arg == NULL)
5851 usage_ref();
5852 error = add_ref(repo, refname, obj_arg);
5854 done:
5855 free(refname);
5856 if (repo) {
5857 const struct got_error *close_err = got_repo_close(repo);
5858 if (error == NULL)
5859 error = close_err;
5861 if (worktree)
5862 got_worktree_close(worktree);
5863 free(cwd);
5864 free(repo_path);
5865 return error;
5868 __dead static void
5869 usage_branch(void)
5871 fprintf(stderr,
5872 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-n] "
5873 "[name]\n", getprogname());
5874 exit(1);
5877 static const struct got_error *
5878 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5879 struct got_reference *ref)
5881 const struct got_error *err = NULL;
5882 const char *refname, *marker = " ";
5883 char *refstr;
5885 refname = got_ref_get_name(ref);
5886 if (worktree && strcmp(refname,
5887 got_worktree_get_head_ref_name(worktree)) == 0) {
5888 struct got_object_id *id = NULL;
5890 err = got_ref_resolve(&id, repo, ref);
5891 if (err)
5892 return err;
5893 if (got_object_id_cmp(id,
5894 got_worktree_get_base_commit_id(worktree)) == 0)
5895 marker = "* ";
5896 else
5897 marker = "~ ";
5898 free(id);
5901 if (strncmp(refname, "refs/heads/", 11) == 0)
5902 refname += 11;
5903 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5904 refname += 18;
5905 if (strncmp(refname, "refs/remotes/", 13) == 0)
5906 refname += 13;
5908 refstr = got_ref_to_str(ref);
5909 if (refstr == NULL)
5910 return got_error_from_errno("got_ref_to_str");
5912 printf("%s%s: %s\n", marker, refname, refstr);
5913 free(refstr);
5914 return NULL;
5917 static const struct got_error *
5918 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5920 const char *refname;
5922 if (worktree == NULL)
5923 return got_error(GOT_ERR_NOT_WORKTREE);
5925 refname = got_worktree_get_head_ref_name(worktree);
5927 if (strncmp(refname, "refs/heads/", 11) == 0)
5928 refname += 11;
5929 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5930 refname += 18;
5932 printf("%s\n", refname);
5934 return NULL;
5937 static const struct got_error *
5938 list_branches(struct got_repository *repo, struct got_worktree *worktree)
5940 static const struct got_error *err = NULL;
5941 struct got_reflist_head refs;
5942 struct got_reflist_entry *re;
5943 struct got_reference *temp_ref = NULL;
5944 int rebase_in_progress, histedit_in_progress;
5946 TAILQ_INIT(&refs);
5948 if (worktree) {
5949 err = got_worktree_rebase_in_progress(&rebase_in_progress,
5950 worktree);
5951 if (err)
5952 return err;
5954 err = got_worktree_histedit_in_progress(&histedit_in_progress,
5955 worktree);
5956 if (err)
5957 return err;
5959 if (rebase_in_progress || histedit_in_progress) {
5960 err = got_ref_open(&temp_ref, repo,
5961 got_worktree_get_head_ref_name(worktree), 0);
5962 if (err)
5963 return err;
5964 list_branch(repo, worktree, temp_ref);
5965 got_ref_close(temp_ref);
5969 err = got_ref_list(&refs, repo, "refs/heads",
5970 got_ref_cmp_by_name, NULL);
5971 if (err)
5972 return err;
5974 TAILQ_FOREACH(re, &refs, entry)
5975 list_branch(repo, worktree, re->ref);
5977 got_ref_list_free(&refs);
5979 err = got_ref_list(&refs, repo, "refs/remotes",
5980 got_ref_cmp_by_name, NULL);
5981 if (err)
5982 return err;
5984 TAILQ_FOREACH(re, &refs, entry)
5985 list_branch(repo, worktree, re->ref);
5987 got_ref_list_free(&refs);
5989 return NULL;
5992 static const struct got_error *
5993 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
5994 const char *branch_name)
5996 const struct got_error *err = NULL;
5997 struct got_reference *ref = NULL;
5998 char *refname, *remote_refname = NULL;
6000 if (strncmp(branch_name, "refs/", 5) == 0)
6001 branch_name += 5;
6002 if (strncmp(branch_name, "heads/", 6) == 0)
6003 branch_name += 6;
6004 else if (strncmp(branch_name, "remotes/", 8) == 0)
6005 branch_name += 8;
6007 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6008 return got_error_from_errno("asprintf");
6010 if (asprintf(&remote_refname, "refs/remotes/%s",
6011 branch_name) == -1) {
6012 err = got_error_from_errno("asprintf");
6013 goto done;
6016 err = got_ref_open(&ref, repo, refname, 0);
6017 if (err) {
6018 const struct got_error *err2;
6019 if (err->code != GOT_ERR_NOT_REF)
6020 goto done;
6022 * Keep 'err' intact such that if neither branch exists
6023 * we report "refs/heads" rather than "refs/remotes" in
6024 * our error message.
6026 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6027 if (err2)
6028 goto done;
6029 err = NULL;
6032 if (worktree &&
6033 strcmp(got_worktree_get_head_ref_name(worktree),
6034 got_ref_get_name(ref)) == 0) {
6035 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6036 "will not delete this work tree's current branch");
6037 goto done;
6040 err = delete_ref(repo, ref);
6041 done:
6042 if (ref)
6043 got_ref_close(ref);
6044 free(refname);
6045 free(remote_refname);
6046 return err;
6049 static const struct got_error *
6050 add_branch(struct got_repository *repo, const char *branch_name,
6051 struct got_object_id *base_commit_id)
6053 const struct got_error *err = NULL;
6054 struct got_reference *ref = NULL;
6055 char *base_refname = NULL, *refname = NULL;
6058 * Don't let the user create a branch name with a leading '-'.
6059 * While technically a valid reference name, this case is usually
6060 * an unintended typo.
6062 if (branch_name[0] == '-')
6063 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6065 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6066 branch_name += 11;
6068 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6069 err = got_error_from_errno("asprintf");
6070 goto done;
6073 err = got_ref_open(&ref, repo, refname, 0);
6074 if (err == NULL) {
6075 err = got_error(GOT_ERR_BRANCH_EXISTS);
6076 goto done;
6077 } else if (err->code != GOT_ERR_NOT_REF)
6078 goto done;
6080 err = got_ref_alloc(&ref, refname, base_commit_id);
6081 if (err)
6082 goto done;
6084 err = got_ref_write(ref, repo);
6085 done:
6086 if (ref)
6087 got_ref_close(ref);
6088 free(base_refname);
6089 free(refname);
6090 return err;
6093 static const struct got_error *
6094 cmd_branch(int argc, char *argv[])
6096 const struct got_error *error = NULL;
6097 struct got_repository *repo = NULL;
6098 struct got_worktree *worktree = NULL;
6099 char *cwd = NULL, *repo_path = NULL;
6100 int ch, do_list = 0, do_show = 0, do_update = 1;
6101 const char *delref = NULL, *commit_id_arg = NULL;
6102 struct got_reference *ref = NULL;
6103 struct got_pathlist_head paths;
6104 struct got_pathlist_entry *pe;
6105 struct got_object_id *commit_id = NULL;
6106 char *commit_id_str = NULL;
6108 TAILQ_INIT(&paths);
6110 while ((ch = getopt(argc, argv, "c:d:r:ln")) != -1) {
6111 switch (ch) {
6112 case 'c':
6113 commit_id_arg = optarg;
6114 break;
6115 case 'd':
6116 delref = optarg;
6117 break;
6118 case 'r':
6119 repo_path = realpath(optarg, NULL);
6120 if (repo_path == NULL)
6121 return got_error_from_errno2("realpath",
6122 optarg);
6123 got_path_strip_trailing_slashes(repo_path);
6124 break;
6125 case 'l':
6126 do_list = 1;
6127 break;
6128 case 'n':
6129 do_update = 0;
6130 break;
6131 default:
6132 usage_branch();
6133 /* NOTREACHED */
6137 if (do_list && delref)
6138 option_conflict('l', 'd');
6140 argc -= optind;
6141 argv += optind;
6143 if (!do_list && !delref && argc == 0)
6144 do_show = 1;
6146 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6147 errx(1, "-c option can only be used when creating a branch");
6149 if (do_list || delref) {
6150 if (argc > 0)
6151 usage_branch();
6152 } else if (!do_show && argc != 1)
6153 usage_branch();
6155 #ifndef PROFILE
6156 if (do_list || do_show) {
6157 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6158 NULL) == -1)
6159 err(1, "pledge");
6160 } else {
6161 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6162 "sendfd unveil", NULL) == -1)
6163 err(1, "pledge");
6165 #endif
6166 cwd = getcwd(NULL, 0);
6167 if (cwd == NULL) {
6168 error = got_error_from_errno("getcwd");
6169 goto done;
6172 if (repo_path == NULL) {
6173 error = got_worktree_open(&worktree, cwd);
6174 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6175 goto done;
6176 else
6177 error = NULL;
6178 if (worktree) {
6179 repo_path =
6180 strdup(got_worktree_get_repo_path(worktree));
6181 if (repo_path == NULL)
6182 error = got_error_from_errno("strdup");
6183 if (error)
6184 goto done;
6185 } else {
6186 repo_path = strdup(cwd);
6187 if (repo_path == NULL) {
6188 error = got_error_from_errno("strdup");
6189 goto done;
6194 error = got_repo_open(&repo, repo_path, NULL);
6195 if (error != NULL)
6196 goto done;
6198 error = apply_unveil(got_repo_get_path(repo), do_list,
6199 worktree ? got_worktree_get_root_path(worktree) : NULL);
6200 if (error)
6201 goto done;
6203 if (do_show)
6204 error = show_current_branch(repo, worktree);
6205 else if (do_list)
6206 error = list_branches(repo, worktree);
6207 else if (delref)
6208 error = delete_branch(repo, worktree, delref);
6209 else {
6210 struct got_reflist_head refs;
6211 TAILQ_INIT(&refs);
6212 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6213 NULL);
6214 if (error)
6215 goto done;
6216 if (commit_id_arg == NULL)
6217 commit_id_arg = worktree ?
6218 got_worktree_get_head_ref_name(worktree) :
6219 GOT_REF_HEAD;
6220 error = got_repo_match_object_id(&commit_id, NULL,
6221 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6222 got_ref_list_free(&refs);
6223 if (error)
6224 goto done;
6225 error = add_branch(repo, argv[0], commit_id);
6226 if (error)
6227 goto done;
6228 if (worktree && do_update) {
6229 struct got_update_progress_arg upa;
6230 char *branch_refname = NULL;
6232 error = got_object_id_str(&commit_id_str, commit_id);
6233 if (error)
6234 goto done;
6235 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6236 worktree);
6237 if (error)
6238 goto done;
6239 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6240 == -1) {
6241 error = got_error_from_errno("asprintf");
6242 goto done;
6244 error = got_ref_open(&ref, repo, branch_refname, 0);
6245 free(branch_refname);
6246 if (error)
6247 goto done;
6248 error = switch_head_ref(ref, commit_id, worktree,
6249 repo);
6250 if (error)
6251 goto done;
6252 error = got_worktree_set_base_commit_id(worktree, repo,
6253 commit_id);
6254 if (error)
6255 goto done;
6256 memset(&upa, 0, sizeof(upa));
6257 error = got_worktree_checkout_files(worktree, &paths,
6258 repo, update_progress, &upa, check_cancelled,
6259 NULL);
6260 if (error)
6261 goto done;
6262 if (upa.did_something) {
6263 printf("Updated to %s: %s\n",
6264 got_worktree_get_head_ref_name(worktree),
6265 commit_id_str);
6267 print_update_progress_stats(&upa);
6270 done:
6271 if (ref)
6272 got_ref_close(ref);
6273 if (repo) {
6274 const struct got_error *close_err = got_repo_close(repo);
6275 if (error == NULL)
6276 error = close_err;
6278 if (worktree)
6279 got_worktree_close(worktree);
6280 free(cwd);
6281 free(repo_path);
6282 free(commit_id);
6283 free(commit_id_str);
6284 TAILQ_FOREACH(pe, &paths, entry)
6285 free((char *)pe->path);
6286 got_pathlist_free(&paths);
6287 return error;
6291 __dead static void
6292 usage_tag(void)
6294 fprintf(stderr,
6295 "usage: %s tag [-c commit] [-r repository] [-l] "
6296 "[-m message] name\n", getprogname());
6297 exit(1);
6300 #if 0
6301 static const struct got_error *
6302 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6304 const struct got_error *err = NULL;
6305 struct got_reflist_entry *re, *se, *new;
6306 struct got_object_id *re_id, *se_id;
6307 struct got_tag_object *re_tag, *se_tag;
6308 time_t re_time, se_time;
6310 STAILQ_FOREACH(re, tags, entry) {
6311 se = STAILQ_FIRST(sorted);
6312 if (se == NULL) {
6313 err = got_reflist_entry_dup(&new, re);
6314 if (err)
6315 return err;
6316 STAILQ_INSERT_HEAD(sorted, new, entry);
6317 continue;
6318 } else {
6319 err = got_ref_resolve(&re_id, repo, re->ref);
6320 if (err)
6321 break;
6322 err = got_object_open_as_tag(&re_tag, repo, re_id);
6323 free(re_id);
6324 if (err)
6325 break;
6326 re_time = got_object_tag_get_tagger_time(re_tag);
6327 got_object_tag_close(re_tag);
6330 while (se) {
6331 err = got_ref_resolve(&se_id, repo, re->ref);
6332 if (err)
6333 break;
6334 err = got_object_open_as_tag(&se_tag, repo, se_id);
6335 free(se_id);
6336 if (err)
6337 break;
6338 se_time = got_object_tag_get_tagger_time(se_tag);
6339 got_object_tag_close(se_tag);
6341 if (se_time > re_time) {
6342 err = got_reflist_entry_dup(&new, re);
6343 if (err)
6344 return err;
6345 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6346 break;
6348 se = STAILQ_NEXT(se, entry);
6349 continue;
6352 done:
6353 return err;
6355 #endif
6357 static const struct got_error *
6358 list_tags(struct got_repository *repo, struct got_worktree *worktree)
6360 static const struct got_error *err = NULL;
6361 struct got_reflist_head refs;
6362 struct got_reflist_entry *re;
6364 TAILQ_INIT(&refs);
6366 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6367 if (err)
6368 return err;
6370 TAILQ_FOREACH(re, &refs, entry) {
6371 const char *refname;
6372 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6373 char datebuf[26];
6374 const char *tagger;
6375 time_t tagger_time;
6376 struct got_object_id *id;
6377 struct got_tag_object *tag;
6378 struct got_commit_object *commit = NULL;
6380 refname = got_ref_get_name(re->ref);
6381 if (strncmp(refname, "refs/tags/", 10) != 0)
6382 continue;
6383 refname += 10;
6384 refstr = got_ref_to_str(re->ref);
6385 if (refstr == NULL) {
6386 err = got_error_from_errno("got_ref_to_str");
6387 break;
6389 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6390 free(refstr);
6392 err = got_ref_resolve(&id, repo, re->ref);
6393 if (err)
6394 break;
6395 err = got_object_open_as_tag(&tag, repo, id);
6396 if (err) {
6397 if (err->code != GOT_ERR_OBJ_TYPE) {
6398 free(id);
6399 break;
6401 /* "lightweight" tag */
6402 err = got_object_open_as_commit(&commit, repo, id);
6403 if (err) {
6404 free(id);
6405 break;
6407 tagger = got_object_commit_get_committer(commit);
6408 tagger_time =
6409 got_object_commit_get_committer_time(commit);
6410 err = got_object_id_str(&id_str, id);
6411 free(id);
6412 if (err)
6413 break;
6414 } else {
6415 free(id);
6416 tagger = got_object_tag_get_tagger(tag);
6417 tagger_time = got_object_tag_get_tagger_time(tag);
6418 err = got_object_id_str(&id_str,
6419 got_object_tag_get_object_id(tag));
6420 if (err)
6421 break;
6423 printf("from: %s\n", tagger);
6424 datestr = get_datestr(&tagger_time, datebuf);
6425 if (datestr)
6426 printf("date: %s UTC\n", datestr);
6427 if (commit)
6428 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6429 else {
6430 switch (got_object_tag_get_object_type(tag)) {
6431 case GOT_OBJ_TYPE_BLOB:
6432 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6433 id_str);
6434 break;
6435 case GOT_OBJ_TYPE_TREE:
6436 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6437 id_str);
6438 break;
6439 case GOT_OBJ_TYPE_COMMIT:
6440 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6441 id_str);
6442 break;
6443 case GOT_OBJ_TYPE_TAG:
6444 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6445 id_str);
6446 break;
6447 default:
6448 break;
6451 free(id_str);
6452 if (commit) {
6453 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6454 if (err)
6455 break;
6456 got_object_commit_close(commit);
6457 } else {
6458 tagmsg0 = strdup(got_object_tag_get_message(tag));
6459 got_object_tag_close(tag);
6460 if (tagmsg0 == NULL) {
6461 err = got_error_from_errno("strdup");
6462 break;
6466 tagmsg = tagmsg0;
6467 do {
6468 line = strsep(&tagmsg, "\n");
6469 if (line)
6470 printf(" %s\n", line);
6471 } while (line);
6472 free(tagmsg0);
6475 got_ref_list_free(&refs);
6476 return NULL;
6479 static const struct got_error *
6480 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6481 const char *tag_name, const char *repo_path)
6483 const struct got_error *err = NULL;
6484 char *template = NULL, *initial_content = NULL;
6485 char *editor = NULL;
6486 int initial_content_len;
6487 int fd = -1;
6489 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6490 err = got_error_from_errno("asprintf");
6491 goto done;
6494 initial_content_len = asprintf(&initial_content,
6495 "\n# tagging commit %s as %s\n",
6496 commit_id_str, tag_name);
6497 if (initial_content_len == -1) {
6498 err = got_error_from_errno("asprintf");
6499 goto done;
6502 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6503 if (err)
6504 goto done;
6506 if (write(fd, initial_content, initial_content_len) == -1) {
6507 err = got_error_from_errno2("write", *tagmsg_path);
6508 goto done;
6511 err = get_editor(&editor);
6512 if (err)
6513 goto done;
6514 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6515 initial_content_len, 1);
6516 done:
6517 free(initial_content);
6518 free(template);
6519 free(editor);
6521 if (fd != -1 && close(fd) == -1 && err == NULL)
6522 err = got_error_from_errno2("close", *tagmsg_path);
6524 /* Editor is done; we can now apply unveil(2) */
6525 if (err == NULL)
6526 err = apply_unveil(repo_path, 0, NULL);
6527 if (err) {
6528 free(*tagmsg);
6529 *tagmsg = NULL;
6531 return err;
6534 static const struct got_error *
6535 add_tag(struct got_repository *repo, struct got_worktree *worktree,
6536 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6538 const struct got_error *err = NULL;
6539 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6540 char *label = NULL, *commit_id_str = NULL;
6541 struct got_reference *ref = NULL;
6542 char *refname = NULL, *tagmsg = NULL, *tagger = NULL;
6543 char *tagmsg_path = NULL, *tag_id_str = NULL;
6544 int preserve_tagmsg = 0;
6545 struct got_reflist_head refs;
6547 TAILQ_INIT(&refs);
6550 * Don't let the user create a tag name with a leading '-'.
6551 * While technically a valid reference name, this case is usually
6552 * an unintended typo.
6554 if (tag_name[0] == '-')
6555 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6557 err = get_author(&tagger, repo, worktree);
6558 if (err)
6559 return err;
6561 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6562 if (err)
6563 goto done;
6565 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6566 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6567 if (err)
6568 goto done;
6570 err = got_object_id_str(&commit_id_str, commit_id);
6571 if (err)
6572 goto done;
6574 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6575 refname = strdup(tag_name);
6576 if (refname == NULL) {
6577 err = got_error_from_errno("strdup");
6578 goto done;
6580 tag_name += 10;
6581 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6582 err = got_error_from_errno("asprintf");
6583 goto done;
6586 err = got_ref_open(&ref, repo, refname, 0);
6587 if (err == NULL) {
6588 err = got_error(GOT_ERR_TAG_EXISTS);
6589 goto done;
6590 } else if (err->code != GOT_ERR_NOT_REF)
6591 goto done;
6593 if (tagmsg_arg == NULL) {
6594 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6595 tag_name, got_repo_get_path(repo));
6596 if (err) {
6597 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6598 tagmsg_path != NULL)
6599 preserve_tagmsg = 1;
6600 goto done;
6604 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6605 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6606 if (err) {
6607 if (tagmsg_path)
6608 preserve_tagmsg = 1;
6609 goto done;
6612 err = got_ref_alloc(&ref, refname, tag_id);
6613 if (err) {
6614 if (tagmsg_path)
6615 preserve_tagmsg = 1;
6616 goto done;
6619 err = got_ref_write(ref, repo);
6620 if (err) {
6621 if (tagmsg_path)
6622 preserve_tagmsg = 1;
6623 goto done;
6626 err = got_object_id_str(&tag_id_str, tag_id);
6627 if (err) {
6628 if (tagmsg_path)
6629 preserve_tagmsg = 1;
6630 goto done;
6632 printf("Created tag %s\n", tag_id_str);
6633 done:
6634 if (preserve_tagmsg) {
6635 fprintf(stderr, "%s: tag message preserved in %s\n",
6636 getprogname(), tagmsg_path);
6637 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6638 err = got_error_from_errno2("unlink", tagmsg_path);
6639 free(tag_id_str);
6640 if (ref)
6641 got_ref_close(ref);
6642 free(commit_id);
6643 free(commit_id_str);
6644 free(refname);
6645 free(tagmsg);
6646 free(tagmsg_path);
6647 free(tagger);
6648 got_ref_list_free(&refs);
6649 return err;
6652 static const struct got_error *
6653 cmd_tag(int argc, char *argv[])
6655 const struct got_error *error = NULL;
6656 struct got_repository *repo = NULL;
6657 struct got_worktree *worktree = NULL;
6658 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6659 char *gitconfig_path = NULL;
6660 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6661 int ch, do_list = 0;
6663 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6664 switch (ch) {
6665 case 'c':
6666 commit_id_arg = optarg;
6667 break;
6668 case 'm':
6669 tagmsg = optarg;
6670 break;
6671 case 'r':
6672 repo_path = realpath(optarg, NULL);
6673 if (repo_path == NULL)
6674 return got_error_from_errno2("realpath",
6675 optarg);
6676 got_path_strip_trailing_slashes(repo_path);
6677 break;
6678 case 'l':
6679 do_list = 1;
6680 break;
6681 default:
6682 usage_tag();
6683 /* NOTREACHED */
6687 argc -= optind;
6688 argv += optind;
6690 if (do_list) {
6691 if (commit_id_arg != NULL)
6692 errx(1,
6693 "-c option can only be used when creating a tag");
6694 if (tagmsg)
6695 option_conflict('l', 'm');
6696 if (argc > 0)
6697 usage_tag();
6698 } else if (argc != 1)
6699 usage_tag();
6701 tag_name = argv[0];
6703 #ifndef PROFILE
6704 if (do_list) {
6705 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6706 NULL) == -1)
6707 err(1, "pledge");
6708 } else {
6709 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6710 "sendfd unveil", NULL) == -1)
6711 err(1, "pledge");
6713 #endif
6714 cwd = getcwd(NULL, 0);
6715 if (cwd == NULL) {
6716 error = got_error_from_errno("getcwd");
6717 goto done;
6720 if (repo_path == NULL) {
6721 error = got_worktree_open(&worktree, cwd);
6722 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6723 goto done;
6724 else
6725 error = NULL;
6726 if (worktree) {
6727 repo_path =
6728 strdup(got_worktree_get_repo_path(worktree));
6729 if (repo_path == NULL)
6730 error = got_error_from_errno("strdup");
6731 if (error)
6732 goto done;
6733 } else {
6734 repo_path = strdup(cwd);
6735 if (repo_path == NULL) {
6736 error = got_error_from_errno("strdup");
6737 goto done;
6742 if (do_list) {
6743 error = got_repo_open(&repo, repo_path, NULL);
6744 if (error != NULL)
6745 goto done;
6746 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6747 if (error)
6748 goto done;
6749 error = list_tags(repo, worktree);
6750 } else {
6751 error = get_gitconfig_path(&gitconfig_path);
6752 if (error)
6753 goto done;
6754 error = got_repo_open(&repo, repo_path, gitconfig_path);
6755 if (error != NULL)
6756 goto done;
6758 if (tagmsg) {
6759 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6760 if (error)
6761 goto done;
6764 if (commit_id_arg == NULL) {
6765 struct got_reference *head_ref;
6766 struct got_object_id *commit_id;
6767 error = got_ref_open(&head_ref, repo,
6768 worktree ? got_worktree_get_head_ref_name(worktree)
6769 : GOT_REF_HEAD, 0);
6770 if (error)
6771 goto done;
6772 error = got_ref_resolve(&commit_id, repo, head_ref);
6773 got_ref_close(head_ref);
6774 if (error)
6775 goto done;
6776 error = got_object_id_str(&commit_id_str, commit_id);
6777 free(commit_id);
6778 if (error)
6779 goto done;
6782 error = add_tag(repo, worktree, tag_name,
6783 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6785 done:
6786 if (repo) {
6787 const struct got_error *close_err = got_repo_close(repo);
6788 if (error == NULL)
6789 error = close_err;
6791 if (worktree)
6792 got_worktree_close(worktree);
6793 free(cwd);
6794 free(repo_path);
6795 free(gitconfig_path);
6796 free(commit_id_str);
6797 return error;
6800 __dead static void
6801 usage_add(void)
6803 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6804 getprogname());
6805 exit(1);
6808 static const struct got_error *
6809 add_progress(void *arg, unsigned char status, const char *path)
6811 while (path[0] == '/')
6812 path++;
6813 printf("%c %s\n", status, path);
6814 return NULL;
6817 static const struct got_error *
6818 cmd_add(int argc, char *argv[])
6820 const struct got_error *error = NULL;
6821 struct got_repository *repo = NULL;
6822 struct got_worktree *worktree = NULL;
6823 char *cwd = NULL;
6824 struct got_pathlist_head paths;
6825 struct got_pathlist_entry *pe;
6826 int ch, can_recurse = 0, no_ignores = 0;
6828 TAILQ_INIT(&paths);
6830 while ((ch = getopt(argc, argv, "IR")) != -1) {
6831 switch (ch) {
6832 case 'I':
6833 no_ignores = 1;
6834 break;
6835 case 'R':
6836 can_recurse = 1;
6837 break;
6838 default:
6839 usage_add();
6840 /* NOTREACHED */
6844 argc -= optind;
6845 argv += optind;
6847 #ifndef PROFILE
6848 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6849 NULL) == -1)
6850 err(1, "pledge");
6851 #endif
6852 if (argc < 1)
6853 usage_add();
6855 cwd = getcwd(NULL, 0);
6856 if (cwd == NULL) {
6857 error = got_error_from_errno("getcwd");
6858 goto done;
6861 error = got_worktree_open(&worktree, cwd);
6862 if (error) {
6863 if (error->code == GOT_ERR_NOT_WORKTREE)
6864 error = wrap_not_worktree_error(error, "add", cwd);
6865 goto done;
6868 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6869 NULL);
6870 if (error != NULL)
6871 goto done;
6873 error = apply_unveil(got_repo_get_path(repo), 1,
6874 got_worktree_get_root_path(worktree));
6875 if (error)
6876 goto done;
6878 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6879 if (error)
6880 goto done;
6882 if (!can_recurse) {
6883 char *ondisk_path;
6884 struct stat sb;
6885 TAILQ_FOREACH(pe, &paths, entry) {
6886 if (asprintf(&ondisk_path, "%s/%s",
6887 got_worktree_get_root_path(worktree),
6888 pe->path) == -1) {
6889 error = got_error_from_errno("asprintf");
6890 goto done;
6892 if (lstat(ondisk_path, &sb) == -1) {
6893 if (errno == ENOENT) {
6894 free(ondisk_path);
6895 continue;
6897 error = got_error_from_errno2("lstat",
6898 ondisk_path);
6899 free(ondisk_path);
6900 goto done;
6902 free(ondisk_path);
6903 if (S_ISDIR(sb.st_mode)) {
6904 error = got_error_msg(GOT_ERR_BAD_PATH,
6905 "adding directories requires -R option");
6906 goto done;
6911 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6912 NULL, repo, no_ignores);
6913 done:
6914 if (repo) {
6915 const struct got_error *close_err = got_repo_close(repo);
6916 if (error == NULL)
6917 error = close_err;
6919 if (worktree)
6920 got_worktree_close(worktree);
6921 TAILQ_FOREACH(pe, &paths, entry)
6922 free((char *)pe->path);
6923 got_pathlist_free(&paths);
6924 free(cwd);
6925 return error;
6928 __dead static void
6929 usage_remove(void)
6931 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
6932 "path ...\n", getprogname());
6933 exit(1);
6936 static const struct got_error *
6937 print_remove_status(void *arg, unsigned char status,
6938 unsigned char staged_status, const char *path)
6940 while (path[0] == '/')
6941 path++;
6942 if (status == GOT_STATUS_NONEXISTENT)
6943 return NULL;
6944 if (status == staged_status && (status == GOT_STATUS_DELETE))
6945 status = GOT_STATUS_NO_CHANGE;
6946 printf("%c%c %s\n", status, staged_status, path);
6947 return NULL;
6950 static const struct got_error *
6951 cmd_remove(int argc, char *argv[])
6953 const struct got_error *error = NULL;
6954 struct got_worktree *worktree = NULL;
6955 struct got_repository *repo = NULL;
6956 const char *status_codes = NULL;
6957 char *cwd = NULL;
6958 struct got_pathlist_head paths;
6959 struct got_pathlist_entry *pe;
6960 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6962 TAILQ_INIT(&paths);
6964 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6965 switch (ch) {
6966 case 'f':
6967 delete_local_mods = 1;
6968 break;
6969 case 'k':
6970 keep_on_disk = 1;
6971 break;
6972 case 'R':
6973 can_recurse = 1;
6974 break;
6975 case 's':
6976 for (i = 0; i < strlen(optarg); i++) {
6977 switch (optarg[i]) {
6978 case GOT_STATUS_MODIFY:
6979 delete_local_mods = 1;
6980 break;
6981 case GOT_STATUS_MISSING:
6982 break;
6983 default:
6984 errx(1, "invalid status code '%c'",
6985 optarg[i]);
6988 status_codes = optarg;
6989 break;
6990 default:
6991 usage_remove();
6992 /* NOTREACHED */
6996 argc -= optind;
6997 argv += optind;
6999 #ifndef PROFILE
7000 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7001 NULL) == -1)
7002 err(1, "pledge");
7003 #endif
7004 if (argc < 1)
7005 usage_remove();
7007 cwd = getcwd(NULL, 0);
7008 if (cwd == NULL) {
7009 error = got_error_from_errno("getcwd");
7010 goto done;
7012 error = got_worktree_open(&worktree, cwd);
7013 if (error) {
7014 if (error->code == GOT_ERR_NOT_WORKTREE)
7015 error = wrap_not_worktree_error(error, "remove", cwd);
7016 goto done;
7019 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7020 NULL);
7021 if (error)
7022 goto done;
7024 error = apply_unveil(got_repo_get_path(repo), 1,
7025 got_worktree_get_root_path(worktree));
7026 if (error)
7027 goto done;
7029 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7030 if (error)
7031 goto done;
7033 if (!can_recurse) {
7034 char *ondisk_path;
7035 struct stat sb;
7036 TAILQ_FOREACH(pe, &paths, entry) {
7037 if (asprintf(&ondisk_path, "%s/%s",
7038 got_worktree_get_root_path(worktree),
7039 pe->path) == -1) {
7040 error = got_error_from_errno("asprintf");
7041 goto done;
7043 if (lstat(ondisk_path, &sb) == -1) {
7044 if (errno == ENOENT) {
7045 free(ondisk_path);
7046 continue;
7048 error = got_error_from_errno2("lstat",
7049 ondisk_path);
7050 free(ondisk_path);
7051 goto done;
7053 free(ondisk_path);
7054 if (S_ISDIR(sb.st_mode)) {
7055 error = got_error_msg(GOT_ERR_BAD_PATH,
7056 "removing directories requires -R option");
7057 goto done;
7062 error = got_worktree_schedule_delete(worktree, &paths,
7063 delete_local_mods, status_codes, print_remove_status, NULL,
7064 repo, keep_on_disk);
7065 done:
7066 if (repo) {
7067 const struct got_error *close_err = got_repo_close(repo);
7068 if (error == NULL)
7069 error = close_err;
7071 if (worktree)
7072 got_worktree_close(worktree);
7073 TAILQ_FOREACH(pe, &paths, entry)
7074 free((char *)pe->path);
7075 got_pathlist_free(&paths);
7076 free(cwd);
7077 return error;
7080 __dead static void
7081 usage_revert(void)
7083 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7084 "path ...\n", getprogname());
7085 exit(1);
7088 static const struct got_error *
7089 revert_progress(void *arg, unsigned char status, const char *path)
7091 if (status == GOT_STATUS_UNVERSIONED)
7092 return NULL;
7094 while (path[0] == '/')
7095 path++;
7096 printf("%c %s\n", status, path);
7097 return NULL;
7100 struct choose_patch_arg {
7101 FILE *patch_script_file;
7102 const char *action;
7105 static const struct got_error *
7106 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7107 int nchanges, const char *action)
7109 char *line = NULL;
7110 size_t linesize = 0;
7111 ssize_t linelen;
7113 switch (status) {
7114 case GOT_STATUS_ADD:
7115 printf("A %s\n%s this addition? [y/n] ", path, action);
7116 break;
7117 case GOT_STATUS_DELETE:
7118 printf("D %s\n%s this deletion? [y/n] ", path, action);
7119 break;
7120 case GOT_STATUS_MODIFY:
7121 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7122 return got_error_from_errno("fseek");
7123 printf(GOT_COMMIT_SEP_STR);
7124 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7125 printf("%s", line);
7126 if (ferror(patch_file))
7127 return got_error_from_errno("getline");
7128 printf(GOT_COMMIT_SEP_STR);
7129 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7130 path, n, nchanges, action);
7131 break;
7132 default:
7133 return got_error_path(path, GOT_ERR_FILE_STATUS);
7136 return NULL;
7139 static const struct got_error *
7140 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7141 FILE *patch_file, int n, int nchanges)
7143 const struct got_error *err = NULL;
7144 char *line = NULL;
7145 size_t linesize = 0;
7146 ssize_t linelen;
7147 int resp = ' ';
7148 struct choose_patch_arg *a = arg;
7150 *choice = GOT_PATCH_CHOICE_NONE;
7152 if (a->patch_script_file) {
7153 char *nl;
7154 err = show_change(status, path, patch_file, n, nchanges,
7155 a->action);
7156 if (err)
7157 return err;
7158 linelen = getline(&line, &linesize, a->patch_script_file);
7159 if (linelen == -1) {
7160 if (ferror(a->patch_script_file))
7161 return got_error_from_errno("getline");
7162 return NULL;
7164 nl = strchr(line, '\n');
7165 if (nl)
7166 *nl = '\0';
7167 if (strcmp(line, "y") == 0) {
7168 *choice = GOT_PATCH_CHOICE_YES;
7169 printf("y\n");
7170 } else if (strcmp(line, "n") == 0) {
7171 *choice = GOT_PATCH_CHOICE_NO;
7172 printf("n\n");
7173 } else if (strcmp(line, "q") == 0 &&
7174 status == GOT_STATUS_MODIFY) {
7175 *choice = GOT_PATCH_CHOICE_QUIT;
7176 printf("q\n");
7177 } else
7178 printf("invalid response '%s'\n", line);
7179 free(line);
7180 return NULL;
7183 while (resp != 'y' && resp != 'n' && resp != 'q') {
7184 err = show_change(status, path, patch_file, n, nchanges,
7185 a->action);
7186 if (err)
7187 return err;
7188 resp = getchar();
7189 if (resp == '\n')
7190 resp = getchar();
7191 if (status == GOT_STATUS_MODIFY) {
7192 if (resp != 'y' && resp != 'n' && resp != 'q') {
7193 printf("invalid response '%c'\n", resp);
7194 resp = ' ';
7196 } else if (resp != 'y' && resp != 'n') {
7197 printf("invalid response '%c'\n", resp);
7198 resp = ' ';
7202 if (resp == 'y')
7203 *choice = GOT_PATCH_CHOICE_YES;
7204 else if (resp == 'n')
7205 *choice = GOT_PATCH_CHOICE_NO;
7206 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7207 *choice = GOT_PATCH_CHOICE_QUIT;
7209 return NULL;
7213 static const struct got_error *
7214 cmd_revert(int argc, char *argv[])
7216 const struct got_error *error = NULL;
7217 struct got_worktree *worktree = NULL;
7218 struct got_repository *repo = NULL;
7219 char *cwd = NULL, *path = NULL;
7220 struct got_pathlist_head paths;
7221 struct got_pathlist_entry *pe;
7222 int ch, can_recurse = 0, pflag = 0;
7223 FILE *patch_script_file = NULL;
7224 const char *patch_script_path = NULL;
7225 struct choose_patch_arg cpa;
7227 TAILQ_INIT(&paths);
7229 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7230 switch (ch) {
7231 case 'p':
7232 pflag = 1;
7233 break;
7234 case 'F':
7235 patch_script_path = optarg;
7236 break;
7237 case 'R':
7238 can_recurse = 1;
7239 break;
7240 default:
7241 usage_revert();
7242 /* NOTREACHED */
7246 argc -= optind;
7247 argv += optind;
7249 #ifndef PROFILE
7250 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7251 "unveil", NULL) == -1)
7252 err(1, "pledge");
7253 #endif
7254 if (argc < 1)
7255 usage_revert();
7256 if (patch_script_path && !pflag)
7257 errx(1, "-F option can only be used together with -p option");
7259 cwd = getcwd(NULL, 0);
7260 if (cwd == NULL) {
7261 error = got_error_from_errno("getcwd");
7262 goto done;
7264 error = got_worktree_open(&worktree, cwd);
7265 if (error) {
7266 if (error->code == GOT_ERR_NOT_WORKTREE)
7267 error = wrap_not_worktree_error(error, "revert", cwd);
7268 goto done;
7271 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7272 NULL);
7273 if (error != NULL)
7274 goto done;
7276 if (patch_script_path) {
7277 patch_script_file = fopen(patch_script_path, "r");
7278 if (patch_script_file == NULL) {
7279 error = got_error_from_errno2("fopen",
7280 patch_script_path);
7281 goto done;
7284 error = apply_unveil(got_repo_get_path(repo), 1,
7285 got_worktree_get_root_path(worktree));
7286 if (error)
7287 goto done;
7289 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7290 if (error)
7291 goto done;
7293 if (!can_recurse) {
7294 char *ondisk_path;
7295 struct stat sb;
7296 TAILQ_FOREACH(pe, &paths, entry) {
7297 if (asprintf(&ondisk_path, "%s/%s",
7298 got_worktree_get_root_path(worktree),
7299 pe->path) == -1) {
7300 error = got_error_from_errno("asprintf");
7301 goto done;
7303 if (lstat(ondisk_path, &sb) == -1) {
7304 if (errno == ENOENT) {
7305 free(ondisk_path);
7306 continue;
7308 error = got_error_from_errno2("lstat",
7309 ondisk_path);
7310 free(ondisk_path);
7311 goto done;
7313 free(ondisk_path);
7314 if (S_ISDIR(sb.st_mode)) {
7315 error = got_error_msg(GOT_ERR_BAD_PATH,
7316 "reverting directories requires -R option");
7317 goto done;
7322 cpa.patch_script_file = patch_script_file;
7323 cpa.action = "revert";
7324 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7325 pflag ? choose_patch : NULL, &cpa, repo);
7326 done:
7327 if (patch_script_file && fclose(patch_script_file) == EOF &&
7328 error == NULL)
7329 error = got_error_from_errno2("fclose", patch_script_path);
7330 if (repo) {
7331 const struct got_error *close_err = got_repo_close(repo);
7332 if (error == NULL)
7333 error = close_err;
7335 if (worktree)
7336 got_worktree_close(worktree);
7337 free(path);
7338 free(cwd);
7339 return error;
7342 __dead static void
7343 usage_commit(void)
7345 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7346 "[path ...]\n", getprogname());
7347 exit(1);
7350 struct collect_commit_logmsg_arg {
7351 const char *cmdline_log;
7352 const char *prepared_log;
7353 int non_interactive;
7354 const char *editor;
7355 const char *worktree_path;
7356 const char *branch_name;
7357 const char *repo_path;
7358 char *logmsg_path;
7362 static const struct got_error *
7363 read_prepared_logmsg(char **logmsg, const char *path)
7365 const struct got_error *err = NULL;
7366 FILE *f = NULL;
7367 struct stat sb;
7368 size_t r;
7370 *logmsg = NULL;
7371 memset(&sb, 0, sizeof(sb));
7373 f = fopen(path, "r");
7374 if (f == NULL)
7375 return got_error_from_errno2("fopen", path);
7377 if (fstat(fileno(f), &sb) == -1) {
7378 err = got_error_from_errno2("fstat", path);
7379 goto done;
7381 if (sb.st_size == 0) {
7382 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7383 goto done;
7386 *logmsg = malloc(sb.st_size + 1);
7387 if (*logmsg == NULL) {
7388 err = got_error_from_errno("malloc");
7389 goto done;
7392 r = fread(*logmsg, 1, sb.st_size, f);
7393 if (r != sb.st_size) {
7394 if (ferror(f))
7395 err = got_error_from_errno2("fread", path);
7396 else
7397 err = got_error(GOT_ERR_IO);
7398 goto done;
7400 (*logmsg)[sb.st_size] = '\0';
7401 done:
7402 if (fclose(f) == EOF && err == NULL)
7403 err = got_error_from_errno2("fclose", path);
7404 if (err) {
7405 free(*logmsg);
7406 *logmsg = NULL;
7408 return err;
7412 static const struct got_error *
7413 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7414 void *arg)
7416 char *initial_content = NULL;
7417 struct got_pathlist_entry *pe;
7418 const struct got_error *err = NULL;
7419 char *template = NULL;
7420 struct collect_commit_logmsg_arg *a = arg;
7421 int initial_content_len;
7422 int fd = -1;
7423 size_t len;
7425 /* if a message was specified on the command line, just use it */
7426 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7427 len = strlen(a->cmdline_log) + 1;
7428 *logmsg = malloc(len + 1);
7429 if (*logmsg == NULL)
7430 return got_error_from_errno("malloc");
7431 strlcpy(*logmsg, a->cmdline_log, len);
7432 return NULL;
7433 } else if (a->prepared_log != NULL && a->non_interactive)
7434 return read_prepared_logmsg(logmsg, a->prepared_log);
7436 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7437 return got_error_from_errno("asprintf");
7439 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7440 if (err)
7441 goto done;
7443 if (a->prepared_log) {
7444 char *msg;
7445 err = read_prepared_logmsg(&msg, a->prepared_log);
7446 if (err)
7447 goto done;
7448 if (write(fd, msg, strlen(msg)) == -1) {
7449 err = got_error_from_errno2("write", a->logmsg_path);
7450 free(msg);
7451 goto done;
7453 free(msg);
7456 initial_content_len = asprintf(&initial_content,
7457 "\n# changes to be committed on branch %s:\n",
7458 a->branch_name);
7459 if (initial_content_len == -1) {
7460 err = got_error_from_errno("asprintf");
7461 goto done;
7464 if (write(fd, initial_content, initial_content_len) == -1) {
7465 err = got_error_from_errno2("write", a->logmsg_path);
7466 goto done;
7469 TAILQ_FOREACH(pe, commitable_paths, entry) {
7470 struct got_commitable *ct = pe->data;
7471 dprintf(fd, "# %c %s\n",
7472 got_commitable_get_status(ct),
7473 got_commitable_get_path(ct));
7476 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7477 initial_content_len, a->prepared_log ? 0 : 1);
7478 done:
7479 free(initial_content);
7480 free(template);
7482 if (fd != -1 && close(fd) == -1 && err == NULL)
7483 err = got_error_from_errno2("close", a->logmsg_path);
7485 /* Editor is done; we can now apply unveil(2) */
7486 if (err == NULL)
7487 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7488 if (err) {
7489 free(*logmsg);
7490 *logmsg = NULL;
7492 return err;
7495 static const struct got_error *
7496 cmd_commit(int argc, char *argv[])
7498 const struct got_error *error = NULL;
7499 struct got_worktree *worktree = NULL;
7500 struct got_repository *repo = NULL;
7501 char *cwd = NULL, *id_str = NULL;
7502 struct got_object_id *id = NULL;
7503 const char *logmsg = NULL;
7504 char *prepared_logmsg = NULL;
7505 struct collect_commit_logmsg_arg cl_arg;
7506 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7507 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7508 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7509 struct got_pathlist_head paths;
7511 TAILQ_INIT(&paths);
7512 cl_arg.logmsg_path = NULL;
7514 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7515 switch (ch) {
7516 case 'F':
7517 if (logmsg != NULL)
7518 option_conflict('F', 'm');
7519 prepared_logmsg = realpath(optarg, NULL);
7520 if (prepared_logmsg == NULL)
7521 return got_error_from_errno2("realpath",
7522 optarg);
7523 break;
7524 case 'm':
7525 if (prepared_logmsg)
7526 option_conflict('m', 'F');
7527 logmsg = optarg;
7528 break;
7529 case 'N':
7530 non_interactive = 1;
7531 break;
7532 case 'S':
7533 allow_bad_symlinks = 1;
7534 break;
7535 default:
7536 usage_commit();
7537 /* NOTREACHED */
7541 argc -= optind;
7542 argv += optind;
7544 #ifndef PROFILE
7545 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7546 "unveil", NULL) == -1)
7547 err(1, "pledge");
7548 #endif
7549 cwd = getcwd(NULL, 0);
7550 if (cwd == NULL) {
7551 error = got_error_from_errno("getcwd");
7552 goto done;
7554 error = got_worktree_open(&worktree, cwd);
7555 if (error) {
7556 if (error->code == GOT_ERR_NOT_WORKTREE)
7557 error = wrap_not_worktree_error(error, "commit", cwd);
7558 goto done;
7561 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7562 if (error)
7563 goto done;
7564 if (rebase_in_progress) {
7565 error = got_error(GOT_ERR_REBASING);
7566 goto done;
7569 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7570 worktree);
7571 if (error)
7572 goto done;
7574 error = get_gitconfig_path(&gitconfig_path);
7575 if (error)
7576 goto done;
7577 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7578 gitconfig_path);
7579 if (error != NULL)
7580 goto done;
7582 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7583 if (error)
7584 goto done;
7585 if (merge_in_progress) {
7586 error = got_error(GOT_ERR_MERGE_BUSY);
7587 goto done;
7590 error = get_author(&author, repo, worktree);
7591 if (error)
7592 return error;
7595 * unveil(2) traverses exec(2); if an editor is used we have
7596 * to apply unveil after the log message has been written.
7598 if (logmsg == NULL || strlen(logmsg) == 0)
7599 error = get_editor(&editor);
7600 else
7601 error = apply_unveil(got_repo_get_path(repo), 0,
7602 got_worktree_get_root_path(worktree));
7603 if (error)
7604 goto done;
7606 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7607 if (error)
7608 goto done;
7610 cl_arg.editor = editor;
7611 cl_arg.cmdline_log = logmsg;
7612 cl_arg.prepared_log = prepared_logmsg;
7613 cl_arg.non_interactive = non_interactive;
7614 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7615 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7616 if (!histedit_in_progress) {
7617 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7618 error = got_error(GOT_ERR_COMMIT_BRANCH);
7619 goto done;
7621 cl_arg.branch_name += 11;
7623 cl_arg.repo_path = got_repo_get_path(repo);
7624 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7625 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7626 print_status, NULL, repo);
7627 if (error) {
7628 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7629 cl_arg.logmsg_path != NULL)
7630 preserve_logmsg = 1;
7631 goto done;
7634 error = got_object_id_str(&id_str, id);
7635 if (error)
7636 goto done;
7637 printf("Created commit %s\n", id_str);
7638 done:
7639 if (preserve_logmsg) {
7640 fprintf(stderr, "%s: log message preserved in %s\n",
7641 getprogname(), cl_arg.logmsg_path);
7642 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7643 error == NULL)
7644 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7645 free(cl_arg.logmsg_path);
7646 if (repo) {
7647 const struct got_error *close_err = got_repo_close(repo);
7648 if (error == NULL)
7649 error = close_err;
7651 if (worktree)
7652 got_worktree_close(worktree);
7653 free(cwd);
7654 free(id_str);
7655 free(gitconfig_path);
7656 free(editor);
7657 free(author);
7658 free(prepared_logmsg);
7659 return error;
7662 __dead static void
7663 usage_send(void)
7665 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7666 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7667 "[remote-repository]\n", getprogname());
7668 exit(1);
7671 struct got_send_progress_arg {
7672 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7673 int verbosity;
7674 int last_ncommits;
7675 int last_nobj_total;
7676 int last_p_deltify;
7677 int last_p_written;
7678 int last_p_sent;
7679 int printed_something;
7680 int sent_something;
7681 struct got_pathlist_head *delete_branches;
7684 static const struct got_error *
7685 send_progress(void *arg, off_t packfile_size, int ncommits, int nobj_total,
7686 int nobj_deltify, int nobj_written, off_t bytes_sent, const char *refname,
7687 int success)
7689 struct got_send_progress_arg *a = arg;
7690 char scaled_packsize[FMT_SCALED_STRSIZE];
7691 char scaled_sent[FMT_SCALED_STRSIZE];
7692 int p_deltify = 0, p_written = 0, p_sent = 0;
7693 int print_searching = 0, print_total = 0;
7694 int print_deltify = 0, print_written = 0, print_sent = 0;
7696 if (a->verbosity < 0)
7697 return NULL;
7699 if (refname) {
7700 const char *status = success ? "accepted" : "rejected";
7702 if (success) {
7703 struct got_pathlist_entry *pe;
7704 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7705 const char *branchname = pe->path;
7706 if (got_path_cmp(branchname, refname,
7707 strlen(branchname), strlen(refname)) == 0) {
7708 status = "deleted";
7709 a->sent_something = 1;
7710 break;
7715 if (a->printed_something)
7716 putchar('\n');
7717 printf("Server has %s %s", status, refname);
7718 a->printed_something = 1;
7719 return NULL;
7722 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
7723 return got_error_from_errno("fmt_scaled");
7724 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
7725 return got_error_from_errno("fmt_scaled");
7727 if (a->last_ncommits != ncommits) {
7728 print_searching = 1;
7729 a->last_ncommits = ncommits;
7732 if (a->last_nobj_total != nobj_total) {
7733 print_searching = 1;
7734 print_total = 1;
7735 a->last_nobj_total = nobj_total;
7738 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
7739 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
7740 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
7741 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
7742 return got_error(GOT_ERR_NO_SPACE);
7745 if (nobj_deltify > 0 || nobj_written > 0) {
7746 if (nobj_deltify > 0) {
7747 p_deltify = (nobj_deltify * 100) / nobj_total;
7748 if (p_deltify != a->last_p_deltify) {
7749 a->last_p_deltify = p_deltify;
7750 print_searching = 1;
7751 print_total = 1;
7752 print_deltify = 1;
7755 if (nobj_written > 0) {
7756 p_written = (nobj_written * 100) / nobj_total;
7757 if (p_written != a->last_p_written) {
7758 a->last_p_written = p_written;
7759 print_searching = 1;
7760 print_total = 1;
7761 print_deltify = 1;
7762 print_written = 1;
7767 if (bytes_sent > 0) {
7768 p_sent = (bytes_sent * 100) / packfile_size;
7769 if (p_sent != a->last_p_sent) {
7770 a->last_p_sent = p_sent;
7771 print_searching = 1;
7772 print_total = 1;
7773 print_deltify = 1;
7774 print_written = 1;
7775 print_sent = 1;
7777 a->sent_something = 1;
7780 if (print_searching || print_total || print_deltify || print_written ||
7781 print_sent)
7782 printf("\r");
7783 if (print_searching)
7784 printf("packing %d reference%s", ncommits,
7785 ncommits == 1 ? "" : "s");
7786 if (print_total)
7787 printf("; %d object%s", nobj_total,
7788 nobj_total == 1 ? "" : "s");
7789 if (print_deltify)
7790 printf("; deltify: %d%%", p_deltify);
7791 if (print_sent)
7792 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE,
7793 scaled_packsize, p_sent);
7794 else if (print_written)
7795 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE,
7796 scaled_packsize, p_written);
7797 if (print_searching || print_total || print_deltify ||
7798 print_written || print_sent) {
7799 a->printed_something = 1;
7800 fflush(stdout);
7802 return NULL;
7805 static const struct got_error *
7806 cmd_send(int argc, char *argv[])
7808 const struct got_error *error = NULL;
7809 char *cwd = NULL, *repo_path = NULL;
7810 const char *remote_name;
7811 char *proto = NULL, *host = NULL, *port = NULL;
7812 char *repo_name = NULL, *server_path = NULL;
7813 const struct got_remote_repo *remotes, *remote = NULL;
7814 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
7815 struct got_repository *repo = NULL;
7816 struct got_worktree *worktree = NULL;
7817 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7818 struct got_pathlist_head branches;
7819 struct got_pathlist_head tags;
7820 struct got_reflist_head all_branches;
7821 struct got_reflist_head all_tags;
7822 struct got_pathlist_head delete_args;
7823 struct got_pathlist_head delete_branches;
7824 struct got_reflist_entry *re;
7825 struct got_pathlist_entry *pe;
7826 int i, ch, sendfd = -1, sendstatus;
7827 pid_t sendpid = -1;
7828 struct got_send_progress_arg spa;
7829 int verbosity = 0, overwrite_refs = 0;
7830 int send_all_branches = 0, send_all_tags = 0;
7831 struct got_reference *ref = NULL;
7833 TAILQ_INIT(&branches);
7834 TAILQ_INIT(&tags);
7835 TAILQ_INIT(&all_branches);
7836 TAILQ_INIT(&all_tags);
7837 TAILQ_INIT(&delete_args);
7838 TAILQ_INIT(&delete_branches);
7840 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
7841 switch (ch) {
7842 case 'a':
7843 send_all_branches = 1;
7844 break;
7845 case 'b':
7846 error = got_pathlist_append(&branches, optarg, NULL);
7847 if (error)
7848 return error;
7849 nbranches++;
7850 break;
7851 case 'd':
7852 error = got_pathlist_append(&delete_args, optarg, NULL);
7853 if (error)
7854 return error;
7855 break;
7856 case 'f':
7857 overwrite_refs = 1;
7858 break;
7859 case 'r':
7860 repo_path = realpath(optarg, NULL);
7861 if (repo_path == NULL)
7862 return got_error_from_errno2("realpath",
7863 optarg);
7864 got_path_strip_trailing_slashes(repo_path);
7865 break;
7866 case 't':
7867 error = got_pathlist_append(&tags, optarg, NULL);
7868 if (error)
7869 return error;
7870 ntags++;
7871 break;
7872 case 'T':
7873 send_all_tags = 1;
7874 break;
7875 case 'v':
7876 if (verbosity < 0)
7877 verbosity = 0;
7878 else if (verbosity < 3)
7879 verbosity++;
7880 break;
7881 case 'q':
7882 verbosity = -1;
7883 break;
7884 default:
7885 usage_send();
7886 /* NOTREACHED */
7889 argc -= optind;
7890 argv += optind;
7892 if (send_all_branches && !TAILQ_EMPTY(&branches))
7893 option_conflict('a', 'b');
7894 if (send_all_tags && !TAILQ_EMPTY(&tags))
7895 option_conflict('T', 't');
7898 if (argc == 0)
7899 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7900 else if (argc == 1)
7901 remote_name = argv[0];
7902 else
7903 usage_send();
7905 cwd = getcwd(NULL, 0);
7906 if (cwd == NULL) {
7907 error = got_error_from_errno("getcwd");
7908 goto done;
7911 if (repo_path == NULL) {
7912 error = got_worktree_open(&worktree, cwd);
7913 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7914 goto done;
7915 else
7916 error = NULL;
7917 if (worktree) {
7918 repo_path =
7919 strdup(got_worktree_get_repo_path(worktree));
7920 if (repo_path == NULL)
7921 error = got_error_from_errno("strdup");
7922 if (error)
7923 goto done;
7924 } else {
7925 repo_path = strdup(cwd);
7926 if (repo_path == NULL) {
7927 error = got_error_from_errno("strdup");
7928 goto done;
7933 error = got_repo_open(&repo, repo_path, NULL);
7934 if (error)
7935 goto done;
7937 if (worktree) {
7938 worktree_conf = got_worktree_get_gotconfig(worktree);
7939 if (worktree_conf) {
7940 got_gotconfig_get_remotes(&nremotes, &remotes,
7941 worktree_conf);
7942 for (i = 0; i < nremotes; i++) {
7943 if (strcmp(remotes[i].name, remote_name) == 0) {
7944 remote = &remotes[i];
7945 break;
7950 if (remote == NULL) {
7951 repo_conf = got_repo_get_gotconfig(repo);
7952 if (repo_conf) {
7953 got_gotconfig_get_remotes(&nremotes, &remotes,
7954 repo_conf);
7955 for (i = 0; i < nremotes; i++) {
7956 if (strcmp(remotes[i].name, remote_name) == 0) {
7957 remote = &remotes[i];
7958 break;
7963 if (remote == NULL) {
7964 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7965 for (i = 0; i < nremotes; i++) {
7966 if (strcmp(remotes[i].name, remote_name) == 0) {
7967 remote = &remotes[i];
7968 break;
7972 if (remote == NULL) {
7973 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7974 goto done;
7977 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7978 &repo_name, remote->send_url);
7979 if (error)
7980 goto done;
7982 if (strcmp(proto, "git") == 0) {
7983 #ifndef PROFILE
7984 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7985 "sendfd dns inet unveil", NULL) == -1)
7986 err(1, "pledge");
7987 #endif
7988 } else if (strcmp(proto, "git+ssh") == 0 ||
7989 strcmp(proto, "ssh") == 0) {
7990 #ifndef PROFILE
7991 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7992 "sendfd unveil", NULL) == -1)
7993 err(1, "pledge");
7994 #endif
7995 } else if (strcmp(proto, "http") == 0 ||
7996 strcmp(proto, "git+http") == 0) {
7997 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7998 goto done;
7999 } else {
8000 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8001 goto done;
8004 error = got_dial_apply_unveil(proto);
8005 if (error)
8006 goto done;
8008 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8009 if (error)
8010 goto done;
8012 if (send_all_branches) {
8013 error = got_ref_list(&all_branches, repo, "refs/heads",
8014 got_ref_cmp_by_name, NULL);
8015 if (error)
8016 goto done;
8017 TAILQ_FOREACH(re, &all_branches, entry) {
8018 const char *branchname = got_ref_get_name(re->ref);
8019 error = got_pathlist_append(&branches,
8020 branchname, NULL);
8021 if (error)
8022 goto done;
8023 nbranches++;
8025 } else if (nbranches == 0) {
8026 for (i = 0; i < remote->nsend_branches; i++) {
8027 got_pathlist_append(&branches,
8028 remote->send_branches[i], NULL);
8032 if (send_all_tags) {
8033 error = got_ref_list(&all_tags, repo, "refs/tags",
8034 got_ref_cmp_by_name, NULL);
8035 if (error)
8036 goto done;
8037 TAILQ_FOREACH(re, &all_tags, entry) {
8038 const char *tagname = got_ref_get_name(re->ref);
8039 error = got_pathlist_append(&tags,
8040 tagname, NULL);
8041 if (error)
8042 goto done;
8043 ntags++;
8048 * To prevent accidents only branches in refs/heads/ can be deleted
8049 * with 'got send -d'.
8050 * Deleting anything else requires local repository access or Git.
8052 TAILQ_FOREACH(pe, &delete_args, entry) {
8053 const char *branchname = pe->path;
8054 char *s;
8055 struct got_pathlist_entry *new;
8056 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8057 s = strdup(branchname);
8058 if (s == NULL) {
8059 error = got_error_from_errno("strdup");
8060 goto done;
8062 } else {
8063 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8064 error = got_error_from_errno("asprintf");
8065 goto done;
8068 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8069 if (error || new == NULL /* duplicate */)
8070 free(s);
8071 if (error)
8072 goto done;
8073 ndelete_branches++;
8076 if (nbranches == 0 && ndelete_branches == 0) {
8077 struct got_reference *head_ref;
8078 if (worktree)
8079 error = got_ref_open(&head_ref, repo,
8080 got_worktree_get_head_ref_name(worktree), 0);
8081 else
8082 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8083 if (error)
8084 goto done;
8085 if (got_ref_is_symbolic(head_ref)) {
8086 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8087 got_ref_close(head_ref);
8088 if (error)
8089 goto done;
8090 } else
8091 ref = head_ref;
8092 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8093 NULL);
8094 if (error)
8095 goto done;
8096 nbranches++;
8099 if (verbosity >= 0)
8100 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8101 port ? ":" : "", port ? port : "");
8103 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8104 server_path, verbosity);
8105 if (error)
8106 goto done;
8108 memset(&spa, 0, sizeof(spa));
8109 spa.last_scaled_packsize[0] = '\0';
8110 spa.last_p_deltify = -1;
8111 spa.last_p_written = -1;
8112 spa.verbosity = verbosity;
8113 spa.delete_branches = &delete_branches;
8114 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8115 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8116 check_cancelled, NULL);
8117 if (spa.printed_something)
8118 putchar('\n');
8119 if (error)
8120 goto done;
8121 if (!spa.sent_something && verbosity >= 0)
8122 printf("Already up-to-date\n");
8123 done:
8124 if (sendpid > 0) {
8125 if (kill(sendpid, SIGTERM) == -1)
8126 error = got_error_from_errno("kill");
8127 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8128 error = got_error_from_errno("waitpid");
8130 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8131 error = got_error_from_errno("close");
8132 if (repo) {
8133 const struct got_error *close_err = got_repo_close(repo);
8134 if (error == NULL)
8135 error = close_err;
8137 if (worktree)
8138 got_worktree_close(worktree);
8139 if (ref)
8140 got_ref_close(ref);
8141 got_pathlist_free(&branches);
8142 got_pathlist_free(&tags);
8143 got_ref_list_free(&all_branches);
8144 got_ref_list_free(&all_tags);
8145 got_pathlist_free(&delete_args);
8146 TAILQ_FOREACH(pe, &delete_branches, entry)
8147 free((char *)pe->path);
8148 got_pathlist_free(&delete_branches);
8149 free(cwd);
8150 free(repo_path);
8151 free(proto);
8152 free(host);
8153 free(port);
8154 free(server_path);
8155 free(repo_name);
8156 return error;
8159 __dead static void
8160 usage_cherrypick(void)
8162 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8163 exit(1);
8166 static const struct got_error *
8167 cmd_cherrypick(int argc, char *argv[])
8169 const struct got_error *error = NULL;
8170 struct got_worktree *worktree = NULL;
8171 struct got_repository *repo = NULL;
8172 char *cwd = NULL, *commit_id_str = NULL;
8173 struct got_object_id *commit_id = NULL;
8174 struct got_commit_object *commit = NULL;
8175 struct got_object_qid *pid;
8176 int ch;
8177 struct got_update_progress_arg upa;
8179 while ((ch = getopt(argc, argv, "")) != -1) {
8180 switch (ch) {
8181 default:
8182 usage_cherrypick();
8183 /* NOTREACHED */
8187 argc -= optind;
8188 argv += optind;
8190 #ifndef PROFILE
8191 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8192 "unveil", NULL) == -1)
8193 err(1, "pledge");
8194 #endif
8195 if (argc != 1)
8196 usage_cherrypick();
8198 cwd = getcwd(NULL, 0);
8199 if (cwd == NULL) {
8200 error = got_error_from_errno("getcwd");
8201 goto done;
8203 error = got_worktree_open(&worktree, cwd);
8204 if (error) {
8205 if (error->code == GOT_ERR_NOT_WORKTREE)
8206 error = wrap_not_worktree_error(error, "cherrypick",
8207 cwd);
8208 goto done;
8211 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8212 NULL);
8213 if (error != NULL)
8214 goto done;
8216 error = apply_unveil(got_repo_get_path(repo), 0,
8217 got_worktree_get_root_path(worktree));
8218 if (error)
8219 goto done;
8221 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8222 GOT_OBJ_TYPE_COMMIT, repo);
8223 if (error != NULL) {
8224 struct got_reference *ref;
8225 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8226 goto done;
8227 error = got_ref_open(&ref, repo, argv[0], 0);
8228 if (error != NULL)
8229 goto done;
8230 error = got_ref_resolve(&commit_id, repo, ref);
8231 got_ref_close(ref);
8232 if (error != NULL)
8233 goto done;
8235 error = got_object_id_str(&commit_id_str, commit_id);
8236 if (error)
8237 goto done;
8239 error = got_object_open_as_commit(&commit, repo, commit_id);
8240 if (error)
8241 goto done;
8242 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8243 memset(&upa, 0, sizeof(upa));
8244 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8245 commit_id, repo, update_progress, &upa, check_cancelled,
8246 NULL);
8247 if (error != NULL)
8248 goto done;
8250 if (upa.did_something)
8251 printf("Merged commit %s\n", commit_id_str);
8252 print_merge_progress_stats(&upa);
8253 done:
8254 if (commit)
8255 got_object_commit_close(commit);
8256 free(commit_id_str);
8257 if (worktree)
8258 got_worktree_close(worktree);
8259 if (repo) {
8260 const struct got_error *close_err = got_repo_close(repo);
8261 if (error == NULL)
8262 error = close_err;
8264 return error;
8267 __dead static void
8268 usage_backout(void)
8270 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8271 exit(1);
8274 static const struct got_error *
8275 cmd_backout(int argc, char *argv[])
8277 const struct got_error *error = NULL;
8278 struct got_worktree *worktree = NULL;
8279 struct got_repository *repo = NULL;
8280 char *cwd = NULL, *commit_id_str = NULL;
8281 struct got_object_id *commit_id = NULL;
8282 struct got_commit_object *commit = NULL;
8283 struct got_object_qid *pid;
8284 int ch;
8285 struct got_update_progress_arg upa;
8287 while ((ch = getopt(argc, argv, "")) != -1) {
8288 switch (ch) {
8289 default:
8290 usage_backout();
8291 /* NOTREACHED */
8295 argc -= optind;
8296 argv += optind;
8298 #ifndef PROFILE
8299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8300 "unveil", NULL) == -1)
8301 err(1, "pledge");
8302 #endif
8303 if (argc != 1)
8304 usage_backout();
8306 cwd = getcwd(NULL, 0);
8307 if (cwd == NULL) {
8308 error = got_error_from_errno("getcwd");
8309 goto done;
8311 error = got_worktree_open(&worktree, cwd);
8312 if (error) {
8313 if (error->code == GOT_ERR_NOT_WORKTREE)
8314 error = wrap_not_worktree_error(error, "backout", cwd);
8315 goto done;
8318 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8319 NULL);
8320 if (error != NULL)
8321 goto done;
8323 error = apply_unveil(got_repo_get_path(repo), 0,
8324 got_worktree_get_root_path(worktree));
8325 if (error)
8326 goto done;
8328 error = got_repo_match_object_id_prefix(&commit_id, argv[0],
8329 GOT_OBJ_TYPE_COMMIT, repo);
8330 if (error != NULL) {
8331 struct got_reference *ref;
8332 if (error->code != GOT_ERR_BAD_OBJ_ID_STR)
8333 goto done;
8334 error = got_ref_open(&ref, repo, argv[0], 0);
8335 if (error != NULL)
8336 goto done;
8337 error = got_ref_resolve(&commit_id, repo, ref);
8338 got_ref_close(ref);
8339 if (error != NULL)
8340 goto done;
8342 error = got_object_id_str(&commit_id_str, commit_id);
8343 if (error)
8344 goto done;
8346 error = got_object_open_as_commit(&commit, repo, commit_id);
8347 if (error)
8348 goto done;
8349 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8350 if (pid == NULL) {
8351 error = got_error(GOT_ERR_ROOT_COMMIT);
8352 goto done;
8355 memset(&upa, 0, sizeof(upa));
8356 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8357 repo, update_progress, &upa, check_cancelled, NULL);
8358 if (error != NULL)
8359 goto done;
8361 if (upa.did_something)
8362 printf("Backed out commit %s\n", commit_id_str);
8363 print_merge_progress_stats(&upa);
8364 done:
8365 if (commit)
8366 got_object_commit_close(commit);
8367 free(commit_id_str);
8368 if (worktree)
8369 got_worktree_close(worktree);
8370 if (repo) {
8371 const struct got_error *close_err = got_repo_close(repo);
8372 if (error == NULL)
8373 error = close_err;
8375 return error;
8378 __dead static void
8379 usage_rebase(void)
8381 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8382 getprogname());
8383 exit(1);
8386 void
8387 trim_logmsg(char *logmsg, int limit)
8389 char *nl;
8390 size_t len;
8392 len = strlen(logmsg);
8393 if (len > limit)
8394 len = limit;
8395 logmsg[len] = '\0';
8396 nl = strchr(logmsg, '\n');
8397 if (nl)
8398 *nl = '\0';
8401 static const struct got_error *
8402 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8404 const struct got_error *err;
8405 char *logmsg0 = NULL;
8406 const char *s;
8408 err = got_object_commit_get_logmsg(&logmsg0, commit);
8409 if (err)
8410 return err;
8412 s = logmsg0;
8413 while (isspace((unsigned char)s[0]))
8414 s++;
8416 *logmsg = strdup(s);
8417 if (*logmsg == NULL) {
8418 err = got_error_from_errno("strdup");
8419 goto done;
8422 trim_logmsg(*logmsg, limit);
8423 done:
8424 free(logmsg0);
8425 return err;
8428 static const struct got_error *
8429 show_rebase_merge_conflict(struct got_object_id *id, struct got_repository *repo)
8431 const struct got_error *err;
8432 struct got_commit_object *commit = NULL;
8433 char *id_str = NULL, *logmsg = NULL;
8435 err = got_object_open_as_commit(&commit, repo, id);
8436 if (err)
8437 return err;
8439 err = got_object_id_str(&id_str, id);
8440 if (err)
8441 goto done;
8443 id_str[12] = '\0';
8445 err = get_short_logmsg(&logmsg, 42, commit);
8446 if (err)
8447 goto done;
8449 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8450 done:
8451 free(id_str);
8452 got_object_commit_close(commit);
8453 free(logmsg);
8454 return err;
8457 static const struct got_error *
8458 show_rebase_progress(struct got_commit_object *commit,
8459 struct got_object_id *old_id, struct got_object_id *new_id)
8461 const struct got_error *err;
8462 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8464 err = got_object_id_str(&old_id_str, old_id);
8465 if (err)
8466 goto done;
8468 if (new_id) {
8469 err = got_object_id_str(&new_id_str, new_id);
8470 if (err)
8471 goto done;
8474 old_id_str[12] = '\0';
8475 if (new_id_str)
8476 new_id_str[12] = '\0';
8478 err = get_short_logmsg(&logmsg, 42, commit);
8479 if (err)
8480 goto done;
8482 printf("%s -> %s: %s\n", old_id_str,
8483 new_id_str ? new_id_str : "no-op change", logmsg);
8484 done:
8485 free(old_id_str);
8486 free(new_id_str);
8487 free(logmsg);
8488 return err;
8491 static const struct got_error *
8492 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8493 struct got_reference *branch, struct got_reference *new_base_branch,
8494 struct got_reference *tmp_branch, struct got_repository *repo,
8495 int create_backup)
8497 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8498 return got_worktree_rebase_complete(worktree, fileindex,
8499 new_base_branch, tmp_branch, branch, repo, create_backup);
8502 static const struct got_error *
8503 rebase_commit(struct got_pathlist_head *merged_paths,
8504 struct got_worktree *worktree, struct got_fileindex *fileindex,
8505 struct got_reference *tmp_branch,
8506 struct got_object_id *commit_id, struct got_repository *repo)
8508 const struct got_error *error;
8509 struct got_commit_object *commit;
8510 struct got_object_id *new_commit_id;
8512 error = got_object_open_as_commit(&commit, repo, commit_id);
8513 if (error)
8514 return error;
8516 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8517 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8518 if (error) {
8519 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8520 goto done;
8521 error = show_rebase_progress(commit, commit_id, NULL);
8522 } else {
8523 error = show_rebase_progress(commit, commit_id, new_commit_id);
8524 free(new_commit_id);
8526 done:
8527 got_object_commit_close(commit);
8528 return error;
8531 struct check_path_prefix_arg {
8532 const char *path_prefix;
8533 size_t len;
8534 int errcode;
8537 static const struct got_error *
8538 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8539 struct got_blob_object *blob2, struct got_object_id *id1,
8540 struct got_object_id *id2, const char *path1, const char *path2,
8541 mode_t mode1, mode_t mode2, struct got_repository *repo)
8543 struct check_path_prefix_arg *a = arg;
8545 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8546 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8547 return got_error(a->errcode);
8549 return NULL;
8552 static const struct got_error *
8553 check_path_prefix(struct got_object_id *parent_id,
8554 struct got_object_id *commit_id, const char *path_prefix,
8555 int errcode, struct got_repository *repo)
8557 const struct got_error *err;
8558 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8559 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8560 struct check_path_prefix_arg cpp_arg;
8562 if (got_path_is_root_dir(path_prefix))
8563 return NULL;
8565 err = got_object_open_as_commit(&commit, repo, commit_id);
8566 if (err)
8567 goto done;
8569 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8570 if (err)
8571 goto done;
8573 err = got_object_open_as_tree(&tree1, repo,
8574 got_object_commit_get_tree_id(parent_commit));
8575 if (err)
8576 goto done;
8578 err = got_object_open_as_tree(&tree2, repo,
8579 got_object_commit_get_tree_id(commit));
8580 if (err)
8581 goto done;
8583 cpp_arg.path_prefix = path_prefix;
8584 while (cpp_arg.path_prefix[0] == '/')
8585 cpp_arg.path_prefix++;
8586 cpp_arg.len = strlen(cpp_arg.path_prefix);
8587 cpp_arg.errcode = errcode;
8588 err = got_diff_tree(tree1, tree2, "", "", repo,
8589 check_path_prefix_in_diff, &cpp_arg, 0);
8590 done:
8591 if (tree1)
8592 got_object_tree_close(tree1);
8593 if (tree2)
8594 got_object_tree_close(tree2);
8595 if (commit)
8596 got_object_commit_close(commit);
8597 if (parent_commit)
8598 got_object_commit_close(parent_commit);
8599 return err;
8602 static const struct got_error *
8603 collect_commits(struct got_object_id_queue *commits,
8604 struct got_object_id *initial_commit_id,
8605 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8606 const char *path_prefix, int path_prefix_errcode,
8607 struct got_repository *repo)
8609 const struct got_error *err = NULL;
8610 struct got_commit_graph *graph = NULL;
8611 struct got_object_id *parent_id = NULL;
8612 struct got_object_qid *qid;
8613 struct got_object_id *commit_id = initial_commit_id;
8615 err = got_commit_graph_open(&graph, "/", 1);
8616 if (err)
8617 return err;
8619 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8620 check_cancelled, NULL);
8621 if (err)
8622 goto done;
8623 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8624 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8625 check_cancelled, NULL);
8626 if (err) {
8627 if (err->code == GOT_ERR_ITER_COMPLETED) {
8628 err = got_error_msg(GOT_ERR_ANCESTRY,
8629 "ran out of commits to rebase before "
8630 "youngest common ancestor commit has "
8631 "been reached?!?");
8633 goto done;
8634 } else {
8635 err = check_path_prefix(parent_id, commit_id,
8636 path_prefix, path_prefix_errcode, repo);
8637 if (err)
8638 goto done;
8640 err = got_object_qid_alloc(&qid, commit_id);
8641 if (err)
8642 goto done;
8643 STAILQ_INSERT_HEAD(commits, qid, entry);
8644 commit_id = parent_id;
8647 done:
8648 got_commit_graph_close(graph);
8649 return err;
8652 static const struct got_error *
8653 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8655 const struct got_error *err = NULL;
8656 time_t committer_time;
8657 struct tm tm;
8658 char datebuf[11]; /* YYYY-MM-DD + NUL */
8659 char *author0 = NULL, *author, *smallerthan;
8660 char *logmsg0 = NULL, *logmsg, *newline;
8662 committer_time = got_object_commit_get_committer_time(commit);
8663 if (gmtime_r(&committer_time, &tm) == NULL)
8664 return got_error_from_errno("gmtime_r");
8665 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8666 return got_error(GOT_ERR_NO_SPACE);
8668 author0 = strdup(got_object_commit_get_author(commit));
8669 if (author0 == NULL)
8670 return got_error_from_errno("strdup");
8671 author = author0;
8672 smallerthan = strchr(author, '<');
8673 if (smallerthan && smallerthan[1] != '\0')
8674 author = smallerthan + 1;
8675 author[strcspn(author, "@>")] = '\0';
8677 err = got_object_commit_get_logmsg(&logmsg0, commit);
8678 if (err)
8679 goto done;
8680 logmsg = logmsg0;
8681 while (*logmsg == '\n')
8682 logmsg++;
8683 newline = strchr(logmsg, '\n');
8684 if (newline)
8685 *newline = '\0';
8687 if (asprintf(brief_str, "%s %s %s",
8688 datebuf, author, logmsg) == -1)
8689 err = got_error_from_errno("asprintf");
8690 done:
8691 free(author0);
8692 free(logmsg0);
8693 return err;
8696 static const struct got_error *
8697 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8698 struct got_repository *repo)
8700 const struct got_error *err;
8701 char *id_str;
8703 err = got_object_id_str(&id_str, id);
8704 if (err)
8705 return err;
8707 err = got_ref_delete(ref, repo);
8708 if (err)
8709 goto done;
8711 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8712 done:
8713 free(id_str);
8714 return err;
8717 static const struct got_error *
8718 print_backup_ref(const char *branch_name, const char *new_id_str,
8719 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
8720 struct got_reflist_object_id_map *refs_idmap,
8721 struct got_repository *repo)
8723 const struct got_error *err = NULL;
8724 struct got_reflist_head *refs;
8725 char *refs_str = NULL;
8726 struct got_object_id *new_commit_id = NULL;
8727 struct got_commit_object *new_commit = NULL;
8728 char *new_commit_brief_str = NULL;
8729 struct got_object_id *yca_id = NULL;
8730 struct got_commit_object *yca_commit = NULL;
8731 char *yca_id_str = NULL, *yca_brief_str = NULL;
8732 char *custom_refs_str;
8734 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
8735 return got_error_from_errno("asprintf");
8737 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
8738 0, 0, refs_idmap, custom_refs_str);
8739 if (err)
8740 goto done;
8742 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
8743 if (err)
8744 goto done;
8746 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
8747 if (refs) {
8748 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
8749 if (err)
8750 goto done;
8753 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
8754 if (err)
8755 goto done;
8757 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
8758 if (err)
8759 goto done;
8761 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
8762 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
8763 if (err)
8764 goto done;
8766 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
8767 refs_str ? " (" : "", refs_str ? refs_str : "",
8768 refs_str ? ")" : "", new_commit_brief_str);
8769 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
8770 got_object_id_cmp(yca_id, old_commit_id) != 0) {
8771 free(refs_str);
8772 refs_str = NULL;
8774 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
8775 if (err)
8776 goto done;
8778 err = get_commit_brief_str(&yca_brief_str, yca_commit);
8779 if (err)
8780 goto done;
8782 err = got_object_id_str(&yca_id_str, yca_id);
8783 if (err)
8784 goto done;
8786 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
8787 if (refs) {
8788 err = build_refs_str(&refs_str, refs, yca_id, repo);
8789 if (err)
8790 goto done;
8792 printf("history forked at %s%s%s%s\n %s\n",
8793 yca_id_str,
8794 refs_str ? " (" : "", refs_str ? refs_str : "",
8795 refs_str ? ")" : "", yca_brief_str);
8797 done:
8798 free(custom_refs_str);
8799 free(new_commit_id);
8800 free(refs_str);
8801 free(yca_id);
8802 free(yca_id_str);
8803 free(yca_brief_str);
8804 if (new_commit)
8805 got_object_commit_close(new_commit);
8806 if (yca_commit)
8807 got_object_commit_close(yca_commit);
8809 return NULL;
8812 static const struct got_error *
8813 process_backup_refs(const char *backup_ref_prefix, const char *wanted_branch_name,
8814 int delete, struct got_repository *repo)
8816 const struct got_error *err;
8817 struct got_reflist_head refs, backup_refs;
8818 struct got_reflist_entry *re;
8819 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
8820 struct got_object_id *old_commit_id = NULL;
8821 char *branch_name = NULL;
8822 struct got_commit_object *old_commit = NULL;
8823 struct got_reflist_object_id_map *refs_idmap = NULL;
8824 int wanted_branch_found = 0;
8826 TAILQ_INIT(&refs);
8827 TAILQ_INIT(&backup_refs);
8829 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8830 if (err)
8831 return err;
8833 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8834 if (err)
8835 goto done;
8837 if (wanted_branch_name) {
8838 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
8839 wanted_branch_name += 11;
8842 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
8843 got_ref_cmp_by_commit_timestamp_descending, repo);
8844 if (err)
8845 goto done;
8847 TAILQ_FOREACH(re, &backup_refs, entry) {
8848 const char *refname = got_ref_get_name(re->ref);
8849 char *slash;
8851 err = check_cancelled(NULL);
8852 if (err)
8853 break;
8855 err = got_ref_resolve(&old_commit_id, repo, re->ref);
8856 if (err)
8857 break;
8859 err = got_object_open_as_commit(&old_commit, repo,
8860 old_commit_id);
8861 if (err)
8862 break;
8864 if (strncmp(backup_ref_prefix, refname,
8865 backup_ref_prefix_len) == 0)
8866 refname += backup_ref_prefix_len;
8868 while (refname[0] == '/')
8869 refname++;
8871 branch_name = strdup(refname);
8872 if (branch_name == NULL) {
8873 err = got_error_from_errno("strdup");
8874 break;
8876 slash = strrchr(branch_name, '/');
8877 if (slash) {
8878 *slash = '\0';
8879 refname += strlen(branch_name) + 1;
8882 if (wanted_branch_name == NULL ||
8883 strcmp(wanted_branch_name, branch_name) == 0) {
8884 wanted_branch_found = 1;
8885 if (delete) {
8886 err = delete_backup_ref(re->ref,
8887 old_commit_id, repo);
8888 } else {
8889 err = print_backup_ref(branch_name, refname,
8890 old_commit_id, old_commit, refs_idmap,
8891 repo);
8893 if (err)
8894 break;
8897 free(old_commit_id);
8898 old_commit_id = NULL;
8899 free(branch_name);
8900 branch_name = NULL;
8901 got_object_commit_close(old_commit);
8902 old_commit = NULL;
8905 if (wanted_branch_name && !wanted_branch_found) {
8906 err = got_error_fmt(GOT_ERR_NOT_REF,
8907 "%s/%s/", backup_ref_prefix, wanted_branch_name);
8909 done:
8910 if (refs_idmap)
8911 got_reflist_object_id_map_free(refs_idmap);
8912 got_ref_list_free(&refs);
8913 got_ref_list_free(&backup_refs);
8914 free(old_commit_id);
8915 free(branch_name);
8916 if (old_commit)
8917 got_object_commit_close(old_commit);
8918 return err;
8921 static const struct got_error *
8922 abort_progress(void *arg, unsigned char status, const char *path)
8925 * Unversioned files should not clutter progress output when
8926 * an operation is aborted.
8928 if (status == GOT_STATUS_UNVERSIONED)
8929 return NULL;
8931 return update_progress(arg, status, path);
8934 static const struct got_error *
8935 cmd_rebase(int argc, char *argv[])
8937 const struct got_error *error = NULL;
8938 struct got_worktree *worktree = NULL;
8939 struct got_repository *repo = NULL;
8940 struct got_fileindex *fileindex = NULL;
8941 char *cwd = NULL;
8942 struct got_reference *branch = NULL;
8943 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
8944 struct got_object_id *commit_id = NULL, *parent_id = NULL;
8945 struct got_object_id *resume_commit_id = NULL;
8946 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
8947 struct got_commit_object *commit = NULL;
8948 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
8949 int histedit_in_progress = 0, merge_in_progress = 0;
8950 int create_backup = 1, list_backups = 0, delete_backups = 0;
8951 struct got_object_id_queue commits;
8952 struct got_pathlist_head merged_paths;
8953 const struct got_object_id_queue *parent_ids;
8954 struct got_object_qid *qid, *pid;
8955 struct got_update_progress_arg upa;
8957 STAILQ_INIT(&commits);
8958 TAILQ_INIT(&merged_paths);
8959 memset(&upa, 0, sizeof(upa));
8961 while ((ch = getopt(argc, argv, "aclX")) != -1) {
8962 switch (ch) {
8963 case 'a':
8964 abort_rebase = 1;
8965 break;
8966 case 'c':
8967 continue_rebase = 1;
8968 break;
8969 case 'l':
8970 list_backups = 1;
8971 break;
8972 case 'X':
8973 delete_backups = 1;
8974 break;
8975 default:
8976 usage_rebase();
8977 /* NOTREACHED */
8981 argc -= optind;
8982 argv += optind;
8984 #ifndef PROFILE
8985 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8986 "unveil", NULL) == -1)
8987 err(1, "pledge");
8988 #endif
8989 if (list_backups) {
8990 if (abort_rebase)
8991 option_conflict('l', 'a');
8992 if (continue_rebase)
8993 option_conflict('l', 'c');
8994 if (delete_backups)
8995 option_conflict('l', 'X');
8996 if (argc != 0 && argc != 1)
8997 usage_rebase();
8998 } else if (delete_backups) {
8999 if (abort_rebase)
9000 option_conflict('X', 'a');
9001 if (continue_rebase)
9002 option_conflict('X', 'c');
9003 if (list_backups)
9004 option_conflict('l', 'X');
9005 if (argc != 0 && argc != 1)
9006 usage_rebase();
9007 } else {
9008 if (abort_rebase && continue_rebase)
9009 usage_rebase();
9010 else if (abort_rebase || continue_rebase) {
9011 if (argc != 0)
9012 usage_rebase();
9013 } else if (argc != 1)
9014 usage_rebase();
9017 cwd = getcwd(NULL, 0);
9018 if (cwd == NULL) {
9019 error = got_error_from_errno("getcwd");
9020 goto done;
9022 error = got_worktree_open(&worktree, cwd);
9023 if (error) {
9024 if (list_backups || delete_backups) {
9025 if (error->code != GOT_ERR_NOT_WORKTREE)
9026 goto done;
9027 } else {
9028 if (error->code == GOT_ERR_NOT_WORKTREE)
9029 error = wrap_not_worktree_error(error,
9030 "rebase", cwd);
9031 goto done;
9035 error = got_repo_open(&repo,
9036 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9037 if (error != NULL)
9038 goto done;
9040 error = apply_unveil(got_repo_get_path(repo), 0,
9041 worktree ? got_worktree_get_root_path(worktree) : NULL);
9042 if (error)
9043 goto done;
9045 if (list_backups || delete_backups) {
9046 error = process_backup_refs(
9047 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9048 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9049 goto done; /* nothing else to do */
9052 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9053 worktree);
9054 if (error)
9055 goto done;
9056 if (histedit_in_progress) {
9057 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9058 goto done;
9061 error = got_worktree_merge_in_progress(&merge_in_progress,
9062 worktree, repo);
9063 if (error)
9064 goto done;
9065 if (merge_in_progress) {
9066 error = got_error(GOT_ERR_MERGE_BUSY);
9067 goto done;
9070 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9071 if (error)
9072 goto done;
9074 if (abort_rebase) {
9075 if (!rebase_in_progress) {
9076 error = got_error(GOT_ERR_NOT_REBASING);
9077 goto done;
9079 error = got_worktree_rebase_continue(&resume_commit_id,
9080 &new_base_branch, &tmp_branch, &branch, &fileindex,
9081 worktree, repo);
9082 if (error)
9083 goto done;
9084 printf("Switching work tree to %s\n",
9085 got_ref_get_symref_target(new_base_branch));
9086 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9087 new_base_branch, abort_progress, &upa);
9088 if (error)
9089 goto done;
9090 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9091 print_merge_progress_stats(&upa);
9092 goto done; /* nothing else to do */
9095 if (continue_rebase) {
9096 if (!rebase_in_progress) {
9097 error = got_error(GOT_ERR_NOT_REBASING);
9098 goto done;
9100 error = got_worktree_rebase_continue(&resume_commit_id,
9101 &new_base_branch, &tmp_branch, &branch, &fileindex,
9102 worktree, repo);
9103 if (error)
9104 goto done;
9106 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9107 resume_commit_id, repo);
9108 if (error)
9109 goto done;
9111 yca_id = got_object_id_dup(resume_commit_id);
9112 if (yca_id == NULL) {
9113 error = got_error_from_errno("got_object_id_dup");
9114 goto done;
9116 } else {
9117 error = got_ref_open(&branch, repo, argv[0], 0);
9118 if (error != NULL)
9119 goto done;
9122 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9123 if (error)
9124 goto done;
9126 if (!continue_rebase) {
9127 struct got_object_id *base_commit_id;
9129 base_commit_id = got_worktree_get_base_commit_id(worktree);
9130 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9131 base_commit_id, branch_head_commit_id, 1, repo,
9132 check_cancelled, NULL);
9133 if (error)
9134 goto done;
9135 if (yca_id == NULL) {
9136 error = got_error_msg(GOT_ERR_ANCESTRY,
9137 "specified branch shares no common ancestry "
9138 "with work tree's branch");
9139 goto done;
9142 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9143 if (error) {
9144 if (error->code != GOT_ERR_ANCESTRY)
9145 goto done;
9146 error = NULL;
9147 } else {
9148 static char msg[128];
9149 snprintf(msg, sizeof(msg),
9150 "%s is already based on %s",
9151 got_ref_get_name(branch),
9152 got_worktree_get_head_ref_name(worktree));
9153 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
9154 goto done;
9156 error = got_worktree_rebase_prepare(&new_base_branch,
9157 &tmp_branch, &fileindex, worktree, branch, repo);
9158 if (error)
9159 goto done;
9162 commit_id = branch_head_commit_id;
9163 error = got_object_open_as_commit(&commit, repo, commit_id);
9164 if (error)
9165 goto done;
9167 parent_ids = got_object_commit_get_parent_ids(commit);
9168 pid = STAILQ_FIRST(parent_ids);
9169 if (pid == NULL) {
9170 if (!continue_rebase) {
9171 error = got_worktree_rebase_abort(worktree, fileindex,
9172 repo, new_base_branch, abort_progress, &upa);
9173 if (error)
9174 goto done;
9175 printf("Rebase of %s aborted\n",
9176 got_ref_get_name(branch));
9177 print_merge_progress_stats(&upa);
9180 error = got_error(GOT_ERR_EMPTY_REBASE);
9181 goto done;
9183 error = collect_commits(&commits, commit_id, pid->id,
9184 yca_id, got_worktree_get_path_prefix(worktree),
9185 GOT_ERR_REBASE_PATH, repo);
9186 got_object_commit_close(commit);
9187 commit = NULL;
9188 if (error)
9189 goto done;
9191 if (STAILQ_EMPTY(&commits)) {
9192 if (continue_rebase) {
9193 error = rebase_complete(worktree, fileindex,
9194 branch, new_base_branch, tmp_branch, repo,
9195 create_backup);
9196 goto done;
9197 } else {
9198 /* Fast-forward the reference of the branch. */
9199 struct got_object_id *new_head_commit_id;
9200 char *id_str;
9201 error = got_ref_resolve(&new_head_commit_id, repo,
9202 new_base_branch);
9203 if (error)
9204 goto done;
9205 error = got_object_id_str(&id_str, new_head_commit_id);
9206 printf("Forwarding %s to commit %s\n",
9207 got_ref_get_name(branch), id_str);
9208 free(id_str);
9209 error = got_ref_change_ref(branch,
9210 new_head_commit_id);
9211 if (error)
9212 goto done;
9213 /* No backup needed since objects did not change. */
9214 create_backup = 0;
9218 pid = NULL;
9219 STAILQ_FOREACH(qid, &commits, entry) {
9221 commit_id = qid->id;
9222 parent_id = pid ? pid->id : yca_id;
9223 pid = qid;
9225 memset(&upa, 0, sizeof(upa));
9226 error = got_worktree_rebase_merge_files(&merged_paths,
9227 worktree, fileindex, parent_id, commit_id, repo,
9228 update_progress, &upa, check_cancelled, NULL);
9229 if (error)
9230 goto done;
9232 print_merge_progress_stats(&upa);
9233 if (upa.conflicts > 0 || upa.missing > 0 ||
9234 upa.not_deleted > 0 || upa.unversioned > 0) {
9235 if (upa.conflicts > 0) {
9236 error = show_rebase_merge_conflict(qid->id,
9237 repo);
9238 if (error)
9239 goto done;
9241 got_worktree_rebase_pathlist_free(&merged_paths);
9242 break;
9245 error = rebase_commit(&merged_paths, worktree, fileindex,
9246 tmp_branch, commit_id, repo);
9247 got_worktree_rebase_pathlist_free(&merged_paths);
9248 if (error)
9249 goto done;
9252 if (upa.conflicts > 0 || upa.missing > 0 ||
9253 upa.not_deleted > 0 || upa.unversioned > 0) {
9254 error = got_worktree_rebase_postpone(worktree, fileindex);
9255 if (error)
9256 goto done;
9257 if (upa.conflicts > 0 && upa.missing == 0 &&
9258 upa.not_deleted == 0 && upa.unversioned == 0) {
9259 error = got_error_msg(GOT_ERR_CONFLICTS,
9260 "conflicts must be resolved before rebasing "
9261 "can continue");
9262 } else if (upa.conflicts > 0) {
9263 error = got_error_msg(GOT_ERR_CONFLICTS,
9264 "conflicts must be resolved before rebasing "
9265 "can continue; changes destined for some "
9266 "files were not yet merged and should be "
9267 "merged manually if required before the "
9268 "rebase operation is continued");
9269 } else {
9270 error = got_error_msg(GOT_ERR_CONFLICTS,
9271 "changes destined for some files were not "
9272 "yet merged and should be merged manually "
9273 "if required before the rebase operation "
9274 "is continued");
9276 } else
9277 error = rebase_complete(worktree, fileindex, branch,
9278 new_base_branch, tmp_branch, repo, create_backup);
9279 done:
9280 got_object_id_queue_free(&commits);
9281 free(branch_head_commit_id);
9282 free(resume_commit_id);
9283 free(yca_id);
9284 if (commit)
9285 got_object_commit_close(commit);
9286 if (branch)
9287 got_ref_close(branch);
9288 if (new_base_branch)
9289 got_ref_close(new_base_branch);
9290 if (tmp_branch)
9291 got_ref_close(tmp_branch);
9292 if (worktree)
9293 got_worktree_close(worktree);
9294 if (repo) {
9295 const struct got_error *close_err = got_repo_close(repo);
9296 if (error == NULL)
9297 error = close_err;
9299 return error;
9302 __dead static void
9303 usage_histedit(void)
9305 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9306 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9307 getprogname());
9308 exit(1);
9311 #define GOT_HISTEDIT_PICK 'p'
9312 #define GOT_HISTEDIT_EDIT 'e'
9313 #define GOT_HISTEDIT_FOLD 'f'
9314 #define GOT_HISTEDIT_DROP 'd'
9315 #define GOT_HISTEDIT_MESG 'm'
9317 static struct got_histedit_cmd {
9318 unsigned char code;
9319 const char *name;
9320 const char *desc;
9321 } got_histedit_cmds[] = {
9322 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9323 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9324 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9325 "be used" },
9326 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9327 { GOT_HISTEDIT_MESG, "mesg",
9328 "single-line log message for commit above (open editor if empty)" },
9331 struct got_histedit_list_entry {
9332 TAILQ_ENTRY(got_histedit_list_entry) entry;
9333 struct got_object_id *commit_id;
9334 const struct got_histedit_cmd *cmd;
9335 char *logmsg;
9337 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9339 static const struct got_error *
9340 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9341 FILE *f, struct got_repository *repo)
9343 const struct got_error *err = NULL;
9344 char *logmsg = NULL, *id_str = NULL;
9345 struct got_commit_object *commit = NULL;
9346 int n;
9348 err = got_object_open_as_commit(&commit, repo, commit_id);
9349 if (err)
9350 goto done;
9352 err = get_short_logmsg(&logmsg, 34, commit);
9353 if (err)
9354 goto done;
9356 err = got_object_id_str(&id_str, commit_id);
9357 if (err)
9358 goto done;
9360 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9361 if (n < 0)
9362 err = got_ferror(f, GOT_ERR_IO);
9363 done:
9364 if (commit)
9365 got_object_commit_close(commit);
9366 free(id_str);
9367 free(logmsg);
9368 return err;
9371 static const struct got_error *
9372 histedit_write_commit_list(struct got_object_id_queue *commits,
9373 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9374 struct got_repository *repo)
9376 const struct got_error *err = NULL;
9377 struct got_object_qid *qid;
9378 const char *histedit_cmd = NULL;
9380 if (STAILQ_EMPTY(commits))
9381 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9383 STAILQ_FOREACH(qid, commits, entry) {
9384 histedit_cmd = got_histedit_cmds[0].name;
9385 if (edit_only)
9386 histedit_cmd = "edit";
9387 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9388 histedit_cmd = "fold";
9389 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9390 if (err)
9391 break;
9392 if (edit_logmsg_only) {
9393 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9394 if (n < 0) {
9395 err = got_ferror(f, GOT_ERR_IO);
9396 break;
9401 return err;
9404 static const struct got_error *
9405 write_cmd_list(FILE *f, const char *branch_name,
9406 struct got_object_id_queue *commits)
9408 const struct got_error *err = NULL;
9409 size_t i;
9410 int n;
9411 char *id_str;
9412 struct got_object_qid *qid;
9414 qid = STAILQ_FIRST(commits);
9415 err = got_object_id_str(&id_str, qid->id);
9416 if (err)
9417 return err;
9419 n = fprintf(f,
9420 "# Editing the history of branch '%s' starting at\n"
9421 "# commit %s\n"
9422 "# Commits will be processed in order from top to "
9423 "bottom of this file.\n", branch_name, id_str);
9424 if (n < 0) {
9425 err = got_ferror(f, GOT_ERR_IO);
9426 goto done;
9429 n = fprintf(f, "# Available histedit commands:\n");
9430 if (n < 0) {
9431 err = got_ferror(f, GOT_ERR_IO);
9432 goto done;
9435 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9436 struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9437 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9438 cmd->desc);
9439 if (n < 0) {
9440 err = got_ferror(f, GOT_ERR_IO);
9441 break;
9444 done:
9445 free(id_str);
9446 return err;
9449 static const struct got_error *
9450 histedit_syntax_error(int lineno)
9452 static char msg[42];
9453 int ret;
9455 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9456 lineno);
9457 if (ret == -1 || ret >= sizeof(msg))
9458 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9460 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9463 static const struct got_error *
9464 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9465 char *logmsg, struct got_repository *repo)
9467 const struct got_error *err;
9468 struct got_commit_object *folded_commit = NULL;
9469 char *id_str, *folded_logmsg = NULL;
9471 err = got_object_id_str(&id_str, hle->commit_id);
9472 if (err)
9473 return err;
9475 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9476 if (err)
9477 goto done;
9479 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9480 if (err)
9481 goto done;
9482 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9483 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9484 folded_logmsg) == -1) {
9485 err = got_error_from_errno("asprintf");
9487 done:
9488 if (folded_commit)
9489 got_object_commit_close(folded_commit);
9490 free(id_str);
9491 free(folded_logmsg);
9492 return err;
9495 static struct got_histedit_list_entry *
9496 get_folded_commits(struct got_histedit_list_entry *hle)
9498 struct got_histedit_list_entry *prev, *folded = NULL;
9500 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9501 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9502 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9503 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9504 folded = prev;
9505 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9508 return folded;
9511 static const struct got_error *
9512 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9513 struct got_repository *repo)
9515 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9516 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9517 const struct got_error *err = NULL;
9518 struct got_commit_object *commit = NULL;
9519 int logmsg_len;
9520 int fd;
9521 struct got_histedit_list_entry *folded = NULL;
9523 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9524 if (err)
9525 return err;
9527 folded = get_folded_commits(hle);
9528 if (folded) {
9529 while (folded != hle) {
9530 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9531 folded = TAILQ_NEXT(folded, entry);
9532 continue;
9534 err = append_folded_commit_msg(&new_msg, folded,
9535 logmsg, repo);
9536 if (err)
9537 goto done;
9538 free(logmsg);
9539 logmsg = new_msg;
9540 folded = TAILQ_NEXT(folded, entry);
9544 err = got_object_id_str(&id_str, hle->commit_id);
9545 if (err)
9546 goto done;
9547 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9548 if (err)
9549 goto done;
9550 logmsg_len = asprintf(&new_msg,
9551 "%s\n# original log message of commit %s: %s",
9552 logmsg ? logmsg : "", id_str, orig_logmsg);
9553 if (logmsg_len == -1) {
9554 err = got_error_from_errno("asprintf");
9555 goto done;
9557 free(logmsg);
9558 logmsg = new_msg;
9560 err = got_object_id_str(&id_str, hle->commit_id);
9561 if (err)
9562 goto done;
9564 err = got_opentemp_named_fd(&logmsg_path, &fd,
9565 GOT_TMPDIR_STR "/got-logmsg");
9566 if (err)
9567 goto done;
9569 write(fd, logmsg, logmsg_len);
9570 close(fd);
9572 err = get_editor(&editor);
9573 if (err)
9574 goto done;
9576 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9577 logmsg_len, 0);
9578 if (err) {
9579 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9580 goto done;
9581 err = NULL;
9582 hle->logmsg = strdup(new_msg);
9583 if (hle->logmsg == NULL)
9584 err = got_error_from_errno("strdup");
9586 done:
9587 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9588 err = got_error_from_errno2("unlink", logmsg_path);
9589 free(logmsg_path);
9590 free(logmsg);
9591 free(orig_logmsg);
9592 free(editor);
9593 if (commit)
9594 got_object_commit_close(commit);
9595 return err;
9598 static const struct got_error *
9599 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9600 FILE *f, struct got_repository *repo)
9602 const struct got_error *err = NULL;
9603 char *line = NULL, *p, *end;
9604 size_t i, size;
9605 ssize_t len;
9606 int lineno = 0;
9607 const struct got_histedit_cmd *cmd;
9608 struct got_object_id *commit_id = NULL;
9609 struct got_histedit_list_entry *hle = NULL;
9611 for (;;) {
9612 len = getline(&line, &size, f);
9613 if (len == -1) {
9614 const struct got_error *getline_err;
9615 if (feof(f))
9616 break;
9617 getline_err = got_error_from_errno("getline");
9618 err = got_ferror(f, getline_err->code);
9619 break;
9621 lineno++;
9622 p = line;
9623 while (isspace((unsigned char)p[0]))
9624 p++;
9625 if (p[0] == '#' || p[0] == '\0') {
9626 free(line);
9627 line = NULL;
9628 continue;
9630 cmd = NULL;
9631 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9632 cmd = &got_histedit_cmds[i];
9633 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9634 isspace((unsigned char)p[strlen(cmd->name)])) {
9635 p += strlen(cmd->name);
9636 break;
9638 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9639 p++;
9640 break;
9643 if (i == nitems(got_histedit_cmds)) {
9644 err = histedit_syntax_error(lineno);
9645 break;
9647 while (isspace((unsigned char)p[0]))
9648 p++;
9649 if (cmd->code == GOT_HISTEDIT_MESG) {
9650 if (hle == NULL || hle->logmsg != NULL) {
9651 err = got_error(GOT_ERR_HISTEDIT_CMD);
9652 break;
9654 if (p[0] == '\0') {
9655 err = histedit_edit_logmsg(hle, repo);
9656 if (err)
9657 break;
9658 } else {
9659 hle->logmsg = strdup(p);
9660 if (hle->logmsg == NULL) {
9661 err = got_error_from_errno("strdup");
9662 break;
9665 free(line);
9666 line = NULL;
9667 continue;
9668 } else {
9669 end = p;
9670 while (end[0] && !isspace((unsigned char)end[0]))
9671 end++;
9672 *end = '\0';
9674 err = got_object_resolve_id_str(&commit_id, repo, p);
9675 if (err) {
9676 /* override error code */
9677 err = histedit_syntax_error(lineno);
9678 break;
9681 hle = malloc(sizeof(*hle));
9682 if (hle == NULL) {
9683 err = got_error_from_errno("malloc");
9684 break;
9686 hle->cmd = cmd;
9687 hle->commit_id = commit_id;
9688 hle->logmsg = NULL;
9689 commit_id = NULL;
9690 free(line);
9691 line = NULL;
9692 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9695 free(line);
9696 free(commit_id);
9697 return err;
9700 static const struct got_error *
9701 histedit_check_script(struct got_histedit_list *histedit_cmds,
9702 struct got_object_id_queue *commits, struct got_repository *repo)
9704 const struct got_error *err = NULL;
9705 struct got_object_qid *qid;
9706 struct got_histedit_list_entry *hle;
9707 static char msg[92];
9708 char *id_str;
9710 if (TAILQ_EMPTY(histedit_cmds))
9711 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
9712 "histedit script contains no commands");
9713 if (STAILQ_EMPTY(commits))
9714 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9716 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9717 struct got_histedit_list_entry *hle2;
9718 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
9719 if (hle == hle2)
9720 continue;
9721 if (got_object_id_cmp(hle->commit_id,
9722 hle2->commit_id) != 0)
9723 continue;
9724 err = got_object_id_str(&id_str, hle->commit_id);
9725 if (err)
9726 return err;
9727 snprintf(msg, sizeof(msg), "commit %s is listed "
9728 "more than once in histedit script", id_str);
9729 free(id_str);
9730 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9734 STAILQ_FOREACH(qid, commits, entry) {
9735 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9736 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
9737 break;
9739 if (hle == NULL) {
9740 err = got_object_id_str(&id_str, qid->id);
9741 if (err)
9742 return err;
9743 snprintf(msg, sizeof(msg),
9744 "commit %s missing from histedit script", id_str);
9745 free(id_str);
9746 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
9750 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
9751 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
9752 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
9753 "last commit in histedit script cannot be folded");
9755 return NULL;
9758 static const struct got_error *
9759 histedit_run_editor(struct got_histedit_list *histedit_cmds,
9760 const char *path, struct got_object_id_queue *commits,
9761 struct got_repository *repo)
9763 const struct got_error *err = NULL;
9764 char *editor;
9765 FILE *f = NULL;
9767 err = get_editor(&editor);
9768 if (err)
9769 return err;
9771 if (spawn_editor(editor, path) == -1) {
9772 err = got_error_from_errno("failed spawning editor");
9773 goto done;
9776 f = fopen(path, "r");
9777 if (f == NULL) {
9778 err = got_error_from_errno("fopen");
9779 goto done;
9781 err = histedit_parse_list(histedit_cmds, f, repo);
9782 if (err)
9783 goto done;
9785 err = histedit_check_script(histedit_cmds, commits, repo);
9786 done:
9787 if (f && fclose(f) == EOF && err == NULL)
9788 err = got_error_from_errno("fclose");
9789 free(editor);
9790 return err;
9793 static const struct got_error *
9794 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
9795 struct got_object_id_queue *, const char *, const char *,
9796 struct got_repository *);
9798 static const struct got_error *
9799 histedit_edit_script(struct got_histedit_list *histedit_cmds,
9800 struct got_object_id_queue *commits, const char *branch_name,
9801 int edit_logmsg_only, int fold_only, int edit_only,
9802 struct got_repository *repo)
9804 const struct got_error *err;
9805 FILE *f = NULL;
9806 char *path = NULL;
9808 err = got_opentemp_named(&path, &f, "got-histedit");
9809 if (err)
9810 return err;
9812 err = write_cmd_list(f, branch_name, commits);
9813 if (err)
9814 goto done;
9816 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
9817 fold_only, edit_only, repo);
9818 if (err)
9819 goto done;
9821 if (edit_logmsg_only || fold_only || edit_only) {
9822 rewind(f);
9823 err = histedit_parse_list(histedit_cmds, f, repo);
9824 } else {
9825 if (fclose(f) == EOF) {
9826 err = got_error_from_errno("fclose");
9827 goto done;
9829 f = NULL;
9830 err = histedit_run_editor(histedit_cmds, path, commits, repo);
9831 if (err) {
9832 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9833 err->code != GOT_ERR_HISTEDIT_CMD)
9834 goto done;
9835 err = histedit_edit_list_retry(histedit_cmds, err,
9836 commits, path, branch_name, repo);
9839 done:
9840 if (f && fclose(f) == EOF && err == NULL)
9841 err = got_error_from_errno("fclose");
9842 if (path && unlink(path) != 0 && err == NULL)
9843 err = got_error_from_errno2("unlink", path);
9844 free(path);
9845 return err;
9848 static const struct got_error *
9849 histedit_save_list(struct got_histedit_list *histedit_cmds,
9850 struct got_worktree *worktree, struct got_repository *repo)
9852 const struct got_error *err = NULL;
9853 char *path = NULL;
9854 FILE *f = NULL;
9855 struct got_histedit_list_entry *hle;
9856 struct got_commit_object *commit = NULL;
9858 err = got_worktree_get_histedit_script_path(&path, worktree);
9859 if (err)
9860 return err;
9862 f = fopen(path, "w");
9863 if (f == NULL) {
9864 err = got_error_from_errno2("fopen", path);
9865 goto done;
9867 TAILQ_FOREACH(hle, histedit_cmds, entry) {
9868 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
9869 repo);
9870 if (err)
9871 break;
9873 if (hle->logmsg) {
9874 int n = fprintf(f, "%c %s\n",
9875 GOT_HISTEDIT_MESG, hle->logmsg);
9876 if (n < 0) {
9877 err = got_ferror(f, GOT_ERR_IO);
9878 break;
9882 done:
9883 if (f && fclose(f) == EOF && err == NULL)
9884 err = got_error_from_errno("fclose");
9885 free(path);
9886 if (commit)
9887 got_object_commit_close(commit);
9888 return err;
9891 void
9892 histedit_free_list(struct got_histedit_list *histedit_cmds)
9894 struct got_histedit_list_entry *hle;
9896 while ((hle = TAILQ_FIRST(histedit_cmds))) {
9897 TAILQ_REMOVE(histedit_cmds, hle, entry);
9898 free(hle);
9902 static const struct got_error *
9903 histedit_load_list(struct got_histedit_list *histedit_cmds,
9904 const char *path, struct got_repository *repo)
9906 const struct got_error *err = NULL;
9907 FILE *f = NULL;
9909 f = fopen(path, "r");
9910 if (f == NULL) {
9911 err = got_error_from_errno2("fopen", path);
9912 goto done;
9915 err = histedit_parse_list(histedit_cmds, f, repo);
9916 done:
9917 if (f && fclose(f) == EOF && err == NULL)
9918 err = got_error_from_errno("fclose");
9919 return err;
9922 static const struct got_error *
9923 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
9924 const struct got_error *edit_err, struct got_object_id_queue *commits,
9925 const char *path, const char *branch_name, struct got_repository *repo)
9927 const struct got_error *err = NULL, *prev_err = edit_err;
9928 int resp = ' ';
9930 while (resp != 'c' && resp != 'r' && resp != 'a') {
9931 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
9932 "or (a)bort: ", getprogname(), prev_err->msg);
9933 resp = getchar();
9934 if (resp == '\n')
9935 resp = getchar();
9936 if (resp == 'c') {
9937 histedit_free_list(histedit_cmds);
9938 err = histedit_run_editor(histedit_cmds, path, commits,
9939 repo);
9940 if (err) {
9941 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9942 err->code != GOT_ERR_HISTEDIT_CMD)
9943 break;
9944 prev_err = err;
9945 resp = ' ';
9946 continue;
9948 break;
9949 } else if (resp == 'r') {
9950 histedit_free_list(histedit_cmds);
9951 err = histedit_edit_script(histedit_cmds,
9952 commits, branch_name, 0, 0, 0, repo);
9953 if (err) {
9954 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
9955 err->code != GOT_ERR_HISTEDIT_CMD)
9956 break;
9957 prev_err = err;
9958 resp = ' ';
9959 continue;
9961 break;
9962 } else if (resp == 'a') {
9963 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
9964 break;
9965 } else
9966 printf("invalid response '%c'\n", resp);
9969 return err;
9972 static const struct got_error *
9973 histedit_complete(struct got_worktree *worktree,
9974 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
9975 struct got_reference *branch, struct got_repository *repo)
9977 printf("Switching work tree to %s\n",
9978 got_ref_get_symref_target(branch));
9979 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
9980 branch, repo);
9983 static const struct got_error *
9984 show_histedit_progress(struct got_commit_object *commit,
9985 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
9987 const struct got_error *err;
9988 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9990 err = got_object_id_str(&old_id_str, hle->commit_id);
9991 if (err)
9992 goto done;
9994 if (new_id) {
9995 err = got_object_id_str(&new_id_str, new_id);
9996 if (err)
9997 goto done;
10000 old_id_str[12] = '\0';
10001 if (new_id_str)
10002 new_id_str[12] = '\0';
10004 if (hle->logmsg) {
10005 logmsg = strdup(hle->logmsg);
10006 if (logmsg == NULL) {
10007 err = got_error_from_errno("strdup");
10008 goto done;
10010 trim_logmsg(logmsg, 42);
10011 } else {
10012 err = get_short_logmsg(&logmsg, 42, commit);
10013 if (err)
10014 goto done;
10017 switch (hle->cmd->code) {
10018 case GOT_HISTEDIT_PICK:
10019 case GOT_HISTEDIT_EDIT:
10020 printf("%s -> %s: %s\n", old_id_str,
10021 new_id_str ? new_id_str : "no-op change", logmsg);
10022 break;
10023 case GOT_HISTEDIT_DROP:
10024 case GOT_HISTEDIT_FOLD:
10025 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10026 logmsg);
10027 break;
10028 default:
10029 break;
10031 done:
10032 free(old_id_str);
10033 free(new_id_str);
10034 return err;
10037 static const struct got_error *
10038 histedit_commit(struct got_pathlist_head *merged_paths,
10039 struct got_worktree *worktree, struct got_fileindex *fileindex,
10040 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10041 struct got_repository *repo)
10043 const struct got_error *err;
10044 struct got_commit_object *commit;
10045 struct got_object_id *new_commit_id;
10047 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10048 && hle->logmsg == NULL) {
10049 err = histedit_edit_logmsg(hle, repo);
10050 if (err)
10051 return err;
10054 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10055 if (err)
10056 return err;
10058 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10059 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10060 hle->logmsg, repo);
10061 if (err) {
10062 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10063 goto done;
10064 err = show_histedit_progress(commit, hle, NULL);
10065 } else {
10066 err = show_histedit_progress(commit, hle, new_commit_id);
10067 free(new_commit_id);
10069 done:
10070 got_object_commit_close(commit);
10071 return err;
10074 static const struct got_error *
10075 histedit_skip_commit(struct got_histedit_list_entry *hle,
10076 struct got_worktree *worktree, struct got_repository *repo)
10078 const struct got_error *error;
10079 struct got_commit_object *commit;
10081 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10082 repo);
10083 if (error)
10084 return error;
10086 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10087 if (error)
10088 return error;
10090 error = show_histedit_progress(commit, hle, NULL);
10091 got_object_commit_close(commit);
10092 return error;
10095 static const struct got_error *
10096 check_local_changes(void *arg, unsigned char status,
10097 unsigned char staged_status, const char *path,
10098 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10099 struct got_object_id *commit_id, int dirfd, const char *de_name)
10101 int *have_local_changes = arg;
10103 switch (status) {
10104 case GOT_STATUS_ADD:
10105 case GOT_STATUS_DELETE:
10106 case GOT_STATUS_MODIFY:
10107 case GOT_STATUS_CONFLICT:
10108 *have_local_changes = 1;
10109 return got_error(GOT_ERR_CANCELLED);
10110 default:
10111 break;
10114 switch (staged_status) {
10115 case GOT_STATUS_ADD:
10116 case GOT_STATUS_DELETE:
10117 case GOT_STATUS_MODIFY:
10118 *have_local_changes = 1;
10119 return got_error(GOT_ERR_CANCELLED);
10120 default:
10121 break;
10124 return NULL;
10127 static const struct got_error *
10128 cmd_histedit(int argc, char *argv[])
10130 const struct got_error *error = NULL;
10131 struct got_worktree *worktree = NULL;
10132 struct got_fileindex *fileindex = NULL;
10133 struct got_repository *repo = NULL;
10134 char *cwd = NULL;
10135 struct got_reference *branch = NULL;
10136 struct got_reference *tmp_branch = NULL;
10137 struct got_object_id *resume_commit_id = NULL;
10138 struct got_object_id *base_commit_id = NULL;
10139 struct got_object_id *head_commit_id = NULL;
10140 struct got_commit_object *commit = NULL;
10141 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10142 struct got_update_progress_arg upa;
10143 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10144 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10145 int list_backups = 0, delete_backups = 0;
10146 const char *edit_script_path = NULL;
10147 struct got_object_id_queue commits;
10148 struct got_pathlist_head merged_paths;
10149 const struct got_object_id_queue *parent_ids;
10150 struct got_object_qid *pid;
10151 struct got_histedit_list histedit_cmds;
10152 struct got_histedit_list_entry *hle;
10154 STAILQ_INIT(&commits);
10155 TAILQ_INIT(&histedit_cmds);
10156 TAILQ_INIT(&merged_paths);
10157 memset(&upa, 0, sizeof(upa));
10159 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10160 switch (ch) {
10161 case 'a':
10162 abort_edit = 1;
10163 break;
10164 case 'c':
10165 continue_edit = 1;
10166 break;
10167 case 'e':
10168 edit_only = 1;
10169 break;
10170 case 'f':
10171 fold_only = 1;
10172 break;
10173 case 'F':
10174 edit_script_path = optarg;
10175 break;
10176 case 'm':
10177 edit_logmsg_only = 1;
10178 break;
10179 case 'l':
10180 list_backups = 1;
10181 break;
10182 case 'X':
10183 delete_backups = 1;
10184 break;
10185 default:
10186 usage_histedit();
10187 /* NOTREACHED */
10191 argc -= optind;
10192 argv += optind;
10194 #ifndef PROFILE
10195 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10196 "unveil", NULL) == -1)
10197 err(1, "pledge");
10198 #endif
10199 if (abort_edit && continue_edit)
10200 option_conflict('a', 'c');
10201 if (edit_script_path && edit_logmsg_only)
10202 option_conflict('F', 'm');
10203 if (abort_edit && edit_logmsg_only)
10204 option_conflict('a', 'm');
10205 if (continue_edit && edit_logmsg_only)
10206 option_conflict('c', 'm');
10207 if (abort_edit && fold_only)
10208 option_conflict('a', 'f');
10209 if (continue_edit && fold_only)
10210 option_conflict('c', 'f');
10211 if (fold_only && edit_logmsg_only)
10212 option_conflict('f', 'm');
10213 if (edit_script_path && fold_only)
10214 option_conflict('F', 'f');
10215 if (abort_edit && edit_only)
10216 option_conflict('a', 'e');
10217 if (continue_edit && edit_only)
10218 option_conflict('c', 'e');
10219 if (edit_only && edit_logmsg_only)
10220 option_conflict('e', 'm');
10221 if (edit_script_path && edit_only)
10222 option_conflict('F', 'e');
10223 if (list_backups) {
10224 if (abort_edit)
10225 option_conflict('l', 'a');
10226 if (continue_edit)
10227 option_conflict('l', 'c');
10228 if (edit_script_path)
10229 option_conflict('l', 'F');
10230 if (edit_logmsg_only)
10231 option_conflict('l', 'm');
10232 if (fold_only)
10233 option_conflict('l', 'f');
10234 if (edit_only)
10235 option_conflict('l', 'e');
10236 if (delete_backups)
10237 option_conflict('l', 'X');
10238 if (argc != 0 && argc != 1)
10239 usage_histedit();
10240 } else if (delete_backups) {
10241 if (abort_edit)
10242 option_conflict('X', 'a');
10243 if (continue_edit)
10244 option_conflict('X', 'c');
10245 if (edit_script_path)
10246 option_conflict('X', 'F');
10247 if (edit_logmsg_only)
10248 option_conflict('X', 'm');
10249 if (fold_only)
10250 option_conflict('X', 'f');
10251 if (edit_only)
10252 option_conflict('X', 'e');
10253 if (list_backups)
10254 option_conflict('X', 'l');
10255 if (argc != 0 && argc != 1)
10256 usage_histedit();
10257 } else if (argc != 0)
10258 usage_histedit();
10261 * This command cannot apply unveil(2) in all cases because the
10262 * user may choose to run an editor to edit the histedit script
10263 * and to edit individual commit log messages.
10264 * unveil(2) traverses exec(2); if an editor is used we have to
10265 * apply unveil after edit script and log messages have been written.
10266 * XXX TODO: Make use of unveil(2) where possible.
10269 cwd = getcwd(NULL, 0);
10270 if (cwd == NULL) {
10271 error = got_error_from_errno("getcwd");
10272 goto done;
10274 error = got_worktree_open(&worktree, cwd);
10275 if (error) {
10276 if (list_backups || delete_backups) {
10277 if (error->code != GOT_ERR_NOT_WORKTREE)
10278 goto done;
10279 } else {
10280 if (error->code == GOT_ERR_NOT_WORKTREE)
10281 error = wrap_not_worktree_error(error,
10282 "histedit", cwd);
10283 goto done;
10287 if (list_backups || delete_backups) {
10288 error = got_repo_open(&repo,
10289 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10290 NULL);
10291 if (error != NULL)
10292 goto done;
10293 error = apply_unveil(got_repo_get_path(repo), 0,
10294 worktree ? got_worktree_get_root_path(worktree) : NULL);
10295 if (error)
10296 goto done;
10297 error = process_backup_refs(
10298 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10299 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10300 goto done; /* nothing else to do */
10303 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10304 NULL);
10305 if (error != NULL)
10306 goto done;
10308 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10309 if (error)
10310 goto done;
10311 if (rebase_in_progress) {
10312 error = got_error(GOT_ERR_REBASING);
10313 goto done;
10316 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10317 repo);
10318 if (error)
10319 goto done;
10320 if (merge_in_progress) {
10321 error = got_error(GOT_ERR_MERGE_BUSY);
10322 goto done;
10325 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10326 if (error)
10327 goto done;
10329 if (edit_in_progress && edit_logmsg_only) {
10330 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10331 "histedit operation is in progress in this "
10332 "work tree and must be continued or aborted "
10333 "before the -m option can be used");
10334 goto done;
10336 if (edit_in_progress && fold_only) {
10337 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10338 "histedit operation is in progress in this "
10339 "work tree and must be continued or aborted "
10340 "before the -f option can be used");
10341 goto done;
10343 if (edit_in_progress && edit_only) {
10344 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10345 "histedit operation is in progress in this "
10346 "work tree and must be continued or aborted "
10347 "before the -e option can be used");
10348 goto done;
10351 if (edit_in_progress && abort_edit) {
10352 error = got_worktree_histedit_continue(&resume_commit_id,
10353 &tmp_branch, &branch, &base_commit_id, &fileindex,
10354 worktree, repo);
10355 if (error)
10356 goto done;
10357 printf("Switching work tree to %s\n",
10358 got_ref_get_symref_target(branch));
10359 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10360 branch, base_commit_id, abort_progress, &upa);
10361 if (error)
10362 goto done;
10363 printf("Histedit of %s aborted\n",
10364 got_ref_get_symref_target(branch));
10365 print_merge_progress_stats(&upa);
10366 goto done; /* nothing else to do */
10367 } else if (abort_edit) {
10368 error = got_error(GOT_ERR_NOT_HISTEDIT);
10369 goto done;
10372 if (continue_edit) {
10373 char *path;
10375 if (!edit_in_progress) {
10376 error = got_error(GOT_ERR_NOT_HISTEDIT);
10377 goto done;
10380 error = got_worktree_get_histedit_script_path(&path, worktree);
10381 if (error)
10382 goto done;
10384 error = histedit_load_list(&histedit_cmds, path, repo);
10385 free(path);
10386 if (error)
10387 goto done;
10389 error = got_worktree_histedit_continue(&resume_commit_id,
10390 &tmp_branch, &branch, &base_commit_id, &fileindex,
10391 worktree, repo);
10392 if (error)
10393 goto done;
10395 error = got_ref_resolve(&head_commit_id, repo, branch);
10396 if (error)
10397 goto done;
10399 error = got_object_open_as_commit(&commit, repo,
10400 head_commit_id);
10401 if (error)
10402 goto done;
10403 parent_ids = got_object_commit_get_parent_ids(commit);
10404 pid = STAILQ_FIRST(parent_ids);
10405 if (pid == NULL) {
10406 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10407 goto done;
10409 error = collect_commits(&commits, head_commit_id, pid->id,
10410 base_commit_id, got_worktree_get_path_prefix(worktree),
10411 GOT_ERR_HISTEDIT_PATH, repo);
10412 got_object_commit_close(commit);
10413 commit = NULL;
10414 if (error)
10415 goto done;
10416 } else {
10417 if (edit_in_progress) {
10418 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10419 goto done;
10422 error = got_ref_open(&branch, repo,
10423 got_worktree_get_head_ref_name(worktree), 0);
10424 if (error != NULL)
10425 goto done;
10427 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10428 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10429 "will not edit commit history of a branch outside "
10430 "the \"refs/heads/\" reference namespace");
10431 goto done;
10434 error = got_ref_resolve(&head_commit_id, repo, branch);
10435 got_ref_close(branch);
10436 branch = NULL;
10437 if (error)
10438 goto done;
10440 error = got_object_open_as_commit(&commit, repo,
10441 head_commit_id);
10442 if (error)
10443 goto done;
10444 parent_ids = got_object_commit_get_parent_ids(commit);
10445 pid = STAILQ_FIRST(parent_ids);
10446 if (pid == NULL) {
10447 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10448 goto done;
10450 error = collect_commits(&commits, head_commit_id, pid->id,
10451 got_worktree_get_base_commit_id(worktree),
10452 got_worktree_get_path_prefix(worktree),
10453 GOT_ERR_HISTEDIT_PATH, repo);
10454 got_object_commit_close(commit);
10455 commit = NULL;
10456 if (error)
10457 goto done;
10459 if (STAILQ_EMPTY(&commits)) {
10460 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10461 goto done;
10464 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10465 &base_commit_id, &fileindex, worktree, repo);
10466 if (error)
10467 goto done;
10469 if (edit_script_path) {
10470 error = histedit_load_list(&histedit_cmds,
10471 edit_script_path, repo);
10472 if (error) {
10473 got_worktree_histedit_abort(worktree, fileindex,
10474 repo, branch, base_commit_id,
10475 abort_progress, &upa);
10476 print_merge_progress_stats(&upa);
10477 goto done;
10479 } else {
10480 const char *branch_name;
10481 branch_name = got_ref_get_symref_target(branch);
10482 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10483 branch_name += 11;
10484 error = histedit_edit_script(&histedit_cmds, &commits,
10485 branch_name, edit_logmsg_only, fold_only,
10486 edit_only, repo);
10487 if (error) {
10488 got_worktree_histedit_abort(worktree, fileindex,
10489 repo, branch, base_commit_id,
10490 abort_progress, &upa);
10491 print_merge_progress_stats(&upa);
10492 goto done;
10497 error = histedit_save_list(&histedit_cmds, worktree,
10498 repo);
10499 if (error) {
10500 got_worktree_histedit_abort(worktree, fileindex,
10501 repo, branch, base_commit_id,
10502 abort_progress, &upa);
10503 print_merge_progress_stats(&upa);
10504 goto done;
10509 error = histedit_check_script(&histedit_cmds, &commits, repo);
10510 if (error)
10511 goto done;
10513 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10514 if (resume_commit_id) {
10515 if (got_object_id_cmp(hle->commit_id,
10516 resume_commit_id) != 0)
10517 continue;
10519 resume_commit_id = NULL;
10520 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10521 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10522 error = histedit_skip_commit(hle, worktree,
10523 repo);
10524 if (error)
10525 goto done;
10526 } else {
10527 struct got_pathlist_head paths;
10528 int have_changes = 0;
10530 TAILQ_INIT(&paths);
10531 error = got_pathlist_append(&paths, "", NULL);
10532 if (error)
10533 goto done;
10534 error = got_worktree_status(worktree, &paths,
10535 repo, 0, check_local_changes, &have_changes,
10536 check_cancelled, NULL);
10537 got_pathlist_free(&paths);
10538 if (error) {
10539 if (error->code != GOT_ERR_CANCELLED)
10540 goto done;
10541 if (sigint_received || sigpipe_received)
10542 goto done;
10544 if (have_changes) {
10545 error = histedit_commit(NULL, worktree,
10546 fileindex, tmp_branch, hle, repo);
10547 if (error)
10548 goto done;
10549 } else {
10550 error = got_object_open_as_commit(
10551 &commit, repo, hle->commit_id);
10552 if (error)
10553 goto done;
10554 error = show_histedit_progress(commit,
10555 hle, NULL);
10556 got_object_commit_close(commit);
10557 commit = NULL;
10558 if (error)
10559 goto done;
10562 continue;
10565 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10566 error = histedit_skip_commit(hle, worktree, repo);
10567 if (error)
10568 goto done;
10569 continue;
10572 error = got_object_open_as_commit(&commit, repo,
10573 hle->commit_id);
10574 if (error)
10575 goto done;
10576 parent_ids = got_object_commit_get_parent_ids(commit);
10577 pid = STAILQ_FIRST(parent_ids);
10579 error = got_worktree_histedit_merge_files(&merged_paths,
10580 worktree, fileindex, pid->id, hle->commit_id, repo,
10581 update_progress, &upa, check_cancelled, NULL);
10582 if (error)
10583 goto done;
10584 got_object_commit_close(commit);
10585 commit = NULL;
10587 print_merge_progress_stats(&upa);
10588 if (upa.conflicts > 0 || upa.missing > 0 ||
10589 upa.not_deleted > 0 || upa.unversioned > 0) {
10590 if (upa.conflicts > 0) {
10591 error = show_rebase_merge_conflict(
10592 hle->commit_id, repo);
10593 if (error)
10594 goto done;
10596 got_worktree_rebase_pathlist_free(&merged_paths);
10597 break;
10600 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10601 char *id_str;
10602 error = got_object_id_str(&id_str, hle->commit_id);
10603 if (error)
10604 goto done;
10605 printf("Stopping histedit for amending commit %s\n",
10606 id_str);
10607 free(id_str);
10608 got_worktree_rebase_pathlist_free(&merged_paths);
10609 error = got_worktree_histedit_postpone(worktree,
10610 fileindex);
10611 goto done;
10614 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10615 error = histedit_skip_commit(hle, worktree, repo);
10616 if (error)
10617 goto done;
10618 continue;
10621 error = histedit_commit(&merged_paths, worktree, fileindex,
10622 tmp_branch, hle, repo);
10623 got_worktree_rebase_pathlist_free(&merged_paths);
10624 if (error)
10625 goto done;
10628 if (upa.conflicts > 0 || upa.missing > 0 ||
10629 upa.not_deleted > 0 || upa.unversioned > 0) {
10630 error = got_worktree_histedit_postpone(worktree, fileindex);
10631 if (error)
10632 goto done;
10633 if (upa.conflicts > 0 && upa.missing == 0 &&
10634 upa.not_deleted == 0 && upa.unversioned == 0) {
10635 error = got_error_msg(GOT_ERR_CONFLICTS,
10636 "conflicts must be resolved before histedit "
10637 "can continue");
10638 } else if (upa.conflicts > 0) {
10639 error = got_error_msg(GOT_ERR_CONFLICTS,
10640 "conflicts must be resolved before histedit "
10641 "can continue; changes destined for some "
10642 "files were not yet merged and should be "
10643 "merged manually if required before the "
10644 "histedit operation is continued");
10645 } else {
10646 error = got_error_msg(GOT_ERR_CONFLICTS,
10647 "changes destined for some files were not "
10648 "yet merged and should be merged manually "
10649 "if required before the histedit operation "
10650 "is continued");
10652 } else
10653 error = histedit_complete(worktree, fileindex, tmp_branch,
10654 branch, repo);
10655 done:
10656 got_object_id_queue_free(&commits);
10657 histedit_free_list(&histedit_cmds);
10658 free(head_commit_id);
10659 free(base_commit_id);
10660 free(resume_commit_id);
10661 if (commit)
10662 got_object_commit_close(commit);
10663 if (branch)
10664 got_ref_close(branch);
10665 if (tmp_branch)
10666 got_ref_close(tmp_branch);
10667 if (worktree)
10668 got_worktree_close(worktree);
10669 if (repo) {
10670 const struct got_error *close_err = got_repo_close(repo);
10671 if (error == NULL)
10672 error = close_err;
10674 return error;
10677 __dead static void
10678 usage_integrate(void)
10680 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10681 exit(1);
10684 static const struct got_error *
10685 cmd_integrate(int argc, char *argv[])
10687 const struct got_error *error = NULL;
10688 struct got_repository *repo = NULL;
10689 struct got_worktree *worktree = NULL;
10690 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10691 const char *branch_arg = NULL;
10692 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10693 struct got_fileindex *fileindex = NULL;
10694 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10695 int ch;
10696 struct got_update_progress_arg upa;
10698 while ((ch = getopt(argc, argv, "")) != -1) {
10699 switch (ch) {
10700 default:
10701 usage_integrate();
10702 /* NOTREACHED */
10706 argc -= optind;
10707 argv += optind;
10709 if (argc != 1)
10710 usage_integrate();
10711 branch_arg = argv[0];
10712 #ifndef PROFILE
10713 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10714 "unveil", NULL) == -1)
10715 err(1, "pledge");
10716 #endif
10717 cwd = getcwd(NULL, 0);
10718 if (cwd == NULL) {
10719 error = got_error_from_errno("getcwd");
10720 goto done;
10723 error = got_worktree_open(&worktree, cwd);
10724 if (error) {
10725 if (error->code == GOT_ERR_NOT_WORKTREE)
10726 error = wrap_not_worktree_error(error, "integrate",
10727 cwd);
10728 goto done;
10731 error = check_rebase_or_histedit_in_progress(worktree);
10732 if (error)
10733 goto done;
10735 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10736 NULL);
10737 if (error != NULL)
10738 goto done;
10740 error = apply_unveil(got_repo_get_path(repo), 0,
10741 got_worktree_get_root_path(worktree));
10742 if (error)
10743 goto done;
10745 error = check_merge_in_progress(worktree, repo);
10746 if (error)
10747 goto done;
10749 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
10750 error = got_error_from_errno("asprintf");
10751 goto done;
10754 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
10755 &base_branch_ref, worktree, refname, repo);
10756 if (error)
10757 goto done;
10759 refname = strdup(got_ref_get_name(branch_ref));
10760 if (refname == NULL) {
10761 error = got_error_from_errno("strdup");
10762 got_worktree_integrate_abort(worktree, fileindex, repo,
10763 branch_ref, base_branch_ref);
10764 goto done;
10766 base_refname = strdup(got_ref_get_name(base_branch_ref));
10767 if (base_refname == NULL) {
10768 error = got_error_from_errno("strdup");
10769 got_worktree_integrate_abort(worktree, fileindex, repo,
10770 branch_ref, base_branch_ref);
10771 goto done;
10774 error = got_ref_resolve(&commit_id, repo, branch_ref);
10775 if (error)
10776 goto done;
10778 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
10779 if (error)
10780 goto done;
10782 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
10783 error = got_error_msg(GOT_ERR_SAME_BRANCH,
10784 "specified branch has already been integrated");
10785 got_worktree_integrate_abort(worktree, fileindex, repo,
10786 branch_ref, base_branch_ref);
10787 goto done;
10790 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
10791 if (error) {
10792 if (error->code == GOT_ERR_ANCESTRY)
10793 error = got_error(GOT_ERR_REBASE_REQUIRED);
10794 got_worktree_integrate_abort(worktree, fileindex, repo,
10795 branch_ref, base_branch_ref);
10796 goto done;
10799 memset(&upa, 0, sizeof(upa));
10800 error = got_worktree_integrate_continue(worktree, fileindex, repo,
10801 branch_ref, base_branch_ref, update_progress, &upa,
10802 check_cancelled, NULL);
10803 if (error)
10804 goto done;
10806 printf("Integrated %s into %s\n", refname, base_refname);
10807 print_update_progress_stats(&upa);
10808 done:
10809 if (repo) {
10810 const struct got_error *close_err = got_repo_close(repo);
10811 if (error == NULL)
10812 error = close_err;
10814 if (worktree)
10815 got_worktree_close(worktree);
10816 free(cwd);
10817 free(base_commit_id);
10818 free(commit_id);
10819 free(refname);
10820 free(base_refname);
10821 return error;
10824 __dead static void
10825 usage_merge(void)
10827 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
10828 getprogname());
10829 exit(1);
10832 static const struct got_error *
10833 cmd_merge(int argc, char *argv[])
10835 const struct got_error *error = NULL;
10836 struct got_worktree *worktree = NULL;
10837 struct got_repository *repo = NULL;
10838 struct got_fileindex *fileindex = NULL;
10839 char *cwd = NULL, *id_str = NULL, *author = NULL;
10840 struct got_reference *branch = NULL, *wt_branch = NULL;
10841 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
10842 struct got_object_id *wt_branch_tip = NULL;
10843 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
10844 int interrupt_merge = 0;
10845 struct got_update_progress_arg upa;
10846 struct got_object_id *merge_commit_id = NULL;
10847 char *branch_name = NULL;
10849 memset(&upa, 0, sizeof(upa));
10851 while ((ch = getopt(argc, argv, "acn")) != -1) {
10852 switch (ch) {
10853 case 'a':
10854 abort_merge = 1;
10855 break;
10856 case 'c':
10857 continue_merge = 1;
10858 break;
10859 case 'n':
10860 interrupt_merge = 1;
10861 break;
10862 default:
10863 usage_rebase();
10864 /* NOTREACHED */
10868 argc -= optind;
10869 argv += optind;
10871 #ifndef PROFILE
10872 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10873 "unveil", NULL) == -1)
10874 err(1, "pledge");
10875 #endif
10877 if (abort_merge && continue_merge)
10878 option_conflict('a', 'c');
10879 if (abort_merge || continue_merge) {
10880 if (argc != 0)
10881 usage_merge();
10882 } else if (argc != 1)
10883 usage_merge();
10885 cwd = getcwd(NULL, 0);
10886 if (cwd == NULL) {
10887 error = got_error_from_errno("getcwd");
10888 goto done;
10891 error = got_worktree_open(&worktree, cwd);
10892 if (error) {
10893 if (error->code == GOT_ERR_NOT_WORKTREE)
10894 error = wrap_not_worktree_error(error,
10895 "merge", cwd);
10896 goto done;
10899 error = got_repo_open(&repo,
10900 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
10901 if (error != NULL)
10902 goto done;
10904 error = apply_unveil(got_repo_get_path(repo), 0,
10905 worktree ? got_worktree_get_root_path(worktree) : NULL);
10906 if (error)
10907 goto done;
10909 error = check_rebase_or_histedit_in_progress(worktree);
10910 if (error)
10911 goto done;
10913 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10914 repo);
10915 if (error)
10916 goto done;
10918 if (abort_merge) {
10919 if (!merge_in_progress) {
10920 error = got_error(GOT_ERR_NOT_MERGING);
10921 goto done;
10923 error = got_worktree_merge_continue(&branch_name,
10924 &branch_tip, &fileindex, worktree, repo);
10925 if (error)
10926 goto done;
10927 error = got_worktree_merge_abort(worktree, fileindex, repo,
10928 abort_progress, &upa);
10929 if (error)
10930 goto done;
10931 printf("Merge of %s aborted\n", branch_name);
10932 goto done; /* nothing else to do */
10935 error = get_author(&author, repo, worktree);
10936 if (error)
10937 goto done;
10939 if (continue_merge) {
10940 if (!merge_in_progress) {
10941 error = got_error(GOT_ERR_NOT_MERGING);
10942 goto done;
10944 error = got_worktree_merge_continue(&branch_name,
10945 &branch_tip, &fileindex, worktree, repo);
10946 if (error)
10947 goto done;
10948 } else {
10949 error = got_ref_open(&branch, repo, argv[0], 0);
10950 if (error != NULL)
10951 goto done;
10952 branch_name = strdup(got_ref_get_name(branch));
10953 if (branch_name == NULL) {
10954 error = got_error_from_errno("strdup");
10955 goto done;
10957 error = got_ref_resolve(&branch_tip, repo, branch);
10958 if (error)
10959 goto done;
10962 error = got_ref_open(&wt_branch, repo,
10963 got_worktree_get_head_ref_name(worktree), 0);
10964 if (error)
10965 goto done;
10966 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
10967 if (error)
10968 goto done;
10969 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10970 wt_branch_tip, branch_tip, 0, repo,
10971 check_cancelled, NULL);
10972 if (error && error->code != GOT_ERR_ANCESTRY)
10973 goto done;
10975 if (!continue_merge) {
10976 error = check_path_prefix(wt_branch_tip, branch_tip,
10977 got_worktree_get_path_prefix(worktree),
10978 GOT_ERR_MERGE_PATH, repo);
10979 if (error)
10980 goto done;
10981 if (yca_id) {
10982 error = check_same_branch(wt_branch_tip, branch,
10983 yca_id, repo);
10984 if (error) {
10985 if (error->code != GOT_ERR_ANCESTRY)
10986 goto done;
10987 error = NULL;
10988 } else {
10989 static char msg[512];
10990 snprintf(msg, sizeof(msg),
10991 "cannot create a merge commit because "
10992 "%s is based on %s; %s can be integrated "
10993 "with 'got integrate' instead", branch_name,
10994 got_worktree_get_head_ref_name(worktree),
10995 branch_name);
10996 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
10997 goto done;
11000 error = got_worktree_merge_prepare(&fileindex, worktree,
11001 branch, repo);
11002 if (error)
11003 goto done;
11005 error = got_worktree_merge_branch(worktree, fileindex,
11006 yca_id, branch_tip, repo, update_progress, &upa,
11007 check_cancelled, NULL);
11008 if (error)
11009 goto done;
11010 print_merge_progress_stats(&upa);
11011 if (!upa.did_something) {
11012 error = got_worktree_merge_abort(worktree, fileindex,
11013 repo, abort_progress, &upa);
11014 if (error)
11015 goto done;
11016 printf("Already up-to-date\n");
11017 goto done;
11021 if (interrupt_merge) {
11022 error = got_worktree_merge_postpone(worktree, fileindex);
11023 if (error)
11024 goto done;
11025 printf("Merge of %s interrupted on request\n", branch_name);
11026 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11027 upa.not_deleted > 0 || upa.unversioned > 0) {
11028 error = got_worktree_merge_postpone(worktree, fileindex);
11029 if (error)
11030 goto done;
11031 if (upa.conflicts > 0 && upa.missing == 0 &&
11032 upa.not_deleted == 0 && upa.unversioned == 0) {
11033 error = got_error_msg(GOT_ERR_CONFLICTS,
11034 "conflicts must be resolved before merging "
11035 "can continue");
11036 } else if (upa.conflicts > 0) {
11037 error = got_error_msg(GOT_ERR_CONFLICTS,
11038 "conflicts must be resolved before merging "
11039 "can continue; changes destined for some "
11040 "files were not yet merged and "
11041 "should be merged manually if required before the "
11042 "merge operation is continued");
11043 } else {
11044 error = got_error_msg(GOT_ERR_CONFLICTS,
11045 "changes destined for some "
11046 "files were not yet merged and should be "
11047 "merged manually if required before the "
11048 "merge operation is continued");
11050 goto done;
11051 } else {
11052 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11053 fileindex, author, NULL, 1, branch_tip, branch_name,
11054 repo, continue_merge ? print_status : NULL, NULL);
11055 if (error)
11056 goto done;
11057 error = got_worktree_merge_complete(worktree, fileindex, repo);
11058 if (error)
11059 goto done;
11060 error = got_object_id_str(&id_str, merge_commit_id);
11061 if (error)
11062 goto done;
11063 printf("Merged %s into %s: %s\n", branch_name,
11064 got_worktree_get_head_ref_name(worktree),
11065 id_str);
11068 done:
11069 free(id_str);
11070 free(merge_commit_id);
11071 free(author);
11072 free(branch_tip);
11073 free(branch_name);
11074 free(yca_id);
11075 if (branch)
11076 got_ref_close(branch);
11077 if (wt_branch)
11078 got_ref_close(wt_branch);
11079 if (worktree)
11080 got_worktree_close(worktree);
11081 if (repo) {
11082 const struct got_error *close_err = got_repo_close(repo);
11083 if (error == NULL)
11084 error = close_err;
11086 return error;
11089 __dead static void
11090 usage_stage(void)
11092 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11093 "[-S] [file-path ...]\n",
11094 getprogname());
11095 exit(1);
11098 static const struct got_error *
11099 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11100 const char *path, struct got_object_id *blob_id,
11101 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11102 int dirfd, const char *de_name)
11104 const struct got_error *err = NULL;
11105 char *id_str = NULL;
11107 if (staged_status != GOT_STATUS_ADD &&
11108 staged_status != GOT_STATUS_MODIFY &&
11109 staged_status != GOT_STATUS_DELETE)
11110 return NULL;
11112 if (staged_status == GOT_STATUS_ADD ||
11113 staged_status == GOT_STATUS_MODIFY)
11114 err = got_object_id_str(&id_str, staged_blob_id);
11115 else
11116 err = got_object_id_str(&id_str, blob_id);
11117 if (err)
11118 return err;
11120 printf("%s %c %s\n", id_str, staged_status, path);
11121 free(id_str);
11122 return NULL;
11125 static const struct got_error *
11126 cmd_stage(int argc, char *argv[])
11128 const struct got_error *error = NULL;
11129 struct got_repository *repo = NULL;
11130 struct got_worktree *worktree = NULL;
11131 char *cwd = NULL;
11132 struct got_pathlist_head paths;
11133 struct got_pathlist_entry *pe;
11134 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11135 FILE *patch_script_file = NULL;
11136 const char *patch_script_path = NULL;
11137 struct choose_patch_arg cpa;
11139 TAILQ_INIT(&paths);
11141 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11142 switch (ch) {
11143 case 'l':
11144 list_stage = 1;
11145 break;
11146 case 'p':
11147 pflag = 1;
11148 break;
11149 case 'F':
11150 patch_script_path = optarg;
11151 break;
11152 case 'S':
11153 allow_bad_symlinks = 1;
11154 break;
11155 default:
11156 usage_stage();
11157 /* NOTREACHED */
11161 argc -= optind;
11162 argv += optind;
11164 #ifndef PROFILE
11165 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11166 "unveil", NULL) == -1)
11167 err(1, "pledge");
11168 #endif
11169 if (list_stage && (pflag || patch_script_path))
11170 errx(1, "-l option cannot be used with other options");
11171 if (patch_script_path && !pflag)
11172 errx(1, "-F option can only be used together with -p option");
11174 cwd = getcwd(NULL, 0);
11175 if (cwd == NULL) {
11176 error = got_error_from_errno("getcwd");
11177 goto done;
11180 error = got_worktree_open(&worktree, cwd);
11181 if (error) {
11182 if (error->code == GOT_ERR_NOT_WORKTREE)
11183 error = wrap_not_worktree_error(error, "stage", cwd);
11184 goto done;
11187 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11188 NULL);
11189 if (error != NULL)
11190 goto done;
11192 if (patch_script_path) {
11193 patch_script_file = fopen(patch_script_path, "r");
11194 if (patch_script_file == NULL) {
11195 error = got_error_from_errno2("fopen",
11196 patch_script_path);
11197 goto done;
11200 error = apply_unveil(got_repo_get_path(repo), 0,
11201 got_worktree_get_root_path(worktree));
11202 if (error)
11203 goto done;
11205 error = check_merge_in_progress(worktree, repo);
11206 if (error)
11207 goto done;
11209 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11210 if (error)
11211 goto done;
11213 if (list_stage)
11214 error = got_worktree_status(worktree, &paths, repo, 0,
11215 print_stage, NULL, check_cancelled, NULL);
11216 else {
11217 cpa.patch_script_file = patch_script_file;
11218 cpa.action = "stage";
11219 error = got_worktree_stage(worktree, &paths,
11220 pflag ? NULL : print_status, NULL,
11221 pflag ? choose_patch : NULL, &cpa,
11222 allow_bad_symlinks, repo);
11224 done:
11225 if (patch_script_file && fclose(patch_script_file) == EOF &&
11226 error == NULL)
11227 error = got_error_from_errno2("fclose", patch_script_path);
11228 if (repo) {
11229 const struct got_error *close_err = got_repo_close(repo);
11230 if (error == NULL)
11231 error = close_err;
11233 if (worktree)
11234 got_worktree_close(worktree);
11235 TAILQ_FOREACH(pe, &paths, entry)
11236 free((char *)pe->path);
11237 got_pathlist_free(&paths);
11238 free(cwd);
11239 return error;
11242 __dead static void
11243 usage_unstage(void)
11245 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11246 "[file-path ...]\n",
11247 getprogname());
11248 exit(1);
11252 static const struct got_error *
11253 cmd_unstage(int argc, char *argv[])
11255 const struct got_error *error = NULL;
11256 struct got_repository *repo = NULL;
11257 struct got_worktree *worktree = NULL;
11258 char *cwd = NULL;
11259 struct got_pathlist_head paths;
11260 struct got_pathlist_entry *pe;
11261 int ch, pflag = 0;
11262 struct got_update_progress_arg upa;
11263 FILE *patch_script_file = NULL;
11264 const char *patch_script_path = NULL;
11265 struct choose_patch_arg cpa;
11267 TAILQ_INIT(&paths);
11269 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11270 switch (ch) {
11271 case 'p':
11272 pflag = 1;
11273 break;
11274 case 'F':
11275 patch_script_path = optarg;
11276 break;
11277 default:
11278 usage_unstage();
11279 /* NOTREACHED */
11283 argc -= optind;
11284 argv += optind;
11286 #ifndef PROFILE
11287 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11288 "unveil", NULL) == -1)
11289 err(1, "pledge");
11290 #endif
11291 if (patch_script_path && !pflag)
11292 errx(1, "-F option can only be used together with -p option");
11294 cwd = getcwd(NULL, 0);
11295 if (cwd == NULL) {
11296 error = got_error_from_errno("getcwd");
11297 goto done;
11300 error = got_worktree_open(&worktree, cwd);
11301 if (error) {
11302 if (error->code == GOT_ERR_NOT_WORKTREE)
11303 error = wrap_not_worktree_error(error, "unstage", cwd);
11304 goto done;
11307 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11308 NULL);
11309 if (error != NULL)
11310 goto done;
11312 if (patch_script_path) {
11313 patch_script_file = fopen(patch_script_path, "r");
11314 if (patch_script_file == NULL) {
11315 error = got_error_from_errno2("fopen",
11316 patch_script_path);
11317 goto done;
11321 error = apply_unveil(got_repo_get_path(repo), 0,
11322 got_worktree_get_root_path(worktree));
11323 if (error)
11324 goto done;
11326 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11327 if (error)
11328 goto done;
11330 cpa.patch_script_file = patch_script_file;
11331 cpa.action = "unstage";
11332 memset(&upa, 0, sizeof(upa));
11333 error = got_worktree_unstage(worktree, &paths, update_progress,
11334 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11335 if (!error)
11336 print_merge_progress_stats(&upa);
11337 done:
11338 if (patch_script_file && fclose(patch_script_file) == EOF &&
11339 error == NULL)
11340 error = got_error_from_errno2("fclose", patch_script_path);
11341 if (repo) {
11342 const struct got_error *close_err = got_repo_close(repo);
11343 if (error == NULL)
11344 error = close_err;
11346 if (worktree)
11347 got_worktree_close(worktree);
11348 TAILQ_FOREACH(pe, &paths, entry)
11349 free((char *)pe->path);
11350 got_pathlist_free(&paths);
11351 free(cwd);
11352 return error;
11355 __dead static void
11356 usage_cat(void)
11358 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11359 "arg1 [arg2 ...]\n", getprogname());
11360 exit(1);
11363 static const struct got_error *
11364 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11366 const struct got_error *err;
11367 struct got_blob_object *blob;
11369 err = got_object_open_as_blob(&blob, repo, id, 8192);
11370 if (err)
11371 return err;
11373 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11374 got_object_blob_close(blob);
11375 return err;
11378 static const struct got_error *
11379 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11381 const struct got_error *err;
11382 struct got_tree_object *tree;
11383 int nentries, i;
11385 err = got_object_open_as_tree(&tree, repo, id);
11386 if (err)
11387 return err;
11389 nentries = got_object_tree_get_nentries(tree);
11390 for (i = 0; i < nentries; i++) {
11391 struct got_tree_entry *te;
11392 char *id_str;
11393 if (sigint_received || sigpipe_received)
11394 break;
11395 te = got_object_tree_get_entry(tree, i);
11396 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11397 if (err)
11398 break;
11399 fprintf(outfile, "%s %.7o %s\n", id_str,
11400 got_tree_entry_get_mode(te),
11401 got_tree_entry_get_name(te));
11402 free(id_str);
11405 got_object_tree_close(tree);
11406 return err;
11409 static const struct got_error *
11410 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11412 const struct got_error *err;
11413 struct got_commit_object *commit;
11414 const struct got_object_id_queue *parent_ids;
11415 struct got_object_qid *pid;
11416 char *id_str = NULL;
11417 const char *logmsg = NULL;
11419 err = got_object_open_as_commit(&commit, repo, id);
11420 if (err)
11421 return err;
11423 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11424 if (err)
11425 goto done;
11427 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11428 parent_ids = got_object_commit_get_parent_ids(commit);
11429 fprintf(outfile, "numparents %d\n",
11430 got_object_commit_get_nparents(commit));
11431 STAILQ_FOREACH(pid, parent_ids, entry) {
11432 char *pid_str;
11433 err = got_object_id_str(&pid_str, pid->id);
11434 if (err)
11435 goto done;
11436 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11437 free(pid_str);
11439 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_AUTHOR,
11440 got_object_commit_get_author(commit),
11441 (long long)got_object_commit_get_author_time(commit));
11443 fprintf(outfile, "%s%s %lld +0000\n", GOT_COMMIT_LABEL_COMMITTER,
11444 got_object_commit_get_author(commit),
11445 (long long)got_object_commit_get_committer_time(commit));
11447 logmsg = got_object_commit_get_logmsg_raw(commit);
11448 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11449 fprintf(outfile, "%s", logmsg);
11450 done:
11451 free(id_str);
11452 got_object_commit_close(commit);
11453 return err;
11456 static const struct got_error *
11457 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11459 const struct got_error *err;
11460 struct got_tag_object *tag;
11461 char *id_str = NULL;
11462 const char *tagmsg = NULL;
11464 err = got_object_open_as_tag(&tag, repo, id);
11465 if (err)
11466 return err;
11468 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11469 if (err)
11470 goto done;
11472 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11474 switch (got_object_tag_get_object_type(tag)) {
11475 case GOT_OBJ_TYPE_BLOB:
11476 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11477 GOT_OBJ_LABEL_BLOB);
11478 break;
11479 case GOT_OBJ_TYPE_TREE:
11480 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11481 GOT_OBJ_LABEL_TREE);
11482 break;
11483 case GOT_OBJ_TYPE_COMMIT:
11484 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11485 GOT_OBJ_LABEL_COMMIT);
11486 break;
11487 case GOT_OBJ_TYPE_TAG:
11488 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11489 GOT_OBJ_LABEL_TAG);
11490 break;
11491 default:
11492 break;
11495 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11496 got_object_tag_get_name(tag));
11498 fprintf(outfile, "%s%s %lld +0000\n", GOT_TAG_LABEL_TAGGER,
11499 got_object_tag_get_tagger(tag),
11500 (long long)got_object_tag_get_tagger_time(tag));
11502 tagmsg = got_object_tag_get_message(tag);
11503 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11504 fprintf(outfile, "%s", tagmsg);
11505 done:
11506 free(id_str);
11507 got_object_tag_close(tag);
11508 return err;
11511 static const struct got_error *
11512 cmd_cat(int argc, char *argv[])
11514 const struct got_error *error;
11515 struct got_repository *repo = NULL;
11516 struct got_worktree *worktree = NULL;
11517 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11518 const char *commit_id_str = NULL;
11519 struct got_object_id *id = NULL, *commit_id = NULL;
11520 int ch, obj_type, i, force_path = 0;
11521 struct got_reflist_head refs;
11523 TAILQ_INIT(&refs);
11525 #ifndef PROFILE
11526 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11527 NULL) == -1)
11528 err(1, "pledge");
11529 #endif
11531 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11532 switch (ch) {
11533 case 'c':
11534 commit_id_str = optarg;
11535 break;
11536 case 'r':
11537 repo_path = realpath(optarg, NULL);
11538 if (repo_path == NULL)
11539 return got_error_from_errno2("realpath",
11540 optarg);
11541 got_path_strip_trailing_slashes(repo_path);
11542 break;
11543 case 'P':
11544 force_path = 1;
11545 break;
11546 default:
11547 usage_cat();
11548 /* NOTREACHED */
11552 argc -= optind;
11553 argv += optind;
11555 cwd = getcwd(NULL, 0);
11556 if (cwd == NULL) {
11557 error = got_error_from_errno("getcwd");
11558 goto done;
11560 error = got_worktree_open(&worktree, cwd);
11561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11562 goto done;
11563 if (worktree) {
11564 if (repo_path == NULL) {
11565 repo_path = strdup(
11566 got_worktree_get_repo_path(worktree));
11567 if (repo_path == NULL) {
11568 error = got_error_from_errno("strdup");
11569 goto done;
11574 if (repo_path == NULL) {
11575 repo_path = getcwd(NULL, 0);
11576 if (repo_path == NULL)
11577 return got_error_from_errno("getcwd");
11580 error = got_repo_open(&repo, repo_path, NULL);
11581 free(repo_path);
11582 if (error != NULL)
11583 goto done;
11585 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11586 if (error)
11587 goto done;
11589 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11590 if (error)
11591 goto done;
11593 if (commit_id_str == NULL)
11594 commit_id_str = GOT_REF_HEAD;
11595 error = got_repo_match_object_id(&commit_id, NULL,
11596 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11597 if (error)
11598 goto done;
11600 for (i = 0; i < argc; i++) {
11601 if (force_path) {
11602 error = got_object_id_by_path(&id, repo, commit_id,
11603 argv[i]);
11604 if (error)
11605 break;
11606 } else {
11607 error = got_repo_match_object_id(&id, &label, argv[i],
11608 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11609 repo);
11610 if (error) {
11611 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11612 error->code != GOT_ERR_NOT_REF)
11613 break;
11614 error = got_object_id_by_path(&id, repo,
11615 commit_id, argv[i]);
11616 if (error)
11617 break;
11621 error = got_object_get_type(&obj_type, repo, id);
11622 if (error)
11623 break;
11625 switch (obj_type) {
11626 case GOT_OBJ_TYPE_BLOB:
11627 error = cat_blob(id, repo, stdout);
11628 break;
11629 case GOT_OBJ_TYPE_TREE:
11630 error = cat_tree(id, repo, stdout);
11631 break;
11632 case GOT_OBJ_TYPE_COMMIT:
11633 error = cat_commit(id, repo, stdout);
11634 break;
11635 case GOT_OBJ_TYPE_TAG:
11636 error = cat_tag(id, repo, stdout);
11637 break;
11638 default:
11639 error = got_error(GOT_ERR_OBJ_TYPE);
11640 break;
11642 if (error)
11643 break;
11644 free(label);
11645 label = NULL;
11646 free(id);
11647 id = NULL;
11649 done:
11650 free(label);
11651 free(id);
11652 free(commit_id);
11653 if (worktree)
11654 got_worktree_close(worktree);
11655 if (repo) {
11656 const struct got_error *close_err = got_repo_close(repo);
11657 if (error == NULL)
11658 error = close_err;
11660 got_ref_list_free(&refs);
11661 return error;
11664 __dead static void
11665 usage_info(void)
11667 fprintf(stderr, "usage: %s info [path ...]\n",
11668 getprogname());
11669 exit(1);
11672 static const struct got_error *
11673 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
11674 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11675 struct got_object_id *commit_id)
11677 const struct got_error *err = NULL;
11678 char *id_str = NULL;
11679 char datebuf[128];
11680 struct tm mytm, *tm;
11681 struct got_pathlist_head *paths = arg;
11682 struct got_pathlist_entry *pe;
11685 * Clear error indication from any of the path arguments which
11686 * would cause this file index entry to be displayed.
11688 TAILQ_FOREACH(pe, paths, entry) {
11689 if (got_path_cmp(path, pe->path, strlen(path),
11690 pe->path_len) == 0 ||
11691 got_path_is_child(path, pe->path, pe->path_len))
11692 pe->data = NULL; /* no error */
11695 printf(GOT_COMMIT_SEP_STR);
11696 if (S_ISLNK(mode))
11697 printf("symlink: %s\n", path);
11698 else if (S_ISREG(mode)) {
11699 printf("file: %s\n", path);
11700 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
11701 } else if (S_ISDIR(mode))
11702 printf("directory: %s\n", path);
11703 else
11704 printf("something: %s\n", path);
11706 tm = localtime_r(&mtime, &mytm);
11707 if (tm == NULL)
11708 return NULL;
11709 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
11710 return got_error(GOT_ERR_NO_SPACE);
11711 printf("timestamp: %s\n", datebuf);
11713 if (blob_id) {
11714 err = got_object_id_str(&id_str, blob_id);
11715 if (err)
11716 return err;
11717 printf("based on blob: %s\n", id_str);
11718 free(id_str);
11721 if (staged_blob_id) {
11722 err = got_object_id_str(&id_str, staged_blob_id);
11723 if (err)
11724 return err;
11725 printf("based on staged blob: %s\n", id_str);
11726 free(id_str);
11729 if (commit_id) {
11730 err = got_object_id_str(&id_str, commit_id);
11731 if (err)
11732 return err;
11733 printf("based on commit: %s\n", id_str);
11734 free(id_str);
11737 return NULL;
11740 static const struct got_error *
11741 cmd_info(int argc, char *argv[])
11743 const struct got_error *error = NULL;
11744 struct got_worktree *worktree = NULL;
11745 char *cwd = NULL, *id_str = NULL;
11746 struct got_pathlist_head paths;
11747 struct got_pathlist_entry *pe;
11748 char *uuidstr = NULL;
11749 int ch, show_files = 0;
11751 TAILQ_INIT(&paths);
11753 while ((ch = getopt(argc, argv, "")) != -1) {
11754 switch (ch) {
11755 default:
11756 usage_info();
11757 /* NOTREACHED */
11761 argc -= optind;
11762 argv += optind;
11764 #ifndef PROFILE
11765 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
11766 NULL) == -1)
11767 err(1, "pledge");
11768 #endif
11769 cwd = getcwd(NULL, 0);
11770 if (cwd == NULL) {
11771 error = got_error_from_errno("getcwd");
11772 goto done;
11775 error = got_worktree_open(&worktree, cwd);
11776 if (error) {
11777 if (error->code == GOT_ERR_NOT_WORKTREE)
11778 error = wrap_not_worktree_error(error, "info", cwd);
11779 goto done;
11782 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
11783 if (error)
11784 goto done;
11786 if (argc >= 1) {
11787 error = get_worktree_paths_from_argv(&paths, argc, argv,
11788 worktree);
11789 if (error)
11790 goto done;
11791 show_files = 1;
11794 error = got_object_id_str(&id_str,
11795 got_worktree_get_base_commit_id(worktree));
11796 if (error)
11797 goto done;
11799 error = got_worktree_get_uuid(&uuidstr, worktree);
11800 if (error)
11801 goto done;
11803 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
11804 printf("work tree base commit: %s\n", id_str);
11805 printf("work tree path prefix: %s\n",
11806 got_worktree_get_path_prefix(worktree));
11807 printf("work tree branch reference: %s\n",
11808 got_worktree_get_head_ref_name(worktree));
11809 printf("work tree UUID: %s\n", uuidstr);
11810 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
11812 if (show_files) {
11813 struct got_pathlist_entry *pe;
11814 TAILQ_FOREACH(pe, &paths, entry) {
11815 if (pe->path_len == 0)
11816 continue;
11818 * Assume this path will fail. This will be corrected
11819 * in print_path_info() in case the path does suceeed.
11821 pe->data = (void *)got_error_path(pe->path,
11822 GOT_ERR_BAD_PATH);
11824 error = got_worktree_path_info(worktree, &paths,
11825 print_path_info, &paths, check_cancelled, NULL);
11826 if (error)
11827 goto done;
11828 TAILQ_FOREACH(pe, &paths, entry) {
11829 if (pe->data != NULL) {
11830 error = pe->data; /* bad path */
11831 break;
11835 done:
11836 TAILQ_FOREACH(pe, &paths, entry)
11837 free((char *)pe->path);
11838 got_pathlist_free(&paths);
11839 free(cwd);
11840 free(id_str);
11841 free(uuidstr);
11842 return error;