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 <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
719 TAILQ_INIT(&ignores);
721 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
722 switch (ch) {
723 case 'b':
724 branch_name = optarg;
725 break;
726 case 'm':
727 logmsg = strdup(optarg);
728 if (logmsg == NULL) {
729 error = got_error_from_errno("strdup");
730 goto done;
732 break;
733 case 'r':
734 repo_path = realpath(optarg, NULL);
735 if (repo_path == NULL) {
736 error = got_error_from_errno2("realpath",
737 optarg);
738 goto done;
740 break;
741 case 'I':
742 if (optarg[0] == '\0')
743 break;
744 error = got_pathlist_insert(&pe, &ignores, optarg,
745 NULL);
746 if (error)
747 goto done;
748 break;
749 default:
750 usage_import();
751 /* NOTREACHED */
755 argc -= optind;
756 argv += optind;
758 #ifndef PROFILE
759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
760 "unveil",
761 NULL) == -1)
762 err(1, "pledge");
763 #endif
764 if (argc != 1)
765 usage_import();
767 if (repo_path == NULL) {
768 repo_path = getcwd(NULL, 0);
769 if (repo_path == NULL)
770 return got_error_from_errno("getcwd");
772 got_path_strip_trailing_slashes(repo_path);
773 error = get_gitconfig_path(&gitconfig_path);
774 if (error)
775 goto done;
776 error = got_repo_open(&repo, repo_path, gitconfig_path);
777 if (error)
778 goto done;
780 error = get_author(&author, repo, NULL);
781 if (error)
782 return error;
784 /*
785 * Don't let the user create a branch name with a leading '-'.
786 * While technically a valid reference name, this case is usually
787 * an unintended typo.
788 */
789 if (branch_name[0] == '-')
790 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
792 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
793 error = got_error_from_errno("asprintf");
794 goto done;
797 error = got_ref_open(&branch_ref, repo, refname, 0);
798 if (error) {
799 if (error->code != GOT_ERR_NOT_REF)
800 goto done;
801 } else {
802 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
803 "import target branch already exists");
804 goto done;
807 path_dir = realpath(argv[0], NULL);
808 if (path_dir == NULL) {
809 error = got_error_from_errno2("realpath", argv[0]);
810 goto done;
812 got_path_strip_trailing_slashes(path_dir);
814 /*
815 * unveil(2) traverses exec(2); if an editor is used we have
816 * to apply unveil after the log message has been written.
817 */
818 if (logmsg == NULL || strlen(logmsg) == 0) {
819 error = get_editor(&editor);
820 if (error)
821 goto done;
822 free(logmsg);
823 error = collect_import_msg(&logmsg, &logmsg_path, editor,
824 path_dir, refname);
825 if (error) {
826 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
827 logmsg_path != NULL)
828 preserve_logmsg = 1;
829 goto done;
833 if (unveil(path_dir, "r") != 0) {
834 error = got_error_from_errno2("unveil", path_dir);
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_repo_import(&new_commit_id, path_dir, logmsg,
848 author, &ignores, repo, import_progress, NULL);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
856 if (error) {
857 if (logmsg_path)
858 preserve_logmsg = 1;
859 goto done;
862 error = got_ref_write(branch_ref, repo);
863 if (error) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_object_id_str(&id_str, new_commit_id);
870 if (error) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
877 if (error) {
878 if (error->code != GOT_ERR_NOT_REF) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
885 branch_ref);
886 if (error) {
887 if (logmsg_path)
888 preserve_logmsg = 1;
889 goto done;
892 error = got_ref_write(head_ref, repo);
893 if (error) {
894 if (logmsg_path)
895 preserve_logmsg = 1;
896 goto done;
900 printf("Created branch %s with commit %s\n",
901 got_ref_get_name(branch_ref), id_str);
902 done:
903 if (preserve_logmsg) {
904 fprintf(stderr, "%s: log message preserved in %s\n",
905 getprogname(), logmsg_path);
906 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
907 error = got_error_from_errno2("unlink", logmsg_path);
908 free(logmsg);
909 free(logmsg_path);
910 free(repo_path);
911 free(editor);
912 free(refname);
913 free(new_commit_id);
914 free(id_str);
915 free(author);
916 free(gitconfig_path);
917 if (branch_ref)
918 got_ref_close(branch_ref);
919 if (head_ref)
920 got_ref_close(head_ref);
921 return error;
924 __dead static void
925 usage_clone(void)
927 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
928 "[-R reference] repository-url [directory]\n", getprogname());
929 exit(1);
932 struct got_fetch_progress_arg {
933 char last_scaled_size[FMT_SCALED_STRSIZE];
934 int last_p_indexed;
935 int last_p_resolved;
936 int verbosity;
938 struct got_repository *repo;
940 int create_configs;
941 int configs_created;
942 struct {
943 struct got_pathlist_head *symrefs;
944 struct got_pathlist_head *wanted_branches;
945 struct got_pathlist_head *wanted_refs;
946 const char *proto;
947 const char *host;
948 const char *port;
949 const char *remote_repo_path;
950 const char *git_url;
951 int fetch_all_branches;
952 int mirror_references;
953 } config_info;
954 };
956 /* XXX forward declaration */
957 static const struct got_error *
958 create_config_files(const char *proto, const char *host, const char *port,
959 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
960 int mirror_references, struct got_pathlist_head *symrefs,
961 struct got_pathlist_head *wanted_branches,
962 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
964 static const struct got_error *
965 fetch_progress(void *arg, const char *message, off_t packfile_size,
966 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
968 const struct got_error *err = NULL;
969 struct got_fetch_progress_arg *a = arg;
970 char scaled_size[FMT_SCALED_STRSIZE];
971 int p_indexed, p_resolved;
972 int print_size = 0, print_indexed = 0, print_resolved = 0;
974 /*
975 * In order to allow a failed clone to be resumed with 'got fetch'
976 * we try to create configuration files as soon as possible.
977 * Once the server has sent information about its default branch
978 * we have all required information.
979 */
980 if (a->create_configs && !a->configs_created &&
981 !TAILQ_EMPTY(a->config_info.symrefs)) {
982 err = create_config_files(a->config_info.proto,
983 a->config_info.host, a->config_info.port,
984 a->config_info.remote_repo_path,
985 a->config_info.git_url,
986 a->config_info.fetch_all_branches,
987 a->config_info.mirror_references,
988 a->config_info.symrefs,
989 a->config_info.wanted_branches,
990 a->config_info.wanted_refs, a->repo);
991 if (err)
992 return err;
993 a->configs_created = 1;
996 if (a->verbosity < 0)
997 return NULL;
999 if (message && message[0] != '\0') {
1000 printf("\rserver: %s", message);
1001 fflush(stdout);
1002 return NULL;
1005 if (packfile_size > 0 || nobj_indexed > 0) {
1006 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1007 (a->last_scaled_size[0] == '\0' ||
1008 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1009 print_size = 1;
1010 if (strlcpy(a->last_scaled_size, scaled_size,
1011 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1012 return got_error(GOT_ERR_NO_SPACE);
1014 if (nobj_indexed > 0) {
1015 p_indexed = (nobj_indexed * 100) / nobj_total;
1016 if (p_indexed != a->last_p_indexed) {
1017 a->last_p_indexed = p_indexed;
1018 print_indexed = 1;
1019 print_size = 1;
1022 if (nobj_resolved > 0) {
1023 p_resolved = (nobj_resolved * 100) /
1024 (nobj_total - nobj_loose);
1025 if (p_resolved != a->last_p_resolved) {
1026 a->last_p_resolved = p_resolved;
1027 print_resolved = 1;
1028 print_indexed = 1;
1029 print_size = 1;
1034 if (print_size || print_indexed || print_resolved)
1035 printf("\r");
1036 if (print_size)
1037 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1038 if (print_indexed)
1039 printf("; indexing %d%%", p_indexed);
1040 if (print_resolved)
1041 printf("; resolving deltas %d%%", p_resolved);
1042 if (print_size || print_indexed || print_resolved)
1043 fflush(stdout);
1045 return NULL;
1048 static const struct got_error *
1049 create_symref(const char *refname, struct got_reference *target_ref,
1050 int verbosity, struct got_repository *repo)
1052 const struct got_error *err;
1053 struct got_reference *head_symref;
1055 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1056 if (err)
1057 return err;
1059 err = got_ref_write(head_symref, repo);
1060 if (err == NULL && verbosity > 0) {
1061 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1062 got_ref_get_name(target_ref));
1064 got_ref_close(head_symref);
1065 return err;
1068 static const struct got_error *
1069 list_remote_refs(struct got_pathlist_head *symrefs,
1070 struct got_pathlist_head *refs)
1072 const struct got_error *err;
1073 struct got_pathlist_entry *pe;
1075 TAILQ_FOREACH(pe, symrefs, entry) {
1076 const char *refname = pe->path;
1077 const char *targetref = pe->data;
1079 printf("%s: %s\n", refname, targetref);
1082 TAILQ_FOREACH(pe, refs, entry) {
1083 const char *refname = pe->path;
1084 struct got_object_id *id = pe->data;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1090 printf("%s: %s\n", refname, id_str);
1091 free(id_str);
1094 return NULL;
1097 static const struct got_error *
1098 create_ref(const char *refname, struct got_object_id *id,
1099 int verbosity, struct got_repository *repo)
1101 const struct got_error *err = NULL;
1102 struct got_reference *ref;
1103 char *id_str;
1105 err = got_object_id_str(&id_str, id);
1106 if (err)
1107 return err;
1109 err = got_ref_alloc(&ref, refname, id);
1110 if (err)
1111 goto done;
1113 err = got_ref_write(ref, repo);
1114 got_ref_close(ref);
1116 if (err == NULL && verbosity >= 0)
1117 printf("Created reference %s: %s\n", refname, id_str);
1118 done:
1119 free(id_str);
1120 return err;
1123 static int
1124 match_wanted_ref(const char *refname, const char *wanted_ref)
1126 if (strncmp(refname, "refs/", 5) != 0)
1127 return 0;
1128 refname += 5;
1131 * Prevent fetching of references that won't make any
1132 * sense outside of the remote repository's context.
1134 if (strncmp(refname, "got/", 4) == 0)
1135 return 0;
1136 if (strncmp(refname, "remotes/", 8) == 0)
1137 return 0;
1139 if (strncmp(wanted_ref, "refs/", 5) == 0)
1140 wanted_ref += 5;
1142 /* Allow prefix match. */
1143 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1144 return 1;
1146 /* Allow exact match. */
1147 return (strcmp(refname, wanted_ref) == 0);
1150 static int
1151 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1153 struct got_pathlist_entry *pe;
1155 TAILQ_FOREACH(pe, wanted_refs, entry) {
1156 if (match_wanted_ref(refname, pe->path))
1157 return 1;
1160 return 0;
1163 static const struct got_error *
1164 create_wanted_ref(const char *refname, struct got_object_id *id,
1165 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1167 const struct got_error *err;
1168 char *remote_refname;
1170 if (strncmp("refs/", refname, 5) == 0)
1171 refname += 5;
1173 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1174 remote_repo_name, refname) == -1)
1175 return got_error_from_errno("asprintf");
1177 err = create_ref(remote_refname, id, verbosity, repo);
1178 free(remote_refname);
1179 return err;
1182 static const struct got_error *
1183 create_gotconfig(const char *proto, const char *host, const char *port,
1184 const char *remote_repo_path, const char *default_branch,
1185 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1186 struct got_pathlist_head *wanted_refs, int mirror_references,
1187 struct got_repository *repo)
1189 const struct got_error *err = NULL;
1190 char *gotconfig_path = NULL;
1191 char *gotconfig = NULL;
1192 FILE *gotconfig_file = NULL;
1193 const char *branchname = NULL;
1194 char *branches = NULL, *refs = NULL;
1195 ssize_t n;
1197 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1198 struct got_pathlist_entry *pe;
1199 TAILQ_FOREACH(pe, wanted_branches, entry) {
1200 char *s;
1201 branchname = pe->path;
1202 if (strncmp(branchname, "refs/heads/", 11) == 0)
1203 branchname += 11;
1204 if (asprintf(&s, "%s\"%s\" ",
1205 branches ? branches : "", branchname) == -1) {
1206 err = got_error_from_errno("asprintf");
1207 goto done;
1209 free(branches);
1210 branches = s;
1212 } else if (!fetch_all_branches && default_branch) {
1213 branchname = default_branch;
1214 if (strncmp(branchname, "refs/heads/", 11) == 0)
1215 branchname += 11;
1216 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1217 err = got_error_from_errno("asprintf");
1218 goto done;
1221 if (!TAILQ_EMPTY(wanted_refs)) {
1222 struct got_pathlist_entry *pe;
1223 TAILQ_FOREACH(pe, wanted_refs, entry) {
1224 char *s;
1225 const char *refname = pe->path;
1226 if (strncmp(refname, "refs/", 5) == 0)
1227 branchname += 5;
1228 if (asprintf(&s, "%s\"%s\" ",
1229 refs ? refs : "", refname) == -1) {
1230 err = got_error_from_errno("asprintf");
1231 goto done;
1233 free(refs);
1234 refs = s;
1238 /* Create got.conf(5). */
1239 gotconfig_path = got_repo_get_path_gotconfig(repo);
1240 if (gotconfig_path == NULL) {
1241 err = got_error_from_errno("got_repo_get_path_gotconfig");
1242 goto done;
1244 gotconfig_file = fopen(gotconfig_path, "ae");
1245 if (gotconfig_file == NULL) {
1246 err = got_error_from_errno2("fopen", gotconfig_path);
1247 goto done;
1249 if (asprintf(&gotconfig,
1250 "remote \"%s\" {\n"
1251 "\tserver %s\n"
1252 "\tprotocol %s\n"
1253 "%s%s%s"
1254 "\trepository \"%s\"\n"
1255 "%s%s%s"
1256 "%s%s%s"
1257 "%s"
1258 "%s"
1259 "}\n",
1260 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1261 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1262 remote_repo_path, branches ? "\tbranch { " : "",
1263 branches ? branches : "", branches ? "}\n" : "",
1264 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1265 mirror_references ? "\tmirror-references yes\n" : "",
1266 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1270 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1271 if (n != strlen(gotconfig)) {
1272 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1273 goto done;
1276 done:
1277 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1278 err = got_error_from_errno2("fclose", gotconfig_path);
1279 free(gotconfig_path);
1280 free(branches);
1281 return err;
1284 static const struct got_error *
1285 create_gitconfig(const char *git_url, const char *default_branch,
1286 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1287 struct got_pathlist_head *wanted_refs, int mirror_references,
1288 struct got_repository *repo)
1290 const struct got_error *err = NULL;
1291 char *gitconfig_path = NULL;
1292 char *gitconfig = NULL;
1293 FILE *gitconfig_file = NULL;
1294 char *branches = NULL, *refs = NULL;
1295 const char *branchname;
1296 ssize_t n;
1298 /* Create a config file Git can understand. */
1299 gitconfig_path = got_repo_get_path_gitconfig(repo);
1300 if (gitconfig_path == NULL) {
1301 err = got_error_from_errno("got_repo_get_path_gitconfig");
1302 goto done;
1304 gitconfig_file = fopen(gitconfig_path, "ae");
1305 if (gitconfig_file == NULL) {
1306 err = got_error_from_errno2("fopen", gitconfig_path);
1307 goto done;
1309 if (fetch_all_branches) {
1310 if (mirror_references) {
1311 if (asprintf(&branches,
1312 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1313 err = got_error_from_errno("asprintf");
1314 goto done;
1316 } else if (asprintf(&branches,
1317 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1318 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1319 err = got_error_from_errno("asprintf");
1320 goto done;
1322 } else if (!TAILQ_EMPTY(wanted_branches)) {
1323 struct got_pathlist_entry *pe;
1324 TAILQ_FOREACH(pe, wanted_branches, entry) {
1325 char *s;
1326 branchname = pe->path;
1327 if (strncmp(branchname, "refs/heads/", 11) == 0)
1328 branchname += 11;
1329 if (mirror_references) {
1330 if (asprintf(&s,
1331 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1332 branches ? branches : "",
1333 branchname, branchname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 } else if (asprintf(&s,
1338 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1339 branches ? branches : "",
1340 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1341 branchname) == -1) {
1342 err = got_error_from_errno("asprintf");
1343 goto done;
1345 free(branches);
1346 branches = s;
1348 } else {
1350 * If the server specified a default branch, use just that one.
1351 * Otherwise fall back to fetching all branches on next fetch.
1353 if (default_branch) {
1354 branchname = default_branch;
1355 if (strncmp(branchname, "refs/heads/", 11) == 0)
1356 branchname += 11;
1357 } else
1358 branchname = "*"; /* fall back to all branches */
1359 if (mirror_references) {
1360 if (asprintf(&branches,
1361 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1362 branchname, branchname) == -1) {
1363 err = got_error_from_errno("asprintf");
1364 goto done;
1366 } else if (asprintf(&branches,
1367 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1368 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1369 branchname) == -1) {
1370 err = got_error_from_errno("asprintf");
1371 goto done;
1374 if (!TAILQ_EMPTY(wanted_refs)) {
1375 struct got_pathlist_entry *pe;
1376 TAILQ_FOREACH(pe, wanted_refs, entry) {
1377 char *s;
1378 const char *refname = pe->path;
1379 if (strncmp(refname, "refs/", 5) == 0)
1380 refname += 5;
1381 if (mirror_references) {
1382 if (asprintf(&s,
1383 "%s\tfetch = refs/%s:refs/%s\n",
1384 refs ? refs : "", refname, refname) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&s,
1389 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1390 refs ? refs : "",
1391 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1392 refname) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 free(refs);
1397 refs = s;
1401 if (asprintf(&gitconfig,
1402 "[remote \"%s\"]\n"
1403 "\turl = %s\n"
1404 "%s"
1405 "%s"
1406 "\tfetch = refs/tags/*:refs/tags/*\n",
1407 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1408 refs ? refs : "") == -1) {
1409 err = got_error_from_errno("asprintf");
1410 goto done;
1412 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1413 if (n != strlen(gitconfig)) {
1414 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1415 goto done;
1417 done:
1418 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1419 err = got_error_from_errno2("fclose", gitconfig_path);
1420 free(gitconfig_path);
1421 free(branches);
1422 return err;
1425 static const struct got_error *
1426 create_config_files(const char *proto, const char *host, const char *port,
1427 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1428 int mirror_references, struct got_pathlist_head *symrefs,
1429 struct got_pathlist_head *wanted_branches,
1430 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1432 const struct got_error *err = NULL;
1433 const char *default_branch = NULL;
1434 struct got_pathlist_entry *pe;
1437 * If we asked for a set of wanted branches then use the first
1438 * one of those.
1440 if (!TAILQ_EMPTY(wanted_branches)) {
1441 pe = TAILQ_FIRST(wanted_branches);
1442 default_branch = pe->path;
1443 } else {
1444 /* First HEAD ref listed by server is the default branch. */
1445 TAILQ_FOREACH(pe, symrefs, entry) {
1446 const char *refname = pe->path;
1447 const char *target = pe->data;
1449 if (strcmp(refname, GOT_REF_HEAD) != 0)
1450 continue;
1452 default_branch = target;
1453 break;
1457 /* Create got.conf(5). */
1458 err = create_gotconfig(proto, host, port, remote_repo_path,
1459 default_branch, fetch_all_branches, wanted_branches,
1460 wanted_refs, mirror_references, repo);
1461 if (err)
1462 return err;
1464 /* Create a config file Git can understand. */
1465 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1466 wanted_branches, wanted_refs, mirror_references, repo);
1469 static const struct got_error *
1470 cmd_clone(int argc, char *argv[])
1472 const struct got_error *error = NULL;
1473 const char *uri, *dirname;
1474 char *proto, *host, *port, *repo_name, *server_path;
1475 char *default_destdir = NULL, *id_str = NULL;
1476 const char *repo_path;
1477 struct got_repository *repo = NULL;
1478 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1479 struct got_pathlist_entry *pe;
1480 struct got_object_id *pack_hash = NULL;
1481 int ch, fetchfd = -1, fetchstatus;
1482 pid_t fetchpid = -1;
1483 struct got_fetch_progress_arg fpa;
1484 char *git_url = NULL;
1485 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1486 int list_refs_only = 0;
1488 TAILQ_INIT(&refs);
1489 TAILQ_INIT(&symrefs);
1490 TAILQ_INIT(&wanted_branches);
1491 TAILQ_INIT(&wanted_refs);
1493 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1494 switch (ch) {
1495 case 'a':
1496 fetch_all_branches = 1;
1497 break;
1498 case 'b':
1499 error = got_pathlist_append(&wanted_branches,
1500 optarg, NULL);
1501 if (error)
1502 return error;
1503 break;
1504 case 'l':
1505 list_refs_only = 1;
1506 break;
1507 case 'm':
1508 mirror_references = 1;
1509 break;
1510 case 'v':
1511 if (verbosity < 0)
1512 verbosity = 0;
1513 else if (verbosity < 3)
1514 verbosity++;
1515 break;
1516 case 'q':
1517 verbosity = -1;
1518 break;
1519 case 'R':
1520 error = got_pathlist_append(&wanted_refs,
1521 optarg, NULL);
1522 if (error)
1523 return error;
1524 break;
1525 default:
1526 usage_clone();
1527 break;
1530 argc -= optind;
1531 argv += optind;
1533 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1534 option_conflict('a', 'b');
1535 if (list_refs_only) {
1536 if (!TAILQ_EMPTY(&wanted_branches))
1537 option_conflict('l', 'b');
1538 if (fetch_all_branches)
1539 option_conflict('l', 'a');
1540 if (mirror_references)
1541 option_conflict('l', 'm');
1542 if (!TAILQ_EMPTY(&wanted_refs))
1543 option_conflict('l', 'R');
1546 uri = argv[0];
1548 if (argc == 1)
1549 dirname = NULL;
1550 else if (argc == 2)
1551 dirname = argv[1];
1552 else
1553 usage_clone();
1555 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1556 &repo_name, uri);
1557 if (error)
1558 goto done;
1560 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1561 host, port ? ":" : "", port ? port : "",
1562 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1563 error = got_error_from_errno("asprintf");
1564 goto done;
1567 if (strcmp(proto, "git") == 0) {
1568 #ifndef PROFILE
1569 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1570 "sendfd dns inet unveil", NULL) == -1)
1571 err(1, "pledge");
1572 #endif
1573 } else if (strcmp(proto, "git+ssh") == 0 ||
1574 strcmp(proto, "ssh") == 0) {
1575 #ifndef PROFILE
1576 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1577 "sendfd unveil", NULL) == -1)
1578 err(1, "pledge");
1579 #endif
1580 } else if (strcmp(proto, "http") == 0 ||
1581 strcmp(proto, "git+http") == 0) {
1582 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1583 goto done;
1584 } else {
1585 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1586 goto done;
1588 if (dirname == NULL) {
1589 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1590 error = got_error_from_errno("asprintf");
1591 goto done;
1593 repo_path = default_destdir;
1594 } else
1595 repo_path = dirname;
1597 if (!list_refs_only) {
1598 error = got_path_mkdir(repo_path);
1599 if (error &&
1600 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1601 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1602 goto done;
1603 if (!got_path_dir_is_empty(repo_path)) {
1604 error = got_error_path(repo_path,
1605 GOT_ERR_DIR_NOT_EMPTY);
1606 goto done;
1610 error = got_dial_apply_unveil(proto);
1611 if (error)
1612 goto done;
1614 error = apply_unveil(repo_path, 0, NULL);
1615 if (error)
1616 goto done;
1618 if (verbosity >= 0)
1619 printf("Connecting to %s%s%s\n", host,
1620 port ? ":" : "", port ? port : "");
1622 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1623 server_path, verbosity);
1624 if (error)
1625 goto done;
1627 if (!list_refs_only) {
1628 error = got_repo_init(repo_path);
1629 if (error)
1630 goto done;
1631 error = got_repo_open(&repo, repo_path, NULL);
1632 if (error)
1633 goto done;
1636 fpa.last_scaled_size[0] = '\0';
1637 fpa.last_p_indexed = -1;
1638 fpa.last_p_resolved = -1;
1639 fpa.verbosity = verbosity;
1640 fpa.create_configs = 1;
1641 fpa.configs_created = 0;
1642 fpa.repo = repo;
1643 fpa.config_info.symrefs = &symrefs;
1644 fpa.config_info.wanted_branches = &wanted_branches;
1645 fpa.config_info.wanted_refs = &wanted_refs;
1646 fpa.config_info.proto = proto;
1647 fpa.config_info.host = host;
1648 fpa.config_info.port = port;
1649 fpa.config_info.remote_repo_path = server_path;
1650 fpa.config_info.git_url = git_url;
1651 fpa.config_info.fetch_all_branches = fetch_all_branches;
1652 fpa.config_info.mirror_references = mirror_references;
1653 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1654 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1655 fetch_all_branches, &wanted_branches, &wanted_refs,
1656 list_refs_only, verbosity, fetchfd, repo,
1657 fetch_progress, &fpa);
1658 if (error)
1659 goto done;
1661 if (list_refs_only) {
1662 error = list_remote_refs(&symrefs, &refs);
1663 goto done;
1666 if (pack_hash == NULL) {
1667 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1668 "server sent an empty pack file");
1669 goto done;
1671 error = got_object_id_str(&id_str, pack_hash);
1672 if (error)
1673 goto done;
1674 if (verbosity >= 0)
1675 printf("\nFetched %s.pack\n", id_str);
1676 free(id_str);
1678 /* Set up references provided with the pack file. */
1679 TAILQ_FOREACH(pe, &refs, entry) {
1680 const char *refname = pe->path;
1681 struct got_object_id *id = pe->data;
1682 char *remote_refname;
1684 if (is_wanted_ref(&wanted_refs, refname) &&
1685 !mirror_references) {
1686 error = create_wanted_ref(refname, id,
1687 GOT_FETCH_DEFAULT_REMOTE_NAME,
1688 verbosity - 1, repo);
1689 if (error)
1690 goto done;
1691 continue;
1694 error = create_ref(refname, id, verbosity - 1, repo);
1695 if (error)
1696 goto done;
1698 if (mirror_references)
1699 continue;
1701 if (strncmp("refs/heads/", refname, 11) != 0)
1702 continue;
1704 if (asprintf(&remote_refname,
1705 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1706 refname + 11) == -1) {
1707 error = got_error_from_errno("asprintf");
1708 goto done;
1710 error = create_ref(remote_refname, id, verbosity - 1, repo);
1711 free(remote_refname);
1712 if (error)
1713 goto done;
1716 /* Set the HEAD reference if the server provided one. */
1717 TAILQ_FOREACH(pe, &symrefs, entry) {
1718 struct got_reference *target_ref;
1719 const char *refname = pe->path;
1720 const char *target = pe->data;
1721 char *remote_refname = NULL, *remote_target = NULL;
1723 if (strcmp(refname, GOT_REF_HEAD) != 0)
1724 continue;
1726 error = got_ref_open(&target_ref, repo, target, 0);
1727 if (error) {
1728 if (error->code == GOT_ERR_NOT_REF) {
1729 error = NULL;
1730 continue;
1732 goto done;
1735 error = create_symref(refname, target_ref, verbosity, repo);
1736 got_ref_close(target_ref);
1737 if (error)
1738 goto done;
1740 if (mirror_references)
1741 continue;
1743 if (strncmp("refs/heads/", target, 11) != 0)
1744 continue;
1746 if (asprintf(&remote_refname,
1747 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1748 refname) == -1) {
1749 error = got_error_from_errno("asprintf");
1750 goto done;
1752 if (asprintf(&remote_target,
1753 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1754 target + 11) == -1) {
1755 error = got_error_from_errno("asprintf");
1756 free(remote_refname);
1757 goto done;
1759 error = got_ref_open(&target_ref, repo, remote_target, 0);
1760 if (error) {
1761 free(remote_refname);
1762 free(remote_target);
1763 if (error->code == GOT_ERR_NOT_REF) {
1764 error = NULL;
1765 continue;
1767 goto done;
1769 error = create_symref(remote_refname, target_ref,
1770 verbosity - 1, repo);
1771 free(remote_refname);
1772 free(remote_target);
1773 got_ref_close(target_ref);
1774 if (error)
1775 goto done;
1777 if (pe == NULL) {
1779 * We failed to set the HEAD reference. If we asked for
1780 * a set of wanted branches use the first of one of those
1781 * which could be fetched instead.
1783 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1784 const char *target = pe->path;
1785 struct got_reference *target_ref;
1787 error = got_ref_open(&target_ref, repo, target, 0);
1788 if (error) {
1789 if (error->code == GOT_ERR_NOT_REF) {
1790 error = NULL;
1791 continue;
1793 goto done;
1796 error = create_symref(GOT_REF_HEAD, target_ref,
1797 verbosity, repo);
1798 got_ref_close(target_ref);
1799 if (error)
1800 goto done;
1801 break;
1805 if (verbosity >= 0)
1806 printf("Created %s repository '%s'\n",
1807 mirror_references ? "mirrored" : "cloned", repo_path);
1808 done:
1809 if (fetchpid > 0) {
1810 if (kill(fetchpid, SIGTERM) == -1)
1811 error = got_error_from_errno("kill");
1812 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1813 error = got_error_from_errno("waitpid");
1815 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1816 error = got_error_from_errno("close");
1817 if (repo) {
1818 const struct got_error *close_err = got_repo_close(repo);
1819 if (error == NULL)
1820 error = close_err;
1822 TAILQ_FOREACH(pe, &refs, entry) {
1823 free((void *)pe->path);
1824 free(pe->data);
1826 got_pathlist_free(&refs);
1827 TAILQ_FOREACH(pe, &symrefs, entry) {
1828 free((void *)pe->path);
1829 free(pe->data);
1831 got_pathlist_free(&symrefs);
1832 got_pathlist_free(&wanted_branches);
1833 got_pathlist_free(&wanted_refs);
1834 free(pack_hash);
1835 free(proto);
1836 free(host);
1837 free(port);
1838 free(server_path);
1839 free(repo_name);
1840 free(default_destdir);
1841 free(git_url);
1842 return error;
1845 static const struct got_error *
1846 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1847 int replace_tags, int verbosity, struct got_repository *repo)
1849 const struct got_error *err = NULL;
1850 char *new_id_str = NULL;
1851 struct got_object_id *old_id = NULL;
1853 err = got_object_id_str(&new_id_str, new_id);
1854 if (err)
1855 goto done;
1857 if (!replace_tags &&
1858 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1859 err = got_ref_resolve(&old_id, repo, ref);
1860 if (err)
1861 goto done;
1862 if (got_object_id_cmp(old_id, new_id) == 0)
1863 goto done;
1864 if (verbosity >= 0) {
1865 printf("Rejecting update of existing tag %s: %s\n",
1866 got_ref_get_name(ref), new_id_str);
1868 goto done;
1871 if (got_ref_is_symbolic(ref)) {
1872 if (verbosity >= 0) {
1873 printf("Replacing reference %s: %s\n",
1874 got_ref_get_name(ref),
1875 got_ref_get_symref_target(ref));
1877 err = got_ref_change_symref_to_ref(ref, new_id);
1878 if (err)
1879 goto done;
1880 err = got_ref_write(ref, repo);
1881 if (err)
1882 goto done;
1883 } else {
1884 err = got_ref_resolve(&old_id, repo, ref);
1885 if (err)
1886 goto done;
1887 if (got_object_id_cmp(old_id, new_id) == 0)
1888 goto done;
1890 err = got_ref_change_ref(ref, new_id);
1891 if (err)
1892 goto done;
1893 err = got_ref_write(ref, repo);
1894 if (err)
1895 goto done;
1898 if (verbosity >= 0)
1899 printf("Updated %s: %s\n", got_ref_get_name(ref),
1900 new_id_str);
1901 done:
1902 free(old_id);
1903 free(new_id_str);
1904 return err;
1907 static const struct got_error *
1908 update_symref(const char *refname, struct got_reference *target_ref,
1909 int verbosity, struct got_repository *repo)
1911 const struct got_error *err = NULL, *unlock_err;
1912 struct got_reference *symref;
1913 int symref_is_locked = 0;
1915 err = got_ref_open(&symref, repo, refname, 1);
1916 if (err) {
1917 if (err->code != GOT_ERR_NOT_REF)
1918 return err;
1919 err = got_ref_alloc_symref(&symref, refname, target_ref);
1920 if (err)
1921 goto done;
1923 err = got_ref_write(symref, repo);
1924 if (err)
1925 goto done;
1927 if (verbosity >= 0)
1928 printf("Created reference %s: %s\n",
1929 got_ref_get_name(symref),
1930 got_ref_get_symref_target(symref));
1931 } else {
1932 symref_is_locked = 1;
1934 if (strcmp(got_ref_get_symref_target(symref),
1935 got_ref_get_name(target_ref)) == 0)
1936 goto done;
1938 err = got_ref_change_symref(symref,
1939 got_ref_get_name(target_ref));
1940 if (err)
1941 goto done;
1943 err = got_ref_write(symref, repo);
1944 if (err)
1945 goto done;
1947 if (verbosity >= 0)
1948 printf("Updated %s: %s\n", got_ref_get_name(symref),
1949 got_ref_get_symref_target(symref));
1952 done:
1953 if (symref_is_locked) {
1954 unlock_err = got_ref_unlock(symref);
1955 if (unlock_err && err == NULL)
1956 err = unlock_err;
1958 got_ref_close(symref);
1959 return err;
1962 __dead static void
1963 usage_fetch(void)
1965 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1966 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1967 "[remote-repository-name]\n",
1968 getprogname());
1969 exit(1);
1972 static const struct got_error *
1973 delete_missing_ref(struct got_reference *ref,
1974 int verbosity, struct got_repository *repo)
1976 const struct got_error *err = NULL;
1977 struct got_object_id *id = NULL;
1978 char *id_str = NULL;
1980 if (got_ref_is_symbolic(ref)) {
1981 err = got_ref_delete(ref, repo);
1982 if (err)
1983 return err;
1984 if (verbosity >= 0) {
1985 printf("Deleted %s: %s\n",
1986 got_ref_get_name(ref),
1987 got_ref_get_symref_target(ref));
1989 } else {
1990 err = got_ref_resolve(&id, repo, ref);
1991 if (err)
1992 return err;
1993 err = got_object_id_str(&id_str, id);
1994 if (err)
1995 goto done;
1997 err = got_ref_delete(ref, repo);
1998 if (err)
1999 goto done;
2000 if (verbosity >= 0) {
2001 printf("Deleted %s: %s\n",
2002 got_ref_get_name(ref), id_str);
2005 done:
2006 free(id);
2007 free(id_str);
2008 return NULL;
2011 static const struct got_error *
2012 delete_missing_refs(struct got_pathlist_head *their_refs,
2013 struct got_pathlist_head *their_symrefs,
2014 const struct got_remote_repo *remote,
2015 int verbosity, struct got_repository *repo)
2017 const struct got_error *err = NULL, *unlock_err;
2018 struct got_reflist_head my_refs;
2019 struct got_reflist_entry *re;
2020 struct got_pathlist_entry *pe;
2021 char *remote_namespace = NULL;
2022 char *local_refname = NULL;
2024 TAILQ_INIT(&my_refs);
2026 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2027 == -1)
2028 return got_error_from_errno("asprintf");
2030 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2031 if (err)
2032 goto done;
2034 TAILQ_FOREACH(re, &my_refs, entry) {
2035 const char *refname = got_ref_get_name(re->ref);
2036 const char *their_refname;
2038 if (remote->mirror_references) {
2039 their_refname = refname;
2040 } else {
2041 if (strncmp(refname, remote_namespace,
2042 strlen(remote_namespace)) == 0) {
2043 if (strcmp(refname + strlen(remote_namespace),
2044 GOT_REF_HEAD) == 0)
2045 continue;
2046 if (asprintf(&local_refname, "refs/heads/%s",
2047 refname + strlen(remote_namespace)) == -1) {
2048 err = got_error_from_errno("asprintf");
2049 goto done;
2051 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2052 continue;
2054 their_refname = local_refname;
2057 TAILQ_FOREACH(pe, their_refs, entry) {
2058 if (strcmp(their_refname, pe->path) == 0)
2059 break;
2061 if (pe != NULL)
2062 continue;
2064 TAILQ_FOREACH(pe, their_symrefs, entry) {
2065 if (strcmp(their_refname, pe->path) == 0)
2066 break;
2068 if (pe != NULL)
2069 continue;
2071 err = delete_missing_ref(re->ref, verbosity, repo);
2072 if (err)
2073 break;
2075 if (local_refname) {
2076 struct got_reference *ref;
2077 err = got_ref_open(&ref, repo, local_refname, 1);
2078 if (err) {
2079 if (err->code != GOT_ERR_NOT_REF)
2080 break;
2081 free(local_refname);
2082 local_refname = NULL;
2083 continue;
2085 err = delete_missing_ref(ref, verbosity, repo);
2086 if (err)
2087 break;
2088 unlock_err = got_ref_unlock(ref);
2089 got_ref_close(ref);
2090 if (unlock_err && err == NULL) {
2091 err = unlock_err;
2092 break;
2095 free(local_refname);
2096 local_refname = NULL;
2099 done:
2100 free(remote_namespace);
2101 free(local_refname);
2102 return err;
2105 static const struct got_error *
2106 update_wanted_ref(const char *refname, struct got_object_id *id,
2107 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2109 const struct got_error *err, *unlock_err;
2110 char *remote_refname;
2111 struct got_reference *ref;
2113 if (strncmp("refs/", refname, 5) == 0)
2114 refname += 5;
2116 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2117 remote_repo_name, refname) == -1)
2118 return got_error_from_errno("asprintf");
2120 err = got_ref_open(&ref, repo, remote_refname, 1);
2121 if (err) {
2122 if (err->code != GOT_ERR_NOT_REF)
2123 goto done;
2124 err = create_ref(remote_refname, id, verbosity, repo);
2125 } else {
2126 err = update_ref(ref, id, 0, verbosity, repo);
2127 unlock_err = got_ref_unlock(ref);
2128 if (unlock_err && err == NULL)
2129 err = unlock_err;
2130 got_ref_close(ref);
2132 done:
2133 free(remote_refname);
2134 return err;
2137 static const struct got_error *
2138 delete_ref(struct got_repository *repo, struct got_reference *ref)
2140 const struct got_error *err = NULL;
2141 struct got_object_id *id = NULL;
2142 char *id_str = NULL;
2143 const char *target;
2145 if (got_ref_is_symbolic(ref)) {
2146 target = got_ref_get_symref_target(ref);
2147 } else {
2148 err = got_ref_resolve(&id, repo, ref);
2149 if (err)
2150 goto done;
2151 err = got_object_id_str(&id_str, id);
2152 if (err)
2153 goto done;
2154 target = id_str;
2157 err = got_ref_delete(ref, repo);
2158 if (err)
2159 goto done;
2161 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2162 done:
2163 free(id);
2164 free(id_str);
2165 return err;
2168 static const struct got_error *
2169 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2171 const struct got_error *err = NULL;
2172 struct got_reflist_head refs;
2173 struct got_reflist_entry *re;
2174 char *prefix;
2176 TAILQ_INIT(&refs);
2178 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2179 err = got_error_from_errno("asprintf");
2180 goto done;
2182 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2183 if (err)
2184 goto done;
2186 TAILQ_FOREACH(re, &refs, entry)
2187 delete_ref(repo, re->ref);
2188 done:
2189 got_ref_list_free(&refs);
2190 return err;
2193 static const struct got_error *
2194 cmd_fetch(int argc, char *argv[])
2196 const struct got_error *error = NULL, *unlock_err;
2197 char *cwd = NULL, *repo_path = NULL;
2198 const char *remote_name;
2199 char *proto = NULL, *host = NULL, *port = NULL;
2200 char *repo_name = NULL, *server_path = NULL;
2201 const struct got_remote_repo *remotes, *remote = NULL;
2202 int nremotes;
2203 char *id_str = NULL;
2204 struct got_repository *repo = NULL;
2205 struct got_worktree *worktree = NULL;
2206 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2207 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2208 struct got_pathlist_entry *pe;
2209 struct got_object_id *pack_hash = NULL;
2210 int i, ch, fetchfd = -1, fetchstatus;
2211 pid_t fetchpid = -1;
2212 struct got_fetch_progress_arg fpa;
2213 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2214 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2216 TAILQ_INIT(&refs);
2217 TAILQ_INIT(&symrefs);
2218 TAILQ_INIT(&wanted_branches);
2219 TAILQ_INIT(&wanted_refs);
2221 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2222 switch (ch) {
2223 case 'a':
2224 fetch_all_branches = 1;
2225 break;
2226 case 'b':
2227 error = got_pathlist_append(&wanted_branches,
2228 optarg, NULL);
2229 if (error)
2230 return error;
2231 break;
2232 case 'd':
2233 delete_refs = 1;
2234 break;
2235 case 'l':
2236 list_refs_only = 1;
2237 break;
2238 case 'r':
2239 repo_path = realpath(optarg, NULL);
2240 if (repo_path == NULL)
2241 return got_error_from_errno2("realpath",
2242 optarg);
2243 got_path_strip_trailing_slashes(repo_path);
2244 break;
2245 case 't':
2246 replace_tags = 1;
2247 break;
2248 case 'v':
2249 if (verbosity < 0)
2250 verbosity = 0;
2251 else if (verbosity < 3)
2252 verbosity++;
2253 break;
2254 case 'q':
2255 verbosity = -1;
2256 break;
2257 case 'R':
2258 error = got_pathlist_append(&wanted_refs,
2259 optarg, NULL);
2260 if (error)
2261 return error;
2262 break;
2263 case 'X':
2264 delete_remote = 1;
2265 break;
2266 default:
2267 usage_fetch();
2268 break;
2271 argc -= optind;
2272 argv += optind;
2274 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2275 option_conflict('a', 'b');
2276 if (list_refs_only) {
2277 if (!TAILQ_EMPTY(&wanted_branches))
2278 option_conflict('l', 'b');
2279 if (fetch_all_branches)
2280 option_conflict('l', 'a');
2281 if (delete_refs)
2282 option_conflict('l', 'd');
2283 if (delete_remote)
2284 option_conflict('l', 'X');
2286 if (delete_remote) {
2287 if (fetch_all_branches)
2288 option_conflict('X', 'a');
2289 if (!TAILQ_EMPTY(&wanted_branches))
2290 option_conflict('X', 'b');
2291 if (delete_refs)
2292 option_conflict('X', 'd');
2293 if (replace_tags)
2294 option_conflict('X', 't');
2295 if (!TAILQ_EMPTY(&wanted_refs))
2296 option_conflict('X', 'R');
2299 if (argc == 0) {
2300 if (delete_remote)
2301 errx(1, "-X option requires a remote name");
2302 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2303 } else if (argc == 1)
2304 remote_name = argv[0];
2305 else
2306 usage_fetch();
2308 cwd = getcwd(NULL, 0);
2309 if (cwd == NULL) {
2310 error = got_error_from_errno("getcwd");
2311 goto done;
2314 if (repo_path == NULL) {
2315 error = got_worktree_open(&worktree, cwd);
2316 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2317 goto done;
2318 else
2319 error = NULL;
2320 if (worktree) {
2321 repo_path =
2322 strdup(got_worktree_get_repo_path(worktree));
2323 if (repo_path == NULL)
2324 error = got_error_from_errno("strdup");
2325 if (error)
2326 goto done;
2327 } else {
2328 repo_path = strdup(cwd);
2329 if (repo_path == NULL) {
2330 error = got_error_from_errno("strdup");
2331 goto done;
2336 error = got_repo_open(&repo, repo_path, NULL);
2337 if (error)
2338 goto done;
2340 if (delete_remote) {
2341 error = delete_refs_for_remote(repo, remote_name);
2342 goto done; /* nothing else to do */
2345 if (worktree) {
2346 worktree_conf = got_worktree_get_gotconfig(worktree);
2347 if (worktree_conf) {
2348 got_gotconfig_get_remotes(&nremotes, &remotes,
2349 worktree_conf);
2350 for (i = 0; i < nremotes; i++) {
2351 if (strcmp(remotes[i].name, remote_name) == 0) {
2352 remote = &remotes[i];
2353 break;
2358 if (remote == NULL) {
2359 repo_conf = got_repo_get_gotconfig(repo);
2360 if (repo_conf) {
2361 got_gotconfig_get_remotes(&nremotes, &remotes,
2362 repo_conf);
2363 for (i = 0; i < nremotes; i++) {
2364 if (strcmp(remotes[i].name, remote_name) == 0) {
2365 remote = &remotes[i];
2366 break;
2371 if (remote == NULL) {
2372 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2373 for (i = 0; i < nremotes; i++) {
2374 if (strcmp(remotes[i].name, remote_name) == 0) {
2375 remote = &remotes[i];
2376 break;
2380 if (remote == NULL) {
2381 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2382 goto done;
2385 if (TAILQ_EMPTY(&wanted_branches)) {
2386 if (!fetch_all_branches)
2387 fetch_all_branches = remote->fetch_all_branches;
2388 for (i = 0; i < remote->nfetch_branches; i++) {
2389 got_pathlist_append(&wanted_branches,
2390 remote->fetch_branches[i], NULL);
2393 if (TAILQ_EMPTY(&wanted_refs)) {
2394 for (i = 0; i < remote->nfetch_refs; i++) {
2395 got_pathlist_append(&wanted_refs,
2396 remote->fetch_refs[i], NULL);
2400 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2401 &repo_name, remote->fetch_url);
2402 if (error)
2403 goto done;
2405 if (strcmp(proto, "git") == 0) {
2406 #ifndef PROFILE
2407 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2408 "sendfd dns inet unveil", NULL) == -1)
2409 err(1, "pledge");
2410 #endif
2411 } else if (strcmp(proto, "git+ssh") == 0 ||
2412 strcmp(proto, "ssh") == 0) {
2413 #ifndef PROFILE
2414 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2415 "sendfd unveil", NULL) == -1)
2416 err(1, "pledge");
2417 #endif
2418 } else if (strcmp(proto, "http") == 0 ||
2419 strcmp(proto, "git+http") == 0) {
2420 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2421 goto done;
2422 } else {
2423 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2424 goto done;
2427 error = got_dial_apply_unveil(proto);
2428 if (error)
2429 goto done;
2431 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2432 if (error)
2433 goto done;
2435 if (verbosity >= 0)
2436 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2437 port ? ":" : "", port ? port : "");
2439 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2440 server_path, verbosity);
2441 if (error)
2442 goto done;
2444 fpa.last_scaled_size[0] = '\0';
2445 fpa.last_p_indexed = -1;
2446 fpa.last_p_resolved = -1;
2447 fpa.verbosity = verbosity;
2448 fpa.repo = repo;
2449 fpa.create_configs = 0;
2450 fpa.configs_created = 0;
2451 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2452 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2453 remote->mirror_references, fetch_all_branches, &wanted_branches,
2454 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2455 fetch_progress, &fpa);
2456 if (error)
2457 goto done;
2459 if (list_refs_only) {
2460 error = list_remote_refs(&symrefs, &refs);
2461 goto done;
2464 if (pack_hash == NULL) {
2465 if (verbosity >= 0)
2466 printf("Already up-to-date\n");
2467 } else if (verbosity >= 0) {
2468 error = got_object_id_str(&id_str, pack_hash);
2469 if (error)
2470 goto done;
2471 printf("\nFetched %s.pack\n", id_str);
2472 free(id_str);
2473 id_str = NULL;
2476 /* Update references provided with the pack file. */
2477 TAILQ_FOREACH(pe, &refs, entry) {
2478 const char *refname = pe->path;
2479 struct got_object_id *id = pe->data;
2480 struct got_reference *ref;
2481 char *remote_refname;
2483 if (is_wanted_ref(&wanted_refs, refname) &&
2484 !remote->mirror_references) {
2485 error = update_wanted_ref(refname, id,
2486 remote->name, verbosity, repo);
2487 if (error)
2488 goto done;
2489 continue;
2492 if (remote->mirror_references ||
2493 strncmp("refs/tags/", refname, 10) == 0) {
2494 error = got_ref_open(&ref, repo, refname, 1);
2495 if (error) {
2496 if (error->code != GOT_ERR_NOT_REF)
2497 goto done;
2498 error = create_ref(refname, id, verbosity,
2499 repo);
2500 if (error)
2501 goto done;
2502 } else {
2503 error = update_ref(ref, id, replace_tags,
2504 verbosity, repo);
2505 unlock_err = got_ref_unlock(ref);
2506 if (unlock_err && error == NULL)
2507 error = unlock_err;
2508 got_ref_close(ref);
2509 if (error)
2510 goto done;
2512 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2513 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2514 remote_name, refname + 11) == -1) {
2515 error = got_error_from_errno("asprintf");
2516 goto done;
2519 error = got_ref_open(&ref, repo, remote_refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(remote_refname, id,
2524 verbosity, repo);
2525 if (error)
2526 goto done;
2527 } else {
2528 error = update_ref(ref, id, replace_tags,
2529 verbosity, repo);
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2534 if (error)
2535 goto done;
2538 /* Also create a local branch if none exists yet. */
2539 error = got_ref_open(&ref, repo, refname, 1);
2540 if (error) {
2541 if (error->code != GOT_ERR_NOT_REF)
2542 goto done;
2543 error = create_ref(refname, id, verbosity,
2544 repo);
2545 if (error)
2546 goto done;
2547 } else {
2548 unlock_err = got_ref_unlock(ref);
2549 if (unlock_err && error == NULL)
2550 error = unlock_err;
2551 got_ref_close(ref);
2555 if (delete_refs) {
2556 error = delete_missing_refs(&refs, &symrefs, remote,
2557 verbosity, repo);
2558 if (error)
2559 goto done;
2562 if (!remote->mirror_references) {
2563 /* Update remote HEAD reference if the server provided one. */
2564 TAILQ_FOREACH(pe, &symrefs, entry) {
2565 struct got_reference *target_ref;
2566 const char *refname = pe->path;
2567 const char *target = pe->data;
2568 char *remote_refname = NULL, *remote_target = NULL;
2570 if (strcmp(refname, GOT_REF_HEAD) != 0)
2571 continue;
2573 if (strncmp("refs/heads/", target, 11) != 0)
2574 continue;
2576 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2577 remote->name, refname) == -1) {
2578 error = got_error_from_errno("asprintf");
2579 goto done;
2581 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2582 remote->name, target + 11) == -1) {
2583 error = got_error_from_errno("asprintf");
2584 free(remote_refname);
2585 goto done;
2588 error = got_ref_open(&target_ref, repo, remote_target,
2589 0);
2590 if (error) {
2591 free(remote_refname);
2592 free(remote_target);
2593 if (error->code == GOT_ERR_NOT_REF) {
2594 error = NULL;
2595 continue;
2597 goto done;
2599 error = update_symref(remote_refname, target_ref,
2600 verbosity, repo);
2601 free(remote_refname);
2602 free(remote_target);
2603 got_ref_close(target_ref);
2604 if (error)
2605 goto done;
2608 done:
2609 if (fetchpid > 0) {
2610 if (kill(fetchpid, SIGTERM) == -1)
2611 error = got_error_from_errno("kill");
2612 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2613 error = got_error_from_errno("waitpid");
2615 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2616 error = got_error_from_errno("close");
2617 if (repo) {
2618 const struct got_error *close_err = got_repo_close(repo);
2619 if (error == NULL)
2620 error = close_err;
2622 if (worktree)
2623 got_worktree_close(worktree);
2624 TAILQ_FOREACH(pe, &refs, entry) {
2625 free((void *)pe->path);
2626 free(pe->data);
2628 got_pathlist_free(&refs);
2629 TAILQ_FOREACH(pe, &symrefs, entry) {
2630 free((void *)pe->path);
2631 free(pe->data);
2633 got_pathlist_free(&symrefs);
2634 got_pathlist_free(&wanted_branches);
2635 got_pathlist_free(&wanted_refs);
2636 free(id_str);
2637 free(cwd);
2638 free(repo_path);
2639 free(pack_hash);
2640 free(proto);
2641 free(host);
2642 free(port);
2643 free(server_path);
2644 free(repo_name);
2645 return error;
2649 __dead static void
2650 usage_checkout(void)
2652 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2653 "[-p prefix] [-q] repository-path [worktree-path]\n",
2654 getprogname());
2655 exit(1);
2658 static void
2659 show_worktree_base_ref_warning(void)
2661 fprintf(stderr, "%s: warning: could not create a reference "
2662 "to the work tree's base commit; the commit could be "
2663 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2664 "repository writable and running 'got update' will prevent this\n",
2665 getprogname());
2668 struct got_checkout_progress_arg {
2669 const char *worktree_path;
2670 int had_base_commit_ref_error;
2671 int verbosity;
2674 static const struct got_error *
2675 checkout_progress(void *arg, unsigned char status, const char *path)
2677 struct got_checkout_progress_arg *a = arg;
2679 /* Base commit bump happens silently. */
2680 if (status == GOT_STATUS_BUMP_BASE)
2681 return NULL;
2683 if (status == GOT_STATUS_BASE_REF_ERR) {
2684 a->had_base_commit_ref_error = 1;
2685 return NULL;
2688 while (path[0] == '/')
2689 path++;
2691 if (a->verbosity >= 0)
2692 printf("%c %s/%s\n", status, a->worktree_path, path);
2694 return NULL;
2697 static const struct got_error *
2698 check_cancelled(void *arg)
2700 if (sigint_received || sigpipe_received)
2701 return got_error(GOT_ERR_CANCELLED);
2702 return NULL;
2705 static const struct got_error *
2706 check_linear_ancestry(struct got_object_id *commit_id,
2707 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2708 struct got_repository *repo)
2710 const struct got_error *err = NULL;
2711 struct got_object_id *yca_id;
2713 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2714 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2715 if (err)
2716 return err;
2718 if (yca_id == NULL)
2719 return got_error(GOT_ERR_ANCESTRY);
2722 * Require a straight line of history between the target commit
2723 * and the work tree's base commit.
2725 * Non-linear situations such as this require a rebase:
2727 * (commit) D F (base_commit)
2728 * \ /
2729 * C E
2730 * \ /
2731 * B (yca)
2732 * |
2733 * A
2735 * 'got update' only handles linear cases:
2736 * Update forwards in time: A (base/yca) - B - C - D (commit)
2737 * Update backwards in time: D (base) - C - B - A (commit/yca)
2739 if (allow_forwards_in_time_only) {
2740 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2741 return got_error(GOT_ERR_ANCESTRY);
2742 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2743 got_object_id_cmp(base_commit_id, yca_id) != 0)
2744 return got_error(GOT_ERR_ANCESTRY);
2746 free(yca_id);
2747 return NULL;
2750 static const struct got_error *
2751 check_same_branch(struct got_object_id *commit_id,
2752 struct got_reference *head_ref, struct got_object_id *yca_id,
2753 struct got_repository *repo)
2755 const struct got_error *err = NULL;
2756 struct got_commit_graph *graph = NULL;
2757 struct got_object_id *head_commit_id = NULL;
2758 int is_same_branch = 0;
2760 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2761 if (err)
2762 goto done;
2764 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2765 is_same_branch = 1;
2766 goto done;
2768 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2769 is_same_branch = 1;
2770 goto done;
2773 err = got_commit_graph_open(&graph, "/", 1);
2774 if (err)
2775 goto done;
2777 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2778 check_cancelled, NULL);
2779 if (err)
2780 goto done;
2782 for (;;) {
2783 struct got_object_id *id;
2784 err = got_commit_graph_iter_next(&id, graph, repo,
2785 check_cancelled, NULL);
2786 if (err) {
2787 if (err->code == GOT_ERR_ITER_COMPLETED)
2788 err = NULL;
2789 break;
2792 if (id) {
2793 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2794 break;
2795 if (got_object_id_cmp(id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 break;
2801 done:
2802 if (graph)
2803 got_commit_graph_close(graph);
2804 free(head_commit_id);
2805 if (!err && !is_same_branch)
2806 err = got_error(GOT_ERR_ANCESTRY);
2807 return err;
2810 static const struct got_error *
2811 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2813 static char msg[512];
2814 const char *branch_name;
2816 if (got_ref_is_symbolic(ref))
2817 branch_name = got_ref_get_symref_target(ref);
2818 else
2819 branch_name = got_ref_get_name(ref);
2821 if (strncmp("refs/heads/", branch_name, 11) == 0)
2822 branch_name += 11;
2824 snprintf(msg, sizeof(msg),
2825 "target commit is not contained in branch '%s'; "
2826 "the branch to use must be specified with -b; "
2827 "if necessary a new branch can be created for "
2828 "this commit with 'got branch -c %s BRANCH_NAME'",
2829 branch_name, commit_id_str);
2831 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2834 static const struct got_error *
2835 cmd_checkout(int argc, char *argv[])
2837 const struct got_error *error = NULL;
2838 struct got_repository *repo = NULL;
2839 struct got_reference *head_ref = NULL, *ref = NULL;
2840 struct got_worktree *worktree = NULL;
2841 char *repo_path = NULL;
2842 char *worktree_path = NULL;
2843 const char *path_prefix = "";
2844 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2845 char *commit_id_str = NULL;
2846 struct got_object_id *commit_id = NULL;
2847 char *cwd = NULL;
2848 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2849 struct got_pathlist_head paths;
2850 struct got_checkout_progress_arg cpa;
2852 TAILQ_INIT(&paths);
2854 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2855 switch (ch) {
2856 case 'b':
2857 branch_name = optarg;
2858 break;
2859 case 'c':
2860 commit_id_str = strdup(optarg);
2861 if (commit_id_str == NULL)
2862 return got_error_from_errno("strdup");
2863 break;
2864 case 'E':
2865 allow_nonempty = 1;
2866 break;
2867 case 'p':
2868 path_prefix = optarg;
2869 break;
2870 case 'q':
2871 verbosity = -1;
2872 break;
2873 default:
2874 usage_checkout();
2875 /* NOTREACHED */
2879 argc -= optind;
2880 argv += optind;
2882 #ifndef PROFILE
2883 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2884 "unveil", NULL) == -1)
2885 err(1, "pledge");
2886 #endif
2887 if (argc == 1) {
2888 char *base, *dotgit;
2889 const char *path;
2890 repo_path = realpath(argv[0], NULL);
2891 if (repo_path == NULL)
2892 return got_error_from_errno2("realpath", argv[0]);
2893 cwd = getcwd(NULL, 0);
2894 if (cwd == NULL) {
2895 error = got_error_from_errno("getcwd");
2896 goto done;
2898 if (path_prefix[0])
2899 path = path_prefix;
2900 else
2901 path = repo_path;
2902 error = got_path_basename(&base, path);
2903 if (error)
2904 goto done;
2905 dotgit = strstr(base, ".git");
2906 if (dotgit)
2907 *dotgit = '\0';
2908 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2909 error = got_error_from_errno("asprintf");
2910 free(base);
2911 goto done;
2913 free(base);
2914 } else if (argc == 2) {
2915 repo_path = realpath(argv[0], NULL);
2916 if (repo_path == NULL) {
2917 error = got_error_from_errno2("realpath", argv[0]);
2918 goto done;
2920 worktree_path = realpath(argv[1], NULL);
2921 if (worktree_path == NULL) {
2922 if (errno != ENOENT) {
2923 error = got_error_from_errno2("realpath",
2924 argv[1]);
2925 goto done;
2927 worktree_path = strdup(argv[1]);
2928 if (worktree_path == NULL) {
2929 error = got_error_from_errno("strdup");
2930 goto done;
2933 } else
2934 usage_checkout();
2936 got_path_strip_trailing_slashes(repo_path);
2937 got_path_strip_trailing_slashes(worktree_path);
2939 error = got_repo_open(&repo, repo_path, NULL);
2940 if (error != NULL)
2941 goto done;
2943 /* Pre-create work tree path for unveil(2) */
2944 error = got_path_mkdir(worktree_path);
2945 if (error) {
2946 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2947 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2948 goto done;
2949 if (!allow_nonempty &&
2950 !got_path_dir_is_empty(worktree_path)) {
2951 error = got_error_path(worktree_path,
2952 GOT_ERR_DIR_NOT_EMPTY);
2953 goto done;
2957 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2958 if (error)
2959 goto done;
2961 error = got_ref_open(&head_ref, repo, branch_name, 0);
2962 if (error != NULL)
2963 goto done;
2965 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2966 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2967 goto done;
2969 error = got_worktree_open(&worktree, worktree_path);
2970 if (error != NULL)
2971 goto done;
2973 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2974 path_prefix);
2975 if (error != NULL)
2976 goto done;
2977 if (!same_path_prefix) {
2978 error = got_error(GOT_ERR_PATH_PREFIX);
2979 goto done;
2982 if (commit_id_str) {
2983 struct got_reflist_head refs;
2984 TAILQ_INIT(&refs);
2985 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2986 NULL);
2987 if (error)
2988 goto done;
2989 error = got_repo_match_object_id(&commit_id, NULL,
2990 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2991 got_ref_list_free(&refs);
2992 if (error)
2993 goto done;
2994 error = check_linear_ancestry(commit_id,
2995 got_worktree_get_base_commit_id(worktree), 0, repo);
2996 if (error != NULL) {
2997 if (error->code == GOT_ERR_ANCESTRY) {
2998 error = checkout_ancestry_error(
2999 head_ref, commit_id_str);
3001 goto done;
3003 error = check_same_branch(commit_id, head_ref, NULL, repo);
3004 if (error) {
3005 if (error->code == GOT_ERR_ANCESTRY) {
3006 error = checkout_ancestry_error(
3007 head_ref, commit_id_str);
3009 goto done;
3011 error = got_worktree_set_base_commit_id(worktree, repo,
3012 commit_id);
3013 if (error)
3014 goto done;
3015 /* Expand potentially abbreviated commit ID string. */
3016 free(commit_id_str);
3017 error = got_object_id_str(&commit_id_str, commit_id);
3018 if (error)
3019 goto done;
3020 } else {
3021 commit_id = got_object_id_dup(
3022 got_worktree_get_base_commit_id(worktree));
3023 if (commit_id == NULL) {
3024 error = got_error_from_errno("got_object_id_dup");
3025 goto done;
3027 error = got_object_id_str(&commit_id_str, commit_id);
3028 if (error)
3029 goto done;
3032 error = got_pathlist_append(&paths, "", NULL);
3033 if (error)
3034 goto done;
3035 cpa.worktree_path = worktree_path;
3036 cpa.had_base_commit_ref_error = 0;
3037 cpa.verbosity = verbosity;
3038 error = got_worktree_checkout_files(worktree, &paths, repo,
3039 checkout_progress, &cpa, check_cancelled, NULL);
3040 if (error != NULL)
3041 goto done;
3043 if (got_ref_is_symbolic(head_ref)) {
3044 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3045 if (error)
3046 goto done;
3047 refname = got_ref_get_name(ref);
3048 } else
3049 refname = got_ref_get_name(head_ref);
3050 printf("Checked out %s: %s\n", refname, commit_id_str);
3051 printf("Now shut up and hack\n");
3052 if (cpa.had_base_commit_ref_error)
3053 show_worktree_base_ref_warning();
3054 done:
3055 if (head_ref)
3056 got_ref_close(head_ref);
3057 if (ref)
3058 got_ref_close(ref);
3059 got_pathlist_free(&paths);
3060 free(commit_id_str);
3061 free(commit_id);
3062 free(repo_path);
3063 free(worktree_path);
3064 free(cwd);
3065 return error;
3068 struct got_update_progress_arg {
3069 int did_something;
3070 int conflicts;
3071 int obstructed;
3072 int not_updated;
3073 int missing;
3074 int not_deleted;
3075 int unversioned;
3076 int verbosity;
3079 void
3080 print_update_progress_stats(struct got_update_progress_arg *upa)
3082 if (!upa->did_something)
3083 return;
3085 if (upa->conflicts > 0)
3086 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3087 if (upa->obstructed > 0)
3088 printf("File paths obstructed by a non-regular file: %d\n",
3089 upa->obstructed);
3090 if (upa->not_updated > 0)
3091 printf("Files not updated because of existing merge "
3092 "conflicts: %d\n", upa->not_updated);
3096 * The meaning of some status codes differs between merge-style operations and
3097 * update operations. For example, the ! status code means "file was missing"
3098 * if changes were merged into the work tree, and "missing file was restored"
3099 * if the work tree was updated. This function should be used by any operation
3100 * which merges changes into the work tree without updating the work tree.
3102 void
3103 print_merge_progress_stats(struct got_update_progress_arg *upa)
3105 if (!upa->did_something)
3106 return;
3108 if (upa->conflicts > 0)
3109 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3110 if (upa->obstructed > 0)
3111 printf("File paths obstructed by a non-regular file: %d\n",
3112 upa->obstructed);
3113 if (upa->missing > 0)
3114 printf("Files which had incoming changes but could not be "
3115 "found in the work tree: %d\n", upa->missing);
3116 if (upa->not_deleted > 0)
3117 printf("Files not deleted due to differences in deleted "
3118 "content: %d\n", upa->not_deleted);
3119 if (upa->unversioned > 0)
3120 printf("Files not merged because an unversioned file was "
3121 "found in the work tree: %d\n", upa->unversioned);
3124 __dead static void
3125 usage_update(void)
3127 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3128 "[path ...]\n",
3129 getprogname());
3130 exit(1);
3133 static const struct got_error *
3134 update_progress(void *arg, unsigned char status, const char *path)
3136 struct got_update_progress_arg *upa = arg;
3138 if (status == GOT_STATUS_EXISTS ||
3139 status == GOT_STATUS_BASE_REF_ERR)
3140 return NULL;
3142 upa->did_something = 1;
3144 /* Base commit bump happens silently. */
3145 if (status == GOT_STATUS_BUMP_BASE)
3146 return NULL;
3148 if (status == GOT_STATUS_CONFLICT)
3149 upa->conflicts++;
3150 if (status == GOT_STATUS_OBSTRUCTED)
3151 upa->obstructed++;
3152 if (status == GOT_STATUS_CANNOT_UPDATE)
3153 upa->not_updated++;
3154 if (status == GOT_STATUS_MISSING)
3155 upa->missing++;
3156 if (status == GOT_STATUS_CANNOT_DELETE)
3157 upa->not_deleted++;
3158 if (status == GOT_STATUS_UNVERSIONED)
3159 upa->unversioned++;
3161 while (path[0] == '/')
3162 path++;
3163 if (upa->verbosity >= 0)
3164 printf("%c %s\n", status, path);
3166 return NULL;
3169 static const struct got_error *
3170 switch_head_ref(struct got_reference *head_ref,
3171 struct got_object_id *commit_id, struct got_worktree *worktree,
3172 struct got_repository *repo)
3174 const struct got_error *err = NULL;
3175 char *base_id_str;
3176 int ref_has_moved = 0;
3178 /* Trivial case: switching between two different references. */
3179 if (strcmp(got_ref_get_name(head_ref),
3180 got_worktree_get_head_ref_name(worktree)) != 0) {
3181 printf("Switching work tree from %s to %s\n",
3182 got_worktree_get_head_ref_name(worktree),
3183 got_ref_get_name(head_ref));
3184 return got_worktree_set_head_ref(worktree, head_ref);
3187 err = check_linear_ancestry(commit_id,
3188 got_worktree_get_base_commit_id(worktree), 0, repo);
3189 if (err) {
3190 if (err->code != GOT_ERR_ANCESTRY)
3191 return err;
3192 ref_has_moved = 1;
3194 if (!ref_has_moved)
3195 return NULL;
3197 /* Switching to a rebased branch with the same reference name. */
3198 err = got_object_id_str(&base_id_str,
3199 got_worktree_get_base_commit_id(worktree));
3200 if (err)
3201 return err;
3202 printf("Reference %s now points at a different branch\n",
3203 got_worktree_get_head_ref_name(worktree));
3204 printf("Switching work tree from %s to %s\n", base_id_str,
3205 got_worktree_get_head_ref_name(worktree));
3206 return NULL;
3209 static const struct got_error *
3210 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3212 const struct got_error *err;
3213 int in_progress;
3215 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3216 if (err)
3217 return err;
3218 if (in_progress)
3219 return got_error(GOT_ERR_REBASING);
3221 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3222 if (err)
3223 return err;
3224 if (in_progress)
3225 return got_error(GOT_ERR_HISTEDIT_BUSY);
3227 return NULL;
3230 static const struct got_error *
3231 check_merge_in_progress(struct got_worktree *worktree,
3232 struct got_repository *repo)
3234 const struct got_error *err;
3235 int in_progress;
3237 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3238 if (err)
3239 return err;
3240 if (in_progress)
3241 return got_error(GOT_ERR_MERGE_BUSY);
3243 return NULL;
3246 static const struct got_error *
3247 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3248 char *argv[], struct got_worktree *worktree)
3250 const struct got_error *err = NULL;
3251 char *path;
3252 struct got_pathlist_entry *new;
3253 int i;
3255 if (argc == 0) {
3256 path = strdup("");
3257 if (path == NULL)
3258 return got_error_from_errno("strdup");
3259 return got_pathlist_append(paths, path, NULL);
3262 for (i = 0; i < argc; i++) {
3263 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3264 if (err)
3265 break;
3266 err = got_pathlist_insert(&new, paths, path, NULL);
3267 if (err || new == NULL /* duplicate */) {
3268 free(path);
3269 if (err)
3270 break;
3274 return err;
3277 static const struct got_error *
3278 wrap_not_worktree_error(const struct got_error *orig_err,
3279 const char *cmdname, const char *path)
3281 const struct got_error *err;
3282 struct got_repository *repo;
3283 static char msg[512];
3285 err = got_repo_open(&repo, path, NULL);
3286 if (err)
3287 return orig_err;
3289 snprintf(msg, sizeof(msg),
3290 "'got %s' needs a work tree in addition to a git repository\n"
3291 "Work trees can be checked out from this Git repository with "
3292 "'got checkout'.\n"
3293 "The got(1) manual page contains more information.", cmdname);
3294 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3295 got_repo_close(repo);
3296 return err;
3299 static const struct got_error *
3300 cmd_update(int argc, char *argv[])
3302 const struct got_error *error = NULL;
3303 struct got_repository *repo = NULL;
3304 struct got_worktree *worktree = NULL;
3305 char *worktree_path = NULL;
3306 struct got_object_id *commit_id = NULL;
3307 char *commit_id_str = NULL;
3308 const char *branch_name = NULL;
3309 struct got_reference *head_ref = NULL;
3310 struct got_pathlist_head paths;
3311 struct got_pathlist_entry *pe;
3312 int ch, verbosity = 0;
3313 struct got_update_progress_arg upa;
3315 TAILQ_INIT(&paths);
3317 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3318 switch (ch) {
3319 case 'b':
3320 branch_name = optarg;
3321 break;
3322 case 'c':
3323 commit_id_str = strdup(optarg);
3324 if (commit_id_str == NULL)
3325 return got_error_from_errno("strdup");
3326 break;
3327 case 'q':
3328 verbosity = -1;
3329 break;
3330 default:
3331 usage_update();
3332 /* NOTREACHED */
3336 argc -= optind;
3337 argv += optind;
3339 #ifndef PROFILE
3340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3341 "unveil", NULL) == -1)
3342 err(1, "pledge");
3343 #endif
3344 worktree_path = getcwd(NULL, 0);
3345 if (worktree_path == NULL) {
3346 error = got_error_from_errno("getcwd");
3347 goto done;
3349 error = got_worktree_open(&worktree, worktree_path);
3350 if (error) {
3351 if (error->code == GOT_ERR_NOT_WORKTREE)
3352 error = wrap_not_worktree_error(error, "update",
3353 worktree_path);
3354 goto done;
3357 error = check_rebase_or_histedit_in_progress(worktree);
3358 if (error)
3359 goto done;
3361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3362 NULL);
3363 if (error != NULL)
3364 goto done;
3366 error = apply_unveil(got_repo_get_path(repo), 0,
3367 got_worktree_get_root_path(worktree));
3368 if (error)
3369 goto done;
3371 error = check_merge_in_progress(worktree, repo);
3372 if (error)
3373 goto done;
3375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3376 if (error)
3377 goto done;
3379 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3380 got_worktree_get_head_ref_name(worktree), 0);
3381 if (error != NULL)
3382 goto done;
3383 if (commit_id_str == NULL) {
3384 error = got_ref_resolve(&commit_id, repo, head_ref);
3385 if (error != NULL)
3386 goto done;
3387 error = got_object_id_str(&commit_id_str, commit_id);
3388 if (error != NULL)
3389 goto done;
3390 } else {
3391 struct got_reflist_head refs;
3392 TAILQ_INIT(&refs);
3393 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3394 NULL);
3395 if (error)
3396 goto done;
3397 error = got_repo_match_object_id(&commit_id, NULL,
3398 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3399 got_ref_list_free(&refs);
3400 free(commit_id_str);
3401 commit_id_str = NULL;
3402 if (error)
3403 goto done;
3404 error = got_object_id_str(&commit_id_str, commit_id);
3405 if (error)
3406 goto done;
3409 if (branch_name) {
3410 struct got_object_id *head_commit_id;
3411 TAILQ_FOREACH(pe, &paths, entry) {
3412 if (pe->path_len == 0)
3413 continue;
3414 error = got_error_msg(GOT_ERR_BAD_PATH,
3415 "switching between branches requires that "
3416 "the entire work tree gets updated");
3417 goto done;
3419 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3420 if (error)
3421 goto done;
3422 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3423 repo);
3424 free(head_commit_id);
3425 if (error != NULL)
3426 goto done;
3427 error = check_same_branch(commit_id, head_ref, NULL, repo);
3428 if (error)
3429 goto done;
3430 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3431 if (error)
3432 goto done;
3433 } else {
3434 error = check_linear_ancestry(commit_id,
3435 got_worktree_get_base_commit_id(worktree), 0, repo);
3436 if (error != NULL) {
3437 if (error->code == GOT_ERR_ANCESTRY)
3438 error = got_error(GOT_ERR_BRANCH_MOVED);
3439 goto done;
3441 error = check_same_branch(commit_id, head_ref, NULL, repo);
3442 if (error)
3443 goto done;
3446 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3447 commit_id) != 0) {
3448 error = got_worktree_set_base_commit_id(worktree, repo,
3449 commit_id);
3450 if (error)
3451 goto done;
3454 memset(&upa, 0, sizeof(upa));
3455 upa.verbosity = verbosity;
3456 error = got_worktree_checkout_files(worktree, &paths, repo,
3457 update_progress, &upa, check_cancelled, NULL);
3458 if (error != NULL)
3459 goto done;
3461 if (upa.did_something) {
3462 printf("Updated to %s: %s\n",
3463 got_worktree_get_head_ref_name(worktree), commit_id_str);
3464 } else
3465 printf("Already up-to-date\n");
3466 print_update_progress_stats(&upa);
3467 done:
3468 free(worktree_path);
3469 TAILQ_FOREACH(pe, &paths, entry)
3470 free((char *)pe->path);
3471 got_pathlist_free(&paths);
3472 free(commit_id);
3473 free(commit_id_str);
3474 return error;
3477 static const struct got_error *
3478 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3479 const char *path, int diff_context, int ignore_whitespace,
3480 int force_text_diff, struct got_repository *repo, FILE *outfile)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3484 FILE *f1 = NULL, *f2 = NULL;
3486 if (blob_id1) {
3487 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3488 if (err)
3489 goto done;
3490 f1 = got_opentemp();
3491 if (f1 == NULL) {
3492 err = got_error_from_errno("got_opentemp");
3493 goto done;
3497 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3498 if (err)
3499 goto done;
3501 f2 = got_opentemp();
3502 if (f2 == NULL) {
3503 err = got_error_from_errno("got_opentemp");
3504 goto done;
3507 while (path[0] == '/')
3508 path++;
3509 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3510 diff_context, ignore_whitespace, force_text_diff, outfile);
3511 done:
3512 if (blob1)
3513 got_object_blob_close(blob1);
3514 got_object_blob_close(blob2);
3515 if (f1 && fclose(f1) == EOF && err == NULL)
3516 err = got_error_from_errno("fclose");
3517 if (f2 && fclose(f2) == EOF && err == NULL)
3518 err = got_error_from_errno("fclose");
3519 return err;
3522 static const struct got_error *
3523 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3524 const char *path, int diff_context, int ignore_whitespace,
3525 int force_text_diff, struct got_repository *repo, FILE *outfile)
3527 const struct got_error *err = NULL;
3528 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3529 struct got_diff_blob_output_unidiff_arg arg;
3530 FILE *f1 = NULL, *f2 = NULL;
3532 if (tree_id1) {
3533 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3534 if (err)
3535 goto done;
3536 f1 = got_opentemp();
3537 if (f1 == NULL) {
3538 err = got_error_from_errno("got_opentemp");
3539 goto done;
3543 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3544 if (err)
3545 goto done;
3547 f2 = got_opentemp();
3548 if (f2 == NULL) {
3549 err = got_error_from_errno("got_opentemp");
3550 goto done;
3553 arg.diff_context = diff_context;
3554 arg.ignore_whitespace = ignore_whitespace;
3555 arg.force_text_diff = force_text_diff;
3556 arg.outfile = outfile;
3557 arg.line_offsets = NULL;
3558 arg.nlines = 0;
3559 while (path[0] == '/')
3560 path++;
3561 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3562 got_diff_blob_output_unidiff, &arg, 1);
3563 done:
3564 if (tree1)
3565 got_object_tree_close(tree1);
3566 if (tree2)
3567 got_object_tree_close(tree2);
3568 if (f1 && fclose(f1) == EOF && err == NULL)
3569 err = got_error_from_errno("fclose");
3570 if (f2 && fclose(f2) == EOF && err == NULL)
3571 err = got_error_from_errno("fclose");
3572 return err;
3575 static const struct got_error *
3576 get_changed_paths(struct got_pathlist_head *paths,
3577 struct got_commit_object *commit, struct got_repository *repo)
3579 const struct got_error *err = NULL;
3580 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3581 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3582 struct got_object_qid *qid;
3584 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3585 if (qid != NULL) {
3586 struct got_commit_object *pcommit;
3587 err = got_object_open_as_commit(&pcommit, repo,
3588 &qid->id);
3589 if (err)
3590 return err;
3592 tree_id1 = got_object_id_dup(
3593 got_object_commit_get_tree_id(pcommit));
3594 if (tree_id1 == NULL) {
3595 got_object_commit_close(pcommit);
3596 return got_error_from_errno("got_object_id_dup");
3598 got_object_commit_close(pcommit);
3602 if (tree_id1) {
3603 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3604 if (err)
3605 goto done;
3608 tree_id2 = got_object_commit_get_tree_id(commit);
3609 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3610 if (err)
3611 goto done;
3613 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3614 got_diff_tree_collect_changed_paths, paths, 0);
3615 done:
3616 if (tree1)
3617 got_object_tree_close(tree1);
3618 if (tree2)
3619 got_object_tree_close(tree2);
3620 free(tree_id1);
3621 return err;
3624 static const struct got_error *
3625 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3626 const char *path, int diff_context, struct got_repository *repo,
3627 FILE *outfile)
3629 const struct got_error *err = NULL;
3630 struct got_commit_object *pcommit = NULL;
3631 char *id_str1 = NULL, *id_str2 = NULL;
3632 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3633 struct got_object_qid *qid;
3635 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3636 if (qid != NULL) {
3637 err = got_object_open_as_commit(&pcommit, repo,
3638 &qid->id);
3639 if (err)
3640 return err;
3643 if (path && path[0] != '\0') {
3644 int obj_type;
3645 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3646 if (err)
3647 goto done;
3648 err = got_object_id_str(&id_str2, obj_id2);
3649 if (err) {
3650 free(obj_id2);
3651 goto done;
3653 if (pcommit) {
3654 err = got_object_id_by_path(&obj_id1, repo,
3655 pcommit, path);
3656 if (err) {
3657 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3658 free(obj_id2);
3659 goto done;
3661 } else {
3662 err = got_object_id_str(&id_str1, obj_id1);
3663 if (err) {
3664 free(obj_id2);
3665 goto done;
3669 err = got_object_get_type(&obj_type, repo, obj_id2);
3670 if (err) {
3671 free(obj_id2);
3672 goto done;
3674 fprintf(outfile,
3675 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3676 switch (obj_type) {
3677 case GOT_OBJ_TYPE_BLOB:
3678 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3679 0, 0, repo, outfile);
3680 break;
3681 case GOT_OBJ_TYPE_TREE:
3682 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3683 0, 0, repo, outfile);
3684 break;
3685 default:
3686 err = got_error(GOT_ERR_OBJ_TYPE);
3687 break;
3689 free(obj_id1);
3690 free(obj_id2);
3691 } else {
3692 obj_id2 = got_object_commit_get_tree_id(commit);
3693 err = got_object_id_str(&id_str2, obj_id2);
3694 if (err)
3695 goto done;
3696 if (pcommit) {
3697 obj_id1 = got_object_commit_get_tree_id(pcommit);
3698 err = got_object_id_str(&id_str1, obj_id1);
3699 if (err)
3700 goto done;
3702 fprintf(outfile,
3703 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3704 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3705 repo, outfile);
3707 done:
3708 free(id_str1);
3709 free(id_str2);
3710 if (pcommit)
3711 got_object_commit_close(pcommit);
3712 return err;
3715 static char *
3716 get_datestr(time_t *time, char *datebuf)
3718 struct tm mytm, *tm;
3719 char *p, *s;
3721 tm = gmtime_r(time, &mytm);
3722 if (tm == NULL)
3723 return NULL;
3724 s = asctime_r(tm, datebuf);
3725 if (s == NULL)
3726 return NULL;
3727 p = strchr(s, '\n');
3728 if (p)
3729 *p = '\0';
3730 return s;
3733 static const struct got_error *
3734 match_logmsg(int *have_match, struct got_object_id *id,
3735 struct got_commit_object *commit, regex_t *regex)
3737 const struct got_error *err = NULL;
3738 regmatch_t regmatch;
3739 char *id_str = NULL, *logmsg = NULL;
3741 *have_match = 0;
3743 err = got_object_id_str(&id_str, id);
3744 if (err)
3745 return err;
3747 err = got_object_commit_get_logmsg(&logmsg, commit);
3748 if (err)
3749 goto done;
3751 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3752 *have_match = 1;
3753 done:
3754 free(id_str);
3755 free(logmsg);
3756 return err;
3759 static void
3760 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3761 regex_t *regex)
3763 regmatch_t regmatch;
3764 struct got_pathlist_entry *pe;
3766 *have_match = 0;
3768 TAILQ_FOREACH(pe, changed_paths, entry) {
3769 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3770 *have_match = 1;
3771 break;
3776 static const struct got_error *
3777 match_patch(int *have_match, struct got_commit_object *commit,
3778 struct got_object_id *id, const char *path, int diff_context,
3779 struct got_repository *repo, regex_t *regex, FILE *f)
3781 const struct got_error *err = NULL;
3782 char *line = NULL;
3783 size_t linesize = 0;
3784 ssize_t linelen;
3785 regmatch_t regmatch;
3787 *have_match = 0;
3789 err = got_opentemp_truncate(f);
3790 if (err)
3791 return err;
3793 err = print_patch(commit, id, path, diff_context, repo, f);
3794 if (err)
3795 goto done;
3797 if (fseeko(f, 0L, SEEK_SET) == -1) {
3798 err = got_error_from_errno("fseeko");
3799 goto done;
3802 while ((linelen = getline(&line, &linesize, f)) != -1) {
3803 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3804 *have_match = 1;
3805 break;
3808 done:
3809 free(line);
3810 return err;
3813 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3815 static const struct got_error*
3816 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3817 struct got_object_id *id, struct got_repository *repo)
3819 static const struct got_error *err = NULL;
3820 struct got_reflist_entry *re;
3821 char *s;
3822 const char *name;
3824 *refs_str = NULL;
3826 TAILQ_FOREACH(re, refs, entry) {
3827 struct got_tag_object *tag = NULL;
3828 struct got_object_id *ref_id;
3829 int cmp;
3831 name = got_ref_get_name(re->ref);
3832 if (strcmp(name, GOT_REF_HEAD) == 0)
3833 continue;
3834 if (strncmp(name, "refs/", 5) == 0)
3835 name += 5;
3836 if (strncmp(name, "got/", 4) == 0)
3837 continue;
3838 if (strncmp(name, "heads/", 6) == 0)
3839 name += 6;
3840 if (strncmp(name, "remotes/", 8) == 0) {
3841 name += 8;
3842 s = strstr(name, "/" GOT_REF_HEAD);
3843 if (s != NULL && s[strlen(s)] == '\0')
3844 continue;
3846 err = got_ref_resolve(&ref_id, repo, re->ref);
3847 if (err)
3848 break;
3849 if (strncmp(name, "tags/", 5) == 0) {
3850 err = got_object_open_as_tag(&tag, repo, ref_id);
3851 if (err) {
3852 if (err->code != GOT_ERR_OBJ_TYPE) {
3853 free(ref_id);
3854 break;
3856 /* Ref points at something other than a tag. */
3857 err = NULL;
3858 tag = NULL;
3861 cmp = got_object_id_cmp(tag ?
3862 got_object_tag_get_object_id(tag) : ref_id, id);
3863 free(ref_id);
3864 if (tag)
3865 got_object_tag_close(tag);
3866 if (cmp != 0)
3867 continue;
3868 s = *refs_str;
3869 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3870 s ? ", " : "", name) == -1) {
3871 err = got_error_from_errno("asprintf");
3872 free(s);
3873 *refs_str = NULL;
3874 break;
3876 free(s);
3879 return err;
3882 static const struct got_error *
3883 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id)
3885 const struct got_error *err = NULL;
3886 char *id_str, *s, *nl, *logmsg0;
3888 err = got_object_id_str(&id_str, id);
3889 if (err)
3890 return err;
3892 err = got_object_commit_get_logmsg(&logmsg0, commit);
3893 if (err)
3894 goto done;
3896 s = logmsg0;
3897 while (isspace((unsigned char)s[0]))
3898 s++;
3900 nl = strchr(s, '\n');
3901 if (nl) {
3902 *nl = '\0';
3905 printf("%.7s %s\n", id_str, s);
3907 if (fflush(stdout) != 0 && err == NULL)
3908 err = got_error_from_errno("fflush");
3909 done:
3910 free(id_str);
3911 free(logmsg0);
3912 return err;
3915 static const struct got_error *
3916 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3917 struct got_repository *repo, const char *path,
3918 struct got_pathlist_head *changed_paths, int show_patch,
3919 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3920 const char *custom_refs_str)
3922 const struct got_error *err = NULL;
3923 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3924 char datebuf[26];
3925 time_t committer_time;
3926 const char *author, *committer;
3927 char *refs_str = NULL;
3929 err = got_object_id_str(&id_str, id);
3930 if (err)
3931 return err;
3933 if (custom_refs_str == NULL) {
3934 struct got_reflist_head *refs;
3935 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3936 if (refs) {
3937 err = build_refs_str(&refs_str, refs, id, repo);
3938 if (err)
3939 goto done;
3943 printf(GOT_COMMIT_SEP_STR);
3944 if (custom_refs_str)
3945 printf("commit %s (%s)\n", id_str, custom_refs_str);
3946 else
3947 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3948 refs_str ? refs_str : "", refs_str ? ")" : "");
3949 free(id_str);
3950 id_str = NULL;
3951 free(refs_str);
3952 refs_str = NULL;
3953 printf("from: %s\n", got_object_commit_get_author(commit));
3954 committer_time = got_object_commit_get_committer_time(commit);
3955 datestr = get_datestr(&committer_time, datebuf);
3956 if (datestr)
3957 printf("date: %s UTC\n", datestr);
3958 author = got_object_commit_get_author(commit);
3959 committer = got_object_commit_get_committer(commit);
3960 if (strcmp(author, committer) != 0)
3961 printf("via: %s\n", committer);
3962 if (got_object_commit_get_nparents(commit) > 1) {
3963 const struct got_object_id_queue *parent_ids;
3964 struct got_object_qid *qid;
3965 int n = 1;
3966 parent_ids = got_object_commit_get_parent_ids(commit);
3967 STAILQ_FOREACH(qid, parent_ids, entry) {
3968 err = got_object_id_str(&id_str, &qid->id);
3969 if (err)
3970 goto done;
3971 printf("parent %d: %s\n", n++, id_str);
3972 free(id_str);
3973 id_str = NULL;
3977 err = got_object_commit_get_logmsg(&logmsg0, commit);
3978 if (err)
3979 goto done;
3981 logmsg = logmsg0;
3982 do {
3983 line = strsep(&logmsg, "\n");
3984 if (line)
3985 printf(" %s\n", line);
3986 } while (line);
3987 free(logmsg0);
3989 if (changed_paths) {
3990 struct got_pathlist_entry *pe;
3991 TAILQ_FOREACH(pe, changed_paths, entry) {
3992 struct got_diff_changed_path *cp = pe->data;
3993 printf(" %c %s\n", cp->status, pe->path);
3995 printf("\n");
3997 if (show_patch) {
3998 err = print_patch(commit, id, path, diff_context, repo, stdout);
3999 if (err == 0)
4000 printf("\n");
4003 if (fflush(stdout) != 0 && err == NULL)
4004 err = got_error_from_errno("fflush");
4005 done:
4006 free(id_str);
4007 free(refs_str);
4008 return err;
4011 static const struct got_error *
4012 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4013 struct got_repository *repo, const char *path, int show_changed_paths,
4014 int show_patch, const char *search_pattern, int diff_context, int limit,
4015 int log_branches, int reverse_display_order,
4016 struct got_reflist_object_id_map *refs_idmap, int one_line,
4017 FILE *tmpfile)
4019 const struct got_error *err;
4020 struct got_commit_graph *graph;
4021 regex_t regex;
4022 int have_match;
4023 struct got_object_id_queue reversed_commits;
4024 struct got_object_qid *qid;
4025 struct got_commit_object *commit;
4026 struct got_pathlist_head changed_paths;
4027 struct got_pathlist_entry *pe;
4029 STAILQ_INIT(&reversed_commits);
4030 TAILQ_INIT(&changed_paths);
4032 if (search_pattern && regcomp(&regex, search_pattern,
4033 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4034 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4036 err = got_commit_graph_open(&graph, path, !log_branches);
4037 if (err)
4038 return err;
4039 err = got_commit_graph_iter_start(graph, root_id, repo,
4040 check_cancelled, NULL);
4041 if (err)
4042 goto done;
4043 for (;;) {
4044 struct got_object_id *id;
4046 if (sigint_received || sigpipe_received)
4047 break;
4049 err = got_commit_graph_iter_next(&id, graph, repo,
4050 check_cancelled, NULL);
4051 if (err) {
4052 if (err->code == GOT_ERR_ITER_COMPLETED)
4053 err = NULL;
4054 break;
4056 if (id == NULL)
4057 break;
4059 err = got_object_open_as_commit(&commit, repo, id);
4060 if (err)
4061 break;
4063 if (show_changed_paths && !reverse_display_order) {
4064 err = get_changed_paths(&changed_paths, commit, repo);
4065 if (err)
4066 break;
4069 if (search_pattern) {
4070 err = match_logmsg(&have_match, id, commit, &regex);
4071 if (err) {
4072 got_object_commit_close(commit);
4073 break;
4075 if (have_match == 0 && show_changed_paths)
4076 match_changed_paths(&have_match,
4077 &changed_paths, &regex);
4078 if (have_match == 0 && show_patch) {
4079 err = match_patch(&have_match, commit, id,
4080 path, diff_context, repo, &regex,
4081 tmpfile);
4082 if (err)
4083 break;
4085 if (have_match == 0) {
4086 got_object_commit_close(commit);
4087 TAILQ_FOREACH(pe, &changed_paths, entry) {
4088 free((char *)pe->path);
4089 free(pe->data);
4091 got_pathlist_free(&changed_paths);
4092 continue;
4096 if (reverse_display_order) {
4097 err = got_object_qid_alloc(&qid, id);
4098 if (err)
4099 break;
4100 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4101 got_object_commit_close(commit);
4102 } else {
4103 if (one_line)
4104 err = print_commit_oneline(commit, id);
4105 else
4106 err = print_commit(commit, id, repo, path,
4107 show_changed_paths ? &changed_paths : NULL,
4108 show_patch, diff_context, refs_idmap, NULL);
4109 got_object_commit_close(commit);
4110 if (err)
4111 break;
4113 if ((limit && --limit == 0) ||
4114 (end_id && got_object_id_cmp(id, end_id) == 0))
4115 break;
4117 TAILQ_FOREACH(pe, &changed_paths, entry) {
4118 free((char *)pe->path);
4119 free(pe->data);
4121 got_pathlist_free(&changed_paths);
4123 if (reverse_display_order) {
4124 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4125 err = got_object_open_as_commit(&commit, repo,
4126 &qid->id);
4127 if (err)
4128 break;
4129 if (show_changed_paths) {
4130 err = get_changed_paths(&changed_paths,
4131 commit, repo);
4132 if (err)
4133 break;
4135 if (one_line)
4136 err = print_commit_oneline(commit, &qid->id);
4137 else
4138 err = print_commit(commit, &qid->id, repo, path,
4139 show_changed_paths ? &changed_paths : NULL,
4140 show_patch, diff_context, refs_idmap, NULL);
4141 got_object_commit_close(commit);
4142 if (err)
4143 break;
4144 TAILQ_FOREACH(pe, &changed_paths, entry) {
4145 free((char *)pe->path);
4146 free(pe->data);
4148 got_pathlist_free(&changed_paths);
4151 done:
4152 while (!STAILQ_EMPTY(&reversed_commits)) {
4153 qid = STAILQ_FIRST(&reversed_commits);
4154 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4155 got_object_qid_free(qid);
4157 TAILQ_FOREACH(pe, &changed_paths, entry) {
4158 free((char *)pe->path);
4159 free(pe->data);
4161 got_pathlist_free(&changed_paths);
4162 if (search_pattern)
4163 regfree(&regex);
4164 got_commit_graph_close(graph);
4165 return err;
4168 __dead static void
4169 usage_log(void)
4171 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4172 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4173 "[-r repository-path] [-R] [path]\n", getprogname());
4174 exit(1);
4177 static int
4178 get_default_log_limit(void)
4180 const char *got_default_log_limit;
4181 long long n;
4182 const char *errstr;
4184 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4185 if (got_default_log_limit == NULL)
4186 return 0;
4187 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4188 if (errstr != NULL)
4189 return 0;
4190 return n;
4193 static const struct got_error *
4194 cmd_log(int argc, char *argv[])
4196 const struct got_error *error;
4197 struct got_repository *repo = NULL;
4198 struct got_worktree *worktree = NULL;
4199 struct got_object_id *start_id = NULL, *end_id = NULL;
4200 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4201 const char *start_commit = NULL, *end_commit = NULL;
4202 const char *search_pattern = NULL;
4203 int diff_context = -1, ch;
4204 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4205 int reverse_display_order = 0, one_line = 0;
4206 const char *errstr;
4207 struct got_reflist_head refs;
4208 struct got_reflist_object_id_map *refs_idmap = NULL;
4209 FILE *tmpfile = NULL;
4211 TAILQ_INIT(&refs);
4213 #ifndef PROFILE
4214 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4215 NULL)
4216 == -1)
4217 err(1, "pledge");
4218 #endif
4220 limit = get_default_log_limit();
4222 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4223 switch (ch) {
4224 case 'p':
4225 show_patch = 1;
4226 break;
4227 case 'P':
4228 show_changed_paths = 1;
4229 break;
4230 case 'c':
4231 start_commit = optarg;
4232 break;
4233 case 'C':
4234 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4235 &errstr);
4236 if (errstr != NULL)
4237 errx(1, "number of context lines is %s: %s",
4238 errstr, optarg);
4239 break;
4240 case 'l':
4241 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4242 if (errstr != NULL)
4243 errx(1, "number of commits is %s: %s",
4244 errstr, optarg);
4245 break;
4246 case 'b':
4247 log_branches = 1;
4248 break;
4249 case 'r':
4250 repo_path = realpath(optarg, NULL);
4251 if (repo_path == NULL)
4252 return got_error_from_errno2("realpath",
4253 optarg);
4254 got_path_strip_trailing_slashes(repo_path);
4255 break;
4256 case 'R':
4257 reverse_display_order = 1;
4258 break;
4259 case 's':
4260 one_line = 1;
4261 break;
4262 case 'S':
4263 search_pattern = optarg;
4264 break;
4265 case 'x':
4266 end_commit = optarg;
4267 break;
4268 default:
4269 usage_log();
4270 /* NOTREACHED */
4274 argc -= optind;
4275 argv += optind;
4277 if (diff_context == -1)
4278 diff_context = 3;
4279 else if (!show_patch)
4280 errx(1, "-C requires -p");
4282 if (one_line && (show_patch || show_changed_paths))
4283 errx(1, "cannot use -s with -p or -P");
4285 cwd = getcwd(NULL, 0);
4286 if (cwd == NULL) {
4287 error = got_error_from_errno("getcwd");
4288 goto done;
4291 if (repo_path == NULL) {
4292 error = got_worktree_open(&worktree, cwd);
4293 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4294 goto done;
4295 error = NULL;
4298 if (argc == 1) {
4299 if (worktree) {
4300 error = got_worktree_resolve_path(&path, worktree,
4301 argv[0]);
4302 if (error)
4303 goto done;
4304 } else {
4305 path = strdup(argv[0]);
4306 if (path == NULL) {
4307 error = got_error_from_errno("strdup");
4308 goto done;
4311 } else if (argc != 0)
4312 usage_log();
4314 if (repo_path == NULL) {
4315 repo_path = worktree ?
4316 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4318 if (repo_path == NULL) {
4319 error = got_error_from_errno("strdup");
4320 goto done;
4323 error = got_repo_open(&repo, repo_path, NULL);
4324 if (error != NULL)
4325 goto done;
4327 error = apply_unveil(got_repo_get_path(repo), 1,
4328 worktree ? got_worktree_get_root_path(worktree) : NULL);
4329 if (error)
4330 goto done;
4332 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4333 if (error)
4334 goto done;
4336 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4337 if (error)
4338 goto done;
4340 if (start_commit == NULL) {
4341 struct got_reference *head_ref;
4342 struct got_commit_object *commit = NULL;
4343 error = got_ref_open(&head_ref, repo,
4344 worktree ? got_worktree_get_head_ref_name(worktree)
4345 : GOT_REF_HEAD, 0);
4346 if (error != NULL)
4347 goto done;
4348 error = got_ref_resolve(&start_id, repo, head_ref);
4349 got_ref_close(head_ref);
4350 if (error != NULL)
4351 goto done;
4352 error = got_object_open_as_commit(&commit, repo,
4353 start_id);
4354 if (error != NULL)
4355 goto done;
4356 got_object_commit_close(commit);
4357 } else {
4358 error = got_repo_match_object_id(&start_id, NULL,
4359 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4360 if (error != NULL)
4361 goto done;
4363 if (end_commit != NULL) {
4364 error = got_repo_match_object_id(&end_id, NULL,
4365 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4366 if (error != NULL)
4367 goto done;
4370 if (worktree) {
4372 * If a path was specified on the command line it was resolved
4373 * to a path in the work tree above. Prepend the work tree's
4374 * path prefix to obtain the corresponding in-repository path.
4376 if (path) {
4377 const char *prefix;
4378 prefix = got_worktree_get_path_prefix(worktree);
4379 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4380 (path[0] != '\0') ? "/" : "", path) == -1) {
4381 error = got_error_from_errno("asprintf");
4382 goto done;
4385 } else
4386 error = got_repo_map_path(&in_repo_path, repo,
4387 path ? path : "");
4388 if (error != NULL)
4389 goto done;
4390 if (in_repo_path) {
4391 free(path);
4392 path = in_repo_path;
4395 if (worktree) {
4396 /* Release work tree lock. */
4397 got_worktree_close(worktree);
4398 worktree = NULL;
4401 if (search_pattern && show_patch) {
4402 tmpfile = got_opentemp();
4403 if (tmpfile == NULL) {
4404 error = got_error_from_errno("got_opentemp");
4405 goto done;
4409 error = print_commits(start_id, end_id, repo, path ? path : "",
4410 show_changed_paths, show_patch, search_pattern, diff_context,
4411 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4412 tmpfile);
4413 done:
4414 free(path);
4415 free(repo_path);
4416 free(cwd);
4417 if (worktree)
4418 got_worktree_close(worktree);
4419 if (repo) {
4420 const struct got_error *close_err = got_repo_close(repo);
4421 if (error == NULL)
4422 error = close_err;
4424 if (refs_idmap)
4425 got_reflist_object_id_map_free(refs_idmap);
4426 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4427 error = got_error_from_errno("fclose");
4428 got_ref_list_free(&refs);
4429 return error;
4432 __dead static void
4433 usage_diff(void)
4435 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4436 "[-r repository-path] [-s] [-w] [-P] "
4437 "[object1 object2 | path ...]\n", getprogname());
4438 exit(1);
4441 struct print_diff_arg {
4442 struct got_repository *repo;
4443 struct got_worktree *worktree;
4444 int diff_context;
4445 const char *id_str;
4446 int header_shown;
4447 int diff_staged;
4448 int ignore_whitespace;
4449 int force_text_diff;
4453 * Create a file which contains the target path of a symlink so we can feed
4454 * it as content to the diff engine.
4456 static const struct got_error *
4457 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4458 const char *abspath)
4460 const struct got_error *err = NULL;
4461 char target_path[PATH_MAX];
4462 ssize_t target_len, outlen;
4464 *fd = -1;
4466 if (dirfd != -1) {
4467 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4468 if (target_len == -1)
4469 return got_error_from_errno2("readlinkat", abspath);
4470 } else {
4471 target_len = readlink(abspath, target_path, PATH_MAX);
4472 if (target_len == -1)
4473 return got_error_from_errno2("readlink", abspath);
4476 *fd = got_opentempfd();
4477 if (*fd == -1)
4478 return got_error_from_errno("got_opentempfd");
4480 outlen = write(*fd, target_path, target_len);
4481 if (outlen == -1) {
4482 err = got_error_from_errno("got_opentempfd");
4483 goto done;
4486 if (lseek(*fd, 0, SEEK_SET) == -1) {
4487 err = got_error_from_errno2("lseek", abspath);
4488 goto done;
4490 done:
4491 if (err) {
4492 close(*fd);
4493 *fd = -1;
4495 return err;
4498 static const struct got_error *
4499 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4500 const char *path, struct got_object_id *blob_id,
4501 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4502 int dirfd, const char *de_name)
4504 struct print_diff_arg *a = arg;
4505 const struct got_error *err = NULL;
4506 struct got_blob_object *blob1 = NULL;
4507 int fd = -1;
4508 FILE *f1 = NULL, *f2 = NULL;
4509 char *abspath = NULL, *label1 = NULL;
4510 struct stat sb;
4511 off_t size1 = 0;
4513 if (a->diff_staged) {
4514 if (staged_status != GOT_STATUS_MODIFY &&
4515 staged_status != GOT_STATUS_ADD &&
4516 staged_status != GOT_STATUS_DELETE)
4517 return NULL;
4518 } else {
4519 if (staged_status == GOT_STATUS_DELETE)
4520 return NULL;
4521 if (status == GOT_STATUS_NONEXISTENT)
4522 return got_error_set_errno(ENOENT, path);
4523 if (status != GOT_STATUS_MODIFY &&
4524 status != GOT_STATUS_ADD &&
4525 status != GOT_STATUS_DELETE &&
4526 status != GOT_STATUS_CONFLICT)
4527 return NULL;
4530 if (!a->header_shown) {
4531 printf("diff %s %s%s\n", a->id_str,
4532 got_worktree_get_root_path(a->worktree),
4533 a->diff_staged ? " (staged changes)" : "");
4534 a->header_shown = 1;
4537 if (a->diff_staged) {
4538 const char *label1 = NULL, *label2 = NULL;
4539 switch (staged_status) {
4540 case GOT_STATUS_MODIFY:
4541 label1 = path;
4542 label2 = path;
4543 break;
4544 case GOT_STATUS_ADD:
4545 label2 = path;
4546 break;
4547 case GOT_STATUS_DELETE:
4548 label1 = path;
4549 break;
4550 default:
4551 return got_error(GOT_ERR_FILE_STATUS);
4553 f1 = got_opentemp();
4554 if (f1 == NULL) {
4555 err = got_error_from_errno("got_opentemp");
4556 goto done;
4558 f2 = got_opentemp();
4559 if (f2 == NULL) {
4560 err = got_error_from_errno("got_opentemp");
4561 goto done;
4563 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4564 blob_id, staged_blob_id, label1, label2, a->diff_context,
4565 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4566 goto done;
4569 if (staged_status == GOT_STATUS_ADD ||
4570 staged_status == GOT_STATUS_MODIFY) {
4571 char *id_str;
4572 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4573 8192);
4574 if (err)
4575 goto done;
4576 err = got_object_id_str(&id_str, staged_blob_id);
4577 if (err)
4578 goto done;
4579 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4580 err = got_error_from_errno("asprintf");
4581 free(id_str);
4582 goto done;
4584 free(id_str);
4585 } else if (status != GOT_STATUS_ADD) {
4586 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4587 if (err)
4588 goto done;
4591 if (status != GOT_STATUS_DELETE) {
4592 if (asprintf(&abspath, "%s/%s",
4593 got_worktree_get_root_path(a->worktree), path) == -1) {
4594 err = got_error_from_errno("asprintf");
4595 goto done;
4598 if (dirfd != -1) {
4599 fd = openat(dirfd, de_name,
4600 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4601 if (fd == -1) {
4602 if (!got_err_open_nofollow_on_symlink()) {
4603 err = got_error_from_errno2("openat",
4604 abspath);
4605 goto done;
4607 err = get_symlink_target_file(&fd, dirfd,
4608 de_name, abspath);
4609 if (err)
4610 goto done;
4612 } else {
4613 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4614 if (fd == -1) {
4615 if (!got_err_open_nofollow_on_symlink()) {
4616 err = got_error_from_errno2("open",
4617 abspath);
4618 goto done;
4620 err = get_symlink_target_file(&fd, dirfd,
4621 de_name, abspath);
4622 if (err)
4623 goto done;
4626 if (fstat(fd, &sb) == -1) {
4627 err = got_error_from_errno2("fstat", abspath);
4628 goto done;
4630 f2 = fdopen(fd, "r");
4631 if (f2 == NULL) {
4632 err = got_error_from_errno2("fdopen", abspath);
4633 goto done;
4635 fd = -1;
4636 } else
4637 sb.st_size = 0;
4639 if (blob1) {
4640 f1 = got_opentemp();
4641 if (f1 == NULL) {
4642 err = got_error_from_errno("got_opentemp");
4643 goto done;
4645 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4646 blob1);
4647 if (err)
4648 goto done;
4651 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4652 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4653 stdout);
4654 done:
4655 if (blob1)
4656 got_object_blob_close(blob1);
4657 if (f1 && fclose(f1) == EOF && err == NULL)
4658 err = got_error_from_errno("fclose");
4659 if (f2 && fclose(f2) == EOF && err == NULL)
4660 err = got_error_from_errno("fclose");
4661 if (fd != -1 && close(fd) == -1 && err == NULL)
4662 err = got_error_from_errno("close");
4663 free(abspath);
4664 return err;
4667 static const struct got_error *
4668 cmd_diff(int argc, char *argv[])
4670 const struct got_error *error;
4671 struct got_repository *repo = NULL;
4672 struct got_worktree *worktree = NULL;
4673 char *cwd = NULL, *repo_path = NULL;
4674 const char *commit_args[2] = { NULL, NULL };
4675 int ncommit_args = 0;
4676 struct got_object_id *ids[2] = { NULL, NULL };
4677 char *labels[2] = { NULL, NULL };
4678 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4679 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4680 int force_text_diff = 0, force_path = 0, rflag = 0;
4681 const char *errstr;
4682 struct got_reflist_head refs;
4683 struct got_pathlist_head paths;
4684 struct got_pathlist_entry *pe;
4685 FILE *f1 = NULL, *f2 = NULL;
4687 TAILQ_INIT(&refs);
4688 TAILQ_INIT(&paths);
4690 #ifndef PROFILE
4691 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4692 NULL) == -1)
4693 err(1, "pledge");
4694 #endif
4696 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4697 switch (ch) {
4698 case 'a':
4699 force_text_diff = 1;
4700 break;
4701 case 'c':
4702 if (ncommit_args >= 2)
4703 errx(1, "too many -c options used");
4704 commit_args[ncommit_args++] = optarg;
4705 break;
4706 case 'C':
4707 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4708 &errstr);
4709 if (errstr != NULL)
4710 errx(1, "number of context lines is %s: %s",
4711 errstr, optarg);
4712 break;
4713 case 'r':
4714 repo_path = realpath(optarg, NULL);
4715 if (repo_path == NULL)
4716 return got_error_from_errno2("realpath",
4717 optarg);
4718 got_path_strip_trailing_slashes(repo_path);
4719 rflag = 1;
4720 break;
4721 case 's':
4722 diff_staged = 1;
4723 break;
4724 case 'w':
4725 ignore_whitespace = 1;
4726 break;
4727 case 'P':
4728 force_path = 1;
4729 break;
4730 default:
4731 usage_diff();
4732 /* NOTREACHED */
4736 argc -= optind;
4737 argv += optind;
4739 cwd = getcwd(NULL, 0);
4740 if (cwd == NULL) {
4741 error = got_error_from_errno("getcwd");
4742 goto done;
4745 if (repo_path == NULL) {
4746 error = got_worktree_open(&worktree, cwd);
4747 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4748 goto done;
4749 else
4750 error = NULL;
4751 if (worktree) {
4752 repo_path =
4753 strdup(got_worktree_get_repo_path(worktree));
4754 if (repo_path == NULL) {
4755 error = got_error_from_errno("strdup");
4756 goto done;
4758 } else {
4759 repo_path = strdup(cwd);
4760 if (repo_path == NULL) {
4761 error = got_error_from_errno("strdup");
4762 goto done;
4767 error = got_repo_open(&repo, repo_path, NULL);
4768 free(repo_path);
4769 if (error != NULL)
4770 goto done;
4772 if (rflag || worktree == NULL || ncommit_args > 0) {
4773 if (force_path) {
4774 error = got_error_msg(GOT_ERR_NOT_IMPL,
4775 "-P option can only be used when diffing "
4776 "a work tree");
4777 goto done;
4779 if (diff_staged) {
4780 error = got_error_msg(GOT_ERR_NOT_IMPL,
4781 "-s option can only be used when diffing "
4782 "a work tree");
4783 goto done;
4787 error = apply_unveil(got_repo_get_path(repo), 1,
4788 worktree ? got_worktree_get_root_path(worktree) : NULL);
4789 if (error)
4790 goto done;
4792 if ((!force_path && argc == 2) || ncommit_args > 0) {
4793 int obj_type = (ncommit_args > 0 ?
4794 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4795 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4796 NULL);
4797 if (error)
4798 goto done;
4799 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4800 const char *arg;
4801 if (ncommit_args > 0)
4802 arg = commit_args[i];
4803 else
4804 arg = argv[i];
4805 error = got_repo_match_object_id(&ids[i], &labels[i],
4806 arg, obj_type, &refs, repo);
4807 if (error) {
4808 if (error->code != GOT_ERR_NOT_REF &&
4809 error->code != GOT_ERR_NO_OBJ)
4810 goto done;
4811 if (ncommit_args > 0)
4812 goto done;
4813 error = NULL;
4814 break;
4819 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4820 struct print_diff_arg arg;
4821 char *id_str;
4823 if (worktree == NULL) {
4824 if (argc == 2 && ids[0] == NULL) {
4825 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4826 goto done;
4827 } else if (argc == 2 && ids[1] == NULL) {
4828 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4829 goto done;
4830 } else if (argc > 0) {
4831 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4832 "%s", "specified paths cannot be resolved");
4833 goto done;
4834 } else {
4835 error = got_error(GOT_ERR_NOT_WORKTREE);
4836 goto done;
4840 error = get_worktree_paths_from_argv(&paths, argc, argv,
4841 worktree);
4842 if (error)
4843 goto done;
4845 error = got_object_id_str(&id_str,
4846 got_worktree_get_base_commit_id(worktree));
4847 if (error)
4848 goto done;
4849 arg.repo = repo;
4850 arg.worktree = worktree;
4851 arg.diff_context = diff_context;
4852 arg.id_str = id_str;
4853 arg.header_shown = 0;
4854 arg.diff_staged = diff_staged;
4855 arg.ignore_whitespace = ignore_whitespace;
4856 arg.force_text_diff = force_text_diff;
4858 error = got_worktree_status(worktree, &paths, repo, 0,
4859 print_diff, &arg, check_cancelled, NULL);
4860 free(id_str);
4861 goto done;
4864 if (ncommit_args == 1) {
4865 struct got_commit_object *commit;
4866 error = got_object_open_as_commit(&commit, repo, ids[0]);
4867 if (error)
4868 goto done;
4870 labels[1] = labels[0];
4871 ids[1] = ids[0];
4872 if (got_object_commit_get_nparents(commit) > 0) {
4873 const struct got_object_id_queue *pids;
4874 struct got_object_qid *pid;
4875 pids = got_object_commit_get_parent_ids(commit);
4876 pid = STAILQ_FIRST(pids);
4877 ids[0] = got_object_id_dup(&pid->id);
4878 if (ids[0] == NULL) {
4879 error = got_error_from_errno(
4880 "got_object_id_dup");
4881 got_object_commit_close(commit);
4882 goto done;
4884 error = got_object_id_str(&labels[0], ids[0]);
4885 if (error) {
4886 got_object_commit_close(commit);
4887 goto done;
4889 } else {
4890 ids[0] = NULL;
4891 labels[0] = strdup("/dev/null");
4892 if (labels[0] == NULL) {
4893 error = got_error_from_errno("strdup");
4894 got_object_commit_close(commit);
4895 goto done;
4899 got_object_commit_close(commit);
4902 if (ncommit_args == 0 && argc > 2) {
4903 error = got_error_msg(GOT_ERR_BAD_PATH,
4904 "path arguments cannot be used when diffing two objects");
4905 goto done;
4908 if (ids[0]) {
4909 error = got_object_get_type(&type1, repo, ids[0]);
4910 if (error)
4911 goto done;
4914 error = got_object_get_type(&type2, repo, ids[1]);
4915 if (error)
4916 goto done;
4917 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4918 error = got_error(GOT_ERR_OBJ_TYPE);
4919 goto done;
4921 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4922 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4923 "path arguments cannot be used when diffing blobs");
4924 goto done;
4927 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4928 char *in_repo_path;
4929 struct got_pathlist_entry *new;
4930 if (worktree) {
4931 const char *prefix;
4932 char *p;
4933 error = got_worktree_resolve_path(&p, worktree,
4934 argv[i]);
4935 if (error)
4936 goto done;
4937 prefix = got_worktree_get_path_prefix(worktree);
4938 while (prefix[0] == '/')
4939 prefix++;
4940 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4941 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4942 p) == -1) {
4943 error = got_error_from_errno("asprintf");
4944 free(p);
4945 goto done;
4947 free(p);
4948 } else {
4949 char *mapped_path, *s;
4950 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4951 if (error)
4952 goto done;
4953 s = mapped_path;
4954 while (s[0] == '/')
4955 s++;
4956 in_repo_path = strdup(s);
4957 if (in_repo_path == NULL) {
4958 error = got_error_from_errno("asprintf");
4959 free(mapped_path);
4960 goto done;
4962 free(mapped_path);
4965 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4966 if (error || new == NULL /* duplicate */)
4967 free(in_repo_path);
4968 if (error)
4969 goto done;
4972 if (worktree) {
4973 /* Release work tree lock. */
4974 got_worktree_close(worktree);
4975 worktree = NULL;
4978 f1 = got_opentemp();
4979 if (f1 == NULL) {
4980 error = got_error_from_errno("got_opentemp");
4981 goto done;
4984 f2 = got_opentemp();
4985 if (f2 == NULL) {
4986 error = got_error_from_errno("got_opentemp");
4987 goto done;
4990 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4991 case GOT_OBJ_TYPE_BLOB:
4992 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4993 ids[0], ids[1], NULL, NULL, diff_context,
4994 ignore_whitespace, force_text_diff, repo, stdout);
4995 break;
4996 case GOT_OBJ_TYPE_TREE:
4997 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
4998 ids[0], ids[1], &paths, "", "", diff_context,
4999 ignore_whitespace, force_text_diff, repo, stdout);
5000 break;
5001 case GOT_OBJ_TYPE_COMMIT:
5002 printf("diff %s %s\n", labels[0], labels[1]);
5003 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5004 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5005 force_text_diff, repo, stdout);
5006 break;
5007 default:
5008 error = got_error(GOT_ERR_OBJ_TYPE);
5010 done:
5011 free(labels[0]);
5012 free(labels[1]);
5013 free(ids[0]);
5014 free(ids[1]);
5015 if (worktree)
5016 got_worktree_close(worktree);
5017 if (repo) {
5018 const struct got_error *close_err = got_repo_close(repo);
5019 if (error == NULL)
5020 error = close_err;
5022 TAILQ_FOREACH(pe, &paths, entry)
5023 free((char *)pe->path);
5024 got_pathlist_free(&paths);
5025 got_ref_list_free(&refs);
5026 if (f1 && fclose(f1) == EOF && error == NULL)
5027 error = got_error_from_errno("fclose");
5028 if (f2 && fclose(f2) == EOF && error == NULL)
5029 error = got_error_from_errno("fclose");
5030 return error;
5033 __dead static void
5034 usage_blame(void)
5036 fprintf(stderr,
5037 "usage: %s blame [-c commit] [-r repository-path] path\n",
5038 getprogname());
5039 exit(1);
5042 struct blame_line {
5043 int annotated;
5044 char *id_str;
5045 char *committer;
5046 char datebuf[11]; /* YYYY-MM-DD + NUL */
5049 struct blame_cb_args {
5050 struct blame_line *lines;
5051 int nlines;
5052 int nlines_prec;
5053 int lineno_cur;
5054 off_t *line_offsets;
5055 FILE *f;
5056 struct got_repository *repo;
5059 static const struct got_error *
5060 blame_cb(void *arg, int nlines, int lineno,
5061 struct got_commit_object *commit, struct got_object_id *id)
5063 const struct got_error *err = NULL;
5064 struct blame_cb_args *a = arg;
5065 struct blame_line *bline;
5066 char *line = NULL;
5067 size_t linesize = 0;
5068 off_t offset;
5069 struct tm tm;
5070 time_t committer_time;
5072 if (nlines != a->nlines ||
5073 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5074 return got_error(GOT_ERR_RANGE);
5076 if (sigint_received)
5077 return got_error(GOT_ERR_ITER_COMPLETED);
5079 if (lineno == -1)
5080 return NULL; /* no change in this commit */
5082 /* Annotate this line. */
5083 bline = &a->lines[lineno - 1];
5084 if (bline->annotated)
5085 return NULL;
5086 err = got_object_id_str(&bline->id_str, id);
5087 if (err)
5088 return err;
5090 bline->committer = strdup(got_object_commit_get_committer(commit));
5091 if (bline->committer == NULL) {
5092 err = got_error_from_errno("strdup");
5093 goto done;
5096 committer_time = got_object_commit_get_committer_time(commit);
5097 if (gmtime_r(&committer_time, &tm) == NULL)
5098 return got_error_from_errno("gmtime_r");
5099 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5100 &tm) == 0) {
5101 err = got_error(GOT_ERR_NO_SPACE);
5102 goto done;
5104 bline->annotated = 1;
5106 /* Print lines annotated so far. */
5107 bline = &a->lines[a->lineno_cur - 1];
5108 if (!bline->annotated)
5109 goto done;
5111 offset = a->line_offsets[a->lineno_cur - 1];
5112 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5113 err = got_error_from_errno("fseeko");
5114 goto done;
5117 while (bline->annotated) {
5118 char *smallerthan, *at, *nl, *committer;
5119 size_t len;
5121 if (getline(&line, &linesize, a->f) == -1) {
5122 if (ferror(a->f))
5123 err = got_error_from_errno("getline");
5124 break;
5127 committer = bline->committer;
5128 smallerthan = strchr(committer, '<');
5129 if (smallerthan && smallerthan[1] != '\0')
5130 committer = smallerthan + 1;
5131 at = strchr(committer, '@');
5132 if (at)
5133 *at = '\0';
5134 len = strlen(committer);
5135 if (len >= 9)
5136 committer[8] = '\0';
5138 nl = strchr(line, '\n');
5139 if (nl)
5140 *nl = '\0';
5141 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5142 bline->id_str, bline->datebuf, committer, line);
5144 a->lineno_cur++;
5145 bline = &a->lines[a->lineno_cur - 1];
5147 done:
5148 free(line);
5149 return err;
5152 static const struct got_error *
5153 cmd_blame(int argc, char *argv[])
5155 const struct got_error *error;
5156 struct got_repository *repo = NULL;
5157 struct got_worktree *worktree = NULL;
5158 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5159 char *link_target = NULL;
5160 struct got_object_id *obj_id = NULL;
5161 struct got_object_id *commit_id = NULL;
5162 struct got_commit_object *commit = NULL;
5163 struct got_blob_object *blob = NULL;
5164 char *commit_id_str = NULL;
5165 struct blame_cb_args bca;
5166 int ch, obj_type, i;
5167 off_t filesize;
5169 memset(&bca, 0, sizeof(bca));
5171 #ifndef PROFILE
5172 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5173 NULL) == -1)
5174 err(1, "pledge");
5175 #endif
5177 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5178 switch (ch) {
5179 case 'c':
5180 commit_id_str = optarg;
5181 break;
5182 case 'r':
5183 repo_path = realpath(optarg, NULL);
5184 if (repo_path == NULL)
5185 return got_error_from_errno2("realpath",
5186 optarg);
5187 got_path_strip_trailing_slashes(repo_path);
5188 break;
5189 default:
5190 usage_blame();
5191 /* NOTREACHED */
5195 argc -= optind;
5196 argv += optind;
5198 if (argc == 1)
5199 path = argv[0];
5200 else
5201 usage_blame();
5203 cwd = getcwd(NULL, 0);
5204 if (cwd == NULL) {
5205 error = got_error_from_errno("getcwd");
5206 goto done;
5208 if (repo_path == NULL) {
5209 error = got_worktree_open(&worktree, cwd);
5210 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5211 goto done;
5212 else
5213 error = NULL;
5214 if (worktree) {
5215 repo_path =
5216 strdup(got_worktree_get_repo_path(worktree));
5217 if (repo_path == NULL) {
5218 error = got_error_from_errno("strdup");
5219 if (error)
5220 goto done;
5222 } else {
5223 repo_path = strdup(cwd);
5224 if (repo_path == NULL) {
5225 error = got_error_from_errno("strdup");
5226 goto done;
5231 error = got_repo_open(&repo, repo_path, NULL);
5232 if (error != NULL)
5233 goto done;
5235 if (worktree) {
5236 const char *prefix = got_worktree_get_path_prefix(worktree);
5237 char *p;
5239 error = got_worktree_resolve_path(&p, worktree, path);
5240 if (error)
5241 goto done;
5242 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5243 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5244 p) == -1) {
5245 error = got_error_from_errno("asprintf");
5246 free(p);
5247 goto done;
5249 free(p);
5250 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5251 } else {
5252 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5253 if (error)
5254 goto done;
5255 error = got_repo_map_path(&in_repo_path, repo, path);
5257 if (error)
5258 goto done;
5260 if (commit_id_str == NULL) {
5261 struct got_reference *head_ref;
5262 error = got_ref_open(&head_ref, repo, worktree ?
5263 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5264 if (error != NULL)
5265 goto done;
5266 error = got_ref_resolve(&commit_id, repo, head_ref);
5267 got_ref_close(head_ref);
5268 if (error != NULL)
5269 goto done;
5270 } else {
5271 struct got_reflist_head refs;
5272 TAILQ_INIT(&refs);
5273 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5274 NULL);
5275 if (error)
5276 goto done;
5277 error = got_repo_match_object_id(&commit_id, NULL,
5278 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5279 got_ref_list_free(&refs);
5280 if (error)
5281 goto done;
5284 if (worktree) {
5285 /* Release work tree lock. */
5286 got_worktree_close(worktree);
5287 worktree = NULL;
5290 error = got_object_open_as_commit(&commit, repo, commit_id);
5291 if (error)
5292 goto done;
5294 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5295 commit, repo);
5296 if (error)
5297 goto done;
5299 error = got_object_id_by_path(&obj_id, repo, commit,
5300 link_target ? link_target : in_repo_path);
5301 if (error)
5302 goto done;
5304 error = got_object_get_type(&obj_type, repo, obj_id);
5305 if (error)
5306 goto done;
5308 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5309 error = got_error_path(link_target ? link_target : in_repo_path,
5310 GOT_ERR_OBJ_TYPE);
5311 goto done;
5314 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5315 if (error)
5316 goto done;
5317 bca.f = got_opentemp();
5318 if (bca.f == NULL) {
5319 error = got_error_from_errno("got_opentemp");
5320 goto done;
5322 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5323 &bca.line_offsets, bca.f, blob);
5324 if (error || bca.nlines == 0)
5325 goto done;
5327 /* Don't include \n at EOF in the blame line count. */
5328 if (bca.line_offsets[bca.nlines - 1] == filesize)
5329 bca.nlines--;
5331 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5332 if (bca.lines == NULL) {
5333 error = got_error_from_errno("calloc");
5334 goto done;
5336 bca.lineno_cur = 1;
5337 bca.nlines_prec = 0;
5338 i = bca.nlines;
5339 while (i > 0) {
5340 i /= 10;
5341 bca.nlines_prec++;
5343 bca.repo = repo;
5345 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5346 repo, blame_cb, &bca, check_cancelled, NULL);
5347 done:
5348 free(in_repo_path);
5349 free(link_target);
5350 free(repo_path);
5351 free(cwd);
5352 free(commit_id);
5353 free(obj_id);
5354 if (commit)
5355 got_object_commit_close(commit);
5356 if (blob)
5357 got_object_blob_close(blob);
5358 if (worktree)
5359 got_worktree_close(worktree);
5360 if (repo) {
5361 const struct got_error *close_err = got_repo_close(repo);
5362 if (error == NULL)
5363 error = close_err;
5365 if (bca.lines) {
5366 for (i = 0; i < bca.nlines; i++) {
5367 struct blame_line *bline = &bca.lines[i];
5368 free(bline->id_str);
5369 free(bline->committer);
5371 free(bca.lines);
5373 free(bca.line_offsets);
5374 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5375 error = got_error_from_errno("fclose");
5376 return error;
5379 __dead static void
5380 usage_tree(void)
5382 fprintf(stderr,
5383 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5384 getprogname());
5385 exit(1);
5388 static const struct got_error *
5389 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5390 const char *root_path, struct got_repository *repo)
5392 const struct got_error *err = NULL;
5393 int is_root_path = (strcmp(path, root_path) == 0);
5394 const char *modestr = "";
5395 mode_t mode = got_tree_entry_get_mode(te);
5396 char *link_target = NULL;
5398 path += strlen(root_path);
5399 while (path[0] == '/')
5400 path++;
5402 if (got_object_tree_entry_is_submodule(te))
5403 modestr = "$";
5404 else if (S_ISLNK(mode)) {
5405 int i;
5407 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5408 if (err)
5409 return err;
5410 for (i = 0; i < strlen(link_target); i++) {
5411 if (!isprint((unsigned char)link_target[i]))
5412 link_target[i] = '?';
5415 modestr = "@";
5417 else if (S_ISDIR(mode))
5418 modestr = "/";
5419 else if (mode & S_IXUSR)
5420 modestr = "*";
5422 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5423 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5424 link_target ? " -> ": "", link_target ? link_target : "");
5426 free(link_target);
5427 return NULL;
5430 static const struct got_error *
5431 print_tree(const char *path, struct got_commit_object *commit,
5432 int show_ids, int recurse, const char *root_path,
5433 struct got_repository *repo)
5435 const struct got_error *err = NULL;
5436 struct got_object_id *tree_id = NULL;
5437 struct got_tree_object *tree = NULL;
5438 int nentries, i;
5440 err = got_object_id_by_path(&tree_id, repo, commit, path);
5441 if (err)
5442 goto done;
5444 err = got_object_open_as_tree(&tree, repo, tree_id);
5445 if (err)
5446 goto done;
5447 nentries = got_object_tree_get_nentries(tree);
5448 for (i = 0; i < nentries; i++) {
5449 struct got_tree_entry *te;
5450 char *id = NULL;
5452 if (sigint_received || sigpipe_received)
5453 break;
5455 te = got_object_tree_get_entry(tree, i);
5456 if (show_ids) {
5457 char *id_str;
5458 err = got_object_id_str(&id_str,
5459 got_tree_entry_get_id(te));
5460 if (err)
5461 goto done;
5462 if (asprintf(&id, "%s ", id_str) == -1) {
5463 err = got_error_from_errno("asprintf");
5464 free(id_str);
5465 goto done;
5467 free(id_str);
5469 err = print_entry(te, id, path, root_path, repo);
5470 free(id);
5471 if (err)
5472 goto done;
5474 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5475 char *child_path;
5476 if (asprintf(&child_path, "%s%s%s", path,
5477 path[0] == '/' && path[1] == '\0' ? "" : "/",
5478 got_tree_entry_get_name(te)) == -1) {
5479 err = got_error_from_errno("asprintf");
5480 goto done;
5482 err = print_tree(child_path, commit, show_ids, 1,
5483 root_path, repo);
5484 free(child_path);
5485 if (err)
5486 goto done;
5489 done:
5490 if (tree)
5491 got_object_tree_close(tree);
5492 free(tree_id);
5493 return err;
5496 static const struct got_error *
5497 cmd_tree(int argc, char *argv[])
5499 const struct got_error *error;
5500 struct got_repository *repo = NULL;
5501 struct got_worktree *worktree = NULL;
5502 const char *path, *refname = NULL;
5503 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5504 struct got_object_id *commit_id = NULL;
5505 struct got_commit_object *commit = NULL;
5506 char *commit_id_str = NULL;
5507 int show_ids = 0, recurse = 0;
5508 int ch;
5510 #ifndef PROFILE
5511 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5512 NULL) == -1)
5513 err(1, "pledge");
5514 #endif
5516 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5517 switch (ch) {
5518 case 'c':
5519 commit_id_str = optarg;
5520 break;
5521 case 'r':
5522 repo_path = realpath(optarg, NULL);
5523 if (repo_path == NULL)
5524 return got_error_from_errno2("realpath",
5525 optarg);
5526 got_path_strip_trailing_slashes(repo_path);
5527 break;
5528 case 'i':
5529 show_ids = 1;
5530 break;
5531 case 'R':
5532 recurse = 1;
5533 break;
5534 default:
5535 usage_tree();
5536 /* NOTREACHED */
5540 argc -= optind;
5541 argv += optind;
5543 if (argc == 1)
5544 path = argv[0];
5545 else if (argc > 1)
5546 usage_tree();
5547 else
5548 path = NULL;
5550 cwd = getcwd(NULL, 0);
5551 if (cwd == NULL) {
5552 error = got_error_from_errno("getcwd");
5553 goto done;
5555 if (repo_path == NULL) {
5556 error = got_worktree_open(&worktree, cwd);
5557 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5558 goto done;
5559 else
5560 error = NULL;
5561 if (worktree) {
5562 repo_path =
5563 strdup(got_worktree_get_repo_path(worktree));
5564 if (repo_path == NULL)
5565 error = got_error_from_errno("strdup");
5566 if (error)
5567 goto done;
5568 } else {
5569 repo_path = strdup(cwd);
5570 if (repo_path == NULL) {
5571 error = got_error_from_errno("strdup");
5572 goto done;
5577 error = got_repo_open(&repo, repo_path, NULL);
5578 if (error != NULL)
5579 goto done;
5581 if (worktree) {
5582 const char *prefix = got_worktree_get_path_prefix(worktree);
5583 char *p;
5585 if (path == NULL)
5586 path = "";
5587 error = got_worktree_resolve_path(&p, worktree, path);
5588 if (error)
5589 goto done;
5590 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5591 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5592 p) == -1) {
5593 error = got_error_from_errno("asprintf");
5594 free(p);
5595 goto done;
5597 free(p);
5598 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5599 if (error)
5600 goto done;
5601 } else {
5602 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5603 if (error)
5604 goto done;
5605 if (path == NULL)
5606 path = "/";
5607 error = got_repo_map_path(&in_repo_path, repo, path);
5608 if (error != NULL)
5609 goto done;
5612 if (commit_id_str == NULL) {
5613 struct got_reference *head_ref;
5614 if (worktree)
5615 refname = got_worktree_get_head_ref_name(worktree);
5616 else
5617 refname = GOT_REF_HEAD;
5618 error = got_ref_open(&head_ref, repo, refname, 0);
5619 if (error != NULL)
5620 goto done;
5621 error = got_ref_resolve(&commit_id, repo, head_ref);
5622 got_ref_close(head_ref);
5623 if (error != NULL)
5624 goto done;
5625 } else {
5626 struct got_reflist_head refs;
5627 TAILQ_INIT(&refs);
5628 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5629 NULL);
5630 if (error)
5631 goto done;
5632 error = got_repo_match_object_id(&commit_id, NULL,
5633 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5634 got_ref_list_free(&refs);
5635 if (error)
5636 goto done;
5639 if (worktree) {
5640 /* Release work tree lock. */
5641 got_worktree_close(worktree);
5642 worktree = NULL;
5645 error = got_object_open_as_commit(&commit, repo, commit_id);
5646 if (error)
5647 goto done;
5649 error = print_tree(in_repo_path, commit, show_ids, recurse,
5650 in_repo_path, repo);
5651 done:
5652 free(in_repo_path);
5653 free(repo_path);
5654 free(cwd);
5655 free(commit_id);
5656 if (commit)
5657 got_object_commit_close(commit);
5658 if (worktree)
5659 got_worktree_close(worktree);
5660 if (repo) {
5661 const struct got_error *close_err = got_repo_close(repo);
5662 if (error == NULL)
5663 error = close_err;
5665 return error;
5668 __dead static void
5669 usage_status(void)
5671 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5672 "[-S status-codes] [path ...]\n", getprogname());
5673 exit(1);
5676 struct got_status_arg {
5677 char *status_codes;
5678 int suppress;
5681 static const struct got_error *
5682 print_status(void *arg, unsigned char status, unsigned char staged_status,
5683 const char *path, struct got_object_id *blob_id,
5684 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5685 int dirfd, const char *de_name)
5687 struct got_status_arg *st = arg;
5689 if (status == staged_status && (status == GOT_STATUS_DELETE))
5690 status = GOT_STATUS_NO_CHANGE;
5691 if (st != NULL && st->status_codes) {
5692 size_t ncodes = strlen(st->status_codes);
5693 int i, j = 0;
5695 for (i = 0; i < ncodes ; i++) {
5696 if (st->suppress) {
5697 if (status == st->status_codes[i] ||
5698 staged_status == st->status_codes[i]) {
5699 j++;
5700 continue;
5702 } else {
5703 if (status == st->status_codes[i] ||
5704 staged_status == st->status_codes[i])
5705 break;
5709 if (st->suppress && j == 0)
5710 goto print;
5712 if (i == ncodes)
5713 return NULL;
5715 print:
5716 printf("%c%c %s\n", status, staged_status, path);
5717 return NULL;
5720 static const struct got_error *
5721 cmd_status(int argc, char *argv[])
5723 const struct got_error *error = NULL;
5724 struct got_repository *repo = NULL;
5725 struct got_worktree *worktree = NULL;
5726 struct got_status_arg st;
5727 char *cwd = NULL;
5728 struct got_pathlist_head paths;
5729 struct got_pathlist_entry *pe;
5730 int ch, i, no_ignores = 0;
5732 TAILQ_INIT(&paths);
5734 memset(&st, 0, sizeof(st));
5735 st.status_codes = NULL;
5736 st.suppress = 0;
5738 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5739 switch (ch) {
5740 case 'I':
5741 no_ignores = 1;
5742 break;
5743 case 'S':
5744 if (st.status_codes != NULL && st.suppress == 0)
5745 option_conflict('S', 's');
5746 st.suppress = 1;
5747 /* fallthrough */
5748 case 's':
5749 for (i = 0; i < strlen(optarg); i++) {
5750 switch (optarg[i]) {
5751 case GOT_STATUS_MODIFY:
5752 case GOT_STATUS_ADD:
5753 case GOT_STATUS_DELETE:
5754 case GOT_STATUS_CONFLICT:
5755 case GOT_STATUS_MISSING:
5756 case GOT_STATUS_OBSTRUCTED:
5757 case GOT_STATUS_UNVERSIONED:
5758 case GOT_STATUS_MODE_CHANGE:
5759 case GOT_STATUS_NONEXISTENT:
5760 break;
5761 default:
5762 errx(1, "invalid status code '%c'",
5763 optarg[i]);
5766 if (ch == 's' && st.suppress)
5767 option_conflict('s', 'S');
5768 st.status_codes = optarg;
5769 break;
5770 default:
5771 usage_status();
5772 /* NOTREACHED */
5776 argc -= optind;
5777 argv += optind;
5779 #ifndef PROFILE
5780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5781 NULL) == -1)
5782 err(1, "pledge");
5783 #endif
5784 cwd = getcwd(NULL, 0);
5785 if (cwd == NULL) {
5786 error = got_error_from_errno("getcwd");
5787 goto done;
5790 error = got_worktree_open(&worktree, cwd);
5791 if (error) {
5792 if (error->code == GOT_ERR_NOT_WORKTREE)
5793 error = wrap_not_worktree_error(error, "status", cwd);
5794 goto done;
5797 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5798 NULL);
5799 if (error != NULL)
5800 goto done;
5802 error = apply_unveil(got_repo_get_path(repo), 1,
5803 got_worktree_get_root_path(worktree));
5804 if (error)
5805 goto done;
5807 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5808 if (error)
5809 goto done;
5811 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5812 print_status, &st, check_cancelled, NULL);
5813 done:
5814 TAILQ_FOREACH(pe, &paths, entry)
5815 free((char *)pe->path);
5816 got_pathlist_free(&paths);
5817 free(cwd);
5818 return error;
5821 __dead static void
5822 usage_ref(void)
5824 fprintf(stderr,
5825 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5826 "[-s reference] [-d] [name]\n",
5827 getprogname());
5828 exit(1);
5831 static const struct got_error *
5832 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5834 static const struct got_error *err = NULL;
5835 struct got_reflist_head refs;
5836 struct got_reflist_entry *re;
5838 TAILQ_INIT(&refs);
5839 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5840 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5841 repo);
5842 if (err)
5843 return err;
5845 TAILQ_FOREACH(re, &refs, entry) {
5846 char *refstr;
5847 refstr = got_ref_to_str(re->ref);
5848 if (refstr == NULL) {
5849 err = got_error_from_errno("got_ref_to_str");
5850 break;
5852 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5853 free(refstr);
5856 got_ref_list_free(&refs);
5857 return err;
5860 static const struct got_error *
5861 delete_ref_by_name(struct got_repository *repo, const char *refname)
5863 const struct got_error *err;
5864 struct got_reference *ref;
5866 err = got_ref_open(&ref, repo, refname, 0);
5867 if (err)
5868 return err;
5870 err = delete_ref(repo, ref);
5871 got_ref_close(ref);
5872 return err;
5875 static const struct got_error *
5876 add_ref(struct got_repository *repo, const char *refname, const char *target)
5878 const struct got_error *err = NULL;
5879 struct got_object_id *id = NULL;
5880 struct got_reference *ref = NULL;
5881 struct got_reflist_head refs;
5884 * Don't let the user create a reference name with a leading '-'.
5885 * While technically a valid reference name, this case is usually
5886 * an unintended typo.
5888 if (refname[0] == '-')
5889 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5891 TAILQ_INIT(&refs);
5892 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5893 if (err)
5894 goto done;
5895 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5896 &refs, repo);
5897 got_ref_list_free(&refs);
5898 if (err)
5899 goto done;
5901 err = got_ref_alloc(&ref, refname, id);
5902 if (err)
5903 goto done;
5905 err = got_ref_write(ref, repo);
5906 done:
5907 if (ref)
5908 got_ref_close(ref);
5909 free(id);
5910 return err;
5913 static const struct got_error *
5914 add_symref(struct got_repository *repo, const char *refname, const char *target)
5916 const struct got_error *err = NULL;
5917 struct got_reference *ref = NULL;
5918 struct got_reference *target_ref = NULL;
5921 * Don't let the user create a reference name with a leading '-'.
5922 * While technically a valid reference name, this case is usually
5923 * an unintended typo.
5925 if (refname[0] == '-')
5926 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5928 err = got_ref_open(&target_ref, repo, target, 0);
5929 if (err)
5930 return err;
5932 err = got_ref_alloc_symref(&ref, refname, target_ref);
5933 if (err)
5934 goto done;
5936 err = got_ref_write(ref, repo);
5937 done:
5938 if (target_ref)
5939 got_ref_close(target_ref);
5940 if (ref)
5941 got_ref_close(ref);
5942 return err;
5945 static const struct got_error *
5946 cmd_ref(int argc, char *argv[])
5948 const struct got_error *error = NULL;
5949 struct got_repository *repo = NULL;
5950 struct got_worktree *worktree = NULL;
5951 char *cwd = NULL, *repo_path = NULL;
5952 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5953 const char *obj_arg = NULL, *symref_target= NULL;
5954 char *refname = NULL;
5956 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5957 switch (ch) {
5958 case 'c':
5959 obj_arg = optarg;
5960 break;
5961 case 'd':
5962 do_delete = 1;
5963 break;
5964 case 'r':
5965 repo_path = realpath(optarg, NULL);
5966 if (repo_path == NULL)
5967 return got_error_from_errno2("realpath",
5968 optarg);
5969 got_path_strip_trailing_slashes(repo_path);
5970 break;
5971 case 'l':
5972 do_list = 1;
5973 break;
5974 case 's':
5975 symref_target = optarg;
5976 break;
5977 case 't':
5978 sort_by_time = 1;
5979 break;
5980 default:
5981 usage_ref();
5982 /* NOTREACHED */
5986 if (obj_arg && do_list)
5987 option_conflict('c', 'l');
5988 if (obj_arg && do_delete)
5989 option_conflict('c', 'd');
5990 if (obj_arg && symref_target)
5991 option_conflict('c', 's');
5992 if (symref_target && do_delete)
5993 option_conflict('s', 'd');
5994 if (symref_target && do_list)
5995 option_conflict('s', 'l');
5996 if (do_delete && do_list)
5997 option_conflict('d', 'l');
5998 if (sort_by_time && !do_list)
5999 errx(1, "-t option requires -l option");
6001 argc -= optind;
6002 argv += optind;
6004 if (do_list) {
6005 if (argc != 0 && argc != 1)
6006 usage_ref();
6007 if (argc == 1) {
6008 refname = strdup(argv[0]);
6009 if (refname == NULL) {
6010 error = got_error_from_errno("strdup");
6011 goto done;
6014 } else {
6015 if (argc != 1)
6016 usage_ref();
6017 refname = strdup(argv[0]);
6018 if (refname == NULL) {
6019 error = got_error_from_errno("strdup");
6020 goto done;
6024 if (refname)
6025 got_path_strip_trailing_slashes(refname);
6027 #ifndef PROFILE
6028 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6029 "sendfd unveil", NULL) == -1)
6030 err(1, "pledge");
6031 #endif
6032 cwd = getcwd(NULL, 0);
6033 if (cwd == NULL) {
6034 error = got_error_from_errno("getcwd");
6035 goto done;
6038 if (repo_path == NULL) {
6039 error = got_worktree_open(&worktree, cwd);
6040 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6041 goto done;
6042 else
6043 error = NULL;
6044 if (worktree) {
6045 repo_path =
6046 strdup(got_worktree_get_repo_path(worktree));
6047 if (repo_path == NULL)
6048 error = got_error_from_errno("strdup");
6049 if (error)
6050 goto done;
6051 } else {
6052 repo_path = strdup(cwd);
6053 if (repo_path == NULL) {
6054 error = got_error_from_errno("strdup");
6055 goto done;
6060 error = got_repo_open(&repo, repo_path, NULL);
6061 if (error != NULL)
6062 goto done;
6064 #ifndef PROFILE
6065 if (do_list) {
6066 /* Remove "cpath" promise. */
6067 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6068 NULL) == -1)
6069 err(1, "pledge");
6071 #endif
6073 error = apply_unveil(got_repo_get_path(repo), do_list,
6074 worktree ? got_worktree_get_root_path(worktree) : NULL);
6075 if (error)
6076 goto done;
6078 if (do_list)
6079 error = list_refs(repo, refname, sort_by_time);
6080 else if (do_delete)
6081 error = delete_ref_by_name(repo, refname);
6082 else if (symref_target)
6083 error = add_symref(repo, refname, symref_target);
6084 else {
6085 if (obj_arg == NULL)
6086 usage_ref();
6087 error = add_ref(repo, refname, obj_arg);
6089 done:
6090 free(refname);
6091 if (repo) {
6092 const struct got_error *close_err = got_repo_close(repo);
6093 if (error == NULL)
6094 error = close_err;
6096 if (worktree)
6097 got_worktree_close(worktree);
6098 free(cwd);
6099 free(repo_path);
6100 return error;
6103 __dead static void
6104 usage_branch(void)
6106 fprintf(stderr,
6107 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6108 "[-n] [name]\n", getprogname());
6109 exit(1);
6112 static const struct got_error *
6113 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6114 struct got_reference *ref)
6116 const struct got_error *err = NULL;
6117 const char *refname, *marker = " ";
6118 char *refstr;
6120 refname = got_ref_get_name(ref);
6121 if (worktree && strcmp(refname,
6122 got_worktree_get_head_ref_name(worktree)) == 0) {
6123 struct got_object_id *id = NULL;
6125 err = got_ref_resolve(&id, repo, ref);
6126 if (err)
6127 return err;
6128 if (got_object_id_cmp(id,
6129 got_worktree_get_base_commit_id(worktree)) == 0)
6130 marker = "* ";
6131 else
6132 marker = "~ ";
6133 free(id);
6136 if (strncmp(refname, "refs/heads/", 11) == 0)
6137 refname += 11;
6138 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6139 refname += 18;
6140 if (strncmp(refname, "refs/remotes/", 13) == 0)
6141 refname += 13;
6143 refstr = got_ref_to_str(ref);
6144 if (refstr == NULL)
6145 return got_error_from_errno("got_ref_to_str");
6147 printf("%s%s: %s\n", marker, refname, refstr);
6148 free(refstr);
6149 return NULL;
6152 static const struct got_error *
6153 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6155 const char *refname;
6157 if (worktree == NULL)
6158 return got_error(GOT_ERR_NOT_WORKTREE);
6160 refname = got_worktree_get_head_ref_name(worktree);
6162 if (strncmp(refname, "refs/heads/", 11) == 0)
6163 refname += 11;
6164 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6165 refname += 18;
6167 printf("%s\n", refname);
6169 return NULL;
6172 static const struct got_error *
6173 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6174 int sort_by_time)
6176 static const struct got_error *err = NULL;
6177 struct got_reflist_head refs;
6178 struct got_reflist_entry *re;
6179 struct got_reference *temp_ref = NULL;
6180 int rebase_in_progress, histedit_in_progress;
6182 TAILQ_INIT(&refs);
6184 if (worktree) {
6185 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6186 worktree);
6187 if (err)
6188 return err;
6190 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6191 worktree);
6192 if (err)
6193 return err;
6195 if (rebase_in_progress || histedit_in_progress) {
6196 err = got_ref_open(&temp_ref, repo,
6197 got_worktree_get_head_ref_name(worktree), 0);
6198 if (err)
6199 return err;
6200 list_branch(repo, worktree, temp_ref);
6201 got_ref_close(temp_ref);
6205 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6206 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6207 repo);
6208 if (err)
6209 return err;
6211 TAILQ_FOREACH(re, &refs, entry)
6212 list_branch(repo, worktree, re->ref);
6214 got_ref_list_free(&refs);
6216 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6217 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6218 repo);
6219 if (err)
6220 return err;
6222 TAILQ_FOREACH(re, &refs, entry)
6223 list_branch(repo, worktree, re->ref);
6225 got_ref_list_free(&refs);
6227 return NULL;
6230 static const struct got_error *
6231 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6232 const char *branch_name)
6234 const struct got_error *err = NULL;
6235 struct got_reference *ref = NULL;
6236 char *refname, *remote_refname = NULL;
6238 if (strncmp(branch_name, "refs/", 5) == 0)
6239 branch_name += 5;
6240 if (strncmp(branch_name, "heads/", 6) == 0)
6241 branch_name += 6;
6242 else if (strncmp(branch_name, "remotes/", 8) == 0)
6243 branch_name += 8;
6245 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6246 return got_error_from_errno("asprintf");
6248 if (asprintf(&remote_refname, "refs/remotes/%s",
6249 branch_name) == -1) {
6250 err = got_error_from_errno("asprintf");
6251 goto done;
6254 err = got_ref_open(&ref, repo, refname, 0);
6255 if (err) {
6256 const struct got_error *err2;
6257 if (err->code != GOT_ERR_NOT_REF)
6258 goto done;
6260 * Keep 'err' intact such that if neither branch exists
6261 * we report "refs/heads" rather than "refs/remotes" in
6262 * our error message.
6264 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6265 if (err2)
6266 goto done;
6267 err = NULL;
6270 if (worktree &&
6271 strcmp(got_worktree_get_head_ref_name(worktree),
6272 got_ref_get_name(ref)) == 0) {
6273 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6274 "will not delete this work tree's current branch");
6275 goto done;
6278 err = delete_ref(repo, ref);
6279 done:
6280 if (ref)
6281 got_ref_close(ref);
6282 free(refname);
6283 free(remote_refname);
6284 return err;
6287 static const struct got_error *
6288 add_branch(struct got_repository *repo, const char *branch_name,
6289 struct got_object_id *base_commit_id)
6291 const struct got_error *err = NULL;
6292 struct got_reference *ref = NULL;
6293 char *base_refname = NULL, *refname = NULL;
6296 * Don't let the user create a branch name with a leading '-'.
6297 * While technically a valid reference name, this case is usually
6298 * an unintended typo.
6300 if (branch_name[0] == '-')
6301 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6303 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6304 branch_name += 11;
6306 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6307 err = got_error_from_errno("asprintf");
6308 goto done;
6311 err = got_ref_open(&ref, repo, refname, 0);
6312 if (err == NULL) {
6313 err = got_error(GOT_ERR_BRANCH_EXISTS);
6314 goto done;
6315 } else if (err->code != GOT_ERR_NOT_REF)
6316 goto done;
6318 err = got_ref_alloc(&ref, refname, base_commit_id);
6319 if (err)
6320 goto done;
6322 err = got_ref_write(ref, repo);
6323 done:
6324 if (ref)
6325 got_ref_close(ref);
6326 free(base_refname);
6327 free(refname);
6328 return err;
6331 static const struct got_error *
6332 cmd_branch(int argc, char *argv[])
6334 const struct got_error *error = NULL;
6335 struct got_repository *repo = NULL;
6336 struct got_worktree *worktree = NULL;
6337 char *cwd = NULL, *repo_path = NULL;
6338 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6339 const char *delref = NULL, *commit_id_arg = NULL;
6340 struct got_reference *ref = NULL;
6341 struct got_pathlist_head paths;
6342 struct got_pathlist_entry *pe;
6343 struct got_object_id *commit_id = NULL;
6344 char *commit_id_str = NULL;
6346 TAILQ_INIT(&paths);
6348 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6349 switch (ch) {
6350 case 'c':
6351 commit_id_arg = optarg;
6352 break;
6353 case 'd':
6354 delref = optarg;
6355 break;
6356 case 'r':
6357 repo_path = realpath(optarg, NULL);
6358 if (repo_path == NULL)
6359 return got_error_from_errno2("realpath",
6360 optarg);
6361 got_path_strip_trailing_slashes(repo_path);
6362 break;
6363 case 'l':
6364 do_list = 1;
6365 break;
6366 case 'n':
6367 do_update = 0;
6368 break;
6369 case 't':
6370 sort_by_time = 1;
6371 break;
6372 default:
6373 usage_branch();
6374 /* NOTREACHED */
6378 if (do_list && delref)
6379 option_conflict('l', 'd');
6380 if (sort_by_time && !do_list)
6381 errx(1, "-t option requires -l option");
6383 argc -= optind;
6384 argv += optind;
6386 if (!do_list && !delref && argc == 0)
6387 do_show = 1;
6389 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6390 errx(1, "-c option can only be used when creating a branch");
6392 if (do_list || delref) {
6393 if (argc > 0)
6394 usage_branch();
6395 } else if (!do_show && argc != 1)
6396 usage_branch();
6398 #ifndef PROFILE
6399 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6400 "sendfd unveil", NULL) == -1)
6401 err(1, "pledge");
6402 #endif
6403 cwd = getcwd(NULL, 0);
6404 if (cwd == NULL) {
6405 error = got_error_from_errno("getcwd");
6406 goto done;
6409 if (repo_path == NULL) {
6410 error = got_worktree_open(&worktree, cwd);
6411 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6412 goto done;
6413 else
6414 error = NULL;
6415 if (worktree) {
6416 repo_path =
6417 strdup(got_worktree_get_repo_path(worktree));
6418 if (repo_path == NULL)
6419 error = got_error_from_errno("strdup");
6420 if (error)
6421 goto done;
6422 } else {
6423 repo_path = strdup(cwd);
6424 if (repo_path == NULL) {
6425 error = got_error_from_errno("strdup");
6426 goto done;
6431 error = got_repo_open(&repo, repo_path, NULL);
6432 if (error != NULL)
6433 goto done;
6435 #ifndef PROFILE
6436 if (do_list || do_show) {
6437 /* Remove "cpath" promise. */
6438 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6439 NULL) == -1)
6440 err(1, "pledge");
6442 #endif
6444 error = apply_unveil(got_repo_get_path(repo), do_list,
6445 worktree ? got_worktree_get_root_path(worktree) : NULL);
6446 if (error)
6447 goto done;
6449 if (do_show)
6450 error = show_current_branch(repo, worktree);
6451 else if (do_list)
6452 error = list_branches(repo, worktree, sort_by_time);
6453 else if (delref)
6454 error = delete_branch(repo, worktree, delref);
6455 else {
6456 struct got_reflist_head refs;
6457 TAILQ_INIT(&refs);
6458 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6459 NULL);
6460 if (error)
6461 goto done;
6462 if (commit_id_arg == NULL)
6463 commit_id_arg = worktree ?
6464 got_worktree_get_head_ref_name(worktree) :
6465 GOT_REF_HEAD;
6466 error = got_repo_match_object_id(&commit_id, NULL,
6467 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6468 got_ref_list_free(&refs);
6469 if (error)
6470 goto done;
6471 error = add_branch(repo, argv[0], commit_id);
6472 if (error)
6473 goto done;
6474 if (worktree && do_update) {
6475 struct got_update_progress_arg upa;
6476 char *branch_refname = NULL;
6478 error = got_object_id_str(&commit_id_str, commit_id);
6479 if (error)
6480 goto done;
6481 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6482 worktree);
6483 if (error)
6484 goto done;
6485 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6486 == -1) {
6487 error = got_error_from_errno("asprintf");
6488 goto done;
6490 error = got_ref_open(&ref, repo, branch_refname, 0);
6491 free(branch_refname);
6492 if (error)
6493 goto done;
6494 error = switch_head_ref(ref, commit_id, worktree,
6495 repo);
6496 if (error)
6497 goto done;
6498 error = got_worktree_set_base_commit_id(worktree, repo,
6499 commit_id);
6500 if (error)
6501 goto done;
6502 memset(&upa, 0, sizeof(upa));
6503 error = got_worktree_checkout_files(worktree, &paths,
6504 repo, update_progress, &upa, check_cancelled,
6505 NULL);
6506 if (error)
6507 goto done;
6508 if (upa.did_something) {
6509 printf("Updated to %s: %s\n",
6510 got_worktree_get_head_ref_name(worktree),
6511 commit_id_str);
6513 print_update_progress_stats(&upa);
6516 done:
6517 if (ref)
6518 got_ref_close(ref);
6519 if (repo) {
6520 const struct got_error *close_err = got_repo_close(repo);
6521 if (error == NULL)
6522 error = close_err;
6524 if (worktree)
6525 got_worktree_close(worktree);
6526 free(cwd);
6527 free(repo_path);
6528 free(commit_id);
6529 free(commit_id_str);
6530 TAILQ_FOREACH(pe, &paths, entry)
6531 free((char *)pe->path);
6532 got_pathlist_free(&paths);
6533 return error;
6537 __dead static void
6538 usage_tag(void)
6540 fprintf(stderr,
6541 "usage: %s tag [-c commit] [-r repository] [-l] "
6542 "[-m message] name\n", getprogname());
6543 exit(1);
6546 #if 0
6547 static const struct got_error *
6548 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6550 const struct got_error *err = NULL;
6551 struct got_reflist_entry *re, *se, *new;
6552 struct got_object_id *re_id, *se_id;
6553 struct got_tag_object *re_tag, *se_tag;
6554 time_t re_time, se_time;
6556 STAILQ_FOREACH(re, tags, entry) {
6557 se = STAILQ_FIRST(sorted);
6558 if (se == NULL) {
6559 err = got_reflist_entry_dup(&new, re);
6560 if (err)
6561 return err;
6562 STAILQ_INSERT_HEAD(sorted, new, entry);
6563 continue;
6564 } else {
6565 err = got_ref_resolve(&re_id, repo, re->ref);
6566 if (err)
6567 break;
6568 err = got_object_open_as_tag(&re_tag, repo, re_id);
6569 free(re_id);
6570 if (err)
6571 break;
6572 re_time = got_object_tag_get_tagger_time(re_tag);
6573 got_object_tag_close(re_tag);
6576 while (se) {
6577 err = got_ref_resolve(&se_id, repo, re->ref);
6578 if (err)
6579 break;
6580 err = got_object_open_as_tag(&se_tag, repo, se_id);
6581 free(se_id);
6582 if (err)
6583 break;
6584 se_time = got_object_tag_get_tagger_time(se_tag);
6585 got_object_tag_close(se_tag);
6587 if (se_time > re_time) {
6588 err = got_reflist_entry_dup(&new, re);
6589 if (err)
6590 return err;
6591 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6592 break;
6594 se = STAILQ_NEXT(se, entry);
6595 continue;
6598 done:
6599 return err;
6601 #endif
6603 static const struct got_error *
6604 list_tags(struct got_repository *repo)
6606 static const struct got_error *err = NULL;
6607 struct got_reflist_head refs;
6608 struct got_reflist_entry *re;
6610 TAILQ_INIT(&refs);
6612 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6613 if (err)
6614 return err;
6616 TAILQ_FOREACH(re, &refs, entry) {
6617 const char *refname;
6618 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6619 char datebuf[26];
6620 const char *tagger;
6621 time_t tagger_time;
6622 struct got_object_id *id;
6623 struct got_tag_object *tag;
6624 struct got_commit_object *commit = NULL;
6626 refname = got_ref_get_name(re->ref);
6627 if (strncmp(refname, "refs/tags/", 10) != 0)
6628 continue;
6629 refname += 10;
6630 refstr = got_ref_to_str(re->ref);
6631 if (refstr == NULL) {
6632 err = got_error_from_errno("got_ref_to_str");
6633 break;
6635 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6636 free(refstr);
6638 err = got_ref_resolve(&id, repo, re->ref);
6639 if (err)
6640 break;
6641 err = got_object_open_as_tag(&tag, repo, id);
6642 if (err) {
6643 if (err->code != GOT_ERR_OBJ_TYPE) {
6644 free(id);
6645 break;
6647 /* "lightweight" tag */
6648 err = got_object_open_as_commit(&commit, repo, id);
6649 if (err) {
6650 free(id);
6651 break;
6653 tagger = got_object_commit_get_committer(commit);
6654 tagger_time =
6655 got_object_commit_get_committer_time(commit);
6656 err = got_object_id_str(&id_str, id);
6657 free(id);
6658 if (err)
6659 break;
6660 } else {
6661 free(id);
6662 tagger = got_object_tag_get_tagger(tag);
6663 tagger_time = got_object_tag_get_tagger_time(tag);
6664 err = got_object_id_str(&id_str,
6665 got_object_tag_get_object_id(tag));
6666 if (err)
6667 break;
6669 printf("from: %s\n", tagger);
6670 datestr = get_datestr(&tagger_time, datebuf);
6671 if (datestr)
6672 printf("date: %s UTC\n", datestr);
6673 if (commit)
6674 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6675 else {
6676 switch (got_object_tag_get_object_type(tag)) {
6677 case GOT_OBJ_TYPE_BLOB:
6678 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6679 id_str);
6680 break;
6681 case GOT_OBJ_TYPE_TREE:
6682 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6683 id_str);
6684 break;
6685 case GOT_OBJ_TYPE_COMMIT:
6686 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6687 id_str);
6688 break;
6689 case GOT_OBJ_TYPE_TAG:
6690 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6691 id_str);
6692 break;
6693 default:
6694 break;
6697 free(id_str);
6698 if (commit) {
6699 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6700 if (err)
6701 break;
6702 got_object_commit_close(commit);
6703 } else {
6704 tagmsg0 = strdup(got_object_tag_get_message(tag));
6705 got_object_tag_close(tag);
6706 if (tagmsg0 == NULL) {
6707 err = got_error_from_errno("strdup");
6708 break;
6712 tagmsg = tagmsg0;
6713 do {
6714 line = strsep(&tagmsg, "\n");
6715 if (line)
6716 printf(" %s\n", line);
6717 } while (line);
6718 free(tagmsg0);
6721 got_ref_list_free(&refs);
6722 return NULL;
6725 static const struct got_error *
6726 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6727 const char *tag_name, const char *repo_path)
6729 const struct got_error *err = NULL;
6730 char *template = NULL, *initial_content = NULL;
6731 char *editor = NULL;
6732 int initial_content_len;
6733 int fd = -1;
6735 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6736 err = got_error_from_errno("asprintf");
6737 goto done;
6740 initial_content_len = asprintf(&initial_content,
6741 "\n# tagging commit %s as %s\n",
6742 commit_id_str, tag_name);
6743 if (initial_content_len == -1) {
6744 err = got_error_from_errno("asprintf");
6745 goto done;
6748 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6749 if (err)
6750 goto done;
6752 if (write(fd, initial_content, initial_content_len) == -1) {
6753 err = got_error_from_errno2("write", *tagmsg_path);
6754 goto done;
6757 err = get_editor(&editor);
6758 if (err)
6759 goto done;
6760 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6761 initial_content_len, 1);
6762 done:
6763 free(initial_content);
6764 free(template);
6765 free(editor);
6767 if (fd != -1 && close(fd) == -1 && err == NULL)
6768 err = got_error_from_errno2("close", *tagmsg_path);
6770 /* Editor is done; we can now apply unveil(2) */
6771 if (err == NULL)
6772 err = apply_unveil(repo_path, 0, NULL);
6773 if (err) {
6774 free(*tagmsg);
6775 *tagmsg = NULL;
6777 return err;
6780 static const struct got_error *
6781 add_tag(struct got_repository *repo, const char *tagger,
6782 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6784 const struct got_error *err = NULL;
6785 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6786 char *label = NULL, *commit_id_str = NULL;
6787 struct got_reference *ref = NULL;
6788 char *refname = NULL, *tagmsg = NULL;
6789 char *tagmsg_path = NULL, *tag_id_str = NULL;
6790 int preserve_tagmsg = 0;
6791 struct got_reflist_head refs;
6793 TAILQ_INIT(&refs);
6796 * Don't let the user create a tag name with a leading '-'.
6797 * While technically a valid reference name, this case is usually
6798 * an unintended typo.
6800 if (tag_name[0] == '-')
6801 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6803 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6804 if (err)
6805 goto done;
6807 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6808 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6809 if (err)
6810 goto done;
6812 err = got_object_id_str(&commit_id_str, commit_id);
6813 if (err)
6814 goto done;
6816 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6817 refname = strdup(tag_name);
6818 if (refname == NULL) {
6819 err = got_error_from_errno("strdup");
6820 goto done;
6822 tag_name += 10;
6823 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6824 err = got_error_from_errno("asprintf");
6825 goto done;
6828 err = got_ref_open(&ref, repo, refname, 0);
6829 if (err == NULL) {
6830 err = got_error(GOT_ERR_TAG_EXISTS);
6831 goto done;
6832 } else if (err->code != GOT_ERR_NOT_REF)
6833 goto done;
6835 if (tagmsg_arg == NULL) {
6836 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6837 tag_name, got_repo_get_path(repo));
6838 if (err) {
6839 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6840 tagmsg_path != NULL)
6841 preserve_tagmsg = 1;
6842 goto done;
6846 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6847 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6848 if (err) {
6849 if (tagmsg_path)
6850 preserve_tagmsg = 1;
6851 goto done;
6854 err = got_ref_alloc(&ref, refname, tag_id);
6855 if (err) {
6856 if (tagmsg_path)
6857 preserve_tagmsg = 1;
6858 goto done;
6861 err = got_ref_write(ref, repo);
6862 if (err) {
6863 if (tagmsg_path)
6864 preserve_tagmsg = 1;
6865 goto done;
6868 err = got_object_id_str(&tag_id_str, tag_id);
6869 if (err) {
6870 if (tagmsg_path)
6871 preserve_tagmsg = 1;
6872 goto done;
6874 printf("Created tag %s\n", tag_id_str);
6875 done:
6876 if (preserve_tagmsg) {
6877 fprintf(stderr, "%s: tag message preserved in %s\n",
6878 getprogname(), tagmsg_path);
6879 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6880 err = got_error_from_errno2("unlink", tagmsg_path);
6881 free(tag_id_str);
6882 if (ref)
6883 got_ref_close(ref);
6884 free(commit_id);
6885 free(commit_id_str);
6886 free(refname);
6887 free(tagmsg);
6888 free(tagmsg_path);
6889 got_ref_list_free(&refs);
6890 return err;
6893 static const struct got_error *
6894 cmd_tag(int argc, char *argv[])
6896 const struct got_error *error = NULL;
6897 struct got_repository *repo = NULL;
6898 struct got_worktree *worktree = NULL;
6899 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6900 char *gitconfig_path = NULL, *tagger = NULL;
6901 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6902 int ch, do_list = 0;
6904 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6905 switch (ch) {
6906 case 'c':
6907 commit_id_arg = optarg;
6908 break;
6909 case 'm':
6910 tagmsg = optarg;
6911 break;
6912 case 'r':
6913 repo_path = realpath(optarg, NULL);
6914 if (repo_path == NULL)
6915 return got_error_from_errno2("realpath",
6916 optarg);
6917 got_path_strip_trailing_slashes(repo_path);
6918 break;
6919 case 'l':
6920 do_list = 1;
6921 break;
6922 default:
6923 usage_tag();
6924 /* NOTREACHED */
6928 argc -= optind;
6929 argv += optind;
6931 if (do_list) {
6932 if (commit_id_arg != NULL)
6933 errx(1,
6934 "-c option can only be used when creating a tag");
6935 if (tagmsg)
6936 option_conflict('l', 'm');
6937 if (argc > 0)
6938 usage_tag();
6939 } else if (argc != 1)
6940 usage_tag();
6942 tag_name = argv[0];
6944 #ifndef PROFILE
6945 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6946 "sendfd unveil", NULL) == -1)
6947 err(1, "pledge");
6948 #endif
6949 cwd = getcwd(NULL, 0);
6950 if (cwd == NULL) {
6951 error = got_error_from_errno("getcwd");
6952 goto done;
6955 if (repo_path == NULL) {
6956 error = got_worktree_open(&worktree, cwd);
6957 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6958 goto done;
6959 else
6960 error = NULL;
6961 if (worktree) {
6962 repo_path =
6963 strdup(got_worktree_get_repo_path(worktree));
6964 if (repo_path == NULL)
6965 error = got_error_from_errno("strdup");
6966 if (error)
6967 goto done;
6968 } else {
6969 repo_path = strdup(cwd);
6970 if (repo_path == NULL) {
6971 error = got_error_from_errno("strdup");
6972 goto done;
6977 if (do_list) {
6978 if (worktree) {
6979 /* Release work tree lock. */
6980 got_worktree_close(worktree);
6981 worktree = NULL;
6983 error = got_repo_open(&repo, repo_path, NULL);
6984 if (error != NULL)
6985 goto done;
6986 #ifndef PROFILE
6987 /* Remove "cpath" promise. */
6988 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6989 NULL) == -1)
6990 err(1, "pledge");
6991 #endif
6992 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6993 if (error)
6994 goto done;
6995 error = list_tags(repo);
6996 } else {
6997 error = get_gitconfig_path(&gitconfig_path);
6998 if (error)
6999 goto done;
7000 error = got_repo_open(&repo, repo_path, gitconfig_path);
7001 if (error != NULL)
7002 goto done;
7004 error = get_author(&tagger, repo, worktree);
7005 if (error)
7006 goto done;
7007 if (worktree) {
7008 /* Release work tree lock. */
7009 got_worktree_close(worktree);
7010 worktree = NULL;
7013 if (tagmsg) {
7014 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7015 if (error)
7016 goto done;
7019 if (commit_id_arg == NULL) {
7020 struct got_reference *head_ref;
7021 struct got_object_id *commit_id;
7022 error = got_ref_open(&head_ref, repo,
7023 worktree ? got_worktree_get_head_ref_name(worktree)
7024 : GOT_REF_HEAD, 0);
7025 if (error)
7026 goto done;
7027 error = got_ref_resolve(&commit_id, repo, head_ref);
7028 got_ref_close(head_ref);
7029 if (error)
7030 goto done;
7031 error = got_object_id_str(&commit_id_str, commit_id);
7032 free(commit_id);
7033 if (error)
7034 goto done;
7037 error = add_tag(repo, tagger, tag_name,
7038 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7040 done:
7041 if (repo) {
7042 const struct got_error *close_err = got_repo_close(repo);
7043 if (error == NULL)
7044 error = close_err;
7046 if (worktree)
7047 got_worktree_close(worktree);
7048 free(cwd);
7049 free(repo_path);
7050 free(gitconfig_path);
7051 free(commit_id_str);
7052 free(tagger);
7053 return error;
7056 __dead static void
7057 usage_add(void)
7059 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7060 getprogname());
7061 exit(1);
7064 static const struct got_error *
7065 add_progress(void *arg, unsigned char status, const char *path)
7067 while (path[0] == '/')
7068 path++;
7069 printf("%c %s\n", status, path);
7070 return NULL;
7073 static const struct got_error *
7074 cmd_add(int argc, char *argv[])
7076 const struct got_error *error = NULL;
7077 struct got_repository *repo = NULL;
7078 struct got_worktree *worktree = NULL;
7079 char *cwd = NULL;
7080 struct got_pathlist_head paths;
7081 struct got_pathlist_entry *pe;
7082 int ch, can_recurse = 0, no_ignores = 0;
7084 TAILQ_INIT(&paths);
7086 while ((ch = getopt(argc, argv, "IR")) != -1) {
7087 switch (ch) {
7088 case 'I':
7089 no_ignores = 1;
7090 break;
7091 case 'R':
7092 can_recurse = 1;
7093 break;
7094 default:
7095 usage_add();
7096 /* NOTREACHED */
7100 argc -= optind;
7101 argv += optind;
7103 #ifndef PROFILE
7104 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7105 NULL) == -1)
7106 err(1, "pledge");
7107 #endif
7108 if (argc < 1)
7109 usage_add();
7111 cwd = getcwd(NULL, 0);
7112 if (cwd == NULL) {
7113 error = got_error_from_errno("getcwd");
7114 goto done;
7117 error = got_worktree_open(&worktree, cwd);
7118 if (error) {
7119 if (error->code == GOT_ERR_NOT_WORKTREE)
7120 error = wrap_not_worktree_error(error, "add", cwd);
7121 goto done;
7124 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7125 NULL);
7126 if (error != NULL)
7127 goto done;
7129 error = apply_unveil(got_repo_get_path(repo), 1,
7130 got_worktree_get_root_path(worktree));
7131 if (error)
7132 goto done;
7134 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7135 if (error)
7136 goto done;
7138 if (!can_recurse) {
7139 char *ondisk_path;
7140 struct stat sb;
7141 TAILQ_FOREACH(pe, &paths, entry) {
7142 if (asprintf(&ondisk_path, "%s/%s",
7143 got_worktree_get_root_path(worktree),
7144 pe->path) == -1) {
7145 error = got_error_from_errno("asprintf");
7146 goto done;
7148 if (lstat(ondisk_path, &sb) == -1) {
7149 if (errno == ENOENT) {
7150 free(ondisk_path);
7151 continue;
7153 error = got_error_from_errno2("lstat",
7154 ondisk_path);
7155 free(ondisk_path);
7156 goto done;
7158 free(ondisk_path);
7159 if (S_ISDIR(sb.st_mode)) {
7160 error = got_error_msg(GOT_ERR_BAD_PATH,
7161 "adding directories requires -R option");
7162 goto done;
7167 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7168 NULL, repo, no_ignores);
7169 done:
7170 if (repo) {
7171 const struct got_error *close_err = got_repo_close(repo);
7172 if (error == NULL)
7173 error = close_err;
7175 if (worktree)
7176 got_worktree_close(worktree);
7177 TAILQ_FOREACH(pe, &paths, entry)
7178 free((char *)pe->path);
7179 got_pathlist_free(&paths);
7180 free(cwd);
7181 return error;
7184 __dead static void
7185 usage_remove(void)
7187 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7188 "path ...\n", getprogname());
7189 exit(1);
7192 static const struct got_error *
7193 print_remove_status(void *arg, unsigned char status,
7194 unsigned char staged_status, const char *path)
7196 while (path[0] == '/')
7197 path++;
7198 if (status == GOT_STATUS_NONEXISTENT)
7199 return NULL;
7200 if (status == staged_status && (status == GOT_STATUS_DELETE))
7201 status = GOT_STATUS_NO_CHANGE;
7202 printf("%c%c %s\n", status, staged_status, path);
7203 return NULL;
7206 static const struct got_error *
7207 cmd_remove(int argc, char *argv[])
7209 const struct got_error *error = NULL;
7210 struct got_worktree *worktree = NULL;
7211 struct got_repository *repo = NULL;
7212 const char *status_codes = NULL;
7213 char *cwd = NULL;
7214 struct got_pathlist_head paths;
7215 struct got_pathlist_entry *pe;
7216 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7217 int ignore_missing_paths = 0;
7219 TAILQ_INIT(&paths);
7221 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7222 switch (ch) {
7223 case 'f':
7224 delete_local_mods = 1;
7225 ignore_missing_paths = 1;
7226 break;
7227 case 'k':
7228 keep_on_disk = 1;
7229 break;
7230 case 'R':
7231 can_recurse = 1;
7232 break;
7233 case 's':
7234 for (i = 0; i < strlen(optarg); i++) {
7235 switch (optarg[i]) {
7236 case GOT_STATUS_MODIFY:
7237 delete_local_mods = 1;
7238 break;
7239 case GOT_STATUS_MISSING:
7240 ignore_missing_paths = 1;
7241 break;
7242 default:
7243 errx(1, "invalid status code '%c'",
7244 optarg[i]);
7247 status_codes = optarg;
7248 break;
7249 default:
7250 usage_remove();
7251 /* NOTREACHED */
7255 argc -= optind;
7256 argv += optind;
7258 #ifndef PROFILE
7259 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7260 NULL) == -1)
7261 err(1, "pledge");
7262 #endif
7263 if (argc < 1)
7264 usage_remove();
7266 cwd = getcwd(NULL, 0);
7267 if (cwd == NULL) {
7268 error = got_error_from_errno("getcwd");
7269 goto done;
7271 error = got_worktree_open(&worktree, cwd);
7272 if (error) {
7273 if (error->code == GOT_ERR_NOT_WORKTREE)
7274 error = wrap_not_worktree_error(error, "remove", cwd);
7275 goto done;
7278 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7279 NULL);
7280 if (error)
7281 goto done;
7283 error = apply_unveil(got_repo_get_path(repo), 1,
7284 got_worktree_get_root_path(worktree));
7285 if (error)
7286 goto done;
7288 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7289 if (error)
7290 goto done;
7292 if (!can_recurse) {
7293 char *ondisk_path;
7294 struct stat sb;
7295 TAILQ_FOREACH(pe, &paths, entry) {
7296 if (asprintf(&ondisk_path, "%s/%s",
7297 got_worktree_get_root_path(worktree),
7298 pe->path) == -1) {
7299 error = got_error_from_errno("asprintf");
7300 goto done;
7302 if (lstat(ondisk_path, &sb) == -1) {
7303 if (errno == ENOENT) {
7304 free(ondisk_path);
7305 continue;
7307 error = got_error_from_errno2("lstat",
7308 ondisk_path);
7309 free(ondisk_path);
7310 goto done;
7312 free(ondisk_path);
7313 if (S_ISDIR(sb.st_mode)) {
7314 error = got_error_msg(GOT_ERR_BAD_PATH,
7315 "removing directories requires -R option");
7316 goto done;
7321 error = got_worktree_schedule_delete(worktree, &paths,
7322 delete_local_mods, status_codes, print_remove_status, NULL,
7323 repo, keep_on_disk, ignore_missing_paths);
7324 done:
7325 if (repo) {
7326 const struct got_error *close_err = got_repo_close(repo);
7327 if (error == NULL)
7328 error = close_err;
7330 if (worktree)
7331 got_worktree_close(worktree);
7332 TAILQ_FOREACH(pe, &paths, entry)
7333 free((char *)pe->path);
7334 got_pathlist_free(&paths);
7335 free(cwd);
7336 return error;
7339 __dead static void
7340 usage_patch(void)
7342 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7343 "[-R] [patchfile]\n", getprogname());
7344 exit(1);
7347 static const struct got_error *
7348 patch_from_stdin(int *patchfd)
7350 const struct got_error *err = NULL;
7351 ssize_t r;
7352 char *path, buf[BUFSIZ];
7353 sig_t sighup, sigint, sigquit;
7355 err = got_opentemp_named_fd(&path, patchfd,
7356 GOT_TMPDIR_STR "/got-patch");
7357 if (err)
7358 return err;
7359 unlink(path);
7360 free(path);
7362 sighup = signal(SIGHUP, SIG_DFL);
7363 sigint = signal(SIGINT, SIG_DFL);
7364 sigquit = signal(SIGQUIT, SIG_DFL);
7366 for (;;) {
7367 r = read(0, buf, sizeof(buf));
7368 if (r == -1) {
7369 err = got_error_from_errno("read");
7370 break;
7372 if (r == 0)
7373 break;
7374 if (write(*patchfd, buf, r) == -1) {
7375 err = got_error_from_errno("write");
7376 break;
7380 signal(SIGHUP, sighup);
7381 signal(SIGINT, sigint);
7382 signal(SIGQUIT, sigquit);
7384 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7385 err = got_error_from_errno("lseek");
7387 if (err != NULL) {
7388 close(*patchfd);
7389 *patchfd = -1;
7392 return err;
7395 static const struct got_error *
7396 patch_progress(void *arg, const char *old, const char *new,
7397 unsigned char status, const struct got_error *error, long old_from,
7398 long old_lines, long new_from, long new_lines, long offset,
7399 const struct got_error *hunk_err)
7401 const char *path = new == NULL ? old : new;
7403 while (*path == '/')
7404 path++;
7406 if (status != 0)
7407 printf("%c %s\n", status, path);
7409 if (error != NULL)
7410 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7412 if (offset != 0 || hunk_err != NULL) {
7413 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7414 old_lines, new_from, new_lines);
7415 if (hunk_err != NULL)
7416 printf("%s\n", hunk_err->msg);
7417 else
7418 printf("applied with offset %ld\n", offset);
7421 return NULL;
7424 static const struct got_error *
7425 cmd_patch(int argc, char *argv[])
7427 const struct got_error *error = NULL, *close_error = NULL;
7428 struct got_worktree *worktree = NULL;
7429 struct got_repository *repo = NULL;
7430 const char *errstr;
7431 char *cwd = NULL;
7432 int ch, nop = 0, strip = -1, reverse = 0;
7433 int patchfd;
7435 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7436 switch (ch) {
7437 case 'n':
7438 nop = 1;
7439 break;
7440 case 'p':
7441 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7442 if (errstr != NULL)
7443 errx(1, "pathname strip count is %s: %s",
7444 errstr, optarg);
7445 break;
7446 case 'R':
7447 reverse = 1;
7448 break;
7449 default:
7450 usage_patch();
7451 /* NOTREACHED */
7455 argc -= optind;
7456 argv += optind;
7458 if (argc == 0) {
7459 error = patch_from_stdin(&patchfd);
7460 if (error)
7461 return error;
7462 } else if (argc == 1) {
7463 patchfd = open(argv[0], O_RDONLY);
7464 if (patchfd == -1) {
7465 error = got_error_from_errno2("open", argv[0]);
7466 return error;
7468 } else
7469 usage_patch();
7471 if ((cwd = getcwd(NULL, 0)) == NULL) {
7472 error = got_error_from_errno("getcwd");
7473 goto done;
7476 error = got_worktree_open(&worktree, cwd);
7477 if (error != NULL)
7478 goto done;
7480 const char *repo_path = got_worktree_get_repo_path(worktree);
7481 error = got_repo_open(&repo, repo_path, NULL);
7482 if (error != NULL)
7483 goto done;
7485 error = apply_unveil(got_repo_get_path(repo), 0,
7486 got_worktree_get_root_path(worktree));
7487 if (error != NULL)
7488 goto done;
7490 #ifndef PROFILE
7491 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7492 NULL) == -1)
7493 err(1, "pledge");
7494 #endif
7496 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7497 &patch_progress, NULL, check_cancelled, NULL);
7499 done:
7500 if (repo) {
7501 close_error = got_repo_close(repo);
7502 if (error == NULL)
7503 error = close_error;
7505 if (worktree != NULL) {
7506 close_error = got_worktree_close(worktree);
7507 if (error == NULL)
7508 error = close_error;
7510 free(cwd);
7511 return error;
7514 __dead static void
7515 usage_revert(void)
7517 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7518 "path ...\n", getprogname());
7519 exit(1);
7522 static const struct got_error *
7523 revert_progress(void *arg, unsigned char status, const char *path)
7525 if (status == GOT_STATUS_UNVERSIONED)
7526 return NULL;
7528 while (path[0] == '/')
7529 path++;
7530 printf("%c %s\n", status, path);
7531 return NULL;
7534 struct choose_patch_arg {
7535 FILE *patch_script_file;
7536 const char *action;
7539 static const struct got_error *
7540 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7541 int nchanges, const char *action)
7543 const struct got_error *err;
7544 char *line = NULL;
7545 size_t linesize = 0;
7546 ssize_t linelen;
7548 switch (status) {
7549 case GOT_STATUS_ADD:
7550 printf("A %s\n%s this addition? [y/n] ", path, action);
7551 break;
7552 case GOT_STATUS_DELETE:
7553 printf("D %s\n%s this deletion? [y/n] ", path, action);
7554 break;
7555 case GOT_STATUS_MODIFY:
7556 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7557 return got_error_from_errno("fseek");
7558 printf(GOT_COMMIT_SEP_STR);
7559 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7560 printf("%s", line);
7561 if (linelen == -1 && ferror(patch_file)) {
7562 err = got_error_from_errno("getline");
7563 free(line);
7564 return err;
7566 free(line);
7567 printf(GOT_COMMIT_SEP_STR);
7568 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7569 path, n, nchanges, action);
7570 break;
7571 default:
7572 return got_error_path(path, GOT_ERR_FILE_STATUS);
7575 return NULL;
7578 static const struct got_error *
7579 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7580 FILE *patch_file, int n, int nchanges)
7582 const struct got_error *err = NULL;
7583 char *line = NULL;
7584 size_t linesize = 0;
7585 ssize_t linelen;
7586 int resp = ' ';
7587 struct choose_patch_arg *a = arg;
7589 *choice = GOT_PATCH_CHOICE_NONE;
7591 if (a->patch_script_file) {
7592 char *nl;
7593 err = show_change(status, path, patch_file, n, nchanges,
7594 a->action);
7595 if (err)
7596 return err;
7597 linelen = getline(&line, &linesize, a->patch_script_file);
7598 if (linelen == -1) {
7599 if (ferror(a->patch_script_file))
7600 return got_error_from_errno("getline");
7601 return NULL;
7603 nl = strchr(line, '\n');
7604 if (nl)
7605 *nl = '\0';
7606 if (strcmp(line, "y") == 0) {
7607 *choice = GOT_PATCH_CHOICE_YES;
7608 printf("y\n");
7609 } else if (strcmp(line, "n") == 0) {
7610 *choice = GOT_PATCH_CHOICE_NO;
7611 printf("n\n");
7612 } else if (strcmp(line, "q") == 0 &&
7613 status == GOT_STATUS_MODIFY) {
7614 *choice = GOT_PATCH_CHOICE_QUIT;
7615 printf("q\n");
7616 } else
7617 printf("invalid response '%s'\n", line);
7618 free(line);
7619 return NULL;
7622 while (resp != 'y' && resp != 'n' && resp != 'q') {
7623 err = show_change(status, path, patch_file, n, nchanges,
7624 a->action);
7625 if (err)
7626 return err;
7627 resp = getchar();
7628 if (resp == '\n')
7629 resp = getchar();
7630 if (status == GOT_STATUS_MODIFY) {
7631 if (resp != 'y' && resp != 'n' && resp != 'q') {
7632 printf("invalid response '%c'\n", resp);
7633 resp = ' ';
7635 } else if (resp != 'y' && resp != 'n') {
7636 printf("invalid response '%c'\n", resp);
7637 resp = ' ';
7641 if (resp == 'y')
7642 *choice = GOT_PATCH_CHOICE_YES;
7643 else if (resp == 'n')
7644 *choice = GOT_PATCH_CHOICE_NO;
7645 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7646 *choice = GOT_PATCH_CHOICE_QUIT;
7648 return NULL;
7651 static const struct got_error *
7652 cmd_revert(int argc, char *argv[])
7654 const struct got_error *error = NULL;
7655 struct got_worktree *worktree = NULL;
7656 struct got_repository *repo = NULL;
7657 char *cwd = NULL, *path = NULL;
7658 struct got_pathlist_head paths;
7659 struct got_pathlist_entry *pe;
7660 int ch, can_recurse = 0, pflag = 0;
7661 FILE *patch_script_file = NULL;
7662 const char *patch_script_path = NULL;
7663 struct choose_patch_arg cpa;
7665 TAILQ_INIT(&paths);
7667 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7668 switch (ch) {
7669 case 'p':
7670 pflag = 1;
7671 break;
7672 case 'F':
7673 patch_script_path = optarg;
7674 break;
7675 case 'R':
7676 can_recurse = 1;
7677 break;
7678 default:
7679 usage_revert();
7680 /* NOTREACHED */
7684 argc -= optind;
7685 argv += optind;
7687 #ifndef PROFILE
7688 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7689 "unveil", NULL) == -1)
7690 err(1, "pledge");
7691 #endif
7692 if (argc < 1)
7693 usage_revert();
7694 if (patch_script_path && !pflag)
7695 errx(1, "-F option can only be used together with -p option");
7697 cwd = getcwd(NULL, 0);
7698 if (cwd == NULL) {
7699 error = got_error_from_errno("getcwd");
7700 goto done;
7702 error = got_worktree_open(&worktree, cwd);
7703 if (error) {
7704 if (error->code == GOT_ERR_NOT_WORKTREE)
7705 error = wrap_not_worktree_error(error, "revert", cwd);
7706 goto done;
7709 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7710 NULL);
7711 if (error != NULL)
7712 goto done;
7714 if (patch_script_path) {
7715 patch_script_file = fopen(patch_script_path, "re");
7716 if (patch_script_file == NULL) {
7717 error = got_error_from_errno2("fopen",
7718 patch_script_path);
7719 goto done;
7722 error = apply_unveil(got_repo_get_path(repo), 1,
7723 got_worktree_get_root_path(worktree));
7724 if (error)
7725 goto done;
7727 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7728 if (error)
7729 goto done;
7731 if (!can_recurse) {
7732 char *ondisk_path;
7733 struct stat sb;
7734 TAILQ_FOREACH(pe, &paths, entry) {
7735 if (asprintf(&ondisk_path, "%s/%s",
7736 got_worktree_get_root_path(worktree),
7737 pe->path) == -1) {
7738 error = got_error_from_errno("asprintf");
7739 goto done;
7741 if (lstat(ondisk_path, &sb) == -1) {
7742 if (errno == ENOENT) {
7743 free(ondisk_path);
7744 continue;
7746 error = got_error_from_errno2("lstat",
7747 ondisk_path);
7748 free(ondisk_path);
7749 goto done;
7751 free(ondisk_path);
7752 if (S_ISDIR(sb.st_mode)) {
7753 error = got_error_msg(GOT_ERR_BAD_PATH,
7754 "reverting directories requires -R option");
7755 goto done;
7760 cpa.patch_script_file = patch_script_file;
7761 cpa.action = "revert";
7762 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7763 pflag ? choose_patch : NULL, &cpa, repo);
7764 done:
7765 if (patch_script_file && fclose(patch_script_file) == EOF &&
7766 error == NULL)
7767 error = got_error_from_errno2("fclose", patch_script_path);
7768 if (repo) {
7769 const struct got_error *close_err = got_repo_close(repo);
7770 if (error == NULL)
7771 error = close_err;
7773 if (worktree)
7774 got_worktree_close(worktree);
7775 free(path);
7776 free(cwd);
7777 return error;
7780 __dead static void
7781 usage_commit(void)
7783 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7784 "[path ...]\n", getprogname());
7785 exit(1);
7788 struct collect_commit_logmsg_arg {
7789 const char *cmdline_log;
7790 const char *prepared_log;
7791 int non_interactive;
7792 const char *editor;
7793 const char *worktree_path;
7794 const char *branch_name;
7795 const char *repo_path;
7796 char *logmsg_path;
7800 static const struct got_error *
7801 read_prepared_logmsg(char **logmsg, const char *path)
7803 const struct got_error *err = NULL;
7804 FILE *f = NULL;
7805 struct stat sb;
7806 size_t r;
7808 *logmsg = NULL;
7809 memset(&sb, 0, sizeof(sb));
7811 f = fopen(path, "re");
7812 if (f == NULL)
7813 return got_error_from_errno2("fopen", path);
7815 if (fstat(fileno(f), &sb) == -1) {
7816 err = got_error_from_errno2("fstat", path);
7817 goto done;
7819 if (sb.st_size == 0) {
7820 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7821 goto done;
7824 *logmsg = malloc(sb.st_size + 1);
7825 if (*logmsg == NULL) {
7826 err = got_error_from_errno("malloc");
7827 goto done;
7830 r = fread(*logmsg, 1, sb.st_size, f);
7831 if (r != sb.st_size) {
7832 if (ferror(f))
7833 err = got_error_from_errno2("fread", path);
7834 else
7835 err = got_error(GOT_ERR_IO);
7836 goto done;
7838 (*logmsg)[sb.st_size] = '\0';
7839 done:
7840 if (fclose(f) == EOF && err == NULL)
7841 err = got_error_from_errno2("fclose", path);
7842 if (err) {
7843 free(*logmsg);
7844 *logmsg = NULL;
7846 return err;
7850 static const struct got_error *
7851 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7852 void *arg)
7854 char *initial_content = NULL;
7855 struct got_pathlist_entry *pe;
7856 const struct got_error *err = NULL;
7857 char *template = NULL;
7858 struct collect_commit_logmsg_arg *a = arg;
7859 int initial_content_len;
7860 int fd = -1;
7861 size_t len;
7863 /* if a message was specified on the command line, just use it */
7864 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7865 len = strlen(a->cmdline_log) + 1;
7866 *logmsg = malloc(len + 1);
7867 if (*logmsg == NULL)
7868 return got_error_from_errno("malloc");
7869 strlcpy(*logmsg, a->cmdline_log, len);
7870 return NULL;
7871 } else if (a->prepared_log != NULL && a->non_interactive)
7872 return read_prepared_logmsg(logmsg, a->prepared_log);
7874 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7875 return got_error_from_errno("asprintf");
7877 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7878 if (err)
7879 goto done;
7881 if (a->prepared_log) {
7882 char *msg;
7883 err = read_prepared_logmsg(&msg, a->prepared_log);
7884 if (err)
7885 goto done;
7886 if (write(fd, msg, strlen(msg)) == -1) {
7887 err = got_error_from_errno2("write", a->logmsg_path);
7888 free(msg);
7889 goto done;
7891 free(msg);
7894 initial_content_len = asprintf(&initial_content,
7895 "\n# changes to be committed on branch %s:\n",
7896 a->branch_name);
7897 if (initial_content_len == -1) {
7898 err = got_error_from_errno("asprintf");
7899 goto done;
7902 if (write(fd, initial_content, initial_content_len) == -1) {
7903 err = got_error_from_errno2("write", a->logmsg_path);
7904 goto done;
7907 TAILQ_FOREACH(pe, commitable_paths, entry) {
7908 struct got_commitable *ct = pe->data;
7909 dprintf(fd, "# %c %s\n",
7910 got_commitable_get_status(ct),
7911 got_commitable_get_path(ct));
7914 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7915 initial_content_len, a->prepared_log ? 0 : 1);
7916 done:
7917 free(initial_content);
7918 free(template);
7920 if (fd != -1 && close(fd) == -1 && err == NULL)
7921 err = got_error_from_errno2("close", a->logmsg_path);
7923 /* Editor is done; we can now apply unveil(2) */
7924 if (err == NULL)
7925 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7926 if (err) {
7927 free(*logmsg);
7928 *logmsg = NULL;
7930 return err;
7933 static const struct got_error *
7934 cmd_commit(int argc, char *argv[])
7936 const struct got_error *error = NULL;
7937 struct got_worktree *worktree = NULL;
7938 struct got_repository *repo = NULL;
7939 char *cwd = NULL, *id_str = NULL;
7940 struct got_object_id *id = NULL;
7941 const char *logmsg = NULL;
7942 char *prepared_logmsg = NULL;
7943 struct collect_commit_logmsg_arg cl_arg;
7944 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7945 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7946 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7947 struct got_pathlist_head paths;
7949 TAILQ_INIT(&paths);
7950 cl_arg.logmsg_path = NULL;
7952 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7953 switch (ch) {
7954 case 'F':
7955 if (logmsg != NULL)
7956 option_conflict('F', 'm');
7957 prepared_logmsg = realpath(optarg, NULL);
7958 if (prepared_logmsg == NULL)
7959 return got_error_from_errno2("realpath",
7960 optarg);
7961 break;
7962 case 'm':
7963 if (prepared_logmsg)
7964 option_conflict('m', 'F');
7965 logmsg = optarg;
7966 break;
7967 case 'N':
7968 non_interactive = 1;
7969 break;
7970 case 'S':
7971 allow_bad_symlinks = 1;
7972 break;
7973 default:
7974 usage_commit();
7975 /* NOTREACHED */
7979 argc -= optind;
7980 argv += optind;
7982 #ifndef PROFILE
7983 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7984 "unveil", NULL) == -1)
7985 err(1, "pledge");
7986 #endif
7987 cwd = getcwd(NULL, 0);
7988 if (cwd == NULL) {
7989 error = got_error_from_errno("getcwd");
7990 goto done;
7992 error = got_worktree_open(&worktree, cwd);
7993 if (error) {
7994 if (error->code == GOT_ERR_NOT_WORKTREE)
7995 error = wrap_not_worktree_error(error, "commit", cwd);
7996 goto done;
7999 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8000 if (error)
8001 goto done;
8002 if (rebase_in_progress) {
8003 error = got_error(GOT_ERR_REBASING);
8004 goto done;
8007 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8008 worktree);
8009 if (error)
8010 goto done;
8012 error = get_gitconfig_path(&gitconfig_path);
8013 if (error)
8014 goto done;
8015 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8016 gitconfig_path);
8017 if (error != NULL)
8018 goto done;
8020 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8021 if (error)
8022 goto done;
8023 if (merge_in_progress) {
8024 error = got_error(GOT_ERR_MERGE_BUSY);
8025 goto done;
8028 error = get_author(&author, repo, worktree);
8029 if (error)
8030 return error;
8033 * unveil(2) traverses exec(2); if an editor is used we have
8034 * to apply unveil after the log message has been written.
8036 if (logmsg == NULL || strlen(logmsg) == 0)
8037 error = get_editor(&editor);
8038 else
8039 error = apply_unveil(got_repo_get_path(repo), 0,
8040 got_worktree_get_root_path(worktree));
8041 if (error)
8042 goto done;
8044 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8045 if (error)
8046 goto done;
8048 cl_arg.editor = editor;
8049 cl_arg.cmdline_log = logmsg;
8050 cl_arg.prepared_log = prepared_logmsg;
8051 cl_arg.non_interactive = non_interactive;
8052 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8053 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8054 if (!histedit_in_progress) {
8055 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8056 error = got_error(GOT_ERR_COMMIT_BRANCH);
8057 goto done;
8059 cl_arg.branch_name += 11;
8061 cl_arg.repo_path = got_repo_get_path(repo);
8062 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8063 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8064 print_status, NULL, repo);
8065 if (error) {
8066 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8067 cl_arg.logmsg_path != NULL)
8068 preserve_logmsg = 1;
8069 goto done;
8072 error = got_object_id_str(&id_str, id);
8073 if (error)
8074 goto done;
8075 printf("Created commit %s\n", id_str);
8076 done:
8077 if (preserve_logmsg) {
8078 fprintf(stderr, "%s: log message preserved in %s\n",
8079 getprogname(), cl_arg.logmsg_path);
8080 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8081 error == NULL)
8082 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8083 free(cl_arg.logmsg_path);
8084 if (repo) {
8085 const struct got_error *close_err = got_repo_close(repo);
8086 if (error == NULL)
8087 error = close_err;
8089 if (worktree)
8090 got_worktree_close(worktree);
8091 free(cwd);
8092 free(id_str);
8093 free(gitconfig_path);
8094 free(editor);
8095 free(author);
8096 free(prepared_logmsg);
8097 return error;
8100 __dead static void
8101 usage_send(void)
8103 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8104 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8105 "[remote-repository]\n", getprogname());
8106 exit(1);
8109 static void
8110 print_load_info(int print_colored, int print_found, int print_trees,
8111 int ncolored, int nfound, int ntrees)
8113 if (print_colored) {
8114 printf("%d commit%s colored", ncolored,
8115 ncolored == 1 ? "" : "s");
8117 if (print_found) {
8118 printf("%s%d object%s found",
8119 ncolored > 0 ? "; " : "",
8120 nfound, nfound == 1 ? "" : "s");
8122 if (print_trees) {
8123 printf("; %d tree%s scanned", ntrees,
8124 ntrees == 1 ? "" : "s");
8128 struct got_send_progress_arg {
8129 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8130 int verbosity;
8131 int last_ncolored;
8132 int last_nfound;
8133 int last_ntrees;
8134 int loading_done;
8135 int last_ncommits;
8136 int last_nobj_total;
8137 int last_p_deltify;
8138 int last_p_written;
8139 int last_p_sent;
8140 int printed_something;
8141 int sent_something;
8142 struct got_pathlist_head *delete_branches;
8145 static const struct got_error *
8146 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8147 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8148 int nobj_written, off_t bytes_sent, const char *refname, int success)
8150 struct got_send_progress_arg *a = arg;
8151 char scaled_packsize[FMT_SCALED_STRSIZE];
8152 char scaled_sent[FMT_SCALED_STRSIZE];
8153 int p_deltify = 0, p_written = 0, p_sent = 0;
8154 int print_colored = 0, print_found = 0, print_trees = 0;
8155 int print_searching = 0, print_total = 0;
8156 int print_deltify = 0, print_written = 0, print_sent = 0;
8158 if (a->verbosity < 0)
8159 return NULL;
8161 if (refname) {
8162 const char *status = success ? "accepted" : "rejected";
8164 if (success) {
8165 struct got_pathlist_entry *pe;
8166 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8167 const char *branchname = pe->path;
8168 if (got_path_cmp(branchname, refname,
8169 strlen(branchname), strlen(refname)) == 0) {
8170 status = "deleted";
8171 a->sent_something = 1;
8172 break;
8177 if (a->printed_something)
8178 putchar('\n');
8179 printf("Server has %s %s", status, refname);
8180 a->printed_something = 1;
8181 return NULL;
8184 if (a->last_ncolored != ncolored) {
8185 print_colored = 1;
8186 a->last_ncolored = ncolored;
8189 if (a->last_nfound != nfound) {
8190 print_colored = 1;
8191 print_found = 1;
8192 a->last_nfound = nfound;
8195 if (a->last_ntrees != ntrees) {
8196 print_colored = 1;
8197 print_found = 1;
8198 print_trees = 1;
8199 a->last_ntrees = ntrees;
8202 if ((print_colored || print_found || print_trees) &&
8203 !a->loading_done) {
8204 printf("\r");
8205 print_load_info(print_colored, print_found, print_trees,
8206 ncolored, nfound, ntrees);
8207 a->printed_something = 1;
8208 fflush(stdout);
8209 return NULL;
8210 } else if (!a->loading_done) {
8211 printf("\r");
8212 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8213 printf("\n");
8214 a->loading_done = 1;
8217 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8218 return got_error_from_errno("fmt_scaled");
8219 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8220 return got_error_from_errno("fmt_scaled");
8222 if (a->last_ncommits != ncommits) {
8223 print_searching = 1;
8224 a->last_ncommits = ncommits;
8227 if (a->last_nobj_total != nobj_total) {
8228 print_searching = 1;
8229 print_total = 1;
8230 a->last_nobj_total = nobj_total;
8233 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8234 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8235 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8236 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8237 return got_error(GOT_ERR_NO_SPACE);
8240 if (nobj_deltify > 0 || nobj_written > 0) {
8241 if (nobj_deltify > 0) {
8242 p_deltify = (nobj_deltify * 100) / nobj_total;
8243 if (p_deltify != a->last_p_deltify) {
8244 a->last_p_deltify = p_deltify;
8245 print_searching = 1;
8246 print_total = 1;
8247 print_deltify = 1;
8250 if (nobj_written > 0) {
8251 p_written = (nobj_written * 100) / nobj_total;
8252 if (p_written != a->last_p_written) {
8253 a->last_p_written = p_written;
8254 print_searching = 1;
8255 print_total = 1;
8256 print_deltify = 1;
8257 print_written = 1;
8262 if (bytes_sent > 0) {
8263 p_sent = (bytes_sent * 100) / packfile_size;
8264 if (p_sent != a->last_p_sent) {
8265 a->last_p_sent = p_sent;
8266 print_searching = 1;
8267 print_total = 1;
8268 print_deltify = 1;
8269 print_written = 1;
8270 print_sent = 1;
8272 a->sent_something = 1;
8275 if (print_searching || print_total || print_deltify || print_written ||
8276 print_sent)
8277 printf("\r");
8278 if (print_searching)
8279 printf("packing %d reference%s", ncommits,
8280 ncommits == 1 ? "" : "s");
8281 if (print_total)
8282 printf("; %d object%s", nobj_total,
8283 nobj_total == 1 ? "" : "s");
8284 if (print_deltify)
8285 printf("; deltify: %d%%", p_deltify);
8286 if (print_sent)
8287 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8288 scaled_packsize, p_sent);
8289 else if (print_written)
8290 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8291 scaled_packsize, p_written);
8292 if (print_searching || print_total || print_deltify ||
8293 print_written || print_sent) {
8294 a->printed_something = 1;
8295 fflush(stdout);
8297 return NULL;
8300 static const struct got_error *
8301 cmd_send(int argc, char *argv[])
8303 const struct got_error *error = NULL;
8304 char *cwd = NULL, *repo_path = NULL;
8305 const char *remote_name;
8306 char *proto = NULL, *host = NULL, *port = NULL;
8307 char *repo_name = NULL, *server_path = NULL;
8308 const struct got_remote_repo *remotes, *remote = NULL;
8309 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8310 struct got_repository *repo = NULL;
8311 struct got_worktree *worktree = NULL;
8312 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8313 struct got_pathlist_head branches;
8314 struct got_pathlist_head tags;
8315 struct got_reflist_head all_branches;
8316 struct got_reflist_head all_tags;
8317 struct got_pathlist_head delete_args;
8318 struct got_pathlist_head delete_branches;
8319 struct got_reflist_entry *re;
8320 struct got_pathlist_entry *pe;
8321 int i, ch, sendfd = -1, sendstatus;
8322 pid_t sendpid = -1;
8323 struct got_send_progress_arg spa;
8324 int verbosity = 0, overwrite_refs = 0;
8325 int send_all_branches = 0, send_all_tags = 0;
8326 struct got_reference *ref = NULL;
8328 TAILQ_INIT(&branches);
8329 TAILQ_INIT(&tags);
8330 TAILQ_INIT(&all_branches);
8331 TAILQ_INIT(&all_tags);
8332 TAILQ_INIT(&delete_args);
8333 TAILQ_INIT(&delete_branches);
8335 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8336 switch (ch) {
8337 case 'a':
8338 send_all_branches = 1;
8339 break;
8340 case 'b':
8341 error = got_pathlist_append(&branches, optarg, NULL);
8342 if (error)
8343 return error;
8344 nbranches++;
8345 break;
8346 case 'd':
8347 error = got_pathlist_append(&delete_args, optarg, NULL);
8348 if (error)
8349 return error;
8350 break;
8351 case 'f':
8352 overwrite_refs = 1;
8353 break;
8354 case 'r':
8355 repo_path = realpath(optarg, NULL);
8356 if (repo_path == NULL)
8357 return got_error_from_errno2("realpath",
8358 optarg);
8359 got_path_strip_trailing_slashes(repo_path);
8360 break;
8361 case 't':
8362 error = got_pathlist_append(&tags, optarg, NULL);
8363 if (error)
8364 return error;
8365 ntags++;
8366 break;
8367 case 'T':
8368 send_all_tags = 1;
8369 break;
8370 case 'v':
8371 if (verbosity < 0)
8372 verbosity = 0;
8373 else if (verbosity < 3)
8374 verbosity++;
8375 break;
8376 case 'q':
8377 verbosity = -1;
8378 break;
8379 default:
8380 usage_send();
8381 /* NOTREACHED */
8384 argc -= optind;
8385 argv += optind;
8387 if (send_all_branches && !TAILQ_EMPTY(&branches))
8388 option_conflict('a', 'b');
8389 if (send_all_tags && !TAILQ_EMPTY(&tags))
8390 option_conflict('T', 't');
8393 if (argc == 0)
8394 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8395 else if (argc == 1)
8396 remote_name = argv[0];
8397 else
8398 usage_send();
8400 cwd = getcwd(NULL, 0);
8401 if (cwd == NULL) {
8402 error = got_error_from_errno("getcwd");
8403 goto done;
8406 if (repo_path == NULL) {
8407 error = got_worktree_open(&worktree, cwd);
8408 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8409 goto done;
8410 else
8411 error = NULL;
8412 if (worktree) {
8413 repo_path =
8414 strdup(got_worktree_get_repo_path(worktree));
8415 if (repo_path == NULL)
8416 error = got_error_from_errno("strdup");
8417 if (error)
8418 goto done;
8419 } else {
8420 repo_path = strdup(cwd);
8421 if (repo_path == NULL) {
8422 error = got_error_from_errno("strdup");
8423 goto done;
8428 error = got_repo_open(&repo, repo_path, NULL);
8429 if (error)
8430 goto done;
8432 if (worktree) {
8433 worktree_conf = got_worktree_get_gotconfig(worktree);
8434 if (worktree_conf) {
8435 got_gotconfig_get_remotes(&nremotes, &remotes,
8436 worktree_conf);
8437 for (i = 0; i < nremotes; i++) {
8438 if (strcmp(remotes[i].name, remote_name) == 0) {
8439 remote = &remotes[i];
8440 break;
8445 if (remote == NULL) {
8446 repo_conf = got_repo_get_gotconfig(repo);
8447 if (repo_conf) {
8448 got_gotconfig_get_remotes(&nremotes, &remotes,
8449 repo_conf);
8450 for (i = 0; i < nremotes; i++) {
8451 if (strcmp(remotes[i].name, remote_name) == 0) {
8452 remote = &remotes[i];
8453 break;
8458 if (remote == NULL) {
8459 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8460 for (i = 0; i < nremotes; i++) {
8461 if (strcmp(remotes[i].name, remote_name) == 0) {
8462 remote = &remotes[i];
8463 break;
8467 if (remote == NULL) {
8468 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8469 goto done;
8472 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8473 &repo_name, remote->send_url);
8474 if (error)
8475 goto done;
8477 if (strcmp(proto, "git") == 0) {
8478 #ifndef PROFILE
8479 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8480 "sendfd dns inet unveil", NULL) == -1)
8481 err(1, "pledge");
8482 #endif
8483 } else if (strcmp(proto, "git+ssh") == 0 ||
8484 strcmp(proto, "ssh") == 0) {
8485 #ifndef PROFILE
8486 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8487 "sendfd unveil", NULL) == -1)
8488 err(1, "pledge");
8489 #endif
8490 } else if (strcmp(proto, "http") == 0 ||
8491 strcmp(proto, "git+http") == 0) {
8492 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8493 goto done;
8494 } else {
8495 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8496 goto done;
8499 error = got_dial_apply_unveil(proto);
8500 if (error)
8501 goto done;
8503 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8504 if (error)
8505 goto done;
8507 if (send_all_branches) {
8508 error = got_ref_list(&all_branches, repo, "refs/heads",
8509 got_ref_cmp_by_name, NULL);
8510 if (error)
8511 goto done;
8512 TAILQ_FOREACH(re, &all_branches, entry) {
8513 const char *branchname = got_ref_get_name(re->ref);
8514 error = got_pathlist_append(&branches,
8515 branchname, NULL);
8516 if (error)
8517 goto done;
8518 nbranches++;
8520 } else if (nbranches == 0) {
8521 for (i = 0; i < remote->nsend_branches; i++) {
8522 got_pathlist_append(&branches,
8523 remote->send_branches[i], NULL);
8527 if (send_all_tags) {
8528 error = got_ref_list(&all_tags, repo, "refs/tags",
8529 got_ref_cmp_by_name, NULL);
8530 if (error)
8531 goto done;
8532 TAILQ_FOREACH(re, &all_tags, entry) {
8533 const char *tagname = got_ref_get_name(re->ref);
8534 error = got_pathlist_append(&tags,
8535 tagname, NULL);
8536 if (error)
8537 goto done;
8538 ntags++;
8543 * To prevent accidents only branches in refs/heads/ can be deleted
8544 * with 'got send -d'.
8545 * Deleting anything else requires local repository access or Git.
8547 TAILQ_FOREACH(pe, &delete_args, entry) {
8548 const char *branchname = pe->path;
8549 char *s;
8550 struct got_pathlist_entry *new;
8551 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8552 s = strdup(branchname);
8553 if (s == NULL) {
8554 error = got_error_from_errno("strdup");
8555 goto done;
8557 } else {
8558 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8559 error = got_error_from_errno("asprintf");
8560 goto done;
8563 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8564 if (error || new == NULL /* duplicate */)
8565 free(s);
8566 if (error)
8567 goto done;
8568 ndelete_branches++;
8571 if (nbranches == 0 && ndelete_branches == 0) {
8572 struct got_reference *head_ref;
8573 if (worktree)
8574 error = got_ref_open(&head_ref, repo,
8575 got_worktree_get_head_ref_name(worktree), 0);
8576 else
8577 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8578 if (error)
8579 goto done;
8580 if (got_ref_is_symbolic(head_ref)) {
8581 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8582 got_ref_close(head_ref);
8583 if (error)
8584 goto done;
8585 } else
8586 ref = head_ref;
8587 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8588 NULL);
8589 if (error)
8590 goto done;
8591 nbranches++;
8594 if (verbosity >= 0)
8595 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8596 port ? ":" : "", port ? port : "");
8598 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8599 server_path, verbosity);
8600 if (error)
8601 goto done;
8603 memset(&spa, 0, sizeof(spa));
8604 spa.last_scaled_packsize[0] = '\0';
8605 spa.last_p_deltify = -1;
8606 spa.last_p_written = -1;
8607 spa.verbosity = verbosity;
8608 spa.delete_branches = &delete_branches;
8609 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8610 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8611 check_cancelled, NULL);
8612 if (spa.printed_something)
8613 putchar('\n');
8614 if (error)
8615 goto done;
8616 if (!spa.sent_something && verbosity >= 0)
8617 printf("Already up-to-date\n");
8618 done:
8619 if (sendpid > 0) {
8620 if (kill(sendpid, SIGTERM) == -1)
8621 error = got_error_from_errno("kill");
8622 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8623 error = got_error_from_errno("waitpid");
8625 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8626 error = got_error_from_errno("close");
8627 if (repo) {
8628 const struct got_error *close_err = got_repo_close(repo);
8629 if (error == NULL)
8630 error = close_err;
8632 if (worktree)
8633 got_worktree_close(worktree);
8634 if (ref)
8635 got_ref_close(ref);
8636 got_pathlist_free(&branches);
8637 got_pathlist_free(&tags);
8638 got_ref_list_free(&all_branches);
8639 got_ref_list_free(&all_tags);
8640 got_pathlist_free(&delete_args);
8641 TAILQ_FOREACH(pe, &delete_branches, entry)
8642 free((char *)pe->path);
8643 got_pathlist_free(&delete_branches);
8644 free(cwd);
8645 free(repo_path);
8646 free(proto);
8647 free(host);
8648 free(port);
8649 free(server_path);
8650 free(repo_name);
8651 return error;
8654 __dead static void
8655 usage_cherrypick(void)
8657 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8658 exit(1);
8661 static const struct got_error *
8662 cmd_cherrypick(int argc, char *argv[])
8664 const struct got_error *error = NULL;
8665 struct got_worktree *worktree = NULL;
8666 struct got_repository *repo = NULL;
8667 char *cwd = NULL, *commit_id_str = NULL;
8668 struct got_object_id *commit_id = NULL;
8669 struct got_commit_object *commit = NULL;
8670 struct got_object_qid *pid;
8671 int ch;
8672 struct got_update_progress_arg upa;
8674 while ((ch = getopt(argc, argv, "")) != -1) {
8675 switch (ch) {
8676 default:
8677 usage_cherrypick();
8678 /* NOTREACHED */
8682 argc -= optind;
8683 argv += optind;
8685 #ifndef PROFILE
8686 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8687 "unveil", NULL) == -1)
8688 err(1, "pledge");
8689 #endif
8690 if (argc != 1)
8691 usage_cherrypick();
8693 cwd = getcwd(NULL, 0);
8694 if (cwd == NULL) {
8695 error = got_error_from_errno("getcwd");
8696 goto done;
8698 error = got_worktree_open(&worktree, cwd);
8699 if (error) {
8700 if (error->code == GOT_ERR_NOT_WORKTREE)
8701 error = wrap_not_worktree_error(error, "cherrypick",
8702 cwd);
8703 goto done;
8706 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8707 NULL);
8708 if (error != NULL)
8709 goto done;
8711 error = apply_unveil(got_repo_get_path(repo), 0,
8712 got_worktree_get_root_path(worktree));
8713 if (error)
8714 goto done;
8716 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8717 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8718 if (error)
8719 goto done;
8720 error = got_object_id_str(&commit_id_str, commit_id);
8721 if (error)
8722 goto done;
8724 error = got_object_open_as_commit(&commit, repo, commit_id);
8725 if (error)
8726 goto done;
8727 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8728 memset(&upa, 0, sizeof(upa));
8729 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8730 commit_id, repo, update_progress, &upa, check_cancelled,
8731 NULL);
8732 if (error != NULL)
8733 goto done;
8735 if (upa.did_something)
8736 printf("Merged commit %s\n", commit_id_str);
8737 print_merge_progress_stats(&upa);
8738 done:
8739 if (commit)
8740 got_object_commit_close(commit);
8741 free(commit_id_str);
8742 if (worktree)
8743 got_worktree_close(worktree);
8744 if (repo) {
8745 const struct got_error *close_err = got_repo_close(repo);
8746 if (error == NULL)
8747 error = close_err;
8749 return error;
8752 __dead static void
8753 usage_backout(void)
8755 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8756 exit(1);
8759 static const struct got_error *
8760 cmd_backout(int argc, char *argv[])
8762 const struct got_error *error = NULL;
8763 struct got_worktree *worktree = NULL;
8764 struct got_repository *repo = NULL;
8765 char *cwd = NULL, *commit_id_str = NULL;
8766 struct got_object_id *commit_id = NULL;
8767 struct got_commit_object *commit = NULL;
8768 struct got_object_qid *pid;
8769 int ch;
8770 struct got_update_progress_arg upa;
8772 while ((ch = getopt(argc, argv, "")) != -1) {
8773 switch (ch) {
8774 default:
8775 usage_backout();
8776 /* NOTREACHED */
8780 argc -= optind;
8781 argv += optind;
8783 #ifndef PROFILE
8784 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8785 "unveil", NULL) == -1)
8786 err(1, "pledge");
8787 #endif
8788 if (argc != 1)
8789 usage_backout();
8791 cwd = getcwd(NULL, 0);
8792 if (cwd == NULL) {
8793 error = got_error_from_errno("getcwd");
8794 goto done;
8796 error = got_worktree_open(&worktree, cwd);
8797 if (error) {
8798 if (error->code == GOT_ERR_NOT_WORKTREE)
8799 error = wrap_not_worktree_error(error, "backout", cwd);
8800 goto done;
8803 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8804 NULL);
8805 if (error != NULL)
8806 goto done;
8808 error = apply_unveil(got_repo_get_path(repo), 0,
8809 got_worktree_get_root_path(worktree));
8810 if (error)
8811 goto done;
8813 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8814 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8815 if (error)
8816 goto done;
8817 error = got_object_id_str(&commit_id_str, commit_id);
8818 if (error)
8819 goto done;
8821 error = got_object_open_as_commit(&commit, repo, commit_id);
8822 if (error)
8823 goto done;
8824 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8825 if (pid == NULL) {
8826 error = got_error(GOT_ERR_ROOT_COMMIT);
8827 goto done;
8830 memset(&upa, 0, sizeof(upa));
8831 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8832 repo, update_progress, &upa, check_cancelled, NULL);
8833 if (error != NULL)
8834 goto done;
8836 if (upa.did_something)
8837 printf("Backed out commit %s\n", commit_id_str);
8838 print_merge_progress_stats(&upa);
8839 done:
8840 if (commit)
8841 got_object_commit_close(commit);
8842 free(commit_id_str);
8843 if (worktree)
8844 got_worktree_close(worktree);
8845 if (repo) {
8846 const struct got_error *close_err = got_repo_close(repo);
8847 if (error == NULL)
8848 error = close_err;
8850 return error;
8853 __dead static void
8854 usage_rebase(void)
8856 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8857 getprogname());
8858 exit(1);
8861 void
8862 trim_logmsg(char *logmsg, int limit)
8864 char *nl;
8865 size_t len;
8867 len = strlen(logmsg);
8868 if (len > limit)
8869 len = limit;
8870 logmsg[len] = '\0';
8871 nl = strchr(logmsg, '\n');
8872 if (nl)
8873 *nl = '\0';
8876 static const struct got_error *
8877 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8879 const struct got_error *err;
8880 char *logmsg0 = NULL;
8881 const char *s;
8883 err = got_object_commit_get_logmsg(&logmsg0, commit);
8884 if (err)
8885 return err;
8887 s = logmsg0;
8888 while (isspace((unsigned char)s[0]))
8889 s++;
8891 *logmsg = strdup(s);
8892 if (*logmsg == NULL) {
8893 err = got_error_from_errno("strdup");
8894 goto done;
8897 trim_logmsg(*logmsg, limit);
8898 done:
8899 free(logmsg0);
8900 return err;
8903 static const struct got_error *
8904 show_rebase_merge_conflict(struct got_object_id *id,
8905 struct got_repository *repo)
8907 const struct got_error *err;
8908 struct got_commit_object *commit = NULL;
8909 char *id_str = NULL, *logmsg = NULL;
8911 err = got_object_open_as_commit(&commit, repo, id);
8912 if (err)
8913 return err;
8915 err = got_object_id_str(&id_str, id);
8916 if (err)
8917 goto done;
8919 id_str[12] = '\0';
8921 err = get_short_logmsg(&logmsg, 42, commit);
8922 if (err)
8923 goto done;
8925 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8926 done:
8927 free(id_str);
8928 got_object_commit_close(commit);
8929 free(logmsg);
8930 return err;
8933 static const struct got_error *
8934 show_rebase_progress(struct got_commit_object *commit,
8935 struct got_object_id *old_id, struct got_object_id *new_id)
8937 const struct got_error *err;
8938 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8940 err = got_object_id_str(&old_id_str, old_id);
8941 if (err)
8942 goto done;
8944 if (new_id) {
8945 err = got_object_id_str(&new_id_str, new_id);
8946 if (err)
8947 goto done;
8950 old_id_str[12] = '\0';
8951 if (new_id_str)
8952 new_id_str[12] = '\0';
8954 err = get_short_logmsg(&logmsg, 42, commit);
8955 if (err)
8956 goto done;
8958 printf("%s -> %s: %s\n", old_id_str,
8959 new_id_str ? new_id_str : "no-op change", logmsg);
8960 done:
8961 free(old_id_str);
8962 free(new_id_str);
8963 free(logmsg);
8964 return err;
8967 static const struct got_error *
8968 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8969 struct got_reference *branch, struct got_reference *new_base_branch,
8970 struct got_reference *tmp_branch, struct got_repository *repo,
8971 int create_backup)
8973 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8974 return got_worktree_rebase_complete(worktree, fileindex,
8975 new_base_branch, tmp_branch, branch, repo, create_backup);
8978 static const struct got_error *
8979 rebase_commit(struct got_pathlist_head *merged_paths,
8980 struct got_worktree *worktree, struct got_fileindex *fileindex,
8981 struct got_reference *tmp_branch,
8982 struct got_object_id *commit_id, struct got_repository *repo)
8984 const struct got_error *error;
8985 struct got_commit_object *commit;
8986 struct got_object_id *new_commit_id;
8988 error = got_object_open_as_commit(&commit, repo, commit_id);
8989 if (error)
8990 return error;
8992 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8993 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8994 if (error) {
8995 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8996 goto done;
8997 error = show_rebase_progress(commit, commit_id, NULL);
8998 } else {
8999 error = show_rebase_progress(commit, commit_id, new_commit_id);
9000 free(new_commit_id);
9002 done:
9003 got_object_commit_close(commit);
9004 return error;
9007 struct check_path_prefix_arg {
9008 const char *path_prefix;
9009 size_t len;
9010 int errcode;
9013 static const struct got_error *
9014 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9015 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9016 struct got_object_id *id1, struct got_object_id *id2,
9017 const char *path1, const char *path2,
9018 mode_t mode1, mode_t mode2, struct got_repository *repo)
9020 struct check_path_prefix_arg *a = arg;
9022 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9023 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9024 return got_error(a->errcode);
9026 return NULL;
9029 static const struct got_error *
9030 check_path_prefix(struct got_object_id *parent_id,
9031 struct got_object_id *commit_id, const char *path_prefix,
9032 int errcode, struct got_repository *repo)
9034 const struct got_error *err;
9035 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9036 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9037 struct check_path_prefix_arg cpp_arg;
9039 if (got_path_is_root_dir(path_prefix))
9040 return NULL;
9042 err = got_object_open_as_commit(&commit, repo, commit_id);
9043 if (err)
9044 goto done;
9046 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9047 if (err)
9048 goto done;
9050 err = got_object_open_as_tree(&tree1, repo,
9051 got_object_commit_get_tree_id(parent_commit));
9052 if (err)
9053 goto done;
9055 err = got_object_open_as_tree(&tree2, repo,
9056 got_object_commit_get_tree_id(commit));
9057 if (err)
9058 goto done;
9060 cpp_arg.path_prefix = path_prefix;
9061 while (cpp_arg.path_prefix[0] == '/')
9062 cpp_arg.path_prefix++;
9063 cpp_arg.len = strlen(cpp_arg.path_prefix);
9064 cpp_arg.errcode = errcode;
9065 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9066 check_path_prefix_in_diff, &cpp_arg, 0);
9067 done:
9068 if (tree1)
9069 got_object_tree_close(tree1);
9070 if (tree2)
9071 got_object_tree_close(tree2);
9072 if (commit)
9073 got_object_commit_close(commit);
9074 if (parent_commit)
9075 got_object_commit_close(parent_commit);
9076 return err;
9079 static const struct got_error *
9080 collect_commits(struct got_object_id_queue *commits,
9081 struct got_object_id *initial_commit_id,
9082 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9083 const char *path_prefix, int path_prefix_errcode,
9084 struct got_repository *repo)
9086 const struct got_error *err = NULL;
9087 struct got_commit_graph *graph = NULL;
9088 struct got_object_id *parent_id = NULL;
9089 struct got_object_qid *qid;
9090 struct got_object_id *commit_id = initial_commit_id;
9092 err = got_commit_graph_open(&graph, "/", 1);
9093 if (err)
9094 return err;
9096 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9097 check_cancelled, NULL);
9098 if (err)
9099 goto done;
9100 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9101 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9102 check_cancelled, NULL);
9103 if (err) {
9104 if (err->code == GOT_ERR_ITER_COMPLETED) {
9105 err = got_error_msg(GOT_ERR_ANCESTRY,
9106 "ran out of commits to rebase before "
9107 "youngest common ancestor commit has "
9108 "been reached?!?");
9110 goto done;
9111 } else {
9112 err = check_path_prefix(parent_id, commit_id,
9113 path_prefix, path_prefix_errcode, repo);
9114 if (err)
9115 goto done;
9117 err = got_object_qid_alloc(&qid, commit_id);
9118 if (err)
9119 goto done;
9120 STAILQ_INSERT_HEAD(commits, qid, entry);
9121 commit_id = parent_id;
9124 done:
9125 got_commit_graph_close(graph);
9126 return err;
9129 static const struct got_error *
9130 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9132 const struct got_error *err = NULL;
9133 time_t committer_time;
9134 struct tm tm;
9135 char datebuf[11]; /* YYYY-MM-DD + NUL */
9136 char *author0 = NULL, *author, *smallerthan;
9137 char *logmsg0 = NULL, *logmsg, *newline;
9139 committer_time = got_object_commit_get_committer_time(commit);
9140 if (gmtime_r(&committer_time, &tm) == NULL)
9141 return got_error_from_errno("gmtime_r");
9142 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9143 return got_error(GOT_ERR_NO_SPACE);
9145 author0 = strdup(got_object_commit_get_author(commit));
9146 if (author0 == NULL)
9147 return got_error_from_errno("strdup");
9148 author = author0;
9149 smallerthan = strchr(author, '<');
9150 if (smallerthan && smallerthan[1] != '\0')
9151 author = smallerthan + 1;
9152 author[strcspn(author, "@>")] = '\0';
9154 err = got_object_commit_get_logmsg(&logmsg0, commit);
9155 if (err)
9156 goto done;
9157 logmsg = logmsg0;
9158 while (*logmsg == '\n')
9159 logmsg++;
9160 newline = strchr(logmsg, '\n');
9161 if (newline)
9162 *newline = '\0';
9164 if (asprintf(brief_str, "%s %s %s",
9165 datebuf, author, logmsg) == -1)
9166 err = got_error_from_errno("asprintf");
9167 done:
9168 free(author0);
9169 free(logmsg0);
9170 return err;
9173 static const struct got_error *
9174 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9175 struct got_repository *repo)
9177 const struct got_error *err;
9178 char *id_str;
9180 err = got_object_id_str(&id_str, id);
9181 if (err)
9182 return err;
9184 err = got_ref_delete(ref, repo);
9185 if (err)
9186 goto done;
9188 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9189 done:
9190 free(id_str);
9191 return err;
9194 static const struct got_error *
9195 print_backup_ref(const char *branch_name, const char *new_id_str,
9196 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9197 struct got_reflist_object_id_map *refs_idmap,
9198 struct got_repository *repo)
9200 const struct got_error *err = NULL;
9201 struct got_reflist_head *refs;
9202 char *refs_str = NULL;
9203 struct got_object_id *new_commit_id = NULL;
9204 struct got_commit_object *new_commit = NULL;
9205 char *new_commit_brief_str = NULL;
9206 struct got_object_id *yca_id = NULL;
9207 struct got_commit_object *yca_commit = NULL;
9208 char *yca_id_str = NULL, *yca_brief_str = NULL;
9209 char *custom_refs_str;
9211 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9212 return got_error_from_errno("asprintf");
9214 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9215 0, 0, refs_idmap, custom_refs_str);
9216 if (err)
9217 goto done;
9219 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9220 if (err)
9221 goto done;
9223 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9224 if (refs) {
9225 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9226 if (err)
9227 goto done;
9230 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9231 if (err)
9232 goto done;
9234 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9235 if (err)
9236 goto done;
9238 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9239 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9240 if (err)
9241 goto done;
9243 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9244 refs_str ? " (" : "", refs_str ? refs_str : "",
9245 refs_str ? ")" : "", new_commit_brief_str);
9246 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9247 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9248 free(refs_str);
9249 refs_str = NULL;
9251 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9252 if (err)
9253 goto done;
9255 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9256 if (err)
9257 goto done;
9259 err = got_object_id_str(&yca_id_str, yca_id);
9260 if (err)
9261 goto done;
9263 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9264 if (refs) {
9265 err = build_refs_str(&refs_str, refs, yca_id, repo);
9266 if (err)
9267 goto done;
9269 printf("history forked at %s%s%s%s\n %s\n",
9270 yca_id_str,
9271 refs_str ? " (" : "", refs_str ? refs_str : "",
9272 refs_str ? ")" : "", yca_brief_str);
9274 done:
9275 free(custom_refs_str);
9276 free(new_commit_id);
9277 free(refs_str);
9278 free(yca_id);
9279 free(yca_id_str);
9280 free(yca_brief_str);
9281 if (new_commit)
9282 got_object_commit_close(new_commit);
9283 if (yca_commit)
9284 got_object_commit_close(yca_commit);
9286 return NULL;
9289 static const struct got_error *
9290 process_backup_refs(const char *backup_ref_prefix,
9291 const char *wanted_branch_name,
9292 int delete, struct got_repository *repo)
9294 const struct got_error *err;
9295 struct got_reflist_head refs, backup_refs;
9296 struct got_reflist_entry *re;
9297 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9298 struct got_object_id *old_commit_id = NULL;
9299 char *branch_name = NULL;
9300 struct got_commit_object *old_commit = NULL;
9301 struct got_reflist_object_id_map *refs_idmap = NULL;
9302 int wanted_branch_found = 0;
9304 TAILQ_INIT(&refs);
9305 TAILQ_INIT(&backup_refs);
9307 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9308 if (err)
9309 return err;
9311 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9312 if (err)
9313 goto done;
9315 if (wanted_branch_name) {
9316 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9317 wanted_branch_name += 11;
9320 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9321 got_ref_cmp_by_commit_timestamp_descending, repo);
9322 if (err)
9323 goto done;
9325 TAILQ_FOREACH(re, &backup_refs, entry) {
9326 const char *refname = got_ref_get_name(re->ref);
9327 char *slash;
9329 err = check_cancelled(NULL);
9330 if (err)
9331 break;
9333 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9334 if (err)
9335 break;
9337 err = got_object_open_as_commit(&old_commit, repo,
9338 old_commit_id);
9339 if (err)
9340 break;
9342 if (strncmp(backup_ref_prefix, refname,
9343 backup_ref_prefix_len) == 0)
9344 refname += backup_ref_prefix_len;
9346 while (refname[0] == '/')
9347 refname++;
9349 branch_name = strdup(refname);
9350 if (branch_name == NULL) {
9351 err = got_error_from_errno("strdup");
9352 break;
9354 slash = strrchr(branch_name, '/');
9355 if (slash) {
9356 *slash = '\0';
9357 refname += strlen(branch_name) + 1;
9360 if (wanted_branch_name == NULL ||
9361 strcmp(wanted_branch_name, branch_name) == 0) {
9362 wanted_branch_found = 1;
9363 if (delete) {
9364 err = delete_backup_ref(re->ref,
9365 old_commit_id, repo);
9366 } else {
9367 err = print_backup_ref(branch_name, refname,
9368 old_commit_id, old_commit, refs_idmap,
9369 repo);
9371 if (err)
9372 break;
9375 free(old_commit_id);
9376 old_commit_id = NULL;
9377 free(branch_name);
9378 branch_name = NULL;
9379 got_object_commit_close(old_commit);
9380 old_commit = NULL;
9383 if (wanted_branch_name && !wanted_branch_found) {
9384 err = got_error_fmt(GOT_ERR_NOT_REF,
9385 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9387 done:
9388 if (refs_idmap)
9389 got_reflist_object_id_map_free(refs_idmap);
9390 got_ref_list_free(&refs);
9391 got_ref_list_free(&backup_refs);
9392 free(old_commit_id);
9393 free(branch_name);
9394 if (old_commit)
9395 got_object_commit_close(old_commit);
9396 return err;
9399 static const struct got_error *
9400 abort_progress(void *arg, unsigned char status, const char *path)
9403 * Unversioned files should not clutter progress output when
9404 * an operation is aborted.
9406 if (status == GOT_STATUS_UNVERSIONED)
9407 return NULL;
9409 return update_progress(arg, status, path);
9412 static const struct got_error *
9413 cmd_rebase(int argc, char *argv[])
9415 const struct got_error *error = NULL;
9416 struct got_worktree *worktree = NULL;
9417 struct got_repository *repo = NULL;
9418 struct got_fileindex *fileindex = NULL;
9419 char *cwd = NULL;
9420 struct got_reference *branch = NULL;
9421 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9422 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9423 struct got_object_id *resume_commit_id = NULL;
9424 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9425 struct got_commit_object *commit = NULL;
9426 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9427 int histedit_in_progress = 0, merge_in_progress = 0;
9428 int create_backup = 1, list_backups = 0, delete_backups = 0;
9429 struct got_object_id_queue commits;
9430 struct got_pathlist_head merged_paths;
9431 const struct got_object_id_queue *parent_ids;
9432 struct got_object_qid *qid, *pid;
9433 struct got_update_progress_arg upa;
9435 STAILQ_INIT(&commits);
9436 TAILQ_INIT(&merged_paths);
9437 memset(&upa, 0, sizeof(upa));
9439 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9440 switch (ch) {
9441 case 'a':
9442 abort_rebase = 1;
9443 break;
9444 case 'c':
9445 continue_rebase = 1;
9446 break;
9447 case 'l':
9448 list_backups = 1;
9449 break;
9450 case 'X':
9451 delete_backups = 1;
9452 break;
9453 default:
9454 usage_rebase();
9455 /* NOTREACHED */
9459 argc -= optind;
9460 argv += optind;
9462 #ifndef PROFILE
9463 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9464 "unveil", NULL) == -1)
9465 err(1, "pledge");
9466 #endif
9467 if (list_backups) {
9468 if (abort_rebase)
9469 option_conflict('l', 'a');
9470 if (continue_rebase)
9471 option_conflict('l', 'c');
9472 if (delete_backups)
9473 option_conflict('l', 'X');
9474 if (argc != 0 && argc != 1)
9475 usage_rebase();
9476 } else if (delete_backups) {
9477 if (abort_rebase)
9478 option_conflict('X', 'a');
9479 if (continue_rebase)
9480 option_conflict('X', 'c');
9481 if (list_backups)
9482 option_conflict('l', 'X');
9483 if (argc != 0 && argc != 1)
9484 usage_rebase();
9485 } else {
9486 if (abort_rebase && continue_rebase)
9487 usage_rebase();
9488 else if (abort_rebase || continue_rebase) {
9489 if (argc != 0)
9490 usage_rebase();
9491 } else if (argc != 1)
9492 usage_rebase();
9495 cwd = getcwd(NULL, 0);
9496 if (cwd == NULL) {
9497 error = got_error_from_errno("getcwd");
9498 goto done;
9500 error = got_worktree_open(&worktree, cwd);
9501 if (error) {
9502 if (list_backups || delete_backups) {
9503 if (error->code != GOT_ERR_NOT_WORKTREE)
9504 goto done;
9505 } else {
9506 if (error->code == GOT_ERR_NOT_WORKTREE)
9507 error = wrap_not_worktree_error(error,
9508 "rebase", cwd);
9509 goto done;
9513 error = got_repo_open(&repo,
9514 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9515 if (error != NULL)
9516 goto done;
9518 error = apply_unveil(got_repo_get_path(repo), 0,
9519 worktree ? got_worktree_get_root_path(worktree) : NULL);
9520 if (error)
9521 goto done;
9523 if (list_backups || delete_backups) {
9524 error = process_backup_refs(
9525 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9526 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9527 goto done; /* nothing else to do */
9530 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9531 worktree);
9532 if (error)
9533 goto done;
9534 if (histedit_in_progress) {
9535 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9536 goto done;
9539 error = got_worktree_merge_in_progress(&merge_in_progress,
9540 worktree, repo);
9541 if (error)
9542 goto done;
9543 if (merge_in_progress) {
9544 error = got_error(GOT_ERR_MERGE_BUSY);
9545 goto done;
9548 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9549 if (error)
9550 goto done;
9552 if (abort_rebase) {
9553 if (!rebase_in_progress) {
9554 error = got_error(GOT_ERR_NOT_REBASING);
9555 goto done;
9557 error = got_worktree_rebase_continue(&resume_commit_id,
9558 &new_base_branch, &tmp_branch, &branch, &fileindex,
9559 worktree, repo);
9560 if (error)
9561 goto done;
9562 printf("Switching work tree to %s\n",
9563 got_ref_get_symref_target(new_base_branch));
9564 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9565 new_base_branch, abort_progress, &upa);
9566 if (error)
9567 goto done;
9568 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9569 print_merge_progress_stats(&upa);
9570 goto done; /* nothing else to do */
9573 if (continue_rebase) {
9574 if (!rebase_in_progress) {
9575 error = got_error(GOT_ERR_NOT_REBASING);
9576 goto done;
9578 error = got_worktree_rebase_continue(&resume_commit_id,
9579 &new_base_branch, &tmp_branch, &branch, &fileindex,
9580 worktree, repo);
9581 if (error)
9582 goto done;
9584 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9585 resume_commit_id, repo);
9586 if (error)
9587 goto done;
9589 yca_id = got_object_id_dup(resume_commit_id);
9590 if (yca_id == NULL) {
9591 error = got_error_from_errno("got_object_id_dup");
9592 goto done;
9594 } else {
9595 error = got_ref_open(&branch, repo, argv[0], 0);
9596 if (error != NULL)
9597 goto done;
9600 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9601 if (error)
9602 goto done;
9604 if (!continue_rebase) {
9605 struct got_object_id *base_commit_id;
9607 base_commit_id = got_worktree_get_base_commit_id(worktree);
9608 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9609 base_commit_id, branch_head_commit_id, 1, repo,
9610 check_cancelled, NULL);
9611 if (error)
9612 goto done;
9613 if (yca_id == NULL) {
9614 error = got_error_msg(GOT_ERR_ANCESTRY,
9615 "specified branch shares no common ancestry "
9616 "with work tree's branch");
9617 goto done;
9620 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9621 if (error) {
9622 if (error->code != GOT_ERR_ANCESTRY)
9623 goto done;
9624 error = NULL;
9625 } else {
9626 struct got_pathlist_head paths;
9627 printf("%s is already based on %s\n",
9628 got_ref_get_name(branch),
9629 got_worktree_get_head_ref_name(worktree));
9630 error = switch_head_ref(branch, branch_head_commit_id,
9631 worktree, repo);
9632 if (error)
9633 goto done;
9634 error = got_worktree_set_base_commit_id(worktree, repo,
9635 branch_head_commit_id);
9636 if (error)
9637 goto done;
9638 TAILQ_INIT(&paths);
9639 error = got_pathlist_append(&paths, "", NULL);
9640 if (error)
9641 goto done;
9642 error = got_worktree_checkout_files(worktree,
9643 &paths, repo, update_progress, &upa,
9644 check_cancelled, NULL);
9645 got_pathlist_free(&paths);
9646 if (error)
9647 goto done;
9648 if (upa.did_something) {
9649 char *id_str;
9650 error = got_object_id_str(&id_str,
9651 branch_head_commit_id);
9652 if (error)
9653 goto done;
9654 printf("Updated to %s: %s\n",
9655 got_worktree_get_head_ref_name(worktree),
9656 id_str);
9657 free(id_str);
9658 } else
9659 printf("Already up-to-date\n");
9660 print_update_progress_stats(&upa);
9661 goto done;
9665 commit_id = branch_head_commit_id;
9666 error = got_object_open_as_commit(&commit, repo, commit_id);
9667 if (error)
9668 goto done;
9670 parent_ids = got_object_commit_get_parent_ids(commit);
9671 pid = STAILQ_FIRST(parent_ids);
9672 if (pid == NULL) {
9673 error = got_error(GOT_ERR_EMPTY_REBASE);
9674 goto done;
9676 error = collect_commits(&commits, commit_id, &pid->id,
9677 yca_id, got_worktree_get_path_prefix(worktree),
9678 GOT_ERR_REBASE_PATH, repo);
9679 got_object_commit_close(commit);
9680 commit = NULL;
9681 if (error)
9682 goto done;
9684 if (!continue_rebase) {
9685 error = got_worktree_rebase_prepare(&new_base_branch,
9686 &tmp_branch, &fileindex, worktree, branch, repo);
9687 if (error)
9688 goto done;
9691 if (STAILQ_EMPTY(&commits)) {
9692 if (continue_rebase) {
9693 error = rebase_complete(worktree, fileindex,
9694 branch, new_base_branch, tmp_branch, repo,
9695 create_backup);
9696 goto done;
9697 } else {
9698 /* Fast-forward the reference of the branch. */
9699 struct got_object_id *new_head_commit_id;
9700 char *id_str;
9701 error = got_ref_resolve(&new_head_commit_id, repo,
9702 new_base_branch);
9703 if (error)
9704 goto done;
9705 error = got_object_id_str(&id_str, new_head_commit_id);
9706 printf("Forwarding %s to commit %s\n",
9707 got_ref_get_name(branch), id_str);
9708 free(id_str);
9709 error = got_ref_change_ref(branch,
9710 new_head_commit_id);
9711 if (error)
9712 goto done;
9713 /* No backup needed since objects did not change. */
9714 create_backup = 0;
9718 pid = NULL;
9719 STAILQ_FOREACH(qid, &commits, entry) {
9721 commit_id = &qid->id;
9722 parent_id = pid ? &pid->id : yca_id;
9723 pid = qid;
9725 memset(&upa, 0, sizeof(upa));
9726 error = got_worktree_rebase_merge_files(&merged_paths,
9727 worktree, fileindex, parent_id, commit_id, repo,
9728 update_progress, &upa, check_cancelled, NULL);
9729 if (error)
9730 goto done;
9732 print_merge_progress_stats(&upa);
9733 if (upa.conflicts > 0 || upa.missing > 0 ||
9734 upa.not_deleted > 0 || upa.unversioned > 0) {
9735 if (upa.conflicts > 0) {
9736 error = show_rebase_merge_conflict(&qid->id,
9737 repo);
9738 if (error)
9739 goto done;
9741 got_worktree_rebase_pathlist_free(&merged_paths);
9742 break;
9745 error = rebase_commit(&merged_paths, worktree, fileindex,
9746 tmp_branch, commit_id, repo);
9747 got_worktree_rebase_pathlist_free(&merged_paths);
9748 if (error)
9749 goto done;
9752 if (upa.conflicts > 0 || upa.missing > 0 ||
9753 upa.not_deleted > 0 || upa.unversioned > 0) {
9754 error = got_worktree_rebase_postpone(worktree, fileindex);
9755 if (error)
9756 goto done;
9757 if (upa.conflicts > 0 && upa.missing == 0 &&
9758 upa.not_deleted == 0 && upa.unversioned == 0) {
9759 error = got_error_msg(GOT_ERR_CONFLICTS,
9760 "conflicts must be resolved before rebasing "
9761 "can continue");
9762 } else if (upa.conflicts > 0) {
9763 error = got_error_msg(GOT_ERR_CONFLICTS,
9764 "conflicts must be resolved before rebasing "
9765 "can continue; changes destined for some "
9766 "files were not yet merged and should be "
9767 "merged manually if required before the "
9768 "rebase operation is continued");
9769 } else {
9770 error = got_error_msg(GOT_ERR_CONFLICTS,
9771 "changes destined for some files were not "
9772 "yet merged and should be merged manually "
9773 "if required before the rebase operation "
9774 "is continued");
9776 } else
9777 error = rebase_complete(worktree, fileindex, branch,
9778 new_base_branch, tmp_branch, repo, create_backup);
9779 done:
9780 got_object_id_queue_free(&commits);
9781 free(branch_head_commit_id);
9782 free(resume_commit_id);
9783 free(yca_id);
9784 if (commit)
9785 got_object_commit_close(commit);
9786 if (branch)
9787 got_ref_close(branch);
9788 if (new_base_branch)
9789 got_ref_close(new_base_branch);
9790 if (tmp_branch)
9791 got_ref_close(tmp_branch);
9792 if (worktree)
9793 got_worktree_close(worktree);
9794 if (repo) {
9795 const struct got_error *close_err = got_repo_close(repo);
9796 if (error == NULL)
9797 error = close_err;
9799 return error;
9802 __dead static void
9803 usage_histedit(void)
9805 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9806 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9807 getprogname());
9808 exit(1);
9811 #define GOT_HISTEDIT_PICK 'p'
9812 #define GOT_HISTEDIT_EDIT 'e'
9813 #define GOT_HISTEDIT_FOLD 'f'
9814 #define GOT_HISTEDIT_DROP 'd'
9815 #define GOT_HISTEDIT_MESG 'm'
9817 static const struct got_histedit_cmd {
9818 unsigned char code;
9819 const char *name;
9820 const char *desc;
9821 } got_histedit_cmds[] = {
9822 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9823 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9824 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9825 "be used" },
9826 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9827 { GOT_HISTEDIT_MESG, "mesg",
9828 "single-line log message for commit above (open editor if empty)" },
9831 struct got_histedit_list_entry {
9832 TAILQ_ENTRY(got_histedit_list_entry) entry;
9833 struct got_object_id *commit_id;
9834 const struct got_histedit_cmd *cmd;
9835 char *logmsg;
9837 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9839 static const struct got_error *
9840 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9841 FILE *f, struct got_repository *repo)
9843 const struct got_error *err = NULL;
9844 char *logmsg = NULL, *id_str = NULL;
9845 struct got_commit_object *commit = NULL;
9846 int n;
9848 err = got_object_open_as_commit(&commit, repo, commit_id);
9849 if (err)
9850 goto done;
9852 err = get_short_logmsg(&logmsg, 34, commit);
9853 if (err)
9854 goto done;
9856 err = got_object_id_str(&id_str, commit_id);
9857 if (err)
9858 goto done;
9860 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9861 if (n < 0)
9862 err = got_ferror(f, GOT_ERR_IO);
9863 done:
9864 if (commit)
9865 got_object_commit_close(commit);
9866 free(id_str);
9867 free(logmsg);
9868 return err;
9871 static const struct got_error *
9872 histedit_write_commit_list(struct got_object_id_queue *commits,
9873 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9874 struct got_repository *repo)
9876 const struct got_error *err = NULL;
9877 struct got_object_qid *qid;
9878 const char *histedit_cmd = NULL;
9880 if (STAILQ_EMPTY(commits))
9881 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9883 STAILQ_FOREACH(qid, commits, entry) {
9884 histedit_cmd = got_histedit_cmds[0].name;
9885 if (edit_only)
9886 histedit_cmd = "edit";
9887 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9888 histedit_cmd = "fold";
9889 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9890 if (err)
9891 break;
9892 if (edit_logmsg_only) {
9893 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9894 if (n < 0) {
9895 err = got_ferror(f, GOT_ERR_IO);
9896 break;
9901 return err;
9904 static const struct got_error *
9905 write_cmd_list(FILE *f, const char *branch_name,
9906 struct got_object_id_queue *commits)
9908 const struct got_error *err = NULL;
9909 size_t i;
9910 int n;
9911 char *id_str;
9912 struct got_object_qid *qid;
9914 qid = STAILQ_FIRST(commits);
9915 err = got_object_id_str(&id_str, &qid->id);
9916 if (err)
9917 return err;
9919 n = fprintf(f,
9920 "# Editing the history of branch '%s' starting at\n"
9921 "# commit %s\n"
9922 "# Commits will be processed in order from top to "
9923 "bottom of this file.\n", branch_name, id_str);
9924 if (n < 0) {
9925 err = got_ferror(f, GOT_ERR_IO);
9926 goto done;
9929 n = fprintf(f, "# Available histedit commands:\n");
9930 if (n < 0) {
9931 err = got_ferror(f, GOT_ERR_IO);
9932 goto done;
9935 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9936 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9937 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9938 cmd->desc);
9939 if (n < 0) {
9940 err = got_ferror(f, GOT_ERR_IO);
9941 break;
9944 done:
9945 free(id_str);
9946 return err;
9949 static const struct got_error *
9950 histedit_syntax_error(int lineno)
9952 static char msg[42];
9953 int ret;
9955 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9956 lineno);
9957 if (ret == -1 || ret >= sizeof(msg))
9958 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9960 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9963 static const struct got_error *
9964 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9965 char *logmsg, struct got_repository *repo)
9967 const struct got_error *err;
9968 struct got_commit_object *folded_commit = NULL;
9969 char *id_str, *folded_logmsg = NULL;
9971 err = got_object_id_str(&id_str, hle->commit_id);
9972 if (err)
9973 return err;
9975 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9976 if (err)
9977 goto done;
9979 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9980 if (err)
9981 goto done;
9982 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9983 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9984 folded_logmsg) == -1) {
9985 err = got_error_from_errno("asprintf");
9987 done:
9988 if (folded_commit)
9989 got_object_commit_close(folded_commit);
9990 free(id_str);
9991 free(folded_logmsg);
9992 return err;
9995 static struct got_histedit_list_entry *
9996 get_folded_commits(struct got_histedit_list_entry *hle)
9998 struct got_histedit_list_entry *prev, *folded = NULL;
10000 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10001 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10002 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10003 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10004 folded = prev;
10005 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10008 return folded;
10011 static const struct got_error *
10012 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10013 struct got_repository *repo)
10015 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10016 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10017 const struct got_error *err = NULL;
10018 struct got_commit_object *commit = NULL;
10019 int logmsg_len;
10020 int fd;
10021 struct got_histedit_list_entry *folded = NULL;
10023 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10024 if (err)
10025 return err;
10027 folded = get_folded_commits(hle);
10028 if (folded) {
10029 while (folded != hle) {
10030 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10031 folded = TAILQ_NEXT(folded, entry);
10032 continue;
10034 err = append_folded_commit_msg(&new_msg, folded,
10035 logmsg, repo);
10036 if (err)
10037 goto done;
10038 free(logmsg);
10039 logmsg = new_msg;
10040 folded = TAILQ_NEXT(folded, entry);
10044 err = got_object_id_str(&id_str, hle->commit_id);
10045 if (err)
10046 goto done;
10047 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10048 if (err)
10049 goto done;
10050 logmsg_len = asprintf(&new_msg,
10051 "%s\n# original log message of commit %s: %s",
10052 logmsg ? logmsg : "", id_str, orig_logmsg);
10053 if (logmsg_len == -1) {
10054 err = got_error_from_errno("asprintf");
10055 goto done;
10057 free(logmsg);
10058 logmsg = new_msg;
10060 err = got_object_id_str(&id_str, hle->commit_id);
10061 if (err)
10062 goto done;
10064 err = got_opentemp_named_fd(&logmsg_path, &fd,
10065 GOT_TMPDIR_STR "/got-logmsg");
10066 if (err)
10067 goto done;
10069 write(fd, logmsg, logmsg_len);
10070 close(fd);
10072 err = get_editor(&editor);
10073 if (err)
10074 goto done;
10076 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10077 logmsg_len, 0);
10078 if (err) {
10079 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10080 goto done;
10081 err = NULL;
10082 hle->logmsg = strdup(new_msg);
10083 if (hle->logmsg == NULL)
10084 err = got_error_from_errno("strdup");
10086 done:
10087 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10088 err = got_error_from_errno2("unlink", logmsg_path);
10089 free(logmsg_path);
10090 free(logmsg);
10091 free(orig_logmsg);
10092 free(editor);
10093 if (commit)
10094 got_object_commit_close(commit);
10095 return err;
10098 static const struct got_error *
10099 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10100 FILE *f, struct got_repository *repo)
10102 const struct got_error *err = NULL;
10103 char *line = NULL, *p, *end;
10104 size_t i, size;
10105 ssize_t len;
10106 int lineno = 0;
10107 const struct got_histedit_cmd *cmd;
10108 struct got_object_id *commit_id = NULL;
10109 struct got_histedit_list_entry *hle = NULL;
10111 for (;;) {
10112 len = getline(&line, &size, f);
10113 if (len == -1) {
10114 const struct got_error *getline_err;
10115 if (feof(f))
10116 break;
10117 getline_err = got_error_from_errno("getline");
10118 err = got_ferror(f, getline_err->code);
10119 break;
10121 lineno++;
10122 p = line;
10123 while (isspace((unsigned char)p[0]))
10124 p++;
10125 if (p[0] == '#' || p[0] == '\0') {
10126 free(line);
10127 line = NULL;
10128 continue;
10130 cmd = NULL;
10131 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10132 cmd = &got_histedit_cmds[i];
10133 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10134 isspace((unsigned char)p[strlen(cmd->name)])) {
10135 p += strlen(cmd->name);
10136 break;
10138 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10139 p++;
10140 break;
10143 if (i == nitems(got_histedit_cmds)) {
10144 err = histedit_syntax_error(lineno);
10145 break;
10147 while (isspace((unsigned char)p[0]))
10148 p++;
10149 if (cmd->code == GOT_HISTEDIT_MESG) {
10150 if (hle == NULL || hle->logmsg != NULL) {
10151 err = got_error(GOT_ERR_HISTEDIT_CMD);
10152 break;
10154 if (p[0] == '\0') {
10155 err = histedit_edit_logmsg(hle, repo);
10156 if (err)
10157 break;
10158 } else {
10159 hle->logmsg = strdup(p);
10160 if (hle->logmsg == NULL) {
10161 err = got_error_from_errno("strdup");
10162 break;
10165 free(line);
10166 line = NULL;
10167 continue;
10168 } else {
10169 end = p;
10170 while (end[0] && !isspace((unsigned char)end[0]))
10171 end++;
10172 *end = '\0';
10174 err = got_object_resolve_id_str(&commit_id, repo, p);
10175 if (err) {
10176 /* override error code */
10177 err = histedit_syntax_error(lineno);
10178 break;
10181 hle = malloc(sizeof(*hle));
10182 if (hle == NULL) {
10183 err = got_error_from_errno("malloc");
10184 break;
10186 hle->cmd = cmd;
10187 hle->commit_id = commit_id;
10188 hle->logmsg = NULL;
10189 commit_id = NULL;
10190 free(line);
10191 line = NULL;
10192 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10195 free(line);
10196 free(commit_id);
10197 return err;
10200 static const struct got_error *
10201 histedit_check_script(struct got_histedit_list *histedit_cmds,
10202 struct got_object_id_queue *commits, struct got_repository *repo)
10204 const struct got_error *err = NULL;
10205 struct got_object_qid *qid;
10206 struct got_histedit_list_entry *hle;
10207 static char msg[92];
10208 char *id_str;
10210 if (TAILQ_EMPTY(histedit_cmds))
10211 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10212 "histedit script contains no commands");
10213 if (STAILQ_EMPTY(commits))
10214 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10216 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10217 struct got_histedit_list_entry *hle2;
10218 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10219 if (hle == hle2)
10220 continue;
10221 if (got_object_id_cmp(hle->commit_id,
10222 hle2->commit_id) != 0)
10223 continue;
10224 err = got_object_id_str(&id_str, hle->commit_id);
10225 if (err)
10226 return err;
10227 snprintf(msg, sizeof(msg), "commit %s is listed "
10228 "more than once in histedit script", id_str);
10229 free(id_str);
10230 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10234 STAILQ_FOREACH(qid, commits, entry) {
10235 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10236 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10237 break;
10239 if (hle == NULL) {
10240 err = got_object_id_str(&id_str, &qid->id);
10241 if (err)
10242 return err;
10243 snprintf(msg, sizeof(msg),
10244 "commit %s missing from histedit script", id_str);
10245 free(id_str);
10246 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10250 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10251 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10252 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10253 "last commit in histedit script cannot be folded");
10255 return NULL;
10258 static const struct got_error *
10259 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10260 const char *path, struct got_object_id_queue *commits,
10261 struct got_repository *repo)
10263 const struct got_error *err = NULL;
10264 char *editor;
10265 FILE *f = NULL;
10267 err = get_editor(&editor);
10268 if (err)
10269 return err;
10271 if (spawn_editor(editor, path) == -1) {
10272 err = got_error_from_errno("failed spawning editor");
10273 goto done;
10276 f = fopen(path, "re");
10277 if (f == NULL) {
10278 err = got_error_from_errno("fopen");
10279 goto done;
10281 err = histedit_parse_list(histedit_cmds, f, repo);
10282 if (err)
10283 goto done;
10285 err = histedit_check_script(histedit_cmds, commits, repo);
10286 done:
10287 if (f && fclose(f) == EOF && err == NULL)
10288 err = got_error_from_errno("fclose");
10289 free(editor);
10290 return err;
10293 static const struct got_error *
10294 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10295 struct got_object_id_queue *, const char *, const char *,
10296 struct got_repository *);
10298 static const struct got_error *
10299 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10300 struct got_object_id_queue *commits, const char *branch_name,
10301 int edit_logmsg_only, int fold_only, int edit_only,
10302 struct got_repository *repo)
10304 const struct got_error *err;
10305 FILE *f = NULL;
10306 char *path = NULL;
10308 err = got_opentemp_named(&path, &f, "got-histedit");
10309 if (err)
10310 return err;
10312 err = write_cmd_list(f, branch_name, commits);
10313 if (err)
10314 goto done;
10316 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10317 fold_only, edit_only, repo);
10318 if (err)
10319 goto done;
10321 if (edit_logmsg_only || fold_only || edit_only) {
10322 rewind(f);
10323 err = histedit_parse_list(histedit_cmds, f, repo);
10324 } else {
10325 if (fclose(f) == EOF) {
10326 err = got_error_from_errno("fclose");
10327 goto done;
10329 f = NULL;
10330 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10331 if (err) {
10332 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10333 err->code != GOT_ERR_HISTEDIT_CMD)
10334 goto done;
10335 err = histedit_edit_list_retry(histedit_cmds, err,
10336 commits, path, branch_name, repo);
10339 done:
10340 if (f && fclose(f) == EOF && err == NULL)
10341 err = got_error_from_errno("fclose");
10342 if (path && unlink(path) != 0 && err == NULL)
10343 err = got_error_from_errno2("unlink", path);
10344 free(path);
10345 return err;
10348 static const struct got_error *
10349 histedit_save_list(struct got_histedit_list *histedit_cmds,
10350 struct got_worktree *worktree, struct got_repository *repo)
10352 const struct got_error *err = NULL;
10353 char *path = NULL;
10354 FILE *f = NULL;
10355 struct got_histedit_list_entry *hle;
10356 struct got_commit_object *commit = NULL;
10358 err = got_worktree_get_histedit_script_path(&path, worktree);
10359 if (err)
10360 return err;
10362 f = fopen(path, "we");
10363 if (f == NULL) {
10364 err = got_error_from_errno2("fopen", path);
10365 goto done;
10367 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10368 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10369 repo);
10370 if (err)
10371 break;
10373 if (hle->logmsg) {
10374 int n = fprintf(f, "%c %s\n",
10375 GOT_HISTEDIT_MESG, hle->logmsg);
10376 if (n < 0) {
10377 err = got_ferror(f, GOT_ERR_IO);
10378 break;
10382 done:
10383 if (f && fclose(f) == EOF && err == NULL)
10384 err = got_error_from_errno("fclose");
10385 free(path);
10386 if (commit)
10387 got_object_commit_close(commit);
10388 return err;
10391 void
10392 histedit_free_list(struct got_histedit_list *histedit_cmds)
10394 struct got_histedit_list_entry *hle;
10396 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10397 TAILQ_REMOVE(histedit_cmds, hle, entry);
10398 free(hle);
10402 static const struct got_error *
10403 histedit_load_list(struct got_histedit_list *histedit_cmds,
10404 const char *path, struct got_repository *repo)
10406 const struct got_error *err = NULL;
10407 FILE *f = NULL;
10409 f = fopen(path, "re");
10410 if (f == NULL) {
10411 err = got_error_from_errno2("fopen", path);
10412 goto done;
10415 err = histedit_parse_list(histedit_cmds, f, repo);
10416 done:
10417 if (f && fclose(f) == EOF && err == NULL)
10418 err = got_error_from_errno("fclose");
10419 return err;
10422 static const struct got_error *
10423 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10424 const struct got_error *edit_err, struct got_object_id_queue *commits,
10425 const char *path, const char *branch_name, struct got_repository *repo)
10427 const struct got_error *err = NULL, *prev_err = edit_err;
10428 int resp = ' ';
10430 while (resp != 'c' && resp != 'r' && resp != 'a') {
10431 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10432 "or (a)bort: ", getprogname(), prev_err->msg);
10433 resp = getchar();
10434 if (resp == '\n')
10435 resp = getchar();
10436 if (resp == 'c') {
10437 histedit_free_list(histedit_cmds);
10438 err = histedit_run_editor(histedit_cmds, path, commits,
10439 repo);
10440 if (err) {
10441 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10442 err->code != GOT_ERR_HISTEDIT_CMD)
10443 break;
10444 prev_err = err;
10445 resp = ' ';
10446 continue;
10448 break;
10449 } else if (resp == 'r') {
10450 histedit_free_list(histedit_cmds);
10451 err = histedit_edit_script(histedit_cmds,
10452 commits, branch_name, 0, 0, 0, repo);
10453 if (err) {
10454 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10455 err->code != GOT_ERR_HISTEDIT_CMD)
10456 break;
10457 prev_err = err;
10458 resp = ' ';
10459 continue;
10461 break;
10462 } else if (resp == 'a') {
10463 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10464 break;
10465 } else
10466 printf("invalid response '%c'\n", resp);
10469 return err;
10472 static const struct got_error *
10473 histedit_complete(struct got_worktree *worktree,
10474 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10475 struct got_reference *branch, struct got_repository *repo)
10477 printf("Switching work tree to %s\n",
10478 got_ref_get_symref_target(branch));
10479 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10480 branch, repo);
10483 static const struct got_error *
10484 show_histedit_progress(struct got_commit_object *commit,
10485 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10487 const struct got_error *err;
10488 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10490 err = got_object_id_str(&old_id_str, hle->commit_id);
10491 if (err)
10492 goto done;
10494 if (new_id) {
10495 err = got_object_id_str(&new_id_str, new_id);
10496 if (err)
10497 goto done;
10500 old_id_str[12] = '\0';
10501 if (new_id_str)
10502 new_id_str[12] = '\0';
10504 if (hle->logmsg) {
10505 logmsg = strdup(hle->logmsg);
10506 if (logmsg == NULL) {
10507 err = got_error_from_errno("strdup");
10508 goto done;
10510 trim_logmsg(logmsg, 42);
10511 } else {
10512 err = get_short_logmsg(&logmsg, 42, commit);
10513 if (err)
10514 goto done;
10517 switch (hle->cmd->code) {
10518 case GOT_HISTEDIT_PICK:
10519 case GOT_HISTEDIT_EDIT:
10520 printf("%s -> %s: %s\n", old_id_str,
10521 new_id_str ? new_id_str : "no-op change", logmsg);
10522 break;
10523 case GOT_HISTEDIT_DROP:
10524 case GOT_HISTEDIT_FOLD:
10525 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10526 logmsg);
10527 break;
10528 default:
10529 break;
10531 done:
10532 free(old_id_str);
10533 free(new_id_str);
10534 return err;
10537 static const struct got_error *
10538 histedit_commit(struct got_pathlist_head *merged_paths,
10539 struct got_worktree *worktree, struct got_fileindex *fileindex,
10540 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10541 struct got_repository *repo)
10543 const struct got_error *err;
10544 struct got_commit_object *commit;
10545 struct got_object_id *new_commit_id;
10547 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10548 && hle->logmsg == NULL) {
10549 err = histedit_edit_logmsg(hle, repo);
10550 if (err)
10551 return err;
10554 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10555 if (err)
10556 return err;
10558 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10559 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10560 hle->logmsg, repo);
10561 if (err) {
10562 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10563 goto done;
10564 err = show_histedit_progress(commit, hle, NULL);
10565 } else {
10566 err = show_histedit_progress(commit, hle, new_commit_id);
10567 free(new_commit_id);
10569 done:
10570 got_object_commit_close(commit);
10571 return err;
10574 static const struct got_error *
10575 histedit_skip_commit(struct got_histedit_list_entry *hle,
10576 struct got_worktree *worktree, struct got_repository *repo)
10578 const struct got_error *error;
10579 struct got_commit_object *commit;
10581 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10582 repo);
10583 if (error)
10584 return error;
10586 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10587 if (error)
10588 return error;
10590 error = show_histedit_progress(commit, hle, NULL);
10591 got_object_commit_close(commit);
10592 return error;
10595 static const struct got_error *
10596 check_local_changes(void *arg, unsigned char status,
10597 unsigned char staged_status, const char *path,
10598 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10599 struct got_object_id *commit_id, int dirfd, const char *de_name)
10601 int *have_local_changes = arg;
10603 switch (status) {
10604 case GOT_STATUS_ADD:
10605 case GOT_STATUS_DELETE:
10606 case GOT_STATUS_MODIFY:
10607 case GOT_STATUS_CONFLICT:
10608 *have_local_changes = 1;
10609 return got_error(GOT_ERR_CANCELLED);
10610 default:
10611 break;
10614 switch (staged_status) {
10615 case GOT_STATUS_ADD:
10616 case GOT_STATUS_DELETE:
10617 case GOT_STATUS_MODIFY:
10618 *have_local_changes = 1;
10619 return got_error(GOT_ERR_CANCELLED);
10620 default:
10621 break;
10624 return NULL;
10627 static const struct got_error *
10628 cmd_histedit(int argc, char *argv[])
10630 const struct got_error *error = NULL;
10631 struct got_worktree *worktree = NULL;
10632 struct got_fileindex *fileindex = NULL;
10633 struct got_repository *repo = NULL;
10634 char *cwd = NULL;
10635 struct got_reference *branch = NULL;
10636 struct got_reference *tmp_branch = NULL;
10637 struct got_object_id *resume_commit_id = NULL;
10638 struct got_object_id *base_commit_id = NULL;
10639 struct got_object_id *head_commit_id = NULL;
10640 struct got_commit_object *commit = NULL;
10641 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10642 struct got_update_progress_arg upa;
10643 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10644 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10645 int list_backups = 0, delete_backups = 0;
10646 const char *edit_script_path = NULL;
10647 struct got_object_id_queue commits;
10648 struct got_pathlist_head merged_paths;
10649 const struct got_object_id_queue *parent_ids;
10650 struct got_object_qid *pid;
10651 struct got_histedit_list histedit_cmds;
10652 struct got_histedit_list_entry *hle;
10654 STAILQ_INIT(&commits);
10655 TAILQ_INIT(&histedit_cmds);
10656 TAILQ_INIT(&merged_paths);
10657 memset(&upa, 0, sizeof(upa));
10659 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10660 switch (ch) {
10661 case 'a':
10662 abort_edit = 1;
10663 break;
10664 case 'c':
10665 continue_edit = 1;
10666 break;
10667 case 'e':
10668 edit_only = 1;
10669 break;
10670 case 'f':
10671 fold_only = 1;
10672 break;
10673 case 'F':
10674 edit_script_path = optarg;
10675 break;
10676 case 'm':
10677 edit_logmsg_only = 1;
10678 break;
10679 case 'l':
10680 list_backups = 1;
10681 break;
10682 case 'X':
10683 delete_backups = 1;
10684 break;
10685 default:
10686 usage_histedit();
10687 /* NOTREACHED */
10691 argc -= optind;
10692 argv += optind;
10694 #ifndef PROFILE
10695 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10696 "unveil", NULL) == -1)
10697 err(1, "pledge");
10698 #endif
10699 if (abort_edit && continue_edit)
10700 option_conflict('a', 'c');
10701 if (edit_script_path && edit_logmsg_only)
10702 option_conflict('F', 'm');
10703 if (abort_edit && edit_logmsg_only)
10704 option_conflict('a', 'm');
10705 if (continue_edit && edit_logmsg_only)
10706 option_conflict('c', 'm');
10707 if (abort_edit && fold_only)
10708 option_conflict('a', 'f');
10709 if (continue_edit && fold_only)
10710 option_conflict('c', 'f');
10711 if (fold_only && edit_logmsg_only)
10712 option_conflict('f', 'm');
10713 if (edit_script_path && fold_only)
10714 option_conflict('F', 'f');
10715 if (abort_edit && edit_only)
10716 option_conflict('a', 'e');
10717 if (continue_edit && edit_only)
10718 option_conflict('c', 'e');
10719 if (edit_only && edit_logmsg_only)
10720 option_conflict('e', 'm');
10721 if (edit_script_path && edit_only)
10722 option_conflict('F', 'e');
10723 if (list_backups) {
10724 if (abort_edit)
10725 option_conflict('l', 'a');
10726 if (continue_edit)
10727 option_conflict('l', 'c');
10728 if (edit_script_path)
10729 option_conflict('l', 'F');
10730 if (edit_logmsg_only)
10731 option_conflict('l', 'm');
10732 if (fold_only)
10733 option_conflict('l', 'f');
10734 if (edit_only)
10735 option_conflict('l', 'e');
10736 if (delete_backups)
10737 option_conflict('l', 'X');
10738 if (argc != 0 && argc != 1)
10739 usage_histedit();
10740 } else if (delete_backups) {
10741 if (abort_edit)
10742 option_conflict('X', 'a');
10743 if (continue_edit)
10744 option_conflict('X', 'c');
10745 if (edit_script_path)
10746 option_conflict('X', 'F');
10747 if (edit_logmsg_only)
10748 option_conflict('X', 'm');
10749 if (fold_only)
10750 option_conflict('X', 'f');
10751 if (edit_only)
10752 option_conflict('X', 'e');
10753 if (list_backups)
10754 option_conflict('X', 'l');
10755 if (argc != 0 && argc != 1)
10756 usage_histedit();
10757 } else if (argc != 0)
10758 usage_histedit();
10761 * This command cannot apply unveil(2) in all cases because the
10762 * user may choose to run an editor to edit the histedit script
10763 * and to edit individual commit log messages.
10764 * unveil(2) traverses exec(2); if an editor is used we have to
10765 * apply unveil after edit script and log messages have been written.
10766 * XXX TODO: Make use of unveil(2) where possible.
10769 cwd = getcwd(NULL, 0);
10770 if (cwd == NULL) {
10771 error = got_error_from_errno("getcwd");
10772 goto done;
10774 error = got_worktree_open(&worktree, cwd);
10775 if (error) {
10776 if (list_backups || delete_backups) {
10777 if (error->code != GOT_ERR_NOT_WORKTREE)
10778 goto done;
10779 } else {
10780 if (error->code == GOT_ERR_NOT_WORKTREE)
10781 error = wrap_not_worktree_error(error,
10782 "histedit", cwd);
10783 goto done;
10787 if (list_backups || delete_backups) {
10788 error = got_repo_open(&repo,
10789 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10790 NULL);
10791 if (error != NULL)
10792 goto done;
10793 error = apply_unveil(got_repo_get_path(repo), 0,
10794 worktree ? got_worktree_get_root_path(worktree) : NULL);
10795 if (error)
10796 goto done;
10797 error = process_backup_refs(
10798 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10799 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10800 goto done; /* nothing else to do */
10803 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10804 NULL);
10805 if (error != NULL)
10806 goto done;
10808 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10809 if (error)
10810 goto done;
10811 if (rebase_in_progress) {
10812 error = got_error(GOT_ERR_REBASING);
10813 goto done;
10816 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10817 repo);
10818 if (error)
10819 goto done;
10820 if (merge_in_progress) {
10821 error = got_error(GOT_ERR_MERGE_BUSY);
10822 goto done;
10825 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10826 if (error)
10827 goto done;
10829 if (edit_in_progress && edit_logmsg_only) {
10830 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10831 "histedit operation is in progress in this "
10832 "work tree and must be continued or aborted "
10833 "before the -m option can be used");
10834 goto done;
10836 if (edit_in_progress && fold_only) {
10837 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10838 "histedit operation is in progress in this "
10839 "work tree and must be continued or aborted "
10840 "before the -f option can be used");
10841 goto done;
10843 if (edit_in_progress && edit_only) {
10844 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10845 "histedit operation is in progress in this "
10846 "work tree and must be continued or aborted "
10847 "before the -e option can be used");
10848 goto done;
10851 if (edit_in_progress && abort_edit) {
10852 error = got_worktree_histedit_continue(&resume_commit_id,
10853 &tmp_branch, &branch, &base_commit_id, &fileindex,
10854 worktree, repo);
10855 if (error)
10856 goto done;
10857 printf("Switching work tree to %s\n",
10858 got_ref_get_symref_target(branch));
10859 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10860 branch, base_commit_id, abort_progress, &upa);
10861 if (error)
10862 goto done;
10863 printf("Histedit of %s aborted\n",
10864 got_ref_get_symref_target(branch));
10865 print_merge_progress_stats(&upa);
10866 goto done; /* nothing else to do */
10867 } else if (abort_edit) {
10868 error = got_error(GOT_ERR_NOT_HISTEDIT);
10869 goto done;
10872 if (continue_edit) {
10873 char *path;
10875 if (!edit_in_progress) {
10876 error = got_error(GOT_ERR_NOT_HISTEDIT);
10877 goto done;
10880 error = got_worktree_get_histedit_script_path(&path, worktree);
10881 if (error)
10882 goto done;
10884 error = histedit_load_list(&histedit_cmds, path, repo);
10885 free(path);
10886 if (error)
10887 goto done;
10889 error = got_worktree_histedit_continue(&resume_commit_id,
10890 &tmp_branch, &branch, &base_commit_id, &fileindex,
10891 worktree, repo);
10892 if (error)
10893 goto done;
10895 error = got_ref_resolve(&head_commit_id, repo, branch);
10896 if (error)
10897 goto done;
10899 error = got_object_open_as_commit(&commit, repo,
10900 head_commit_id);
10901 if (error)
10902 goto done;
10903 parent_ids = got_object_commit_get_parent_ids(commit);
10904 pid = STAILQ_FIRST(parent_ids);
10905 if (pid == NULL) {
10906 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10907 goto done;
10909 error = collect_commits(&commits, head_commit_id, &pid->id,
10910 base_commit_id, got_worktree_get_path_prefix(worktree),
10911 GOT_ERR_HISTEDIT_PATH, repo);
10912 got_object_commit_close(commit);
10913 commit = NULL;
10914 if (error)
10915 goto done;
10916 } else {
10917 if (edit_in_progress) {
10918 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10919 goto done;
10922 error = got_ref_open(&branch, repo,
10923 got_worktree_get_head_ref_name(worktree), 0);
10924 if (error != NULL)
10925 goto done;
10927 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10928 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10929 "will not edit commit history of a branch outside "
10930 "the \"refs/heads/\" reference namespace");
10931 goto done;
10934 error = got_ref_resolve(&head_commit_id, repo, branch);
10935 got_ref_close(branch);
10936 branch = NULL;
10937 if (error)
10938 goto done;
10940 error = got_object_open_as_commit(&commit, repo,
10941 head_commit_id);
10942 if (error)
10943 goto done;
10944 parent_ids = got_object_commit_get_parent_ids(commit);
10945 pid = STAILQ_FIRST(parent_ids);
10946 if (pid == NULL) {
10947 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10948 goto done;
10950 error = collect_commits(&commits, head_commit_id, &pid->id,
10951 got_worktree_get_base_commit_id(worktree),
10952 got_worktree_get_path_prefix(worktree),
10953 GOT_ERR_HISTEDIT_PATH, repo);
10954 got_object_commit_close(commit);
10955 commit = NULL;
10956 if (error)
10957 goto done;
10959 if (STAILQ_EMPTY(&commits)) {
10960 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10961 goto done;
10964 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10965 &base_commit_id, &fileindex, worktree, repo);
10966 if (error)
10967 goto done;
10969 if (edit_script_path) {
10970 error = histedit_load_list(&histedit_cmds,
10971 edit_script_path, repo);
10972 if (error) {
10973 got_worktree_histedit_abort(worktree, fileindex,
10974 repo, branch, base_commit_id,
10975 abort_progress, &upa);
10976 print_merge_progress_stats(&upa);
10977 goto done;
10979 } else {
10980 const char *branch_name;
10981 branch_name = got_ref_get_symref_target(branch);
10982 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10983 branch_name += 11;
10984 error = histedit_edit_script(&histedit_cmds, &commits,
10985 branch_name, edit_logmsg_only, fold_only,
10986 edit_only, repo);
10987 if (error) {
10988 got_worktree_histedit_abort(worktree, fileindex,
10989 repo, branch, base_commit_id,
10990 abort_progress, &upa);
10991 print_merge_progress_stats(&upa);
10992 goto done;
10997 error = histedit_save_list(&histedit_cmds, worktree,
10998 repo);
10999 if (error) {
11000 got_worktree_histedit_abort(worktree, fileindex,
11001 repo, branch, base_commit_id,
11002 abort_progress, &upa);
11003 print_merge_progress_stats(&upa);
11004 goto done;
11009 error = histedit_check_script(&histedit_cmds, &commits, repo);
11010 if (error)
11011 goto done;
11013 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11014 if (resume_commit_id) {
11015 if (got_object_id_cmp(hle->commit_id,
11016 resume_commit_id) != 0)
11017 continue;
11019 resume_commit_id = NULL;
11020 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11021 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11022 error = histedit_skip_commit(hle, worktree,
11023 repo);
11024 if (error)
11025 goto done;
11026 } else {
11027 struct got_pathlist_head paths;
11028 int have_changes = 0;
11030 TAILQ_INIT(&paths);
11031 error = got_pathlist_append(&paths, "", NULL);
11032 if (error)
11033 goto done;
11034 error = got_worktree_status(worktree, &paths,
11035 repo, 0, check_local_changes, &have_changes,
11036 check_cancelled, NULL);
11037 got_pathlist_free(&paths);
11038 if (error) {
11039 if (error->code != GOT_ERR_CANCELLED)
11040 goto done;
11041 if (sigint_received || sigpipe_received)
11042 goto done;
11044 if (have_changes) {
11045 error = histedit_commit(NULL, worktree,
11046 fileindex, tmp_branch, hle, repo);
11047 if (error)
11048 goto done;
11049 } else {
11050 error = got_object_open_as_commit(
11051 &commit, repo, hle->commit_id);
11052 if (error)
11053 goto done;
11054 error = show_histedit_progress(commit,
11055 hle, NULL);
11056 got_object_commit_close(commit);
11057 commit = NULL;
11058 if (error)
11059 goto done;
11062 continue;
11065 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11066 error = histedit_skip_commit(hle, worktree, repo);
11067 if (error)
11068 goto done;
11069 continue;
11072 error = got_object_open_as_commit(&commit, repo,
11073 hle->commit_id);
11074 if (error)
11075 goto done;
11076 parent_ids = got_object_commit_get_parent_ids(commit);
11077 pid = STAILQ_FIRST(parent_ids);
11079 error = got_worktree_histedit_merge_files(&merged_paths,
11080 worktree, fileindex, &pid->id, hle->commit_id, repo,
11081 update_progress, &upa, check_cancelled, NULL);
11082 if (error)
11083 goto done;
11084 got_object_commit_close(commit);
11085 commit = NULL;
11087 print_merge_progress_stats(&upa);
11088 if (upa.conflicts > 0 || upa.missing > 0 ||
11089 upa.not_deleted > 0 || upa.unversioned > 0) {
11090 if (upa.conflicts > 0) {
11091 error = show_rebase_merge_conflict(
11092 hle->commit_id, repo);
11093 if (error)
11094 goto done;
11096 got_worktree_rebase_pathlist_free(&merged_paths);
11097 break;
11100 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11101 char *id_str;
11102 error = got_object_id_str(&id_str, hle->commit_id);
11103 if (error)
11104 goto done;
11105 printf("Stopping histedit for amending commit %s\n",
11106 id_str);
11107 free(id_str);
11108 got_worktree_rebase_pathlist_free(&merged_paths);
11109 error = got_worktree_histedit_postpone(worktree,
11110 fileindex);
11111 goto done;
11114 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11115 error = histedit_skip_commit(hle, worktree, repo);
11116 if (error)
11117 goto done;
11118 continue;
11121 error = histedit_commit(&merged_paths, worktree, fileindex,
11122 tmp_branch, hle, repo);
11123 got_worktree_rebase_pathlist_free(&merged_paths);
11124 if (error)
11125 goto done;
11128 if (upa.conflicts > 0 || upa.missing > 0 ||
11129 upa.not_deleted > 0 || upa.unversioned > 0) {
11130 error = got_worktree_histedit_postpone(worktree, fileindex);
11131 if (error)
11132 goto done;
11133 if (upa.conflicts > 0 && upa.missing == 0 &&
11134 upa.not_deleted == 0 && upa.unversioned == 0) {
11135 error = got_error_msg(GOT_ERR_CONFLICTS,
11136 "conflicts must be resolved before histedit "
11137 "can continue");
11138 } else if (upa.conflicts > 0) {
11139 error = got_error_msg(GOT_ERR_CONFLICTS,
11140 "conflicts must be resolved before histedit "
11141 "can continue; changes destined for some "
11142 "files were not yet merged and should be "
11143 "merged manually if required before the "
11144 "histedit operation is continued");
11145 } else {
11146 error = got_error_msg(GOT_ERR_CONFLICTS,
11147 "changes destined for some files were not "
11148 "yet merged and should be merged manually "
11149 "if required before the histedit operation "
11150 "is continued");
11152 } else
11153 error = histedit_complete(worktree, fileindex, tmp_branch,
11154 branch, repo);
11155 done:
11156 got_object_id_queue_free(&commits);
11157 histedit_free_list(&histedit_cmds);
11158 free(head_commit_id);
11159 free(base_commit_id);
11160 free(resume_commit_id);
11161 if (commit)
11162 got_object_commit_close(commit);
11163 if (branch)
11164 got_ref_close(branch);
11165 if (tmp_branch)
11166 got_ref_close(tmp_branch);
11167 if (worktree)
11168 got_worktree_close(worktree);
11169 if (repo) {
11170 const struct got_error *close_err = got_repo_close(repo);
11171 if (error == NULL)
11172 error = close_err;
11174 return error;
11177 __dead static void
11178 usage_integrate(void)
11180 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11181 exit(1);
11184 static const struct got_error *
11185 cmd_integrate(int argc, char *argv[])
11187 const struct got_error *error = NULL;
11188 struct got_repository *repo = NULL;
11189 struct got_worktree *worktree = NULL;
11190 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11191 const char *branch_arg = NULL;
11192 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11193 struct got_fileindex *fileindex = NULL;
11194 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11195 int ch;
11196 struct got_update_progress_arg upa;
11198 while ((ch = getopt(argc, argv, "")) != -1) {
11199 switch (ch) {
11200 default:
11201 usage_integrate();
11202 /* NOTREACHED */
11206 argc -= optind;
11207 argv += optind;
11209 if (argc != 1)
11210 usage_integrate();
11211 branch_arg = argv[0];
11212 #ifndef PROFILE
11213 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11214 "unveil", NULL) == -1)
11215 err(1, "pledge");
11216 #endif
11217 cwd = getcwd(NULL, 0);
11218 if (cwd == NULL) {
11219 error = got_error_from_errno("getcwd");
11220 goto done;
11223 error = got_worktree_open(&worktree, cwd);
11224 if (error) {
11225 if (error->code == GOT_ERR_NOT_WORKTREE)
11226 error = wrap_not_worktree_error(error, "integrate",
11227 cwd);
11228 goto done;
11231 error = check_rebase_or_histedit_in_progress(worktree);
11232 if (error)
11233 goto done;
11235 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11236 NULL);
11237 if (error != NULL)
11238 goto done;
11240 error = apply_unveil(got_repo_get_path(repo), 0,
11241 got_worktree_get_root_path(worktree));
11242 if (error)
11243 goto done;
11245 error = check_merge_in_progress(worktree, repo);
11246 if (error)
11247 goto done;
11249 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11250 error = got_error_from_errno("asprintf");
11251 goto done;
11254 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11255 &base_branch_ref, worktree, refname, repo);
11256 if (error)
11257 goto done;
11259 refname = strdup(got_ref_get_name(branch_ref));
11260 if (refname == NULL) {
11261 error = got_error_from_errno("strdup");
11262 got_worktree_integrate_abort(worktree, fileindex, repo,
11263 branch_ref, base_branch_ref);
11264 goto done;
11266 base_refname = strdup(got_ref_get_name(base_branch_ref));
11267 if (base_refname == NULL) {
11268 error = got_error_from_errno("strdup");
11269 got_worktree_integrate_abort(worktree, fileindex, repo,
11270 branch_ref, base_branch_ref);
11271 goto done;
11274 error = got_ref_resolve(&commit_id, repo, branch_ref);
11275 if (error)
11276 goto done;
11278 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11279 if (error)
11280 goto done;
11282 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11283 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11284 "specified branch has already been integrated");
11285 got_worktree_integrate_abort(worktree, fileindex, repo,
11286 branch_ref, base_branch_ref);
11287 goto done;
11290 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11291 if (error) {
11292 if (error->code == GOT_ERR_ANCESTRY)
11293 error = got_error(GOT_ERR_REBASE_REQUIRED);
11294 got_worktree_integrate_abort(worktree, fileindex, repo,
11295 branch_ref, base_branch_ref);
11296 goto done;
11299 memset(&upa, 0, sizeof(upa));
11300 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11301 branch_ref, base_branch_ref, update_progress, &upa,
11302 check_cancelled, NULL);
11303 if (error)
11304 goto done;
11306 printf("Integrated %s into %s\n", refname, base_refname);
11307 print_update_progress_stats(&upa);
11308 done:
11309 if (repo) {
11310 const struct got_error *close_err = got_repo_close(repo);
11311 if (error == NULL)
11312 error = close_err;
11314 if (worktree)
11315 got_worktree_close(worktree);
11316 free(cwd);
11317 free(base_commit_id);
11318 free(commit_id);
11319 free(refname);
11320 free(base_refname);
11321 return error;
11324 __dead static void
11325 usage_merge(void)
11327 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11328 getprogname());
11329 exit(1);
11332 static const struct got_error *
11333 cmd_merge(int argc, char *argv[])
11335 const struct got_error *error = NULL;
11336 struct got_worktree *worktree = NULL;
11337 struct got_repository *repo = NULL;
11338 struct got_fileindex *fileindex = NULL;
11339 char *cwd = NULL, *id_str = NULL, *author = NULL;
11340 struct got_reference *branch = NULL, *wt_branch = NULL;
11341 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11342 struct got_object_id *wt_branch_tip = NULL;
11343 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11344 int interrupt_merge = 0;
11345 struct got_update_progress_arg upa;
11346 struct got_object_id *merge_commit_id = NULL;
11347 char *branch_name = NULL;
11349 memset(&upa, 0, sizeof(upa));
11351 while ((ch = getopt(argc, argv, "acn")) != -1) {
11352 switch (ch) {
11353 case 'a':
11354 abort_merge = 1;
11355 break;
11356 case 'c':
11357 continue_merge = 1;
11358 break;
11359 case 'n':
11360 interrupt_merge = 1;
11361 break;
11362 default:
11363 usage_rebase();
11364 /* NOTREACHED */
11368 argc -= optind;
11369 argv += optind;
11371 #ifndef PROFILE
11372 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11373 "unveil", NULL) == -1)
11374 err(1, "pledge");
11375 #endif
11377 if (abort_merge && continue_merge)
11378 option_conflict('a', 'c');
11379 if (abort_merge || continue_merge) {
11380 if (argc != 0)
11381 usage_merge();
11382 } else if (argc != 1)
11383 usage_merge();
11385 cwd = getcwd(NULL, 0);
11386 if (cwd == NULL) {
11387 error = got_error_from_errno("getcwd");
11388 goto done;
11391 error = got_worktree_open(&worktree, cwd);
11392 if (error) {
11393 if (error->code == GOT_ERR_NOT_WORKTREE)
11394 error = wrap_not_worktree_error(error,
11395 "merge", cwd);
11396 goto done;
11399 error = got_repo_open(&repo,
11400 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11401 if (error != NULL)
11402 goto done;
11404 error = apply_unveil(got_repo_get_path(repo), 0,
11405 worktree ? got_worktree_get_root_path(worktree) : NULL);
11406 if (error)
11407 goto done;
11409 error = check_rebase_or_histedit_in_progress(worktree);
11410 if (error)
11411 goto done;
11413 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11414 repo);
11415 if (error)
11416 goto done;
11418 if (abort_merge) {
11419 if (!merge_in_progress) {
11420 error = got_error(GOT_ERR_NOT_MERGING);
11421 goto done;
11423 error = got_worktree_merge_continue(&branch_name,
11424 &branch_tip, &fileindex, worktree, repo);
11425 if (error)
11426 goto done;
11427 error = got_worktree_merge_abort(worktree, fileindex, repo,
11428 abort_progress, &upa);
11429 if (error)
11430 goto done;
11431 printf("Merge of %s aborted\n", branch_name);
11432 goto done; /* nothing else to do */
11435 error = get_author(&author, repo, worktree);
11436 if (error)
11437 goto done;
11439 if (continue_merge) {
11440 if (!merge_in_progress) {
11441 error = got_error(GOT_ERR_NOT_MERGING);
11442 goto done;
11444 error = got_worktree_merge_continue(&branch_name,
11445 &branch_tip, &fileindex, worktree, repo);
11446 if (error)
11447 goto done;
11448 } else {
11449 error = got_ref_open(&branch, repo, argv[0], 0);
11450 if (error != NULL)
11451 goto done;
11452 branch_name = strdup(got_ref_get_name(branch));
11453 if (branch_name == NULL) {
11454 error = got_error_from_errno("strdup");
11455 goto done;
11457 error = got_ref_resolve(&branch_tip, repo, branch);
11458 if (error)
11459 goto done;
11462 error = got_ref_open(&wt_branch, repo,
11463 got_worktree_get_head_ref_name(worktree), 0);
11464 if (error)
11465 goto done;
11466 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11467 if (error)
11468 goto done;
11469 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11470 wt_branch_tip, branch_tip, 0, repo,
11471 check_cancelled, NULL);
11472 if (error && error->code != GOT_ERR_ANCESTRY)
11473 goto done;
11475 if (!continue_merge) {
11476 error = check_path_prefix(wt_branch_tip, branch_tip,
11477 got_worktree_get_path_prefix(worktree),
11478 GOT_ERR_MERGE_PATH, repo);
11479 if (error)
11480 goto done;
11481 if (yca_id) {
11482 error = check_same_branch(wt_branch_tip, branch,
11483 yca_id, repo);
11484 if (error) {
11485 if (error->code != GOT_ERR_ANCESTRY)
11486 goto done;
11487 error = NULL;
11488 } else {
11489 static char msg[512];
11490 snprintf(msg, sizeof(msg),
11491 "cannot create a merge commit because "
11492 "%s is based on %s; %s can be integrated "
11493 "with 'got integrate' instead", branch_name,
11494 got_worktree_get_head_ref_name(worktree),
11495 branch_name);
11496 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11497 goto done;
11500 error = got_worktree_merge_prepare(&fileindex, worktree,
11501 branch, repo);
11502 if (error)
11503 goto done;
11505 error = got_worktree_merge_branch(worktree, fileindex,
11506 yca_id, branch_tip, repo, update_progress, &upa,
11507 check_cancelled, NULL);
11508 if (error)
11509 goto done;
11510 print_merge_progress_stats(&upa);
11511 if (!upa.did_something) {
11512 error = got_worktree_merge_abort(worktree, fileindex,
11513 repo, abort_progress, &upa);
11514 if (error)
11515 goto done;
11516 printf("Already up-to-date\n");
11517 goto done;
11521 if (interrupt_merge) {
11522 error = got_worktree_merge_postpone(worktree, fileindex);
11523 if (error)
11524 goto done;
11525 printf("Merge of %s interrupted on request\n", branch_name);
11526 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11527 upa.not_deleted > 0 || upa.unversioned > 0) {
11528 error = got_worktree_merge_postpone(worktree, fileindex);
11529 if (error)
11530 goto done;
11531 if (upa.conflicts > 0 && upa.missing == 0 &&
11532 upa.not_deleted == 0 && upa.unversioned == 0) {
11533 error = got_error_msg(GOT_ERR_CONFLICTS,
11534 "conflicts must be resolved before merging "
11535 "can continue");
11536 } else if (upa.conflicts > 0) {
11537 error = got_error_msg(GOT_ERR_CONFLICTS,
11538 "conflicts must be resolved before merging "
11539 "can continue; changes destined for some "
11540 "files were not yet merged and "
11541 "should be merged manually if required before the "
11542 "merge operation is continued");
11543 } else {
11544 error = got_error_msg(GOT_ERR_CONFLICTS,
11545 "changes destined for some "
11546 "files were not yet merged and should be "
11547 "merged manually if required before the "
11548 "merge operation is continued");
11550 goto done;
11551 } else {
11552 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11553 fileindex, author, NULL, 1, branch_tip, branch_name,
11554 repo, continue_merge ? print_status : NULL, NULL);
11555 if (error)
11556 goto done;
11557 error = got_worktree_merge_complete(worktree, fileindex, repo);
11558 if (error)
11559 goto done;
11560 error = got_object_id_str(&id_str, merge_commit_id);
11561 if (error)
11562 goto done;
11563 printf("Merged %s into %s: %s\n", branch_name,
11564 got_worktree_get_head_ref_name(worktree),
11565 id_str);
11568 done:
11569 free(id_str);
11570 free(merge_commit_id);
11571 free(author);
11572 free(branch_tip);
11573 free(branch_name);
11574 free(yca_id);
11575 if (branch)
11576 got_ref_close(branch);
11577 if (wt_branch)
11578 got_ref_close(wt_branch);
11579 if (worktree)
11580 got_worktree_close(worktree);
11581 if (repo) {
11582 const struct got_error *close_err = got_repo_close(repo);
11583 if (error == NULL)
11584 error = close_err;
11586 return error;
11589 __dead static void
11590 usage_stage(void)
11592 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11593 "[-S] [file-path ...]\n",
11594 getprogname());
11595 exit(1);
11598 static const struct got_error *
11599 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11600 const char *path, struct got_object_id *blob_id,
11601 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11602 int dirfd, const char *de_name)
11604 const struct got_error *err = NULL;
11605 char *id_str = NULL;
11607 if (staged_status != GOT_STATUS_ADD &&
11608 staged_status != GOT_STATUS_MODIFY &&
11609 staged_status != GOT_STATUS_DELETE)
11610 return NULL;
11612 if (staged_status == GOT_STATUS_ADD ||
11613 staged_status == GOT_STATUS_MODIFY)
11614 err = got_object_id_str(&id_str, staged_blob_id);
11615 else
11616 err = got_object_id_str(&id_str, blob_id);
11617 if (err)
11618 return err;
11620 printf("%s %c %s\n", id_str, staged_status, path);
11621 free(id_str);
11622 return NULL;
11625 static const struct got_error *
11626 cmd_stage(int argc, char *argv[])
11628 const struct got_error *error = NULL;
11629 struct got_repository *repo = NULL;
11630 struct got_worktree *worktree = NULL;
11631 char *cwd = NULL;
11632 struct got_pathlist_head paths;
11633 struct got_pathlist_entry *pe;
11634 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11635 FILE *patch_script_file = NULL;
11636 const char *patch_script_path = NULL;
11637 struct choose_patch_arg cpa;
11639 TAILQ_INIT(&paths);
11641 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11642 switch (ch) {
11643 case 'l':
11644 list_stage = 1;
11645 break;
11646 case 'p':
11647 pflag = 1;
11648 break;
11649 case 'F':
11650 patch_script_path = optarg;
11651 break;
11652 case 'S':
11653 allow_bad_symlinks = 1;
11654 break;
11655 default:
11656 usage_stage();
11657 /* NOTREACHED */
11661 argc -= optind;
11662 argv += optind;
11664 #ifndef PROFILE
11665 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11666 "unveil", NULL) == -1)
11667 err(1, "pledge");
11668 #endif
11669 if (list_stage && (pflag || patch_script_path))
11670 errx(1, "-l option cannot be used with other options");
11671 if (patch_script_path && !pflag)
11672 errx(1, "-F option can only be used together with -p option");
11674 cwd = getcwd(NULL, 0);
11675 if (cwd == NULL) {
11676 error = got_error_from_errno("getcwd");
11677 goto done;
11680 error = got_worktree_open(&worktree, cwd);
11681 if (error) {
11682 if (error->code == GOT_ERR_NOT_WORKTREE)
11683 error = wrap_not_worktree_error(error, "stage", cwd);
11684 goto done;
11687 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11688 NULL);
11689 if (error != NULL)
11690 goto done;
11692 if (patch_script_path) {
11693 patch_script_file = fopen(patch_script_path, "re");
11694 if (patch_script_file == NULL) {
11695 error = got_error_from_errno2("fopen",
11696 patch_script_path);
11697 goto done;
11700 error = apply_unveil(got_repo_get_path(repo), 0,
11701 got_worktree_get_root_path(worktree));
11702 if (error)
11703 goto done;
11705 error = check_merge_in_progress(worktree, repo);
11706 if (error)
11707 goto done;
11709 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11710 if (error)
11711 goto done;
11713 if (list_stage)
11714 error = got_worktree_status(worktree, &paths, repo, 0,
11715 print_stage, NULL, check_cancelled, NULL);
11716 else {
11717 cpa.patch_script_file = patch_script_file;
11718 cpa.action = "stage";
11719 error = got_worktree_stage(worktree, &paths,
11720 pflag ? NULL : print_status, NULL,
11721 pflag ? choose_patch : NULL, &cpa,
11722 allow_bad_symlinks, repo);
11724 done:
11725 if (patch_script_file && fclose(patch_script_file) == EOF &&
11726 error == NULL)
11727 error = got_error_from_errno2("fclose", patch_script_path);
11728 if (repo) {
11729 const struct got_error *close_err = got_repo_close(repo);
11730 if (error == NULL)
11731 error = close_err;
11733 if (worktree)
11734 got_worktree_close(worktree);
11735 TAILQ_FOREACH(pe, &paths, entry)
11736 free((char *)pe->path);
11737 got_pathlist_free(&paths);
11738 free(cwd);
11739 return error;
11742 __dead static void
11743 usage_unstage(void)
11745 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11746 "[file-path ...]\n",
11747 getprogname());
11748 exit(1);
11752 static const struct got_error *
11753 cmd_unstage(int argc, char *argv[])
11755 const struct got_error *error = NULL;
11756 struct got_repository *repo = NULL;
11757 struct got_worktree *worktree = NULL;
11758 char *cwd = NULL;
11759 struct got_pathlist_head paths;
11760 struct got_pathlist_entry *pe;
11761 int ch, pflag = 0;
11762 struct got_update_progress_arg upa;
11763 FILE *patch_script_file = NULL;
11764 const char *patch_script_path = NULL;
11765 struct choose_patch_arg cpa;
11767 TAILQ_INIT(&paths);
11769 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11770 switch (ch) {
11771 case 'p':
11772 pflag = 1;
11773 break;
11774 case 'F':
11775 patch_script_path = optarg;
11776 break;
11777 default:
11778 usage_unstage();
11779 /* NOTREACHED */
11783 argc -= optind;
11784 argv += optind;
11786 #ifndef PROFILE
11787 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11788 "unveil", NULL) == -1)
11789 err(1, "pledge");
11790 #endif
11791 if (patch_script_path && !pflag)
11792 errx(1, "-F option can only be used together with -p option");
11794 cwd = getcwd(NULL, 0);
11795 if (cwd == NULL) {
11796 error = got_error_from_errno("getcwd");
11797 goto done;
11800 error = got_worktree_open(&worktree, cwd);
11801 if (error) {
11802 if (error->code == GOT_ERR_NOT_WORKTREE)
11803 error = wrap_not_worktree_error(error, "unstage", cwd);
11804 goto done;
11807 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11808 NULL);
11809 if (error != NULL)
11810 goto done;
11812 if (patch_script_path) {
11813 patch_script_file = fopen(patch_script_path, "re");
11814 if (patch_script_file == NULL) {
11815 error = got_error_from_errno2("fopen",
11816 patch_script_path);
11817 goto done;
11821 error = apply_unveil(got_repo_get_path(repo), 0,
11822 got_worktree_get_root_path(worktree));
11823 if (error)
11824 goto done;
11826 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11827 if (error)
11828 goto done;
11830 cpa.patch_script_file = patch_script_file;
11831 cpa.action = "unstage";
11832 memset(&upa, 0, sizeof(upa));
11833 error = got_worktree_unstage(worktree, &paths, update_progress,
11834 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11835 if (!error)
11836 print_merge_progress_stats(&upa);
11837 done:
11838 if (patch_script_file && fclose(patch_script_file) == EOF &&
11839 error == NULL)
11840 error = got_error_from_errno2("fclose", patch_script_path);
11841 if (repo) {
11842 const struct got_error *close_err = got_repo_close(repo);
11843 if (error == NULL)
11844 error = close_err;
11846 if (worktree)
11847 got_worktree_close(worktree);
11848 TAILQ_FOREACH(pe, &paths, entry)
11849 free((char *)pe->path);
11850 got_pathlist_free(&paths);
11851 free(cwd);
11852 return error;
11855 __dead static void
11856 usage_cat(void)
11858 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11859 "arg1 [arg2 ...]\n", getprogname());
11860 exit(1);
11863 static const struct got_error *
11864 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11866 const struct got_error *err;
11867 struct got_blob_object *blob;
11869 err = got_object_open_as_blob(&blob, repo, id, 8192);
11870 if (err)
11871 return err;
11873 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11874 got_object_blob_close(blob);
11875 return err;
11878 static const struct got_error *
11879 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11881 const struct got_error *err;
11882 struct got_tree_object *tree;
11883 int nentries, i;
11885 err = got_object_open_as_tree(&tree, repo, id);
11886 if (err)
11887 return err;
11889 nentries = got_object_tree_get_nentries(tree);
11890 for (i = 0; i < nentries; i++) {
11891 struct got_tree_entry *te;
11892 char *id_str;
11893 if (sigint_received || sigpipe_received)
11894 break;
11895 te = got_object_tree_get_entry(tree, i);
11896 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11897 if (err)
11898 break;
11899 fprintf(outfile, "%s %.7o %s\n", id_str,
11900 got_tree_entry_get_mode(te),
11901 got_tree_entry_get_name(te));
11902 free(id_str);
11905 got_object_tree_close(tree);
11906 return err;
11909 static void
11910 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11912 long long h, m;
11913 char sign = '+';
11915 if (gmtoff < 0) {
11916 sign = '-';
11917 gmtoff = -gmtoff;
11920 h = (long long)gmtoff / 3600;
11921 m = ((long long)gmtoff - h*3600) / 60;
11922 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11925 static const struct got_error *
11926 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11928 const struct got_error *err;
11929 struct got_commit_object *commit;
11930 const struct got_object_id_queue *parent_ids;
11931 struct got_object_qid *pid;
11932 char *id_str = NULL;
11933 const char *logmsg = NULL;
11934 char gmtoff[6];
11936 err = got_object_open_as_commit(&commit, repo, id);
11937 if (err)
11938 return err;
11940 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11941 if (err)
11942 goto done;
11944 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11945 parent_ids = got_object_commit_get_parent_ids(commit);
11946 fprintf(outfile, "numparents %d\n",
11947 got_object_commit_get_nparents(commit));
11948 STAILQ_FOREACH(pid, parent_ids, entry) {
11949 char *pid_str;
11950 err = got_object_id_str(&pid_str, &pid->id);
11951 if (err)
11952 goto done;
11953 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11954 free(pid_str);
11956 format_gmtoff(gmtoff, sizeof(gmtoff),
11957 got_object_commit_get_author_gmtoff(commit));
11958 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11959 got_object_commit_get_author(commit),
11960 (long long)got_object_commit_get_author_time(commit),
11961 gmtoff);
11963 format_gmtoff(gmtoff, sizeof(gmtoff),
11964 got_object_commit_get_committer_gmtoff(commit));
11965 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11966 got_object_commit_get_author(commit),
11967 (long long)got_object_commit_get_committer_time(commit),
11968 gmtoff);
11970 logmsg = got_object_commit_get_logmsg_raw(commit);
11971 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11972 fprintf(outfile, "%s", logmsg);
11973 done:
11974 free(id_str);
11975 got_object_commit_close(commit);
11976 return err;
11979 static const struct got_error *
11980 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11982 const struct got_error *err;
11983 struct got_tag_object *tag;
11984 char *id_str = NULL;
11985 const char *tagmsg = NULL;
11986 char gmtoff[6];
11988 err = got_object_open_as_tag(&tag, repo, id);
11989 if (err)
11990 return err;
11992 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11993 if (err)
11994 goto done;
11996 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11998 switch (got_object_tag_get_object_type(tag)) {
11999 case GOT_OBJ_TYPE_BLOB:
12000 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12001 GOT_OBJ_LABEL_BLOB);
12002 break;
12003 case GOT_OBJ_TYPE_TREE:
12004 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12005 GOT_OBJ_LABEL_TREE);
12006 break;
12007 case GOT_OBJ_TYPE_COMMIT:
12008 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12009 GOT_OBJ_LABEL_COMMIT);
12010 break;
12011 case GOT_OBJ_TYPE_TAG:
12012 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12013 GOT_OBJ_LABEL_TAG);
12014 break;
12015 default:
12016 break;
12019 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12020 got_object_tag_get_name(tag));
12022 format_gmtoff(gmtoff, sizeof(gmtoff),
12023 got_object_tag_get_tagger_gmtoff(tag));
12024 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12025 got_object_tag_get_tagger(tag),
12026 (long long)got_object_tag_get_tagger_time(tag),
12027 gmtoff);
12029 tagmsg = got_object_tag_get_message(tag);
12030 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12031 fprintf(outfile, "%s", tagmsg);
12032 done:
12033 free(id_str);
12034 got_object_tag_close(tag);
12035 return err;
12038 static const struct got_error *
12039 cmd_cat(int argc, char *argv[])
12041 const struct got_error *error;
12042 struct got_repository *repo = NULL;
12043 struct got_worktree *worktree = NULL;
12044 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12045 const char *commit_id_str = NULL;
12046 struct got_object_id *id = NULL, *commit_id = NULL;
12047 struct got_commit_object *commit = NULL;
12048 int ch, obj_type, i, force_path = 0;
12049 struct got_reflist_head refs;
12051 TAILQ_INIT(&refs);
12053 #ifndef PROFILE
12054 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12055 NULL) == -1)
12056 err(1, "pledge");
12057 #endif
12059 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12060 switch (ch) {
12061 case 'c':
12062 commit_id_str = optarg;
12063 break;
12064 case 'r':
12065 repo_path = realpath(optarg, NULL);
12066 if (repo_path == NULL)
12067 return got_error_from_errno2("realpath",
12068 optarg);
12069 got_path_strip_trailing_slashes(repo_path);
12070 break;
12071 case 'P':
12072 force_path = 1;
12073 break;
12074 default:
12075 usage_cat();
12076 /* NOTREACHED */
12080 argc -= optind;
12081 argv += optind;
12083 cwd = getcwd(NULL, 0);
12084 if (cwd == NULL) {
12085 error = got_error_from_errno("getcwd");
12086 goto done;
12089 if (repo_path == NULL) {
12090 error = got_worktree_open(&worktree, cwd);
12091 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12092 goto done;
12093 if (worktree) {
12094 repo_path = strdup(
12095 got_worktree_get_repo_path(worktree));
12096 if (repo_path == NULL) {
12097 error = got_error_from_errno("strdup");
12098 goto done;
12101 /* Release work tree lock. */
12102 got_worktree_close(worktree);
12103 worktree = NULL;
12107 if (repo_path == NULL) {
12108 repo_path = strdup(cwd);
12109 if (repo_path == NULL)
12110 return got_error_from_errno("strdup");
12113 error = got_repo_open(&repo, repo_path, NULL);
12114 free(repo_path);
12115 if (error != NULL)
12116 goto done;
12118 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12119 if (error)
12120 goto done;
12122 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12123 if (error)
12124 goto done;
12126 if (commit_id_str == NULL)
12127 commit_id_str = GOT_REF_HEAD;
12128 error = got_repo_match_object_id(&commit_id, NULL,
12129 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12130 if (error)
12131 goto done;
12133 error = got_object_open_as_commit(&commit, repo, commit_id);
12134 if (error)
12135 goto done;
12137 for (i = 0; i < argc; i++) {
12138 if (force_path) {
12139 error = got_object_id_by_path(&id, repo, commit,
12140 argv[i]);
12141 if (error)
12142 break;
12143 } else {
12144 error = got_repo_match_object_id(&id, &label, argv[i],
12145 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12146 repo);
12147 if (error) {
12148 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12149 error->code != GOT_ERR_NOT_REF)
12150 break;
12151 error = got_object_id_by_path(&id, repo,
12152 commit, argv[i]);
12153 if (error)
12154 break;
12158 error = got_object_get_type(&obj_type, repo, id);
12159 if (error)
12160 break;
12162 switch (obj_type) {
12163 case GOT_OBJ_TYPE_BLOB:
12164 error = cat_blob(id, repo, stdout);
12165 break;
12166 case GOT_OBJ_TYPE_TREE:
12167 error = cat_tree(id, repo, stdout);
12168 break;
12169 case GOT_OBJ_TYPE_COMMIT:
12170 error = cat_commit(id, repo, stdout);
12171 break;
12172 case GOT_OBJ_TYPE_TAG:
12173 error = cat_tag(id, repo, stdout);
12174 break;
12175 default:
12176 error = got_error(GOT_ERR_OBJ_TYPE);
12177 break;
12179 if (error)
12180 break;
12181 free(label);
12182 label = NULL;
12183 free(id);
12184 id = NULL;
12186 done:
12187 free(label);
12188 free(id);
12189 free(commit_id);
12190 if (commit)
12191 got_object_commit_close(commit);
12192 if (worktree)
12193 got_worktree_close(worktree);
12194 if (repo) {
12195 const struct got_error *close_err = got_repo_close(repo);
12196 if (error == NULL)
12197 error = close_err;
12199 got_ref_list_free(&refs);
12200 return error;
12203 __dead static void
12204 usage_info(void)
12206 fprintf(stderr, "usage: %s info [path ...]\n",
12207 getprogname());
12208 exit(1);
12211 static const struct got_error *
12212 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12213 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12214 struct got_object_id *commit_id)
12216 const struct got_error *err = NULL;
12217 char *id_str = NULL;
12218 char datebuf[128];
12219 struct tm mytm, *tm;
12220 struct got_pathlist_head *paths = arg;
12221 struct got_pathlist_entry *pe;
12224 * Clear error indication from any of the path arguments which
12225 * would cause this file index entry to be displayed.
12227 TAILQ_FOREACH(pe, paths, entry) {
12228 if (got_path_cmp(path, pe->path, strlen(path),
12229 pe->path_len) == 0 ||
12230 got_path_is_child(path, pe->path, pe->path_len))
12231 pe->data = NULL; /* no error */
12234 printf(GOT_COMMIT_SEP_STR);
12235 if (S_ISLNK(mode))
12236 printf("symlink: %s\n", path);
12237 else if (S_ISREG(mode)) {
12238 printf("file: %s\n", path);
12239 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12240 } else if (S_ISDIR(mode))
12241 printf("directory: %s\n", path);
12242 else
12243 printf("something: %s\n", path);
12245 tm = localtime_r(&mtime, &mytm);
12246 if (tm == NULL)
12247 return NULL;
12248 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12249 return got_error(GOT_ERR_NO_SPACE);
12250 printf("timestamp: %s\n", datebuf);
12252 if (blob_id) {
12253 err = got_object_id_str(&id_str, blob_id);
12254 if (err)
12255 return err;
12256 printf("based on blob: %s\n", id_str);
12257 free(id_str);
12260 if (staged_blob_id) {
12261 err = got_object_id_str(&id_str, staged_blob_id);
12262 if (err)
12263 return err;
12264 printf("based on staged blob: %s\n", id_str);
12265 free(id_str);
12268 if (commit_id) {
12269 err = got_object_id_str(&id_str, commit_id);
12270 if (err)
12271 return err;
12272 printf("based on commit: %s\n", id_str);
12273 free(id_str);
12276 return NULL;
12279 static const struct got_error *
12280 cmd_info(int argc, char *argv[])
12282 const struct got_error *error = NULL;
12283 struct got_worktree *worktree = NULL;
12284 char *cwd = NULL, *id_str = NULL;
12285 struct got_pathlist_head paths;
12286 struct got_pathlist_entry *pe;
12287 char *uuidstr = NULL;
12288 int ch, show_files = 0;
12290 TAILQ_INIT(&paths);
12292 while ((ch = getopt(argc, argv, "")) != -1) {
12293 switch (ch) {
12294 default:
12295 usage_info();
12296 /* NOTREACHED */
12300 argc -= optind;
12301 argv += optind;
12303 #ifndef PROFILE
12304 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12305 NULL) == -1)
12306 err(1, "pledge");
12307 #endif
12308 cwd = getcwd(NULL, 0);
12309 if (cwd == NULL) {
12310 error = got_error_from_errno("getcwd");
12311 goto done;
12314 error = got_worktree_open(&worktree, cwd);
12315 if (error) {
12316 if (error->code == GOT_ERR_NOT_WORKTREE)
12317 error = wrap_not_worktree_error(error, "info", cwd);
12318 goto done;
12321 #ifndef PROFILE
12322 /* Remove "cpath" promise. */
12323 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12324 NULL) == -1)
12325 err(1, "pledge");
12326 #endif
12327 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12328 if (error)
12329 goto done;
12331 if (argc >= 1) {
12332 error = get_worktree_paths_from_argv(&paths, argc, argv,
12333 worktree);
12334 if (error)
12335 goto done;
12336 show_files = 1;
12339 error = got_object_id_str(&id_str,
12340 got_worktree_get_base_commit_id(worktree));
12341 if (error)
12342 goto done;
12344 error = got_worktree_get_uuid(&uuidstr, worktree);
12345 if (error)
12346 goto done;
12348 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12349 printf("work tree base commit: %s\n", id_str);
12350 printf("work tree path prefix: %s\n",
12351 got_worktree_get_path_prefix(worktree));
12352 printf("work tree branch reference: %s\n",
12353 got_worktree_get_head_ref_name(worktree));
12354 printf("work tree UUID: %s\n", uuidstr);
12355 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12357 if (show_files) {
12358 struct got_pathlist_entry *pe;
12359 TAILQ_FOREACH(pe, &paths, entry) {
12360 if (pe->path_len == 0)
12361 continue;
12363 * Assume this path will fail. This will be corrected
12364 * in print_path_info() in case the path does suceeed.
12366 pe->data = (void *)got_error_path(pe->path,
12367 GOT_ERR_BAD_PATH);
12369 error = got_worktree_path_info(worktree, &paths,
12370 print_path_info, &paths, check_cancelled, NULL);
12371 if (error)
12372 goto done;
12373 TAILQ_FOREACH(pe, &paths, entry) {
12374 if (pe->data != NULL) {
12375 error = pe->data; /* bad path */
12376 break;
12380 done:
12381 TAILQ_FOREACH(pe, &paths, entry)
12382 free((char *)pe->path);
12383 got_pathlist_free(&paths);
12384 free(cwd);
12385 free(id_str);
12386 free(uuidstr);
12387 return error;