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_commit(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, got_object_commit_get_author(commit), 1,
3752 &regmatch, 0) == 0 ||
3753 regexec(regex, got_object_commit_get_committer(commit), 1,
3754 &regmatch, 0) == 0 ||
3755 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3756 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3757 *have_match = 1;
3758 done:
3759 free(id_str);
3760 free(logmsg);
3761 return err;
3764 static void
3765 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3766 regex_t *regex)
3768 regmatch_t regmatch;
3769 struct got_pathlist_entry *pe;
3771 *have_match = 0;
3773 TAILQ_FOREACH(pe, changed_paths, entry) {
3774 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3775 *have_match = 1;
3776 break;
3781 static const struct got_error *
3782 match_patch(int *have_match, struct got_commit_object *commit,
3783 struct got_object_id *id, const char *path, int diff_context,
3784 struct got_repository *repo, regex_t *regex, FILE *f)
3786 const struct got_error *err = NULL;
3787 char *line = NULL;
3788 size_t linesize = 0;
3789 ssize_t linelen;
3790 regmatch_t regmatch;
3792 *have_match = 0;
3794 err = got_opentemp_truncate(f);
3795 if (err)
3796 return err;
3798 err = print_patch(commit, id, path, diff_context, repo, f);
3799 if (err)
3800 goto done;
3802 if (fseeko(f, 0L, SEEK_SET) == -1) {
3803 err = got_error_from_errno("fseeko");
3804 goto done;
3807 while ((linelen = getline(&line, &linesize, f)) != -1) {
3808 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3809 *have_match = 1;
3810 break;
3813 done:
3814 free(line);
3815 return err;
3818 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3820 static const struct got_error*
3821 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3822 struct got_object_id *id, struct got_repository *repo)
3824 static const struct got_error *err = NULL;
3825 struct got_reflist_entry *re;
3826 char *s;
3827 const char *name;
3829 *refs_str = NULL;
3831 TAILQ_FOREACH(re, refs, entry) {
3832 struct got_tag_object *tag = NULL;
3833 struct got_object_id *ref_id;
3834 int cmp;
3836 name = got_ref_get_name(re->ref);
3837 if (strcmp(name, GOT_REF_HEAD) == 0)
3838 continue;
3839 if (strncmp(name, "refs/", 5) == 0)
3840 name += 5;
3841 if (strncmp(name, "got/", 4) == 0)
3842 continue;
3843 if (strncmp(name, "heads/", 6) == 0)
3844 name += 6;
3845 if (strncmp(name, "remotes/", 8) == 0) {
3846 name += 8;
3847 s = strstr(name, "/" GOT_REF_HEAD);
3848 if (s != NULL && s[strlen(s)] == '\0')
3849 continue;
3851 err = got_ref_resolve(&ref_id, repo, re->ref);
3852 if (err)
3853 break;
3854 if (strncmp(name, "tags/", 5) == 0) {
3855 err = got_object_open_as_tag(&tag, repo, ref_id);
3856 if (err) {
3857 if (err->code != GOT_ERR_OBJ_TYPE) {
3858 free(ref_id);
3859 break;
3861 /* Ref points at something other than a tag. */
3862 err = NULL;
3863 tag = NULL;
3866 cmp = got_object_id_cmp(tag ?
3867 got_object_tag_get_object_id(tag) : ref_id, id);
3868 free(ref_id);
3869 if (tag)
3870 got_object_tag_close(tag);
3871 if (cmp != 0)
3872 continue;
3873 s = *refs_str;
3874 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3875 s ? ", " : "", name) == -1) {
3876 err = got_error_from_errno("asprintf");
3877 free(s);
3878 *refs_str = NULL;
3879 break;
3881 free(s);
3884 return err;
3887 static const struct got_error *
3888 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id)
3890 const struct got_error *err = NULL;
3891 char *id_str, *s, *nl, *logmsg0;
3893 err = got_object_id_str(&id_str, id);
3894 if (err)
3895 return err;
3897 err = got_object_commit_get_logmsg(&logmsg0, commit);
3898 if (err)
3899 goto done;
3901 s = logmsg0;
3902 while (isspace((unsigned char)s[0]))
3903 s++;
3905 nl = strchr(s, '\n');
3906 if (nl) {
3907 *nl = '\0';
3910 printf("%.7s %s\n", id_str, s);
3912 if (fflush(stdout) != 0 && err == NULL)
3913 err = got_error_from_errno("fflush");
3914 done:
3915 free(id_str);
3916 free(logmsg0);
3917 return err;
3920 static const struct got_error *
3921 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3922 struct got_repository *repo, const char *path,
3923 struct got_pathlist_head *changed_paths, int show_patch,
3924 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3925 const char *custom_refs_str)
3927 const struct got_error *err = NULL;
3928 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3929 char datebuf[26];
3930 time_t committer_time;
3931 const char *author, *committer;
3932 char *refs_str = NULL;
3934 err = got_object_id_str(&id_str, id);
3935 if (err)
3936 return err;
3938 if (custom_refs_str == NULL) {
3939 struct got_reflist_head *refs;
3940 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3941 if (refs) {
3942 err = build_refs_str(&refs_str, refs, id, repo);
3943 if (err)
3944 goto done;
3948 printf(GOT_COMMIT_SEP_STR);
3949 if (custom_refs_str)
3950 printf("commit %s (%s)\n", id_str, custom_refs_str);
3951 else
3952 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3953 refs_str ? refs_str : "", refs_str ? ")" : "");
3954 free(id_str);
3955 id_str = NULL;
3956 free(refs_str);
3957 refs_str = NULL;
3958 printf("from: %s\n", got_object_commit_get_author(commit));
3959 committer_time = got_object_commit_get_committer_time(commit);
3960 datestr = get_datestr(&committer_time, datebuf);
3961 if (datestr)
3962 printf("date: %s UTC\n", datestr);
3963 author = got_object_commit_get_author(commit);
3964 committer = got_object_commit_get_committer(commit);
3965 if (strcmp(author, committer) != 0)
3966 printf("via: %s\n", committer);
3967 if (got_object_commit_get_nparents(commit) > 1) {
3968 const struct got_object_id_queue *parent_ids;
3969 struct got_object_qid *qid;
3970 int n = 1;
3971 parent_ids = got_object_commit_get_parent_ids(commit);
3972 STAILQ_FOREACH(qid, parent_ids, entry) {
3973 err = got_object_id_str(&id_str, &qid->id);
3974 if (err)
3975 goto done;
3976 printf("parent %d: %s\n", n++, id_str);
3977 free(id_str);
3978 id_str = NULL;
3982 err = got_object_commit_get_logmsg(&logmsg0, commit);
3983 if (err)
3984 goto done;
3986 logmsg = logmsg0;
3987 do {
3988 line = strsep(&logmsg, "\n");
3989 if (line)
3990 printf(" %s\n", line);
3991 } while (line);
3992 free(logmsg0);
3994 if (changed_paths) {
3995 struct got_pathlist_entry *pe;
3996 TAILQ_FOREACH(pe, changed_paths, entry) {
3997 struct got_diff_changed_path *cp = pe->data;
3998 printf(" %c %s\n", cp->status, pe->path);
4000 printf("\n");
4002 if (show_patch) {
4003 err = print_patch(commit, id, path, diff_context, repo, stdout);
4004 if (err == 0)
4005 printf("\n");
4008 if (fflush(stdout) != 0 && err == NULL)
4009 err = got_error_from_errno("fflush");
4010 done:
4011 free(id_str);
4012 free(refs_str);
4013 return err;
4016 static const struct got_error *
4017 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4018 struct got_repository *repo, const char *path, int show_changed_paths,
4019 int show_patch, const char *search_pattern, int diff_context, int limit,
4020 int log_branches, int reverse_display_order,
4021 struct got_reflist_object_id_map *refs_idmap, int one_line,
4022 FILE *tmpfile)
4024 const struct got_error *err;
4025 struct got_commit_graph *graph;
4026 regex_t regex;
4027 int have_match;
4028 struct got_object_id_queue reversed_commits;
4029 struct got_object_qid *qid;
4030 struct got_commit_object *commit;
4031 struct got_pathlist_head changed_paths;
4032 struct got_pathlist_entry *pe;
4034 STAILQ_INIT(&reversed_commits);
4035 TAILQ_INIT(&changed_paths);
4037 if (search_pattern && regcomp(&regex, search_pattern,
4038 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4039 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4041 err = got_commit_graph_open(&graph, path, !log_branches);
4042 if (err)
4043 return err;
4044 err = got_commit_graph_iter_start(graph, root_id, repo,
4045 check_cancelled, NULL);
4046 if (err)
4047 goto done;
4048 for (;;) {
4049 struct got_object_id *id;
4051 if (sigint_received || sigpipe_received)
4052 break;
4054 err = got_commit_graph_iter_next(&id, graph, repo,
4055 check_cancelled, NULL);
4056 if (err) {
4057 if (err->code == GOT_ERR_ITER_COMPLETED)
4058 err = NULL;
4059 break;
4061 if (id == NULL)
4062 break;
4064 err = got_object_open_as_commit(&commit, repo, id);
4065 if (err)
4066 break;
4068 if (show_changed_paths && !reverse_display_order) {
4069 err = get_changed_paths(&changed_paths, commit, repo);
4070 if (err)
4071 break;
4074 if (search_pattern) {
4075 err = match_commit(&have_match, id, commit, &regex);
4076 if (err) {
4077 got_object_commit_close(commit);
4078 break;
4080 if (have_match == 0 && show_changed_paths)
4081 match_changed_paths(&have_match,
4082 &changed_paths, &regex);
4083 if (have_match == 0 && show_patch) {
4084 err = match_patch(&have_match, commit, id,
4085 path, diff_context, repo, &regex,
4086 tmpfile);
4087 if (err)
4088 break;
4090 if (have_match == 0) {
4091 got_object_commit_close(commit);
4092 TAILQ_FOREACH(pe, &changed_paths, entry) {
4093 free((char *)pe->path);
4094 free(pe->data);
4096 got_pathlist_free(&changed_paths);
4097 continue;
4101 if (reverse_display_order) {
4102 err = got_object_qid_alloc(&qid, id);
4103 if (err)
4104 break;
4105 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4106 got_object_commit_close(commit);
4107 } else {
4108 if (one_line)
4109 err = print_commit_oneline(commit, id);
4110 else
4111 err = print_commit(commit, id, repo, path,
4112 show_changed_paths ? &changed_paths : NULL,
4113 show_patch, diff_context, refs_idmap, NULL);
4114 got_object_commit_close(commit);
4115 if (err)
4116 break;
4118 if ((limit && --limit == 0) ||
4119 (end_id && got_object_id_cmp(id, end_id) == 0))
4120 break;
4122 TAILQ_FOREACH(pe, &changed_paths, entry) {
4123 free((char *)pe->path);
4124 free(pe->data);
4126 got_pathlist_free(&changed_paths);
4128 if (reverse_display_order) {
4129 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4130 err = got_object_open_as_commit(&commit, repo,
4131 &qid->id);
4132 if (err)
4133 break;
4134 if (show_changed_paths) {
4135 err = get_changed_paths(&changed_paths,
4136 commit, repo);
4137 if (err)
4138 break;
4140 if (one_line)
4141 err = print_commit_oneline(commit, &qid->id);
4142 else
4143 err = print_commit(commit, &qid->id, repo, path,
4144 show_changed_paths ? &changed_paths : NULL,
4145 show_patch, diff_context, refs_idmap, NULL);
4146 got_object_commit_close(commit);
4147 if (err)
4148 break;
4149 TAILQ_FOREACH(pe, &changed_paths, entry) {
4150 free((char *)pe->path);
4151 free(pe->data);
4153 got_pathlist_free(&changed_paths);
4156 done:
4157 while (!STAILQ_EMPTY(&reversed_commits)) {
4158 qid = STAILQ_FIRST(&reversed_commits);
4159 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4160 got_object_qid_free(qid);
4162 TAILQ_FOREACH(pe, &changed_paths, entry) {
4163 free((char *)pe->path);
4164 free(pe->data);
4166 got_pathlist_free(&changed_paths);
4167 if (search_pattern)
4168 regfree(&regex);
4169 got_commit_graph_close(graph);
4170 return err;
4173 __dead static void
4174 usage_log(void)
4176 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4177 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4178 "[-r repository-path] [-R] [path]\n", getprogname());
4179 exit(1);
4182 static int
4183 get_default_log_limit(void)
4185 const char *got_default_log_limit;
4186 long long n;
4187 const char *errstr;
4189 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4190 if (got_default_log_limit == NULL)
4191 return 0;
4192 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4193 if (errstr != NULL)
4194 return 0;
4195 return n;
4198 static const struct got_error *
4199 cmd_log(int argc, char *argv[])
4201 const struct got_error *error;
4202 struct got_repository *repo = NULL;
4203 struct got_worktree *worktree = NULL;
4204 struct got_object_id *start_id = NULL, *end_id = NULL;
4205 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4206 const char *start_commit = NULL, *end_commit = NULL;
4207 const char *search_pattern = NULL;
4208 int diff_context = -1, ch;
4209 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4210 int reverse_display_order = 0, one_line = 0;
4211 const char *errstr;
4212 struct got_reflist_head refs;
4213 struct got_reflist_object_id_map *refs_idmap = NULL;
4214 FILE *tmpfile = NULL;
4216 TAILQ_INIT(&refs);
4218 #ifndef PROFILE
4219 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4220 NULL)
4221 == -1)
4222 err(1, "pledge");
4223 #endif
4225 limit = get_default_log_limit();
4227 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4228 switch (ch) {
4229 case 'p':
4230 show_patch = 1;
4231 break;
4232 case 'P':
4233 show_changed_paths = 1;
4234 break;
4235 case 'c':
4236 start_commit = optarg;
4237 break;
4238 case 'C':
4239 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4240 &errstr);
4241 if (errstr != NULL)
4242 errx(1, "number of context lines is %s: %s",
4243 errstr, optarg);
4244 break;
4245 case 'l':
4246 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4247 if (errstr != NULL)
4248 errx(1, "number of commits is %s: %s",
4249 errstr, optarg);
4250 break;
4251 case 'b':
4252 log_branches = 1;
4253 break;
4254 case 'r':
4255 repo_path = realpath(optarg, NULL);
4256 if (repo_path == NULL)
4257 return got_error_from_errno2("realpath",
4258 optarg);
4259 got_path_strip_trailing_slashes(repo_path);
4260 break;
4261 case 'R':
4262 reverse_display_order = 1;
4263 break;
4264 case 's':
4265 one_line = 1;
4266 break;
4267 case 'S':
4268 search_pattern = optarg;
4269 break;
4270 case 'x':
4271 end_commit = optarg;
4272 break;
4273 default:
4274 usage_log();
4275 /* NOTREACHED */
4279 argc -= optind;
4280 argv += optind;
4282 if (diff_context == -1)
4283 diff_context = 3;
4284 else if (!show_patch)
4285 errx(1, "-C requires -p");
4287 if (one_line && (show_patch || show_changed_paths))
4288 errx(1, "cannot use -s with -p or -P");
4290 cwd = getcwd(NULL, 0);
4291 if (cwd == NULL) {
4292 error = got_error_from_errno("getcwd");
4293 goto done;
4296 if (repo_path == NULL) {
4297 error = got_worktree_open(&worktree, cwd);
4298 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4299 goto done;
4300 error = NULL;
4303 if (argc == 1) {
4304 if (worktree) {
4305 error = got_worktree_resolve_path(&path, worktree,
4306 argv[0]);
4307 if (error)
4308 goto done;
4309 } else {
4310 path = strdup(argv[0]);
4311 if (path == NULL) {
4312 error = got_error_from_errno("strdup");
4313 goto done;
4316 } else if (argc != 0)
4317 usage_log();
4319 if (repo_path == NULL) {
4320 repo_path = worktree ?
4321 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4323 if (repo_path == NULL) {
4324 error = got_error_from_errno("strdup");
4325 goto done;
4328 error = got_repo_open(&repo, repo_path, NULL);
4329 if (error != NULL)
4330 goto done;
4332 error = apply_unveil(got_repo_get_path(repo), 1,
4333 worktree ? got_worktree_get_root_path(worktree) : NULL);
4334 if (error)
4335 goto done;
4337 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4338 if (error)
4339 goto done;
4341 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4342 if (error)
4343 goto done;
4345 if (start_commit == NULL) {
4346 struct got_reference *head_ref;
4347 struct got_commit_object *commit = NULL;
4348 error = got_ref_open(&head_ref, repo,
4349 worktree ? got_worktree_get_head_ref_name(worktree)
4350 : GOT_REF_HEAD, 0);
4351 if (error != NULL)
4352 goto done;
4353 error = got_ref_resolve(&start_id, repo, head_ref);
4354 got_ref_close(head_ref);
4355 if (error != NULL)
4356 goto done;
4357 error = got_object_open_as_commit(&commit, repo,
4358 start_id);
4359 if (error != NULL)
4360 goto done;
4361 got_object_commit_close(commit);
4362 } else {
4363 error = got_repo_match_object_id(&start_id, NULL,
4364 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4365 if (error != NULL)
4366 goto done;
4368 if (end_commit != NULL) {
4369 error = got_repo_match_object_id(&end_id, NULL,
4370 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4371 if (error != NULL)
4372 goto done;
4375 if (worktree) {
4377 * If a path was specified on the command line it was resolved
4378 * to a path in the work tree above. Prepend the work tree's
4379 * path prefix to obtain the corresponding in-repository path.
4381 if (path) {
4382 const char *prefix;
4383 prefix = got_worktree_get_path_prefix(worktree);
4384 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4385 (path[0] != '\0') ? "/" : "", path) == -1) {
4386 error = got_error_from_errno("asprintf");
4387 goto done;
4390 } else
4391 error = got_repo_map_path(&in_repo_path, repo,
4392 path ? path : "");
4393 if (error != NULL)
4394 goto done;
4395 if (in_repo_path) {
4396 free(path);
4397 path = in_repo_path;
4400 if (worktree) {
4401 /* Release work tree lock. */
4402 got_worktree_close(worktree);
4403 worktree = NULL;
4406 if (search_pattern && show_patch) {
4407 tmpfile = got_opentemp();
4408 if (tmpfile == NULL) {
4409 error = got_error_from_errno("got_opentemp");
4410 goto done;
4414 error = print_commits(start_id, end_id, repo, path ? path : "",
4415 show_changed_paths, show_patch, search_pattern, diff_context,
4416 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4417 tmpfile);
4418 done:
4419 free(path);
4420 free(repo_path);
4421 free(cwd);
4422 if (worktree)
4423 got_worktree_close(worktree);
4424 if (repo) {
4425 const struct got_error *close_err = got_repo_close(repo);
4426 if (error == NULL)
4427 error = close_err;
4429 if (refs_idmap)
4430 got_reflist_object_id_map_free(refs_idmap);
4431 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4432 error = got_error_from_errno("fclose");
4433 got_ref_list_free(&refs);
4434 return error;
4437 __dead static void
4438 usage_diff(void)
4440 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4441 "[-r repository-path] [-s] [-w] [-P] "
4442 "[object1 object2 | path ...]\n", getprogname());
4443 exit(1);
4446 struct print_diff_arg {
4447 struct got_repository *repo;
4448 struct got_worktree *worktree;
4449 int diff_context;
4450 const char *id_str;
4451 int header_shown;
4452 int diff_staged;
4453 int ignore_whitespace;
4454 int force_text_diff;
4458 * Create a file which contains the target path of a symlink so we can feed
4459 * it as content to the diff engine.
4461 static const struct got_error *
4462 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4463 const char *abspath)
4465 const struct got_error *err = NULL;
4466 char target_path[PATH_MAX];
4467 ssize_t target_len, outlen;
4469 *fd = -1;
4471 if (dirfd != -1) {
4472 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4473 if (target_len == -1)
4474 return got_error_from_errno2("readlinkat", abspath);
4475 } else {
4476 target_len = readlink(abspath, target_path, PATH_MAX);
4477 if (target_len == -1)
4478 return got_error_from_errno2("readlink", abspath);
4481 *fd = got_opentempfd();
4482 if (*fd == -1)
4483 return got_error_from_errno("got_opentempfd");
4485 outlen = write(*fd, target_path, target_len);
4486 if (outlen == -1) {
4487 err = got_error_from_errno("got_opentempfd");
4488 goto done;
4491 if (lseek(*fd, 0, SEEK_SET) == -1) {
4492 err = got_error_from_errno2("lseek", abspath);
4493 goto done;
4495 done:
4496 if (err) {
4497 close(*fd);
4498 *fd = -1;
4500 return err;
4503 static const struct got_error *
4504 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4505 const char *path, struct got_object_id *blob_id,
4506 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4507 int dirfd, const char *de_name)
4509 struct print_diff_arg *a = arg;
4510 const struct got_error *err = NULL;
4511 struct got_blob_object *blob1 = NULL;
4512 int fd = -1;
4513 FILE *f1 = NULL, *f2 = NULL;
4514 char *abspath = NULL, *label1 = NULL;
4515 struct stat sb;
4516 off_t size1 = 0;
4518 if (a->diff_staged) {
4519 if (staged_status != GOT_STATUS_MODIFY &&
4520 staged_status != GOT_STATUS_ADD &&
4521 staged_status != GOT_STATUS_DELETE)
4522 return NULL;
4523 } else {
4524 if (staged_status == GOT_STATUS_DELETE)
4525 return NULL;
4526 if (status == GOT_STATUS_NONEXISTENT)
4527 return got_error_set_errno(ENOENT, path);
4528 if (status != GOT_STATUS_MODIFY &&
4529 status != GOT_STATUS_ADD &&
4530 status != GOT_STATUS_DELETE &&
4531 status != GOT_STATUS_CONFLICT)
4532 return NULL;
4535 if (!a->header_shown) {
4536 printf("diff %s %s%s\n", a->id_str,
4537 got_worktree_get_root_path(a->worktree),
4538 a->diff_staged ? " (staged changes)" : "");
4539 a->header_shown = 1;
4542 if (a->diff_staged) {
4543 const char *label1 = NULL, *label2 = NULL;
4544 switch (staged_status) {
4545 case GOT_STATUS_MODIFY:
4546 label1 = path;
4547 label2 = path;
4548 break;
4549 case GOT_STATUS_ADD:
4550 label2 = path;
4551 break;
4552 case GOT_STATUS_DELETE:
4553 label1 = path;
4554 break;
4555 default:
4556 return got_error(GOT_ERR_FILE_STATUS);
4558 f1 = got_opentemp();
4559 if (f1 == NULL) {
4560 err = got_error_from_errno("got_opentemp");
4561 goto done;
4563 f2 = got_opentemp();
4564 if (f2 == NULL) {
4565 err = got_error_from_errno("got_opentemp");
4566 goto done;
4568 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4569 blob_id, staged_blob_id, label1, label2, a->diff_context,
4570 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4571 goto done;
4574 if (staged_status == GOT_STATUS_ADD ||
4575 staged_status == GOT_STATUS_MODIFY) {
4576 char *id_str;
4577 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4578 8192);
4579 if (err)
4580 goto done;
4581 err = got_object_id_str(&id_str, staged_blob_id);
4582 if (err)
4583 goto done;
4584 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4585 err = got_error_from_errno("asprintf");
4586 free(id_str);
4587 goto done;
4589 free(id_str);
4590 } else if (status != GOT_STATUS_ADD) {
4591 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4592 if (err)
4593 goto done;
4596 if (status != GOT_STATUS_DELETE) {
4597 if (asprintf(&abspath, "%s/%s",
4598 got_worktree_get_root_path(a->worktree), path) == -1) {
4599 err = got_error_from_errno("asprintf");
4600 goto done;
4603 if (dirfd != -1) {
4604 fd = openat(dirfd, de_name,
4605 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4606 if (fd == -1) {
4607 if (!got_err_open_nofollow_on_symlink()) {
4608 err = got_error_from_errno2("openat",
4609 abspath);
4610 goto done;
4612 err = get_symlink_target_file(&fd, dirfd,
4613 de_name, abspath);
4614 if (err)
4615 goto done;
4617 } else {
4618 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4619 if (fd == -1) {
4620 if (!got_err_open_nofollow_on_symlink()) {
4621 err = got_error_from_errno2("open",
4622 abspath);
4623 goto done;
4625 err = get_symlink_target_file(&fd, dirfd,
4626 de_name, abspath);
4627 if (err)
4628 goto done;
4631 if (fstat(fd, &sb) == -1) {
4632 err = got_error_from_errno2("fstat", abspath);
4633 goto done;
4635 f2 = fdopen(fd, "r");
4636 if (f2 == NULL) {
4637 err = got_error_from_errno2("fdopen", abspath);
4638 goto done;
4640 fd = -1;
4641 } else
4642 sb.st_size = 0;
4644 if (blob1) {
4645 f1 = got_opentemp();
4646 if (f1 == NULL) {
4647 err = got_error_from_errno("got_opentemp");
4648 goto done;
4650 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4651 blob1);
4652 if (err)
4653 goto done;
4656 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4657 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4658 stdout);
4659 done:
4660 if (blob1)
4661 got_object_blob_close(blob1);
4662 if (f1 && fclose(f1) == EOF && err == NULL)
4663 err = got_error_from_errno("fclose");
4664 if (f2 && fclose(f2) == EOF && err == NULL)
4665 err = got_error_from_errno("fclose");
4666 if (fd != -1 && close(fd) == -1 && err == NULL)
4667 err = got_error_from_errno("close");
4668 free(abspath);
4669 return err;
4672 static const struct got_error *
4673 cmd_diff(int argc, char *argv[])
4675 const struct got_error *error;
4676 struct got_repository *repo = NULL;
4677 struct got_worktree *worktree = NULL;
4678 char *cwd = NULL, *repo_path = NULL;
4679 const char *commit_args[2] = { NULL, NULL };
4680 int ncommit_args = 0;
4681 struct got_object_id *ids[2] = { NULL, NULL };
4682 char *labels[2] = { NULL, NULL };
4683 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4684 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4685 int force_text_diff = 0, force_path = 0, rflag = 0;
4686 const char *errstr;
4687 struct got_reflist_head refs;
4688 struct got_pathlist_head paths;
4689 struct got_pathlist_entry *pe;
4690 FILE *f1 = NULL, *f2 = NULL;
4692 TAILQ_INIT(&refs);
4693 TAILQ_INIT(&paths);
4695 #ifndef PROFILE
4696 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4697 NULL) == -1)
4698 err(1, "pledge");
4699 #endif
4701 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4702 switch (ch) {
4703 case 'a':
4704 force_text_diff = 1;
4705 break;
4706 case 'c':
4707 if (ncommit_args >= 2)
4708 errx(1, "too many -c options used");
4709 commit_args[ncommit_args++] = optarg;
4710 break;
4711 case 'C':
4712 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4713 &errstr);
4714 if (errstr != NULL)
4715 errx(1, "number of context lines is %s: %s",
4716 errstr, optarg);
4717 break;
4718 case 'r':
4719 repo_path = realpath(optarg, NULL);
4720 if (repo_path == NULL)
4721 return got_error_from_errno2("realpath",
4722 optarg);
4723 got_path_strip_trailing_slashes(repo_path);
4724 rflag = 1;
4725 break;
4726 case 's':
4727 diff_staged = 1;
4728 break;
4729 case 'w':
4730 ignore_whitespace = 1;
4731 break;
4732 case 'P':
4733 force_path = 1;
4734 break;
4735 default:
4736 usage_diff();
4737 /* NOTREACHED */
4741 argc -= optind;
4742 argv += optind;
4744 cwd = getcwd(NULL, 0);
4745 if (cwd == NULL) {
4746 error = got_error_from_errno("getcwd");
4747 goto done;
4750 if (repo_path == NULL) {
4751 error = got_worktree_open(&worktree, cwd);
4752 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4753 goto done;
4754 else
4755 error = NULL;
4756 if (worktree) {
4757 repo_path =
4758 strdup(got_worktree_get_repo_path(worktree));
4759 if (repo_path == NULL) {
4760 error = got_error_from_errno("strdup");
4761 goto done;
4763 } else {
4764 repo_path = strdup(cwd);
4765 if (repo_path == NULL) {
4766 error = got_error_from_errno("strdup");
4767 goto done;
4772 error = got_repo_open(&repo, repo_path, NULL);
4773 free(repo_path);
4774 if (error != NULL)
4775 goto done;
4777 if (rflag || worktree == NULL || ncommit_args > 0) {
4778 if (force_path) {
4779 error = got_error_msg(GOT_ERR_NOT_IMPL,
4780 "-P option can only be used when diffing "
4781 "a work tree");
4782 goto done;
4784 if (diff_staged) {
4785 error = got_error_msg(GOT_ERR_NOT_IMPL,
4786 "-s option can only be used when diffing "
4787 "a work tree");
4788 goto done;
4792 error = apply_unveil(got_repo_get_path(repo), 1,
4793 worktree ? got_worktree_get_root_path(worktree) : NULL);
4794 if (error)
4795 goto done;
4797 if ((!force_path && argc == 2) || ncommit_args > 0) {
4798 int obj_type = (ncommit_args > 0 ?
4799 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4800 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4801 NULL);
4802 if (error)
4803 goto done;
4804 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4805 const char *arg;
4806 if (ncommit_args > 0)
4807 arg = commit_args[i];
4808 else
4809 arg = argv[i];
4810 error = got_repo_match_object_id(&ids[i], &labels[i],
4811 arg, obj_type, &refs, repo);
4812 if (error) {
4813 if (error->code != GOT_ERR_NOT_REF &&
4814 error->code != GOT_ERR_NO_OBJ)
4815 goto done;
4816 if (ncommit_args > 0)
4817 goto done;
4818 error = NULL;
4819 break;
4824 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4825 struct print_diff_arg arg;
4826 char *id_str;
4828 if (worktree == NULL) {
4829 if (argc == 2 && ids[0] == NULL) {
4830 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4831 goto done;
4832 } else if (argc == 2 && ids[1] == NULL) {
4833 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4834 goto done;
4835 } else if (argc > 0) {
4836 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4837 "%s", "specified paths cannot be resolved");
4838 goto done;
4839 } else {
4840 error = got_error(GOT_ERR_NOT_WORKTREE);
4841 goto done;
4845 error = get_worktree_paths_from_argv(&paths, argc, argv,
4846 worktree);
4847 if (error)
4848 goto done;
4850 error = got_object_id_str(&id_str,
4851 got_worktree_get_base_commit_id(worktree));
4852 if (error)
4853 goto done;
4854 arg.repo = repo;
4855 arg.worktree = worktree;
4856 arg.diff_context = diff_context;
4857 arg.id_str = id_str;
4858 arg.header_shown = 0;
4859 arg.diff_staged = diff_staged;
4860 arg.ignore_whitespace = ignore_whitespace;
4861 arg.force_text_diff = force_text_diff;
4863 error = got_worktree_status(worktree, &paths, repo, 0,
4864 print_diff, &arg, check_cancelled, NULL);
4865 free(id_str);
4866 goto done;
4869 if (ncommit_args == 1) {
4870 struct got_commit_object *commit;
4871 error = got_object_open_as_commit(&commit, repo, ids[0]);
4872 if (error)
4873 goto done;
4875 labels[1] = labels[0];
4876 ids[1] = ids[0];
4877 if (got_object_commit_get_nparents(commit) > 0) {
4878 const struct got_object_id_queue *pids;
4879 struct got_object_qid *pid;
4880 pids = got_object_commit_get_parent_ids(commit);
4881 pid = STAILQ_FIRST(pids);
4882 ids[0] = got_object_id_dup(&pid->id);
4883 if (ids[0] == NULL) {
4884 error = got_error_from_errno(
4885 "got_object_id_dup");
4886 got_object_commit_close(commit);
4887 goto done;
4889 error = got_object_id_str(&labels[0], ids[0]);
4890 if (error) {
4891 got_object_commit_close(commit);
4892 goto done;
4894 } else {
4895 ids[0] = NULL;
4896 labels[0] = strdup("/dev/null");
4897 if (labels[0] == NULL) {
4898 error = got_error_from_errno("strdup");
4899 got_object_commit_close(commit);
4900 goto done;
4904 got_object_commit_close(commit);
4907 if (ncommit_args == 0 && argc > 2) {
4908 error = got_error_msg(GOT_ERR_BAD_PATH,
4909 "path arguments cannot be used when diffing two objects");
4910 goto done;
4913 if (ids[0]) {
4914 error = got_object_get_type(&type1, repo, ids[0]);
4915 if (error)
4916 goto done;
4919 error = got_object_get_type(&type2, repo, ids[1]);
4920 if (error)
4921 goto done;
4922 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4923 error = got_error(GOT_ERR_OBJ_TYPE);
4924 goto done;
4926 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4927 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4928 "path arguments cannot be used when diffing blobs");
4929 goto done;
4932 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4933 char *in_repo_path;
4934 struct got_pathlist_entry *new;
4935 if (worktree) {
4936 const char *prefix;
4937 char *p;
4938 error = got_worktree_resolve_path(&p, worktree,
4939 argv[i]);
4940 if (error)
4941 goto done;
4942 prefix = got_worktree_get_path_prefix(worktree);
4943 while (prefix[0] == '/')
4944 prefix++;
4945 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4946 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4947 p) == -1) {
4948 error = got_error_from_errno("asprintf");
4949 free(p);
4950 goto done;
4952 free(p);
4953 } else {
4954 char *mapped_path, *s;
4955 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4956 if (error)
4957 goto done;
4958 s = mapped_path;
4959 while (s[0] == '/')
4960 s++;
4961 in_repo_path = strdup(s);
4962 if (in_repo_path == NULL) {
4963 error = got_error_from_errno("asprintf");
4964 free(mapped_path);
4965 goto done;
4967 free(mapped_path);
4970 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4971 if (error || new == NULL /* duplicate */)
4972 free(in_repo_path);
4973 if (error)
4974 goto done;
4977 if (worktree) {
4978 /* Release work tree lock. */
4979 got_worktree_close(worktree);
4980 worktree = NULL;
4983 f1 = got_opentemp();
4984 if (f1 == NULL) {
4985 error = got_error_from_errno("got_opentemp");
4986 goto done;
4989 f2 = got_opentemp();
4990 if (f2 == NULL) {
4991 error = got_error_from_errno("got_opentemp");
4992 goto done;
4995 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4996 case GOT_OBJ_TYPE_BLOB:
4997 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4998 ids[0], ids[1], NULL, NULL, diff_context,
4999 ignore_whitespace, force_text_diff, repo, stdout);
5000 break;
5001 case GOT_OBJ_TYPE_TREE:
5002 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5003 ids[0], ids[1], &paths, "", "", diff_context,
5004 ignore_whitespace, force_text_diff, repo, stdout);
5005 break;
5006 case GOT_OBJ_TYPE_COMMIT:
5007 printf("diff %s %s\n", labels[0], labels[1]);
5008 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5009 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5010 force_text_diff, repo, stdout);
5011 break;
5012 default:
5013 error = got_error(GOT_ERR_OBJ_TYPE);
5015 done:
5016 free(labels[0]);
5017 free(labels[1]);
5018 free(ids[0]);
5019 free(ids[1]);
5020 if (worktree)
5021 got_worktree_close(worktree);
5022 if (repo) {
5023 const struct got_error *close_err = got_repo_close(repo);
5024 if (error == NULL)
5025 error = close_err;
5027 TAILQ_FOREACH(pe, &paths, entry)
5028 free((char *)pe->path);
5029 got_pathlist_free(&paths);
5030 got_ref_list_free(&refs);
5031 if (f1 && fclose(f1) == EOF && error == NULL)
5032 error = got_error_from_errno("fclose");
5033 if (f2 && fclose(f2) == EOF && error == NULL)
5034 error = got_error_from_errno("fclose");
5035 return error;
5038 __dead static void
5039 usage_blame(void)
5041 fprintf(stderr,
5042 "usage: %s blame [-c commit] [-r repository-path] path\n",
5043 getprogname());
5044 exit(1);
5047 struct blame_line {
5048 int annotated;
5049 char *id_str;
5050 char *committer;
5051 char datebuf[11]; /* YYYY-MM-DD + NUL */
5054 struct blame_cb_args {
5055 struct blame_line *lines;
5056 int nlines;
5057 int nlines_prec;
5058 int lineno_cur;
5059 off_t *line_offsets;
5060 FILE *f;
5061 struct got_repository *repo;
5064 static const struct got_error *
5065 blame_cb(void *arg, int nlines, int lineno,
5066 struct got_commit_object *commit, struct got_object_id *id)
5068 const struct got_error *err = NULL;
5069 struct blame_cb_args *a = arg;
5070 struct blame_line *bline;
5071 char *line = NULL;
5072 size_t linesize = 0;
5073 off_t offset;
5074 struct tm tm;
5075 time_t committer_time;
5077 if (nlines != a->nlines ||
5078 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5079 return got_error(GOT_ERR_RANGE);
5081 if (sigint_received)
5082 return got_error(GOT_ERR_ITER_COMPLETED);
5084 if (lineno == -1)
5085 return NULL; /* no change in this commit */
5087 /* Annotate this line. */
5088 bline = &a->lines[lineno - 1];
5089 if (bline->annotated)
5090 return NULL;
5091 err = got_object_id_str(&bline->id_str, id);
5092 if (err)
5093 return err;
5095 bline->committer = strdup(got_object_commit_get_committer(commit));
5096 if (bline->committer == NULL) {
5097 err = got_error_from_errno("strdup");
5098 goto done;
5101 committer_time = got_object_commit_get_committer_time(commit);
5102 if (gmtime_r(&committer_time, &tm) == NULL)
5103 return got_error_from_errno("gmtime_r");
5104 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5105 &tm) == 0) {
5106 err = got_error(GOT_ERR_NO_SPACE);
5107 goto done;
5109 bline->annotated = 1;
5111 /* Print lines annotated so far. */
5112 bline = &a->lines[a->lineno_cur - 1];
5113 if (!bline->annotated)
5114 goto done;
5116 offset = a->line_offsets[a->lineno_cur - 1];
5117 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5118 err = got_error_from_errno("fseeko");
5119 goto done;
5122 while (bline->annotated) {
5123 char *smallerthan, *at, *nl, *committer;
5124 size_t len;
5126 if (getline(&line, &linesize, a->f) == -1) {
5127 if (ferror(a->f))
5128 err = got_error_from_errno("getline");
5129 break;
5132 committer = bline->committer;
5133 smallerthan = strchr(committer, '<');
5134 if (smallerthan && smallerthan[1] != '\0')
5135 committer = smallerthan + 1;
5136 at = strchr(committer, '@');
5137 if (at)
5138 *at = '\0';
5139 len = strlen(committer);
5140 if (len >= 9)
5141 committer[8] = '\0';
5143 nl = strchr(line, '\n');
5144 if (nl)
5145 *nl = '\0';
5146 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5147 bline->id_str, bline->datebuf, committer, line);
5149 a->lineno_cur++;
5150 bline = &a->lines[a->lineno_cur - 1];
5152 done:
5153 free(line);
5154 return err;
5157 static const struct got_error *
5158 cmd_blame(int argc, char *argv[])
5160 const struct got_error *error;
5161 struct got_repository *repo = NULL;
5162 struct got_worktree *worktree = NULL;
5163 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5164 char *link_target = NULL;
5165 struct got_object_id *obj_id = NULL;
5166 struct got_object_id *commit_id = NULL;
5167 struct got_commit_object *commit = NULL;
5168 struct got_blob_object *blob = NULL;
5169 char *commit_id_str = NULL;
5170 struct blame_cb_args bca;
5171 int ch, obj_type, i;
5172 off_t filesize;
5174 memset(&bca, 0, sizeof(bca));
5176 #ifndef PROFILE
5177 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5178 NULL) == -1)
5179 err(1, "pledge");
5180 #endif
5182 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5183 switch (ch) {
5184 case 'c':
5185 commit_id_str = optarg;
5186 break;
5187 case 'r':
5188 repo_path = realpath(optarg, NULL);
5189 if (repo_path == NULL)
5190 return got_error_from_errno2("realpath",
5191 optarg);
5192 got_path_strip_trailing_slashes(repo_path);
5193 break;
5194 default:
5195 usage_blame();
5196 /* NOTREACHED */
5200 argc -= optind;
5201 argv += optind;
5203 if (argc == 1)
5204 path = argv[0];
5205 else
5206 usage_blame();
5208 cwd = getcwd(NULL, 0);
5209 if (cwd == NULL) {
5210 error = got_error_from_errno("getcwd");
5211 goto done;
5213 if (repo_path == NULL) {
5214 error = got_worktree_open(&worktree, cwd);
5215 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5216 goto done;
5217 else
5218 error = NULL;
5219 if (worktree) {
5220 repo_path =
5221 strdup(got_worktree_get_repo_path(worktree));
5222 if (repo_path == NULL) {
5223 error = got_error_from_errno("strdup");
5224 if (error)
5225 goto done;
5227 } else {
5228 repo_path = strdup(cwd);
5229 if (repo_path == NULL) {
5230 error = got_error_from_errno("strdup");
5231 goto done;
5236 error = got_repo_open(&repo, repo_path, NULL);
5237 if (error != NULL)
5238 goto done;
5240 if (worktree) {
5241 const char *prefix = got_worktree_get_path_prefix(worktree);
5242 char *p;
5244 error = got_worktree_resolve_path(&p, worktree, path);
5245 if (error)
5246 goto done;
5247 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5248 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5249 p) == -1) {
5250 error = got_error_from_errno("asprintf");
5251 free(p);
5252 goto done;
5254 free(p);
5255 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5256 } else {
5257 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5258 if (error)
5259 goto done;
5260 error = got_repo_map_path(&in_repo_path, repo, path);
5262 if (error)
5263 goto done;
5265 if (commit_id_str == NULL) {
5266 struct got_reference *head_ref;
5267 error = got_ref_open(&head_ref, repo, worktree ?
5268 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5269 if (error != NULL)
5270 goto done;
5271 error = got_ref_resolve(&commit_id, repo, head_ref);
5272 got_ref_close(head_ref);
5273 if (error != NULL)
5274 goto done;
5275 } else {
5276 struct got_reflist_head refs;
5277 TAILQ_INIT(&refs);
5278 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5279 NULL);
5280 if (error)
5281 goto done;
5282 error = got_repo_match_object_id(&commit_id, NULL,
5283 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5284 got_ref_list_free(&refs);
5285 if (error)
5286 goto done;
5289 if (worktree) {
5290 /* Release work tree lock. */
5291 got_worktree_close(worktree);
5292 worktree = NULL;
5295 error = got_object_open_as_commit(&commit, repo, commit_id);
5296 if (error)
5297 goto done;
5299 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5300 commit, repo);
5301 if (error)
5302 goto done;
5304 error = got_object_id_by_path(&obj_id, repo, commit,
5305 link_target ? link_target : in_repo_path);
5306 if (error)
5307 goto done;
5309 error = got_object_get_type(&obj_type, repo, obj_id);
5310 if (error)
5311 goto done;
5313 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5314 error = got_error_path(link_target ? link_target : in_repo_path,
5315 GOT_ERR_OBJ_TYPE);
5316 goto done;
5319 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5320 if (error)
5321 goto done;
5322 bca.f = got_opentemp();
5323 if (bca.f == NULL) {
5324 error = got_error_from_errno("got_opentemp");
5325 goto done;
5327 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5328 &bca.line_offsets, bca.f, blob);
5329 if (error || bca.nlines == 0)
5330 goto done;
5332 /* Don't include \n at EOF in the blame line count. */
5333 if (bca.line_offsets[bca.nlines - 1] == filesize)
5334 bca.nlines--;
5336 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5337 if (bca.lines == NULL) {
5338 error = got_error_from_errno("calloc");
5339 goto done;
5341 bca.lineno_cur = 1;
5342 bca.nlines_prec = 0;
5343 i = bca.nlines;
5344 while (i > 0) {
5345 i /= 10;
5346 bca.nlines_prec++;
5348 bca.repo = repo;
5350 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5351 repo, blame_cb, &bca, check_cancelled, NULL);
5352 done:
5353 free(in_repo_path);
5354 free(link_target);
5355 free(repo_path);
5356 free(cwd);
5357 free(commit_id);
5358 free(obj_id);
5359 if (commit)
5360 got_object_commit_close(commit);
5361 if (blob)
5362 got_object_blob_close(blob);
5363 if (worktree)
5364 got_worktree_close(worktree);
5365 if (repo) {
5366 const struct got_error *close_err = got_repo_close(repo);
5367 if (error == NULL)
5368 error = close_err;
5370 if (bca.lines) {
5371 for (i = 0; i < bca.nlines; i++) {
5372 struct blame_line *bline = &bca.lines[i];
5373 free(bline->id_str);
5374 free(bline->committer);
5376 free(bca.lines);
5378 free(bca.line_offsets);
5379 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5380 error = got_error_from_errno("fclose");
5381 return error;
5384 __dead static void
5385 usage_tree(void)
5387 fprintf(stderr,
5388 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5389 getprogname());
5390 exit(1);
5393 static const struct got_error *
5394 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5395 const char *root_path, struct got_repository *repo)
5397 const struct got_error *err = NULL;
5398 int is_root_path = (strcmp(path, root_path) == 0);
5399 const char *modestr = "";
5400 mode_t mode = got_tree_entry_get_mode(te);
5401 char *link_target = NULL;
5403 path += strlen(root_path);
5404 while (path[0] == '/')
5405 path++;
5407 if (got_object_tree_entry_is_submodule(te))
5408 modestr = "$";
5409 else if (S_ISLNK(mode)) {
5410 int i;
5412 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5413 if (err)
5414 return err;
5415 for (i = 0; i < strlen(link_target); i++) {
5416 if (!isprint((unsigned char)link_target[i]))
5417 link_target[i] = '?';
5420 modestr = "@";
5422 else if (S_ISDIR(mode))
5423 modestr = "/";
5424 else if (mode & S_IXUSR)
5425 modestr = "*";
5427 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5428 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5429 link_target ? " -> ": "", link_target ? link_target : "");
5431 free(link_target);
5432 return NULL;
5435 static const struct got_error *
5436 print_tree(const char *path, struct got_commit_object *commit,
5437 int show_ids, int recurse, const char *root_path,
5438 struct got_repository *repo)
5440 const struct got_error *err = NULL;
5441 struct got_object_id *tree_id = NULL;
5442 struct got_tree_object *tree = NULL;
5443 int nentries, i;
5445 err = got_object_id_by_path(&tree_id, repo, commit, path);
5446 if (err)
5447 goto done;
5449 err = got_object_open_as_tree(&tree, repo, tree_id);
5450 if (err)
5451 goto done;
5452 nentries = got_object_tree_get_nentries(tree);
5453 for (i = 0; i < nentries; i++) {
5454 struct got_tree_entry *te;
5455 char *id = NULL;
5457 if (sigint_received || sigpipe_received)
5458 break;
5460 te = got_object_tree_get_entry(tree, i);
5461 if (show_ids) {
5462 char *id_str;
5463 err = got_object_id_str(&id_str,
5464 got_tree_entry_get_id(te));
5465 if (err)
5466 goto done;
5467 if (asprintf(&id, "%s ", id_str) == -1) {
5468 err = got_error_from_errno("asprintf");
5469 free(id_str);
5470 goto done;
5472 free(id_str);
5474 err = print_entry(te, id, path, root_path, repo);
5475 free(id);
5476 if (err)
5477 goto done;
5479 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5480 char *child_path;
5481 if (asprintf(&child_path, "%s%s%s", path,
5482 path[0] == '/' && path[1] == '\0' ? "" : "/",
5483 got_tree_entry_get_name(te)) == -1) {
5484 err = got_error_from_errno("asprintf");
5485 goto done;
5487 err = print_tree(child_path, commit, show_ids, 1,
5488 root_path, repo);
5489 free(child_path);
5490 if (err)
5491 goto done;
5494 done:
5495 if (tree)
5496 got_object_tree_close(tree);
5497 free(tree_id);
5498 return err;
5501 static const struct got_error *
5502 cmd_tree(int argc, char *argv[])
5504 const struct got_error *error;
5505 struct got_repository *repo = NULL;
5506 struct got_worktree *worktree = NULL;
5507 const char *path, *refname = NULL;
5508 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5509 struct got_object_id *commit_id = NULL;
5510 struct got_commit_object *commit = NULL;
5511 char *commit_id_str = NULL;
5512 int show_ids = 0, recurse = 0;
5513 int ch;
5515 #ifndef PROFILE
5516 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5517 NULL) == -1)
5518 err(1, "pledge");
5519 #endif
5521 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5522 switch (ch) {
5523 case 'c':
5524 commit_id_str = optarg;
5525 break;
5526 case 'r':
5527 repo_path = realpath(optarg, NULL);
5528 if (repo_path == NULL)
5529 return got_error_from_errno2("realpath",
5530 optarg);
5531 got_path_strip_trailing_slashes(repo_path);
5532 break;
5533 case 'i':
5534 show_ids = 1;
5535 break;
5536 case 'R':
5537 recurse = 1;
5538 break;
5539 default:
5540 usage_tree();
5541 /* NOTREACHED */
5545 argc -= optind;
5546 argv += optind;
5548 if (argc == 1)
5549 path = argv[0];
5550 else if (argc > 1)
5551 usage_tree();
5552 else
5553 path = NULL;
5555 cwd = getcwd(NULL, 0);
5556 if (cwd == NULL) {
5557 error = got_error_from_errno("getcwd");
5558 goto done;
5560 if (repo_path == NULL) {
5561 error = got_worktree_open(&worktree, cwd);
5562 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5563 goto done;
5564 else
5565 error = NULL;
5566 if (worktree) {
5567 repo_path =
5568 strdup(got_worktree_get_repo_path(worktree));
5569 if (repo_path == NULL)
5570 error = got_error_from_errno("strdup");
5571 if (error)
5572 goto done;
5573 } else {
5574 repo_path = strdup(cwd);
5575 if (repo_path == NULL) {
5576 error = got_error_from_errno("strdup");
5577 goto done;
5582 error = got_repo_open(&repo, repo_path, NULL);
5583 if (error != NULL)
5584 goto done;
5586 if (worktree) {
5587 const char *prefix = got_worktree_get_path_prefix(worktree);
5588 char *p;
5590 if (path == NULL)
5591 path = "";
5592 error = got_worktree_resolve_path(&p, worktree, path);
5593 if (error)
5594 goto done;
5595 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5596 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5597 p) == -1) {
5598 error = got_error_from_errno("asprintf");
5599 free(p);
5600 goto done;
5602 free(p);
5603 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5604 if (error)
5605 goto done;
5606 } else {
5607 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5608 if (error)
5609 goto done;
5610 if (path == NULL)
5611 path = "/";
5612 error = got_repo_map_path(&in_repo_path, repo, path);
5613 if (error != NULL)
5614 goto done;
5617 if (commit_id_str == NULL) {
5618 struct got_reference *head_ref;
5619 if (worktree)
5620 refname = got_worktree_get_head_ref_name(worktree);
5621 else
5622 refname = GOT_REF_HEAD;
5623 error = got_ref_open(&head_ref, repo, refname, 0);
5624 if (error != NULL)
5625 goto done;
5626 error = got_ref_resolve(&commit_id, repo, head_ref);
5627 got_ref_close(head_ref);
5628 if (error != NULL)
5629 goto done;
5630 } else {
5631 struct got_reflist_head refs;
5632 TAILQ_INIT(&refs);
5633 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5634 NULL);
5635 if (error)
5636 goto done;
5637 error = got_repo_match_object_id(&commit_id, NULL,
5638 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5639 got_ref_list_free(&refs);
5640 if (error)
5641 goto done;
5644 if (worktree) {
5645 /* Release work tree lock. */
5646 got_worktree_close(worktree);
5647 worktree = NULL;
5650 error = got_object_open_as_commit(&commit, repo, commit_id);
5651 if (error)
5652 goto done;
5654 error = print_tree(in_repo_path, commit, show_ids, recurse,
5655 in_repo_path, repo);
5656 done:
5657 free(in_repo_path);
5658 free(repo_path);
5659 free(cwd);
5660 free(commit_id);
5661 if (commit)
5662 got_object_commit_close(commit);
5663 if (worktree)
5664 got_worktree_close(worktree);
5665 if (repo) {
5666 const struct got_error *close_err = got_repo_close(repo);
5667 if (error == NULL)
5668 error = close_err;
5670 return error;
5673 __dead static void
5674 usage_status(void)
5676 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5677 "[-S status-codes] [path ...]\n", getprogname());
5678 exit(1);
5681 struct got_status_arg {
5682 char *status_codes;
5683 int suppress;
5686 static const struct got_error *
5687 print_status(void *arg, unsigned char status, unsigned char staged_status,
5688 const char *path, struct got_object_id *blob_id,
5689 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5690 int dirfd, const char *de_name)
5692 struct got_status_arg *st = arg;
5694 if (status == staged_status && (status == GOT_STATUS_DELETE))
5695 status = GOT_STATUS_NO_CHANGE;
5696 if (st != NULL && st->status_codes) {
5697 size_t ncodes = strlen(st->status_codes);
5698 int i, j = 0;
5700 for (i = 0; i < ncodes ; i++) {
5701 if (st->suppress) {
5702 if (status == st->status_codes[i] ||
5703 staged_status == st->status_codes[i]) {
5704 j++;
5705 continue;
5707 } else {
5708 if (status == st->status_codes[i] ||
5709 staged_status == st->status_codes[i])
5710 break;
5714 if (st->suppress && j == 0)
5715 goto print;
5717 if (i == ncodes)
5718 return NULL;
5720 print:
5721 printf("%c%c %s\n", status, staged_status, path);
5722 return NULL;
5725 static const struct got_error *
5726 cmd_status(int argc, char *argv[])
5728 const struct got_error *error = NULL;
5729 struct got_repository *repo = NULL;
5730 struct got_worktree *worktree = NULL;
5731 struct got_status_arg st;
5732 char *cwd = NULL;
5733 struct got_pathlist_head paths;
5734 struct got_pathlist_entry *pe;
5735 int ch, i, no_ignores = 0;
5737 TAILQ_INIT(&paths);
5739 memset(&st, 0, sizeof(st));
5740 st.status_codes = NULL;
5741 st.suppress = 0;
5743 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5744 switch (ch) {
5745 case 'I':
5746 no_ignores = 1;
5747 break;
5748 case 'S':
5749 if (st.status_codes != NULL && st.suppress == 0)
5750 option_conflict('S', 's');
5751 st.suppress = 1;
5752 /* fallthrough */
5753 case 's':
5754 for (i = 0; i < strlen(optarg); i++) {
5755 switch (optarg[i]) {
5756 case GOT_STATUS_MODIFY:
5757 case GOT_STATUS_ADD:
5758 case GOT_STATUS_DELETE:
5759 case GOT_STATUS_CONFLICT:
5760 case GOT_STATUS_MISSING:
5761 case GOT_STATUS_OBSTRUCTED:
5762 case GOT_STATUS_UNVERSIONED:
5763 case GOT_STATUS_MODE_CHANGE:
5764 case GOT_STATUS_NONEXISTENT:
5765 break;
5766 default:
5767 errx(1, "invalid status code '%c'",
5768 optarg[i]);
5771 if (ch == 's' && st.suppress)
5772 option_conflict('s', 'S');
5773 st.status_codes = optarg;
5774 break;
5775 default:
5776 usage_status();
5777 /* NOTREACHED */
5781 argc -= optind;
5782 argv += optind;
5784 #ifndef PROFILE
5785 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5786 NULL) == -1)
5787 err(1, "pledge");
5788 #endif
5789 cwd = getcwd(NULL, 0);
5790 if (cwd == NULL) {
5791 error = got_error_from_errno("getcwd");
5792 goto done;
5795 error = got_worktree_open(&worktree, cwd);
5796 if (error) {
5797 if (error->code == GOT_ERR_NOT_WORKTREE)
5798 error = wrap_not_worktree_error(error, "status", cwd);
5799 goto done;
5802 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5803 NULL);
5804 if (error != NULL)
5805 goto done;
5807 error = apply_unveil(got_repo_get_path(repo), 1,
5808 got_worktree_get_root_path(worktree));
5809 if (error)
5810 goto done;
5812 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5813 if (error)
5814 goto done;
5816 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5817 print_status, &st, check_cancelled, NULL);
5818 done:
5819 TAILQ_FOREACH(pe, &paths, entry)
5820 free((char *)pe->path);
5821 got_pathlist_free(&paths);
5822 free(cwd);
5823 return error;
5826 __dead static void
5827 usage_ref(void)
5829 fprintf(stderr,
5830 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5831 "[-s reference] [-d] [name]\n",
5832 getprogname());
5833 exit(1);
5836 static const struct got_error *
5837 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5839 static const struct got_error *err = NULL;
5840 struct got_reflist_head refs;
5841 struct got_reflist_entry *re;
5843 TAILQ_INIT(&refs);
5844 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5845 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5846 repo);
5847 if (err)
5848 return err;
5850 TAILQ_FOREACH(re, &refs, entry) {
5851 char *refstr;
5852 refstr = got_ref_to_str(re->ref);
5853 if (refstr == NULL) {
5854 err = got_error_from_errno("got_ref_to_str");
5855 break;
5857 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5858 free(refstr);
5861 got_ref_list_free(&refs);
5862 return err;
5865 static const struct got_error *
5866 delete_ref_by_name(struct got_repository *repo, const char *refname)
5868 const struct got_error *err;
5869 struct got_reference *ref;
5871 err = got_ref_open(&ref, repo, refname, 0);
5872 if (err)
5873 return err;
5875 err = delete_ref(repo, ref);
5876 got_ref_close(ref);
5877 return err;
5880 static const struct got_error *
5881 add_ref(struct got_repository *repo, const char *refname, const char *target)
5883 const struct got_error *err = NULL;
5884 struct got_object_id *id = NULL;
5885 struct got_reference *ref = NULL;
5886 struct got_reflist_head refs;
5889 * Don't let the user create a reference name with a leading '-'.
5890 * While technically a valid reference name, this case is usually
5891 * an unintended typo.
5893 if (refname[0] == '-')
5894 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5896 TAILQ_INIT(&refs);
5897 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5898 if (err)
5899 goto done;
5900 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5901 &refs, repo);
5902 got_ref_list_free(&refs);
5903 if (err)
5904 goto done;
5906 err = got_ref_alloc(&ref, refname, id);
5907 if (err)
5908 goto done;
5910 err = got_ref_write(ref, repo);
5911 done:
5912 if (ref)
5913 got_ref_close(ref);
5914 free(id);
5915 return err;
5918 static const struct got_error *
5919 add_symref(struct got_repository *repo, const char *refname, const char *target)
5921 const struct got_error *err = NULL;
5922 struct got_reference *ref = NULL;
5923 struct got_reference *target_ref = NULL;
5926 * Don't let the user create a reference name with a leading '-'.
5927 * While technically a valid reference name, this case is usually
5928 * an unintended typo.
5930 if (refname[0] == '-')
5931 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5933 err = got_ref_open(&target_ref, repo, target, 0);
5934 if (err)
5935 return err;
5937 err = got_ref_alloc_symref(&ref, refname, target_ref);
5938 if (err)
5939 goto done;
5941 err = got_ref_write(ref, repo);
5942 done:
5943 if (target_ref)
5944 got_ref_close(target_ref);
5945 if (ref)
5946 got_ref_close(ref);
5947 return err;
5950 static const struct got_error *
5951 cmd_ref(int argc, char *argv[])
5953 const struct got_error *error = NULL;
5954 struct got_repository *repo = NULL;
5955 struct got_worktree *worktree = NULL;
5956 char *cwd = NULL, *repo_path = NULL;
5957 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5958 const char *obj_arg = NULL, *symref_target= NULL;
5959 char *refname = NULL;
5961 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5962 switch (ch) {
5963 case 'c':
5964 obj_arg = optarg;
5965 break;
5966 case 'd':
5967 do_delete = 1;
5968 break;
5969 case 'r':
5970 repo_path = realpath(optarg, NULL);
5971 if (repo_path == NULL)
5972 return got_error_from_errno2("realpath",
5973 optarg);
5974 got_path_strip_trailing_slashes(repo_path);
5975 break;
5976 case 'l':
5977 do_list = 1;
5978 break;
5979 case 's':
5980 symref_target = optarg;
5981 break;
5982 case 't':
5983 sort_by_time = 1;
5984 break;
5985 default:
5986 usage_ref();
5987 /* NOTREACHED */
5991 if (obj_arg && do_list)
5992 option_conflict('c', 'l');
5993 if (obj_arg && do_delete)
5994 option_conflict('c', 'd');
5995 if (obj_arg && symref_target)
5996 option_conflict('c', 's');
5997 if (symref_target && do_delete)
5998 option_conflict('s', 'd');
5999 if (symref_target && do_list)
6000 option_conflict('s', 'l');
6001 if (do_delete && do_list)
6002 option_conflict('d', 'l');
6003 if (sort_by_time && !do_list)
6004 errx(1, "-t option requires -l option");
6006 argc -= optind;
6007 argv += optind;
6009 if (do_list) {
6010 if (argc != 0 && argc != 1)
6011 usage_ref();
6012 if (argc == 1) {
6013 refname = strdup(argv[0]);
6014 if (refname == NULL) {
6015 error = got_error_from_errno("strdup");
6016 goto done;
6019 } else {
6020 if (argc != 1)
6021 usage_ref();
6022 refname = strdup(argv[0]);
6023 if (refname == NULL) {
6024 error = got_error_from_errno("strdup");
6025 goto done;
6029 if (refname)
6030 got_path_strip_trailing_slashes(refname);
6032 #ifndef PROFILE
6033 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6034 "sendfd unveil", NULL) == -1)
6035 err(1, "pledge");
6036 #endif
6037 cwd = getcwd(NULL, 0);
6038 if (cwd == NULL) {
6039 error = got_error_from_errno("getcwd");
6040 goto done;
6043 if (repo_path == NULL) {
6044 error = got_worktree_open(&worktree, cwd);
6045 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6046 goto done;
6047 else
6048 error = NULL;
6049 if (worktree) {
6050 repo_path =
6051 strdup(got_worktree_get_repo_path(worktree));
6052 if (repo_path == NULL)
6053 error = got_error_from_errno("strdup");
6054 if (error)
6055 goto done;
6056 } else {
6057 repo_path = strdup(cwd);
6058 if (repo_path == NULL) {
6059 error = got_error_from_errno("strdup");
6060 goto done;
6065 error = got_repo_open(&repo, repo_path, NULL);
6066 if (error != NULL)
6067 goto done;
6069 #ifndef PROFILE
6070 if (do_list) {
6071 /* Remove "cpath" promise. */
6072 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6073 NULL) == -1)
6074 err(1, "pledge");
6076 #endif
6078 error = apply_unveil(got_repo_get_path(repo), do_list,
6079 worktree ? got_worktree_get_root_path(worktree) : NULL);
6080 if (error)
6081 goto done;
6083 if (do_list)
6084 error = list_refs(repo, refname, sort_by_time);
6085 else if (do_delete)
6086 error = delete_ref_by_name(repo, refname);
6087 else if (symref_target)
6088 error = add_symref(repo, refname, symref_target);
6089 else {
6090 if (obj_arg == NULL)
6091 usage_ref();
6092 error = add_ref(repo, refname, obj_arg);
6094 done:
6095 free(refname);
6096 if (repo) {
6097 const struct got_error *close_err = got_repo_close(repo);
6098 if (error == NULL)
6099 error = close_err;
6101 if (worktree)
6102 got_worktree_close(worktree);
6103 free(cwd);
6104 free(repo_path);
6105 return error;
6108 __dead static void
6109 usage_branch(void)
6111 fprintf(stderr,
6112 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6113 "[-n] [name]\n", getprogname());
6114 exit(1);
6117 static const struct got_error *
6118 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6119 struct got_reference *ref)
6121 const struct got_error *err = NULL;
6122 const char *refname, *marker = " ";
6123 char *refstr;
6125 refname = got_ref_get_name(ref);
6126 if (worktree && strcmp(refname,
6127 got_worktree_get_head_ref_name(worktree)) == 0) {
6128 struct got_object_id *id = NULL;
6130 err = got_ref_resolve(&id, repo, ref);
6131 if (err)
6132 return err;
6133 if (got_object_id_cmp(id,
6134 got_worktree_get_base_commit_id(worktree)) == 0)
6135 marker = "* ";
6136 else
6137 marker = "~ ";
6138 free(id);
6141 if (strncmp(refname, "refs/heads/", 11) == 0)
6142 refname += 11;
6143 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6144 refname += 18;
6145 if (strncmp(refname, "refs/remotes/", 13) == 0)
6146 refname += 13;
6148 refstr = got_ref_to_str(ref);
6149 if (refstr == NULL)
6150 return got_error_from_errno("got_ref_to_str");
6152 printf("%s%s: %s\n", marker, refname, refstr);
6153 free(refstr);
6154 return NULL;
6157 static const struct got_error *
6158 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6160 const char *refname;
6162 if (worktree == NULL)
6163 return got_error(GOT_ERR_NOT_WORKTREE);
6165 refname = got_worktree_get_head_ref_name(worktree);
6167 if (strncmp(refname, "refs/heads/", 11) == 0)
6168 refname += 11;
6169 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6170 refname += 18;
6172 printf("%s\n", refname);
6174 return NULL;
6177 static const struct got_error *
6178 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6179 int sort_by_time)
6181 static const struct got_error *err = NULL;
6182 struct got_reflist_head refs;
6183 struct got_reflist_entry *re;
6184 struct got_reference *temp_ref = NULL;
6185 int rebase_in_progress, histedit_in_progress;
6187 TAILQ_INIT(&refs);
6189 if (worktree) {
6190 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6191 worktree);
6192 if (err)
6193 return err;
6195 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6196 worktree);
6197 if (err)
6198 return err;
6200 if (rebase_in_progress || histedit_in_progress) {
6201 err = got_ref_open(&temp_ref, repo,
6202 got_worktree_get_head_ref_name(worktree), 0);
6203 if (err)
6204 return err;
6205 list_branch(repo, worktree, temp_ref);
6206 got_ref_close(temp_ref);
6210 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6211 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6212 repo);
6213 if (err)
6214 return err;
6216 TAILQ_FOREACH(re, &refs, entry)
6217 list_branch(repo, worktree, re->ref);
6219 got_ref_list_free(&refs);
6221 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6222 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6223 repo);
6224 if (err)
6225 return err;
6227 TAILQ_FOREACH(re, &refs, entry)
6228 list_branch(repo, worktree, re->ref);
6230 got_ref_list_free(&refs);
6232 return NULL;
6235 static const struct got_error *
6236 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6237 const char *branch_name)
6239 const struct got_error *err = NULL;
6240 struct got_reference *ref = NULL;
6241 char *refname, *remote_refname = NULL;
6243 if (strncmp(branch_name, "refs/", 5) == 0)
6244 branch_name += 5;
6245 if (strncmp(branch_name, "heads/", 6) == 0)
6246 branch_name += 6;
6247 else if (strncmp(branch_name, "remotes/", 8) == 0)
6248 branch_name += 8;
6250 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6251 return got_error_from_errno("asprintf");
6253 if (asprintf(&remote_refname, "refs/remotes/%s",
6254 branch_name) == -1) {
6255 err = got_error_from_errno("asprintf");
6256 goto done;
6259 err = got_ref_open(&ref, repo, refname, 0);
6260 if (err) {
6261 const struct got_error *err2;
6262 if (err->code != GOT_ERR_NOT_REF)
6263 goto done;
6265 * Keep 'err' intact such that if neither branch exists
6266 * we report "refs/heads" rather than "refs/remotes" in
6267 * our error message.
6269 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6270 if (err2)
6271 goto done;
6272 err = NULL;
6275 if (worktree &&
6276 strcmp(got_worktree_get_head_ref_name(worktree),
6277 got_ref_get_name(ref)) == 0) {
6278 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6279 "will not delete this work tree's current branch");
6280 goto done;
6283 err = delete_ref(repo, ref);
6284 done:
6285 if (ref)
6286 got_ref_close(ref);
6287 free(refname);
6288 free(remote_refname);
6289 return err;
6292 static const struct got_error *
6293 add_branch(struct got_repository *repo, const char *branch_name,
6294 struct got_object_id *base_commit_id)
6296 const struct got_error *err = NULL;
6297 struct got_reference *ref = NULL;
6298 char *base_refname = NULL, *refname = NULL;
6301 * Don't let the user create a branch name with a leading '-'.
6302 * While technically a valid reference name, this case is usually
6303 * an unintended typo.
6305 if (branch_name[0] == '-')
6306 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6308 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6309 branch_name += 11;
6311 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6312 err = got_error_from_errno("asprintf");
6313 goto done;
6316 err = got_ref_open(&ref, repo, refname, 0);
6317 if (err == NULL) {
6318 err = got_error(GOT_ERR_BRANCH_EXISTS);
6319 goto done;
6320 } else if (err->code != GOT_ERR_NOT_REF)
6321 goto done;
6323 err = got_ref_alloc(&ref, refname, base_commit_id);
6324 if (err)
6325 goto done;
6327 err = got_ref_write(ref, repo);
6328 done:
6329 if (ref)
6330 got_ref_close(ref);
6331 free(base_refname);
6332 free(refname);
6333 return err;
6336 static const struct got_error *
6337 cmd_branch(int argc, char *argv[])
6339 const struct got_error *error = NULL;
6340 struct got_repository *repo = NULL;
6341 struct got_worktree *worktree = NULL;
6342 char *cwd = NULL, *repo_path = NULL;
6343 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6344 const char *delref = NULL, *commit_id_arg = NULL;
6345 struct got_reference *ref = NULL;
6346 struct got_pathlist_head paths;
6347 struct got_pathlist_entry *pe;
6348 struct got_object_id *commit_id = NULL;
6349 char *commit_id_str = NULL;
6351 TAILQ_INIT(&paths);
6353 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6354 switch (ch) {
6355 case 'c':
6356 commit_id_arg = optarg;
6357 break;
6358 case 'd':
6359 delref = optarg;
6360 break;
6361 case 'r':
6362 repo_path = realpath(optarg, NULL);
6363 if (repo_path == NULL)
6364 return got_error_from_errno2("realpath",
6365 optarg);
6366 got_path_strip_trailing_slashes(repo_path);
6367 break;
6368 case 'l':
6369 do_list = 1;
6370 break;
6371 case 'n':
6372 do_update = 0;
6373 break;
6374 case 't':
6375 sort_by_time = 1;
6376 break;
6377 default:
6378 usage_branch();
6379 /* NOTREACHED */
6383 if (do_list && delref)
6384 option_conflict('l', 'd');
6385 if (sort_by_time && !do_list)
6386 errx(1, "-t option requires -l option");
6388 argc -= optind;
6389 argv += optind;
6391 if (!do_list && !delref && argc == 0)
6392 do_show = 1;
6394 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6395 errx(1, "-c option can only be used when creating a branch");
6397 if (do_list || delref) {
6398 if (argc > 0)
6399 usage_branch();
6400 } else if (!do_show && argc != 1)
6401 usage_branch();
6403 #ifndef PROFILE
6404 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6405 "sendfd unveil", NULL) == -1)
6406 err(1, "pledge");
6407 #endif
6408 cwd = getcwd(NULL, 0);
6409 if (cwd == NULL) {
6410 error = got_error_from_errno("getcwd");
6411 goto done;
6414 if (repo_path == NULL) {
6415 error = got_worktree_open(&worktree, cwd);
6416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6417 goto done;
6418 else
6419 error = NULL;
6420 if (worktree) {
6421 repo_path =
6422 strdup(got_worktree_get_repo_path(worktree));
6423 if (repo_path == NULL)
6424 error = got_error_from_errno("strdup");
6425 if (error)
6426 goto done;
6427 } else {
6428 repo_path = strdup(cwd);
6429 if (repo_path == NULL) {
6430 error = got_error_from_errno("strdup");
6431 goto done;
6436 error = got_repo_open(&repo, repo_path, NULL);
6437 if (error != NULL)
6438 goto done;
6440 #ifndef PROFILE
6441 if (do_list || do_show) {
6442 /* Remove "cpath" promise. */
6443 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6444 NULL) == -1)
6445 err(1, "pledge");
6447 #endif
6449 error = apply_unveil(got_repo_get_path(repo), do_list,
6450 worktree ? got_worktree_get_root_path(worktree) : NULL);
6451 if (error)
6452 goto done;
6454 if (do_show)
6455 error = show_current_branch(repo, worktree);
6456 else if (do_list)
6457 error = list_branches(repo, worktree, sort_by_time);
6458 else if (delref)
6459 error = delete_branch(repo, worktree, delref);
6460 else {
6461 struct got_reflist_head refs;
6462 TAILQ_INIT(&refs);
6463 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6464 NULL);
6465 if (error)
6466 goto done;
6467 if (commit_id_arg == NULL)
6468 commit_id_arg = worktree ?
6469 got_worktree_get_head_ref_name(worktree) :
6470 GOT_REF_HEAD;
6471 error = got_repo_match_object_id(&commit_id, NULL,
6472 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6473 got_ref_list_free(&refs);
6474 if (error)
6475 goto done;
6476 error = add_branch(repo, argv[0], commit_id);
6477 if (error)
6478 goto done;
6479 if (worktree && do_update) {
6480 struct got_update_progress_arg upa;
6481 char *branch_refname = NULL;
6483 error = got_object_id_str(&commit_id_str, commit_id);
6484 if (error)
6485 goto done;
6486 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6487 worktree);
6488 if (error)
6489 goto done;
6490 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6491 == -1) {
6492 error = got_error_from_errno("asprintf");
6493 goto done;
6495 error = got_ref_open(&ref, repo, branch_refname, 0);
6496 free(branch_refname);
6497 if (error)
6498 goto done;
6499 error = switch_head_ref(ref, commit_id, worktree,
6500 repo);
6501 if (error)
6502 goto done;
6503 error = got_worktree_set_base_commit_id(worktree, repo,
6504 commit_id);
6505 if (error)
6506 goto done;
6507 memset(&upa, 0, sizeof(upa));
6508 error = got_worktree_checkout_files(worktree, &paths,
6509 repo, update_progress, &upa, check_cancelled,
6510 NULL);
6511 if (error)
6512 goto done;
6513 if (upa.did_something) {
6514 printf("Updated to %s: %s\n",
6515 got_worktree_get_head_ref_name(worktree),
6516 commit_id_str);
6518 print_update_progress_stats(&upa);
6521 done:
6522 if (ref)
6523 got_ref_close(ref);
6524 if (repo) {
6525 const struct got_error *close_err = got_repo_close(repo);
6526 if (error == NULL)
6527 error = close_err;
6529 if (worktree)
6530 got_worktree_close(worktree);
6531 free(cwd);
6532 free(repo_path);
6533 free(commit_id);
6534 free(commit_id_str);
6535 TAILQ_FOREACH(pe, &paths, entry)
6536 free((char *)pe->path);
6537 got_pathlist_free(&paths);
6538 return error;
6542 __dead static void
6543 usage_tag(void)
6545 fprintf(stderr,
6546 "usage: %s tag [-c commit] [-r repository] [-l] "
6547 "[-m message] name\n", getprogname());
6548 exit(1);
6551 #if 0
6552 static const struct got_error *
6553 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6555 const struct got_error *err = NULL;
6556 struct got_reflist_entry *re, *se, *new;
6557 struct got_object_id *re_id, *se_id;
6558 struct got_tag_object *re_tag, *se_tag;
6559 time_t re_time, se_time;
6561 STAILQ_FOREACH(re, tags, entry) {
6562 se = STAILQ_FIRST(sorted);
6563 if (se == NULL) {
6564 err = got_reflist_entry_dup(&new, re);
6565 if (err)
6566 return err;
6567 STAILQ_INSERT_HEAD(sorted, new, entry);
6568 continue;
6569 } else {
6570 err = got_ref_resolve(&re_id, repo, re->ref);
6571 if (err)
6572 break;
6573 err = got_object_open_as_tag(&re_tag, repo, re_id);
6574 free(re_id);
6575 if (err)
6576 break;
6577 re_time = got_object_tag_get_tagger_time(re_tag);
6578 got_object_tag_close(re_tag);
6581 while (se) {
6582 err = got_ref_resolve(&se_id, repo, re->ref);
6583 if (err)
6584 break;
6585 err = got_object_open_as_tag(&se_tag, repo, se_id);
6586 free(se_id);
6587 if (err)
6588 break;
6589 se_time = got_object_tag_get_tagger_time(se_tag);
6590 got_object_tag_close(se_tag);
6592 if (se_time > re_time) {
6593 err = got_reflist_entry_dup(&new, re);
6594 if (err)
6595 return err;
6596 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6597 break;
6599 se = STAILQ_NEXT(se, entry);
6600 continue;
6603 done:
6604 return err;
6606 #endif
6608 static const struct got_error *
6609 list_tags(struct got_repository *repo)
6611 static const struct got_error *err = NULL;
6612 struct got_reflist_head refs;
6613 struct got_reflist_entry *re;
6615 TAILQ_INIT(&refs);
6617 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6618 if (err)
6619 return err;
6621 TAILQ_FOREACH(re, &refs, entry) {
6622 const char *refname;
6623 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6624 char datebuf[26];
6625 const char *tagger;
6626 time_t tagger_time;
6627 struct got_object_id *id;
6628 struct got_tag_object *tag;
6629 struct got_commit_object *commit = NULL;
6631 refname = got_ref_get_name(re->ref);
6632 if (strncmp(refname, "refs/tags/", 10) != 0)
6633 continue;
6634 refname += 10;
6635 refstr = got_ref_to_str(re->ref);
6636 if (refstr == NULL) {
6637 err = got_error_from_errno("got_ref_to_str");
6638 break;
6640 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6641 free(refstr);
6643 err = got_ref_resolve(&id, repo, re->ref);
6644 if (err)
6645 break;
6646 err = got_object_open_as_tag(&tag, repo, id);
6647 if (err) {
6648 if (err->code != GOT_ERR_OBJ_TYPE) {
6649 free(id);
6650 break;
6652 /* "lightweight" tag */
6653 err = got_object_open_as_commit(&commit, repo, id);
6654 if (err) {
6655 free(id);
6656 break;
6658 tagger = got_object_commit_get_committer(commit);
6659 tagger_time =
6660 got_object_commit_get_committer_time(commit);
6661 err = got_object_id_str(&id_str, id);
6662 free(id);
6663 if (err)
6664 break;
6665 } else {
6666 free(id);
6667 tagger = got_object_tag_get_tagger(tag);
6668 tagger_time = got_object_tag_get_tagger_time(tag);
6669 err = got_object_id_str(&id_str,
6670 got_object_tag_get_object_id(tag));
6671 if (err)
6672 break;
6674 printf("from: %s\n", tagger);
6675 datestr = get_datestr(&tagger_time, datebuf);
6676 if (datestr)
6677 printf("date: %s UTC\n", datestr);
6678 if (commit)
6679 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6680 else {
6681 switch (got_object_tag_get_object_type(tag)) {
6682 case GOT_OBJ_TYPE_BLOB:
6683 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6684 id_str);
6685 break;
6686 case GOT_OBJ_TYPE_TREE:
6687 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6688 id_str);
6689 break;
6690 case GOT_OBJ_TYPE_COMMIT:
6691 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6692 id_str);
6693 break;
6694 case GOT_OBJ_TYPE_TAG:
6695 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6696 id_str);
6697 break;
6698 default:
6699 break;
6702 free(id_str);
6703 if (commit) {
6704 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6705 if (err)
6706 break;
6707 got_object_commit_close(commit);
6708 } else {
6709 tagmsg0 = strdup(got_object_tag_get_message(tag));
6710 got_object_tag_close(tag);
6711 if (tagmsg0 == NULL) {
6712 err = got_error_from_errno("strdup");
6713 break;
6717 tagmsg = tagmsg0;
6718 do {
6719 line = strsep(&tagmsg, "\n");
6720 if (line)
6721 printf(" %s\n", line);
6722 } while (line);
6723 free(tagmsg0);
6726 got_ref_list_free(&refs);
6727 return NULL;
6730 static const struct got_error *
6731 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6732 const char *tag_name, const char *repo_path)
6734 const struct got_error *err = NULL;
6735 char *template = NULL, *initial_content = NULL;
6736 char *editor = NULL;
6737 int initial_content_len;
6738 int fd = -1;
6740 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6741 err = got_error_from_errno("asprintf");
6742 goto done;
6745 initial_content_len = asprintf(&initial_content,
6746 "\n# tagging commit %s as %s\n",
6747 commit_id_str, tag_name);
6748 if (initial_content_len == -1) {
6749 err = got_error_from_errno("asprintf");
6750 goto done;
6753 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6754 if (err)
6755 goto done;
6757 if (write(fd, initial_content, initial_content_len) == -1) {
6758 err = got_error_from_errno2("write", *tagmsg_path);
6759 goto done;
6762 err = get_editor(&editor);
6763 if (err)
6764 goto done;
6765 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6766 initial_content_len, 1);
6767 done:
6768 free(initial_content);
6769 free(template);
6770 free(editor);
6772 if (fd != -1 && close(fd) == -1 && err == NULL)
6773 err = got_error_from_errno2("close", *tagmsg_path);
6775 /* Editor is done; we can now apply unveil(2) */
6776 if (err == NULL)
6777 err = apply_unveil(repo_path, 0, NULL);
6778 if (err) {
6779 free(*tagmsg);
6780 *tagmsg = NULL;
6782 return err;
6785 static const struct got_error *
6786 add_tag(struct got_repository *repo, const char *tagger,
6787 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6789 const struct got_error *err = NULL;
6790 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6791 char *label = NULL, *commit_id_str = NULL;
6792 struct got_reference *ref = NULL;
6793 char *refname = NULL, *tagmsg = NULL;
6794 char *tagmsg_path = NULL, *tag_id_str = NULL;
6795 int preserve_tagmsg = 0;
6796 struct got_reflist_head refs;
6798 TAILQ_INIT(&refs);
6801 * Don't let the user create a tag name with a leading '-'.
6802 * While technically a valid reference name, this case is usually
6803 * an unintended typo.
6805 if (tag_name[0] == '-')
6806 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6808 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6809 if (err)
6810 goto done;
6812 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6813 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6814 if (err)
6815 goto done;
6817 err = got_object_id_str(&commit_id_str, commit_id);
6818 if (err)
6819 goto done;
6821 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6822 refname = strdup(tag_name);
6823 if (refname == NULL) {
6824 err = got_error_from_errno("strdup");
6825 goto done;
6827 tag_name += 10;
6828 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6829 err = got_error_from_errno("asprintf");
6830 goto done;
6833 err = got_ref_open(&ref, repo, refname, 0);
6834 if (err == NULL) {
6835 err = got_error(GOT_ERR_TAG_EXISTS);
6836 goto done;
6837 } else if (err->code != GOT_ERR_NOT_REF)
6838 goto done;
6840 if (tagmsg_arg == NULL) {
6841 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6842 tag_name, got_repo_get_path(repo));
6843 if (err) {
6844 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6845 tagmsg_path != NULL)
6846 preserve_tagmsg = 1;
6847 goto done;
6851 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6852 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6853 if (err) {
6854 if (tagmsg_path)
6855 preserve_tagmsg = 1;
6856 goto done;
6859 err = got_ref_alloc(&ref, refname, tag_id);
6860 if (err) {
6861 if (tagmsg_path)
6862 preserve_tagmsg = 1;
6863 goto done;
6866 err = got_ref_write(ref, repo);
6867 if (err) {
6868 if (tagmsg_path)
6869 preserve_tagmsg = 1;
6870 goto done;
6873 err = got_object_id_str(&tag_id_str, tag_id);
6874 if (err) {
6875 if (tagmsg_path)
6876 preserve_tagmsg = 1;
6877 goto done;
6879 printf("Created tag %s\n", tag_id_str);
6880 done:
6881 if (preserve_tagmsg) {
6882 fprintf(stderr, "%s: tag message preserved in %s\n",
6883 getprogname(), tagmsg_path);
6884 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6885 err = got_error_from_errno2("unlink", tagmsg_path);
6886 free(tag_id_str);
6887 if (ref)
6888 got_ref_close(ref);
6889 free(commit_id);
6890 free(commit_id_str);
6891 free(refname);
6892 free(tagmsg);
6893 free(tagmsg_path);
6894 got_ref_list_free(&refs);
6895 return err;
6898 static const struct got_error *
6899 cmd_tag(int argc, char *argv[])
6901 const struct got_error *error = NULL;
6902 struct got_repository *repo = NULL;
6903 struct got_worktree *worktree = NULL;
6904 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6905 char *gitconfig_path = NULL, *tagger = NULL;
6906 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6907 int ch, do_list = 0;
6909 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6910 switch (ch) {
6911 case 'c':
6912 commit_id_arg = optarg;
6913 break;
6914 case 'm':
6915 tagmsg = optarg;
6916 break;
6917 case 'r':
6918 repo_path = realpath(optarg, NULL);
6919 if (repo_path == NULL)
6920 return got_error_from_errno2("realpath",
6921 optarg);
6922 got_path_strip_trailing_slashes(repo_path);
6923 break;
6924 case 'l':
6925 do_list = 1;
6926 break;
6927 default:
6928 usage_tag();
6929 /* NOTREACHED */
6933 argc -= optind;
6934 argv += optind;
6936 if (do_list) {
6937 if (commit_id_arg != NULL)
6938 errx(1,
6939 "-c option can only be used when creating a tag");
6940 if (tagmsg)
6941 option_conflict('l', 'm');
6942 if (argc > 0)
6943 usage_tag();
6944 } else if (argc != 1)
6945 usage_tag();
6947 tag_name = argv[0];
6949 #ifndef PROFILE
6950 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6951 "sendfd unveil", NULL) == -1)
6952 err(1, "pledge");
6953 #endif
6954 cwd = getcwd(NULL, 0);
6955 if (cwd == NULL) {
6956 error = got_error_from_errno("getcwd");
6957 goto done;
6960 if (repo_path == NULL) {
6961 error = got_worktree_open(&worktree, cwd);
6962 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6963 goto done;
6964 else
6965 error = NULL;
6966 if (worktree) {
6967 repo_path =
6968 strdup(got_worktree_get_repo_path(worktree));
6969 if (repo_path == NULL)
6970 error = got_error_from_errno("strdup");
6971 if (error)
6972 goto done;
6973 } else {
6974 repo_path = strdup(cwd);
6975 if (repo_path == NULL) {
6976 error = got_error_from_errno("strdup");
6977 goto done;
6982 if (do_list) {
6983 if (worktree) {
6984 /* Release work tree lock. */
6985 got_worktree_close(worktree);
6986 worktree = NULL;
6988 error = got_repo_open(&repo, repo_path, NULL);
6989 if (error != NULL)
6990 goto done;
6991 #ifndef PROFILE
6992 /* Remove "cpath" promise. */
6993 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6994 NULL) == -1)
6995 err(1, "pledge");
6996 #endif
6997 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6998 if (error)
6999 goto done;
7000 error = list_tags(repo);
7001 } else {
7002 error = get_gitconfig_path(&gitconfig_path);
7003 if (error)
7004 goto done;
7005 error = got_repo_open(&repo, repo_path, gitconfig_path);
7006 if (error != NULL)
7007 goto done;
7009 error = get_author(&tagger, repo, worktree);
7010 if (error)
7011 goto done;
7012 if (worktree) {
7013 /* Release work tree lock. */
7014 got_worktree_close(worktree);
7015 worktree = NULL;
7018 if (tagmsg) {
7019 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7020 if (error)
7021 goto done;
7024 if (commit_id_arg == NULL) {
7025 struct got_reference *head_ref;
7026 struct got_object_id *commit_id;
7027 error = got_ref_open(&head_ref, repo,
7028 worktree ? got_worktree_get_head_ref_name(worktree)
7029 : GOT_REF_HEAD, 0);
7030 if (error)
7031 goto done;
7032 error = got_ref_resolve(&commit_id, repo, head_ref);
7033 got_ref_close(head_ref);
7034 if (error)
7035 goto done;
7036 error = got_object_id_str(&commit_id_str, commit_id);
7037 free(commit_id);
7038 if (error)
7039 goto done;
7042 error = add_tag(repo, tagger, tag_name,
7043 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7045 done:
7046 if (repo) {
7047 const struct got_error *close_err = got_repo_close(repo);
7048 if (error == NULL)
7049 error = close_err;
7051 if (worktree)
7052 got_worktree_close(worktree);
7053 free(cwd);
7054 free(repo_path);
7055 free(gitconfig_path);
7056 free(commit_id_str);
7057 free(tagger);
7058 return error;
7061 __dead static void
7062 usage_add(void)
7064 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7065 getprogname());
7066 exit(1);
7069 static const struct got_error *
7070 add_progress(void *arg, unsigned char status, const char *path)
7072 while (path[0] == '/')
7073 path++;
7074 printf("%c %s\n", status, path);
7075 return NULL;
7078 static const struct got_error *
7079 cmd_add(int argc, char *argv[])
7081 const struct got_error *error = NULL;
7082 struct got_repository *repo = NULL;
7083 struct got_worktree *worktree = NULL;
7084 char *cwd = NULL;
7085 struct got_pathlist_head paths;
7086 struct got_pathlist_entry *pe;
7087 int ch, can_recurse = 0, no_ignores = 0;
7089 TAILQ_INIT(&paths);
7091 while ((ch = getopt(argc, argv, "IR")) != -1) {
7092 switch (ch) {
7093 case 'I':
7094 no_ignores = 1;
7095 break;
7096 case 'R':
7097 can_recurse = 1;
7098 break;
7099 default:
7100 usage_add();
7101 /* NOTREACHED */
7105 argc -= optind;
7106 argv += optind;
7108 #ifndef PROFILE
7109 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7110 NULL) == -1)
7111 err(1, "pledge");
7112 #endif
7113 if (argc < 1)
7114 usage_add();
7116 cwd = getcwd(NULL, 0);
7117 if (cwd == NULL) {
7118 error = got_error_from_errno("getcwd");
7119 goto done;
7122 error = got_worktree_open(&worktree, cwd);
7123 if (error) {
7124 if (error->code == GOT_ERR_NOT_WORKTREE)
7125 error = wrap_not_worktree_error(error, "add", cwd);
7126 goto done;
7129 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7130 NULL);
7131 if (error != NULL)
7132 goto done;
7134 error = apply_unveil(got_repo_get_path(repo), 1,
7135 got_worktree_get_root_path(worktree));
7136 if (error)
7137 goto done;
7139 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7140 if (error)
7141 goto done;
7143 if (!can_recurse) {
7144 char *ondisk_path;
7145 struct stat sb;
7146 TAILQ_FOREACH(pe, &paths, entry) {
7147 if (asprintf(&ondisk_path, "%s/%s",
7148 got_worktree_get_root_path(worktree),
7149 pe->path) == -1) {
7150 error = got_error_from_errno("asprintf");
7151 goto done;
7153 if (lstat(ondisk_path, &sb) == -1) {
7154 if (errno == ENOENT) {
7155 free(ondisk_path);
7156 continue;
7158 error = got_error_from_errno2("lstat",
7159 ondisk_path);
7160 free(ondisk_path);
7161 goto done;
7163 free(ondisk_path);
7164 if (S_ISDIR(sb.st_mode)) {
7165 error = got_error_msg(GOT_ERR_BAD_PATH,
7166 "adding directories requires -R option");
7167 goto done;
7172 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7173 NULL, repo, no_ignores);
7174 done:
7175 if (repo) {
7176 const struct got_error *close_err = got_repo_close(repo);
7177 if (error == NULL)
7178 error = close_err;
7180 if (worktree)
7181 got_worktree_close(worktree);
7182 TAILQ_FOREACH(pe, &paths, entry)
7183 free((char *)pe->path);
7184 got_pathlist_free(&paths);
7185 free(cwd);
7186 return error;
7189 __dead static void
7190 usage_remove(void)
7192 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7193 "path ...\n", getprogname());
7194 exit(1);
7197 static const struct got_error *
7198 print_remove_status(void *arg, unsigned char status,
7199 unsigned char staged_status, const char *path)
7201 while (path[0] == '/')
7202 path++;
7203 if (status == GOT_STATUS_NONEXISTENT)
7204 return NULL;
7205 if (status == staged_status && (status == GOT_STATUS_DELETE))
7206 status = GOT_STATUS_NO_CHANGE;
7207 printf("%c%c %s\n", status, staged_status, path);
7208 return NULL;
7211 static const struct got_error *
7212 cmd_remove(int argc, char *argv[])
7214 const struct got_error *error = NULL;
7215 struct got_worktree *worktree = NULL;
7216 struct got_repository *repo = NULL;
7217 const char *status_codes = NULL;
7218 char *cwd = NULL;
7219 struct got_pathlist_head paths;
7220 struct got_pathlist_entry *pe;
7221 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7222 int ignore_missing_paths = 0;
7224 TAILQ_INIT(&paths);
7226 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7227 switch (ch) {
7228 case 'f':
7229 delete_local_mods = 1;
7230 ignore_missing_paths = 1;
7231 break;
7232 case 'k':
7233 keep_on_disk = 1;
7234 break;
7235 case 'R':
7236 can_recurse = 1;
7237 break;
7238 case 's':
7239 for (i = 0; i < strlen(optarg); i++) {
7240 switch (optarg[i]) {
7241 case GOT_STATUS_MODIFY:
7242 delete_local_mods = 1;
7243 break;
7244 case GOT_STATUS_MISSING:
7245 ignore_missing_paths = 1;
7246 break;
7247 default:
7248 errx(1, "invalid status code '%c'",
7249 optarg[i]);
7252 status_codes = optarg;
7253 break;
7254 default:
7255 usage_remove();
7256 /* NOTREACHED */
7260 argc -= optind;
7261 argv += optind;
7263 #ifndef PROFILE
7264 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7265 NULL) == -1)
7266 err(1, "pledge");
7267 #endif
7268 if (argc < 1)
7269 usage_remove();
7271 cwd = getcwd(NULL, 0);
7272 if (cwd == NULL) {
7273 error = got_error_from_errno("getcwd");
7274 goto done;
7276 error = got_worktree_open(&worktree, cwd);
7277 if (error) {
7278 if (error->code == GOT_ERR_NOT_WORKTREE)
7279 error = wrap_not_worktree_error(error, "remove", cwd);
7280 goto done;
7283 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7284 NULL);
7285 if (error)
7286 goto done;
7288 error = apply_unveil(got_repo_get_path(repo), 1,
7289 got_worktree_get_root_path(worktree));
7290 if (error)
7291 goto done;
7293 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7294 if (error)
7295 goto done;
7297 if (!can_recurse) {
7298 char *ondisk_path;
7299 struct stat sb;
7300 TAILQ_FOREACH(pe, &paths, entry) {
7301 if (asprintf(&ondisk_path, "%s/%s",
7302 got_worktree_get_root_path(worktree),
7303 pe->path) == -1) {
7304 error = got_error_from_errno("asprintf");
7305 goto done;
7307 if (lstat(ondisk_path, &sb) == -1) {
7308 if (errno == ENOENT) {
7309 free(ondisk_path);
7310 continue;
7312 error = got_error_from_errno2("lstat",
7313 ondisk_path);
7314 free(ondisk_path);
7315 goto done;
7317 free(ondisk_path);
7318 if (S_ISDIR(sb.st_mode)) {
7319 error = got_error_msg(GOT_ERR_BAD_PATH,
7320 "removing directories requires -R option");
7321 goto done;
7326 error = got_worktree_schedule_delete(worktree, &paths,
7327 delete_local_mods, status_codes, print_remove_status, NULL,
7328 repo, keep_on_disk, ignore_missing_paths);
7329 done:
7330 if (repo) {
7331 const struct got_error *close_err = got_repo_close(repo);
7332 if (error == NULL)
7333 error = close_err;
7335 if (worktree)
7336 got_worktree_close(worktree);
7337 TAILQ_FOREACH(pe, &paths, entry)
7338 free((char *)pe->path);
7339 got_pathlist_free(&paths);
7340 free(cwd);
7341 return error;
7344 __dead static void
7345 usage_patch(void)
7347 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7348 "[-R] [patchfile]\n", getprogname());
7349 exit(1);
7352 static const struct got_error *
7353 patch_from_stdin(int *patchfd)
7355 const struct got_error *err = NULL;
7356 ssize_t r;
7357 char *path, buf[BUFSIZ];
7358 sig_t sighup, sigint, sigquit;
7360 err = got_opentemp_named_fd(&path, patchfd,
7361 GOT_TMPDIR_STR "/got-patch");
7362 if (err)
7363 return err;
7364 unlink(path);
7365 free(path);
7367 sighup = signal(SIGHUP, SIG_DFL);
7368 sigint = signal(SIGINT, SIG_DFL);
7369 sigquit = signal(SIGQUIT, SIG_DFL);
7371 for (;;) {
7372 r = read(0, buf, sizeof(buf));
7373 if (r == -1) {
7374 err = got_error_from_errno("read");
7375 break;
7377 if (r == 0)
7378 break;
7379 if (write(*patchfd, buf, r) == -1) {
7380 err = got_error_from_errno("write");
7381 break;
7385 signal(SIGHUP, sighup);
7386 signal(SIGINT, sigint);
7387 signal(SIGQUIT, sigquit);
7389 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7390 err = got_error_from_errno("lseek");
7392 if (err != NULL) {
7393 close(*patchfd);
7394 *patchfd = -1;
7397 return err;
7400 static const struct got_error *
7401 patch_progress(void *arg, const char *old, const char *new,
7402 unsigned char status, const struct got_error *error, long old_from,
7403 long old_lines, long new_from, long new_lines, long offset,
7404 const struct got_error *hunk_err)
7406 const char *path = new == NULL ? old : new;
7408 while (*path == '/')
7409 path++;
7411 if (status != 0)
7412 printf("%c %s\n", status, path);
7414 if (error != NULL)
7415 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7417 if (offset != 0 || hunk_err != NULL) {
7418 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7419 old_lines, new_from, new_lines);
7420 if (hunk_err != NULL)
7421 printf("%s\n", hunk_err->msg);
7422 else
7423 printf("applied with offset %ld\n", offset);
7426 return NULL;
7429 static const struct got_error *
7430 cmd_patch(int argc, char *argv[])
7432 const struct got_error *error = NULL, *close_error = NULL;
7433 struct got_worktree *worktree = NULL;
7434 struct got_repository *repo = NULL;
7435 const char *errstr;
7436 char *cwd = NULL;
7437 int ch, nop = 0, strip = -1, reverse = 0;
7438 int patchfd;
7440 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7441 switch (ch) {
7442 case 'n':
7443 nop = 1;
7444 break;
7445 case 'p':
7446 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7447 if (errstr != NULL)
7448 errx(1, "pathname strip count is %s: %s",
7449 errstr, optarg);
7450 break;
7451 case 'R':
7452 reverse = 1;
7453 break;
7454 default:
7455 usage_patch();
7456 /* NOTREACHED */
7460 argc -= optind;
7461 argv += optind;
7463 if (argc == 0) {
7464 error = patch_from_stdin(&patchfd);
7465 if (error)
7466 return error;
7467 } else if (argc == 1) {
7468 patchfd = open(argv[0], O_RDONLY);
7469 if (patchfd == -1) {
7470 error = got_error_from_errno2("open", argv[0]);
7471 return error;
7473 } else
7474 usage_patch();
7476 if ((cwd = getcwd(NULL, 0)) == NULL) {
7477 error = got_error_from_errno("getcwd");
7478 goto done;
7481 error = got_worktree_open(&worktree, cwd);
7482 if (error != NULL)
7483 goto done;
7485 const char *repo_path = got_worktree_get_repo_path(worktree);
7486 error = got_repo_open(&repo, repo_path, NULL);
7487 if (error != NULL)
7488 goto done;
7490 error = apply_unveil(got_repo_get_path(repo), 0,
7491 got_worktree_get_root_path(worktree));
7492 if (error != NULL)
7493 goto done;
7495 #ifndef PROFILE
7496 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7497 NULL) == -1)
7498 err(1, "pledge");
7499 #endif
7501 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7502 &patch_progress, NULL, check_cancelled, NULL);
7504 done:
7505 if (repo) {
7506 close_error = got_repo_close(repo);
7507 if (error == NULL)
7508 error = close_error;
7510 if (worktree != NULL) {
7511 close_error = got_worktree_close(worktree);
7512 if (error == NULL)
7513 error = close_error;
7515 free(cwd);
7516 return error;
7519 __dead static void
7520 usage_revert(void)
7522 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7523 "path ...\n", getprogname());
7524 exit(1);
7527 static const struct got_error *
7528 revert_progress(void *arg, unsigned char status, const char *path)
7530 if (status == GOT_STATUS_UNVERSIONED)
7531 return NULL;
7533 while (path[0] == '/')
7534 path++;
7535 printf("%c %s\n", status, path);
7536 return NULL;
7539 struct choose_patch_arg {
7540 FILE *patch_script_file;
7541 const char *action;
7544 static const struct got_error *
7545 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7546 int nchanges, const char *action)
7548 const struct got_error *err;
7549 char *line = NULL;
7550 size_t linesize = 0;
7551 ssize_t linelen;
7553 switch (status) {
7554 case GOT_STATUS_ADD:
7555 printf("A %s\n%s this addition? [y/n] ", path, action);
7556 break;
7557 case GOT_STATUS_DELETE:
7558 printf("D %s\n%s this deletion? [y/n] ", path, action);
7559 break;
7560 case GOT_STATUS_MODIFY:
7561 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7562 return got_error_from_errno("fseek");
7563 printf(GOT_COMMIT_SEP_STR);
7564 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7565 printf("%s", line);
7566 if (linelen == -1 && ferror(patch_file)) {
7567 err = got_error_from_errno("getline");
7568 free(line);
7569 return err;
7571 free(line);
7572 printf(GOT_COMMIT_SEP_STR);
7573 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7574 path, n, nchanges, action);
7575 break;
7576 default:
7577 return got_error_path(path, GOT_ERR_FILE_STATUS);
7580 return NULL;
7583 static const struct got_error *
7584 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7585 FILE *patch_file, int n, int nchanges)
7587 const struct got_error *err = NULL;
7588 char *line = NULL;
7589 size_t linesize = 0;
7590 ssize_t linelen;
7591 int resp = ' ';
7592 struct choose_patch_arg *a = arg;
7594 *choice = GOT_PATCH_CHOICE_NONE;
7596 if (a->patch_script_file) {
7597 char *nl;
7598 err = show_change(status, path, patch_file, n, nchanges,
7599 a->action);
7600 if (err)
7601 return err;
7602 linelen = getline(&line, &linesize, a->patch_script_file);
7603 if (linelen == -1) {
7604 if (ferror(a->patch_script_file))
7605 return got_error_from_errno("getline");
7606 return NULL;
7608 nl = strchr(line, '\n');
7609 if (nl)
7610 *nl = '\0';
7611 if (strcmp(line, "y") == 0) {
7612 *choice = GOT_PATCH_CHOICE_YES;
7613 printf("y\n");
7614 } else if (strcmp(line, "n") == 0) {
7615 *choice = GOT_PATCH_CHOICE_NO;
7616 printf("n\n");
7617 } else if (strcmp(line, "q") == 0 &&
7618 status == GOT_STATUS_MODIFY) {
7619 *choice = GOT_PATCH_CHOICE_QUIT;
7620 printf("q\n");
7621 } else
7622 printf("invalid response '%s'\n", line);
7623 free(line);
7624 return NULL;
7627 while (resp != 'y' && resp != 'n' && resp != 'q') {
7628 err = show_change(status, path, patch_file, n, nchanges,
7629 a->action);
7630 if (err)
7631 return err;
7632 resp = getchar();
7633 if (resp == '\n')
7634 resp = getchar();
7635 if (status == GOT_STATUS_MODIFY) {
7636 if (resp != 'y' && resp != 'n' && resp != 'q') {
7637 printf("invalid response '%c'\n", resp);
7638 resp = ' ';
7640 } else if (resp != 'y' && resp != 'n') {
7641 printf("invalid response '%c'\n", resp);
7642 resp = ' ';
7646 if (resp == 'y')
7647 *choice = GOT_PATCH_CHOICE_YES;
7648 else if (resp == 'n')
7649 *choice = GOT_PATCH_CHOICE_NO;
7650 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7651 *choice = GOT_PATCH_CHOICE_QUIT;
7653 return NULL;
7656 static const struct got_error *
7657 cmd_revert(int argc, char *argv[])
7659 const struct got_error *error = NULL;
7660 struct got_worktree *worktree = NULL;
7661 struct got_repository *repo = NULL;
7662 char *cwd = NULL, *path = NULL;
7663 struct got_pathlist_head paths;
7664 struct got_pathlist_entry *pe;
7665 int ch, can_recurse = 0, pflag = 0;
7666 FILE *patch_script_file = NULL;
7667 const char *patch_script_path = NULL;
7668 struct choose_patch_arg cpa;
7670 TAILQ_INIT(&paths);
7672 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7673 switch (ch) {
7674 case 'p':
7675 pflag = 1;
7676 break;
7677 case 'F':
7678 patch_script_path = optarg;
7679 break;
7680 case 'R':
7681 can_recurse = 1;
7682 break;
7683 default:
7684 usage_revert();
7685 /* NOTREACHED */
7689 argc -= optind;
7690 argv += optind;
7692 #ifndef PROFILE
7693 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7694 "unveil", NULL) == -1)
7695 err(1, "pledge");
7696 #endif
7697 if (argc < 1)
7698 usage_revert();
7699 if (patch_script_path && !pflag)
7700 errx(1, "-F option can only be used together with -p option");
7702 cwd = getcwd(NULL, 0);
7703 if (cwd == NULL) {
7704 error = got_error_from_errno("getcwd");
7705 goto done;
7707 error = got_worktree_open(&worktree, cwd);
7708 if (error) {
7709 if (error->code == GOT_ERR_NOT_WORKTREE)
7710 error = wrap_not_worktree_error(error, "revert", cwd);
7711 goto done;
7714 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7715 NULL);
7716 if (error != NULL)
7717 goto done;
7719 if (patch_script_path) {
7720 patch_script_file = fopen(patch_script_path, "re");
7721 if (patch_script_file == NULL) {
7722 error = got_error_from_errno2("fopen",
7723 patch_script_path);
7724 goto done;
7727 error = apply_unveil(got_repo_get_path(repo), 1,
7728 got_worktree_get_root_path(worktree));
7729 if (error)
7730 goto done;
7732 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7733 if (error)
7734 goto done;
7736 if (!can_recurse) {
7737 char *ondisk_path;
7738 struct stat sb;
7739 TAILQ_FOREACH(pe, &paths, entry) {
7740 if (asprintf(&ondisk_path, "%s/%s",
7741 got_worktree_get_root_path(worktree),
7742 pe->path) == -1) {
7743 error = got_error_from_errno("asprintf");
7744 goto done;
7746 if (lstat(ondisk_path, &sb) == -1) {
7747 if (errno == ENOENT) {
7748 free(ondisk_path);
7749 continue;
7751 error = got_error_from_errno2("lstat",
7752 ondisk_path);
7753 free(ondisk_path);
7754 goto done;
7756 free(ondisk_path);
7757 if (S_ISDIR(sb.st_mode)) {
7758 error = got_error_msg(GOT_ERR_BAD_PATH,
7759 "reverting directories requires -R option");
7760 goto done;
7765 cpa.patch_script_file = patch_script_file;
7766 cpa.action = "revert";
7767 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7768 pflag ? choose_patch : NULL, &cpa, repo);
7769 done:
7770 if (patch_script_file && fclose(patch_script_file) == EOF &&
7771 error == NULL)
7772 error = got_error_from_errno2("fclose", patch_script_path);
7773 if (repo) {
7774 const struct got_error *close_err = got_repo_close(repo);
7775 if (error == NULL)
7776 error = close_err;
7778 if (worktree)
7779 got_worktree_close(worktree);
7780 free(path);
7781 free(cwd);
7782 return error;
7785 __dead static void
7786 usage_commit(void)
7788 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7789 "[path ...]\n", getprogname());
7790 exit(1);
7793 struct collect_commit_logmsg_arg {
7794 const char *cmdline_log;
7795 const char *prepared_log;
7796 int non_interactive;
7797 const char *editor;
7798 const char *worktree_path;
7799 const char *branch_name;
7800 const char *repo_path;
7801 char *logmsg_path;
7805 static const struct got_error *
7806 read_prepared_logmsg(char **logmsg, const char *path)
7808 const struct got_error *err = NULL;
7809 FILE *f = NULL;
7810 struct stat sb;
7811 size_t r;
7813 *logmsg = NULL;
7814 memset(&sb, 0, sizeof(sb));
7816 f = fopen(path, "re");
7817 if (f == NULL)
7818 return got_error_from_errno2("fopen", path);
7820 if (fstat(fileno(f), &sb) == -1) {
7821 err = got_error_from_errno2("fstat", path);
7822 goto done;
7824 if (sb.st_size == 0) {
7825 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7826 goto done;
7829 *logmsg = malloc(sb.st_size + 1);
7830 if (*logmsg == NULL) {
7831 err = got_error_from_errno("malloc");
7832 goto done;
7835 r = fread(*logmsg, 1, sb.st_size, f);
7836 if (r != sb.st_size) {
7837 if (ferror(f))
7838 err = got_error_from_errno2("fread", path);
7839 else
7840 err = got_error(GOT_ERR_IO);
7841 goto done;
7843 (*logmsg)[sb.st_size] = '\0';
7844 done:
7845 if (fclose(f) == EOF && err == NULL)
7846 err = got_error_from_errno2("fclose", path);
7847 if (err) {
7848 free(*logmsg);
7849 *logmsg = NULL;
7851 return err;
7855 static const struct got_error *
7856 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7857 void *arg)
7859 char *initial_content = NULL;
7860 struct got_pathlist_entry *pe;
7861 const struct got_error *err = NULL;
7862 char *template = NULL;
7863 struct collect_commit_logmsg_arg *a = arg;
7864 int initial_content_len;
7865 int fd = -1;
7866 size_t len;
7868 /* if a message was specified on the command line, just use it */
7869 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7870 len = strlen(a->cmdline_log) + 1;
7871 *logmsg = malloc(len + 1);
7872 if (*logmsg == NULL)
7873 return got_error_from_errno("malloc");
7874 strlcpy(*logmsg, a->cmdline_log, len);
7875 return NULL;
7876 } else if (a->prepared_log != NULL && a->non_interactive)
7877 return read_prepared_logmsg(logmsg, a->prepared_log);
7879 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7880 return got_error_from_errno("asprintf");
7882 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7883 if (err)
7884 goto done;
7886 if (a->prepared_log) {
7887 char *msg;
7888 err = read_prepared_logmsg(&msg, a->prepared_log);
7889 if (err)
7890 goto done;
7891 if (write(fd, msg, strlen(msg)) == -1) {
7892 err = got_error_from_errno2("write", a->logmsg_path);
7893 free(msg);
7894 goto done;
7896 free(msg);
7899 initial_content_len = asprintf(&initial_content,
7900 "\n# changes to be committed on branch %s:\n",
7901 a->branch_name);
7902 if (initial_content_len == -1) {
7903 err = got_error_from_errno("asprintf");
7904 goto done;
7907 if (write(fd, initial_content, initial_content_len) == -1) {
7908 err = got_error_from_errno2("write", a->logmsg_path);
7909 goto done;
7912 TAILQ_FOREACH(pe, commitable_paths, entry) {
7913 struct got_commitable *ct = pe->data;
7914 dprintf(fd, "# %c %s\n",
7915 got_commitable_get_status(ct),
7916 got_commitable_get_path(ct));
7919 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7920 initial_content_len, a->prepared_log ? 0 : 1);
7921 done:
7922 free(initial_content);
7923 free(template);
7925 if (fd != -1 && close(fd) == -1 && err == NULL)
7926 err = got_error_from_errno2("close", a->logmsg_path);
7928 /* Editor is done; we can now apply unveil(2) */
7929 if (err == NULL)
7930 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7931 if (err) {
7932 free(*logmsg);
7933 *logmsg = NULL;
7935 return err;
7938 static const struct got_error *
7939 cmd_commit(int argc, char *argv[])
7941 const struct got_error *error = NULL;
7942 struct got_worktree *worktree = NULL;
7943 struct got_repository *repo = NULL;
7944 char *cwd = NULL, *id_str = NULL;
7945 struct got_object_id *id = NULL;
7946 const char *logmsg = NULL;
7947 char *prepared_logmsg = NULL;
7948 struct collect_commit_logmsg_arg cl_arg;
7949 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7950 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7951 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7952 struct got_pathlist_head paths;
7954 TAILQ_INIT(&paths);
7955 cl_arg.logmsg_path = NULL;
7957 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7958 switch (ch) {
7959 case 'F':
7960 if (logmsg != NULL)
7961 option_conflict('F', 'm');
7962 prepared_logmsg = realpath(optarg, NULL);
7963 if (prepared_logmsg == NULL)
7964 return got_error_from_errno2("realpath",
7965 optarg);
7966 break;
7967 case 'm':
7968 if (prepared_logmsg)
7969 option_conflict('m', 'F');
7970 logmsg = optarg;
7971 break;
7972 case 'N':
7973 non_interactive = 1;
7974 break;
7975 case 'S':
7976 allow_bad_symlinks = 1;
7977 break;
7978 default:
7979 usage_commit();
7980 /* NOTREACHED */
7984 argc -= optind;
7985 argv += optind;
7987 #ifndef PROFILE
7988 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7989 "unveil", NULL) == -1)
7990 err(1, "pledge");
7991 #endif
7992 cwd = getcwd(NULL, 0);
7993 if (cwd == NULL) {
7994 error = got_error_from_errno("getcwd");
7995 goto done;
7997 error = got_worktree_open(&worktree, cwd);
7998 if (error) {
7999 if (error->code == GOT_ERR_NOT_WORKTREE)
8000 error = wrap_not_worktree_error(error, "commit", cwd);
8001 goto done;
8004 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8005 if (error)
8006 goto done;
8007 if (rebase_in_progress) {
8008 error = got_error(GOT_ERR_REBASING);
8009 goto done;
8012 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8013 worktree);
8014 if (error)
8015 goto done;
8017 error = get_gitconfig_path(&gitconfig_path);
8018 if (error)
8019 goto done;
8020 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8021 gitconfig_path);
8022 if (error != NULL)
8023 goto done;
8025 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8026 if (error)
8027 goto done;
8028 if (merge_in_progress) {
8029 error = got_error(GOT_ERR_MERGE_BUSY);
8030 goto done;
8033 error = get_author(&author, repo, worktree);
8034 if (error)
8035 return error;
8038 * unveil(2) traverses exec(2); if an editor is used we have
8039 * to apply unveil after the log message has been written.
8041 if (logmsg == NULL || strlen(logmsg) == 0)
8042 error = get_editor(&editor);
8043 else
8044 error = apply_unveil(got_repo_get_path(repo), 0,
8045 got_worktree_get_root_path(worktree));
8046 if (error)
8047 goto done;
8049 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8050 if (error)
8051 goto done;
8053 cl_arg.editor = editor;
8054 cl_arg.cmdline_log = logmsg;
8055 cl_arg.prepared_log = prepared_logmsg;
8056 cl_arg.non_interactive = non_interactive;
8057 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8058 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8059 if (!histedit_in_progress) {
8060 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8061 error = got_error(GOT_ERR_COMMIT_BRANCH);
8062 goto done;
8064 cl_arg.branch_name += 11;
8066 cl_arg.repo_path = got_repo_get_path(repo);
8067 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8068 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8069 print_status, NULL, repo);
8070 if (error) {
8071 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8072 cl_arg.logmsg_path != NULL)
8073 preserve_logmsg = 1;
8074 goto done;
8077 error = got_object_id_str(&id_str, id);
8078 if (error)
8079 goto done;
8080 printf("Created commit %s\n", id_str);
8081 done:
8082 if (preserve_logmsg) {
8083 fprintf(stderr, "%s: log message preserved in %s\n",
8084 getprogname(), cl_arg.logmsg_path);
8085 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8086 error == NULL)
8087 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8088 free(cl_arg.logmsg_path);
8089 if (repo) {
8090 const struct got_error *close_err = got_repo_close(repo);
8091 if (error == NULL)
8092 error = close_err;
8094 if (worktree)
8095 got_worktree_close(worktree);
8096 free(cwd);
8097 free(id_str);
8098 free(gitconfig_path);
8099 free(editor);
8100 free(author);
8101 free(prepared_logmsg);
8102 return error;
8105 __dead static void
8106 usage_send(void)
8108 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8109 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8110 "[remote-repository]\n", getprogname());
8111 exit(1);
8114 static void
8115 print_load_info(int print_colored, int print_found, int print_trees,
8116 int ncolored, int nfound, int ntrees)
8118 if (print_colored) {
8119 printf("%d commit%s colored", ncolored,
8120 ncolored == 1 ? "" : "s");
8122 if (print_found) {
8123 printf("%s%d object%s found",
8124 ncolored > 0 ? "; " : "",
8125 nfound, nfound == 1 ? "" : "s");
8127 if (print_trees) {
8128 printf("; %d tree%s scanned", ntrees,
8129 ntrees == 1 ? "" : "s");
8133 struct got_send_progress_arg {
8134 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8135 int verbosity;
8136 int last_ncolored;
8137 int last_nfound;
8138 int last_ntrees;
8139 int loading_done;
8140 int last_ncommits;
8141 int last_nobj_total;
8142 int last_p_deltify;
8143 int last_p_written;
8144 int last_p_sent;
8145 int printed_something;
8146 int sent_something;
8147 struct got_pathlist_head *delete_branches;
8150 static const struct got_error *
8151 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8152 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8153 int nobj_written, off_t bytes_sent, const char *refname, int success)
8155 struct got_send_progress_arg *a = arg;
8156 char scaled_packsize[FMT_SCALED_STRSIZE];
8157 char scaled_sent[FMT_SCALED_STRSIZE];
8158 int p_deltify = 0, p_written = 0, p_sent = 0;
8159 int print_colored = 0, print_found = 0, print_trees = 0;
8160 int print_searching = 0, print_total = 0;
8161 int print_deltify = 0, print_written = 0, print_sent = 0;
8163 if (a->verbosity < 0)
8164 return NULL;
8166 if (refname) {
8167 const char *status = success ? "accepted" : "rejected";
8169 if (success) {
8170 struct got_pathlist_entry *pe;
8171 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8172 const char *branchname = pe->path;
8173 if (got_path_cmp(branchname, refname,
8174 strlen(branchname), strlen(refname)) == 0) {
8175 status = "deleted";
8176 a->sent_something = 1;
8177 break;
8182 if (a->printed_something)
8183 putchar('\n');
8184 printf("Server has %s %s", status, refname);
8185 a->printed_something = 1;
8186 return NULL;
8189 if (a->last_ncolored != ncolored) {
8190 print_colored = 1;
8191 a->last_ncolored = ncolored;
8194 if (a->last_nfound != nfound) {
8195 print_colored = 1;
8196 print_found = 1;
8197 a->last_nfound = nfound;
8200 if (a->last_ntrees != ntrees) {
8201 print_colored = 1;
8202 print_found = 1;
8203 print_trees = 1;
8204 a->last_ntrees = ntrees;
8207 if ((print_colored || print_found || print_trees) &&
8208 !a->loading_done) {
8209 printf("\r");
8210 print_load_info(print_colored, print_found, print_trees,
8211 ncolored, nfound, ntrees);
8212 a->printed_something = 1;
8213 fflush(stdout);
8214 return NULL;
8215 } else if (!a->loading_done) {
8216 printf("\r");
8217 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8218 printf("\n");
8219 a->loading_done = 1;
8222 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8223 return got_error_from_errno("fmt_scaled");
8224 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8225 return got_error_from_errno("fmt_scaled");
8227 if (a->last_ncommits != ncommits) {
8228 print_searching = 1;
8229 a->last_ncommits = ncommits;
8232 if (a->last_nobj_total != nobj_total) {
8233 print_searching = 1;
8234 print_total = 1;
8235 a->last_nobj_total = nobj_total;
8238 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8239 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8240 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8241 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8242 return got_error(GOT_ERR_NO_SPACE);
8245 if (nobj_deltify > 0 || nobj_written > 0) {
8246 if (nobj_deltify > 0) {
8247 p_deltify = (nobj_deltify * 100) / nobj_total;
8248 if (p_deltify != a->last_p_deltify) {
8249 a->last_p_deltify = p_deltify;
8250 print_searching = 1;
8251 print_total = 1;
8252 print_deltify = 1;
8255 if (nobj_written > 0) {
8256 p_written = (nobj_written * 100) / nobj_total;
8257 if (p_written != a->last_p_written) {
8258 a->last_p_written = p_written;
8259 print_searching = 1;
8260 print_total = 1;
8261 print_deltify = 1;
8262 print_written = 1;
8267 if (bytes_sent > 0) {
8268 p_sent = (bytes_sent * 100) / packfile_size;
8269 if (p_sent != a->last_p_sent) {
8270 a->last_p_sent = p_sent;
8271 print_searching = 1;
8272 print_total = 1;
8273 print_deltify = 1;
8274 print_written = 1;
8275 print_sent = 1;
8277 a->sent_something = 1;
8280 if (print_searching || print_total || print_deltify || print_written ||
8281 print_sent)
8282 printf("\r");
8283 if (print_searching)
8284 printf("packing %d reference%s", ncommits,
8285 ncommits == 1 ? "" : "s");
8286 if (print_total)
8287 printf("; %d object%s", nobj_total,
8288 nobj_total == 1 ? "" : "s");
8289 if (print_deltify)
8290 printf("; deltify: %d%%", p_deltify);
8291 if (print_sent)
8292 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8293 scaled_packsize, p_sent);
8294 else if (print_written)
8295 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8296 scaled_packsize, p_written);
8297 if (print_searching || print_total || print_deltify ||
8298 print_written || print_sent) {
8299 a->printed_something = 1;
8300 fflush(stdout);
8302 return NULL;
8305 static const struct got_error *
8306 cmd_send(int argc, char *argv[])
8308 const struct got_error *error = NULL;
8309 char *cwd = NULL, *repo_path = NULL;
8310 const char *remote_name;
8311 char *proto = NULL, *host = NULL, *port = NULL;
8312 char *repo_name = NULL, *server_path = NULL;
8313 const struct got_remote_repo *remotes, *remote = NULL;
8314 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8315 struct got_repository *repo = NULL;
8316 struct got_worktree *worktree = NULL;
8317 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8318 struct got_pathlist_head branches;
8319 struct got_pathlist_head tags;
8320 struct got_reflist_head all_branches;
8321 struct got_reflist_head all_tags;
8322 struct got_pathlist_head delete_args;
8323 struct got_pathlist_head delete_branches;
8324 struct got_reflist_entry *re;
8325 struct got_pathlist_entry *pe;
8326 int i, ch, sendfd = -1, sendstatus;
8327 pid_t sendpid = -1;
8328 struct got_send_progress_arg spa;
8329 int verbosity = 0, overwrite_refs = 0;
8330 int send_all_branches = 0, send_all_tags = 0;
8331 struct got_reference *ref = NULL;
8333 TAILQ_INIT(&branches);
8334 TAILQ_INIT(&tags);
8335 TAILQ_INIT(&all_branches);
8336 TAILQ_INIT(&all_tags);
8337 TAILQ_INIT(&delete_args);
8338 TAILQ_INIT(&delete_branches);
8340 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8341 switch (ch) {
8342 case 'a':
8343 send_all_branches = 1;
8344 break;
8345 case 'b':
8346 error = got_pathlist_append(&branches, optarg, NULL);
8347 if (error)
8348 return error;
8349 nbranches++;
8350 break;
8351 case 'd':
8352 error = got_pathlist_append(&delete_args, optarg, NULL);
8353 if (error)
8354 return error;
8355 break;
8356 case 'f':
8357 overwrite_refs = 1;
8358 break;
8359 case 'r':
8360 repo_path = realpath(optarg, NULL);
8361 if (repo_path == NULL)
8362 return got_error_from_errno2("realpath",
8363 optarg);
8364 got_path_strip_trailing_slashes(repo_path);
8365 break;
8366 case 't':
8367 error = got_pathlist_append(&tags, optarg, NULL);
8368 if (error)
8369 return error;
8370 ntags++;
8371 break;
8372 case 'T':
8373 send_all_tags = 1;
8374 break;
8375 case 'v':
8376 if (verbosity < 0)
8377 verbosity = 0;
8378 else if (verbosity < 3)
8379 verbosity++;
8380 break;
8381 case 'q':
8382 verbosity = -1;
8383 break;
8384 default:
8385 usage_send();
8386 /* NOTREACHED */
8389 argc -= optind;
8390 argv += optind;
8392 if (send_all_branches && !TAILQ_EMPTY(&branches))
8393 option_conflict('a', 'b');
8394 if (send_all_tags && !TAILQ_EMPTY(&tags))
8395 option_conflict('T', 't');
8398 if (argc == 0)
8399 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8400 else if (argc == 1)
8401 remote_name = argv[0];
8402 else
8403 usage_send();
8405 cwd = getcwd(NULL, 0);
8406 if (cwd == NULL) {
8407 error = got_error_from_errno("getcwd");
8408 goto done;
8411 if (repo_path == NULL) {
8412 error = got_worktree_open(&worktree, cwd);
8413 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8414 goto done;
8415 else
8416 error = NULL;
8417 if (worktree) {
8418 repo_path =
8419 strdup(got_worktree_get_repo_path(worktree));
8420 if (repo_path == NULL)
8421 error = got_error_from_errno("strdup");
8422 if (error)
8423 goto done;
8424 } else {
8425 repo_path = strdup(cwd);
8426 if (repo_path == NULL) {
8427 error = got_error_from_errno("strdup");
8428 goto done;
8433 error = got_repo_open(&repo, repo_path, NULL);
8434 if (error)
8435 goto done;
8437 if (worktree) {
8438 worktree_conf = got_worktree_get_gotconfig(worktree);
8439 if (worktree_conf) {
8440 got_gotconfig_get_remotes(&nremotes, &remotes,
8441 worktree_conf);
8442 for (i = 0; i < nremotes; i++) {
8443 if (strcmp(remotes[i].name, remote_name) == 0) {
8444 remote = &remotes[i];
8445 break;
8450 if (remote == NULL) {
8451 repo_conf = got_repo_get_gotconfig(repo);
8452 if (repo_conf) {
8453 got_gotconfig_get_remotes(&nremotes, &remotes,
8454 repo_conf);
8455 for (i = 0; i < nremotes; i++) {
8456 if (strcmp(remotes[i].name, remote_name) == 0) {
8457 remote = &remotes[i];
8458 break;
8463 if (remote == NULL) {
8464 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8465 for (i = 0; i < nremotes; i++) {
8466 if (strcmp(remotes[i].name, remote_name) == 0) {
8467 remote = &remotes[i];
8468 break;
8472 if (remote == NULL) {
8473 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8474 goto done;
8477 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8478 &repo_name, remote->send_url);
8479 if (error)
8480 goto done;
8482 if (strcmp(proto, "git") == 0) {
8483 #ifndef PROFILE
8484 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8485 "sendfd dns inet unveil", NULL) == -1)
8486 err(1, "pledge");
8487 #endif
8488 } else if (strcmp(proto, "git+ssh") == 0 ||
8489 strcmp(proto, "ssh") == 0) {
8490 #ifndef PROFILE
8491 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8492 "sendfd unveil", NULL) == -1)
8493 err(1, "pledge");
8494 #endif
8495 } else if (strcmp(proto, "http") == 0 ||
8496 strcmp(proto, "git+http") == 0) {
8497 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8498 goto done;
8499 } else {
8500 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8501 goto done;
8504 error = got_dial_apply_unveil(proto);
8505 if (error)
8506 goto done;
8508 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8509 if (error)
8510 goto done;
8512 if (send_all_branches) {
8513 error = got_ref_list(&all_branches, repo, "refs/heads",
8514 got_ref_cmp_by_name, NULL);
8515 if (error)
8516 goto done;
8517 TAILQ_FOREACH(re, &all_branches, entry) {
8518 const char *branchname = got_ref_get_name(re->ref);
8519 error = got_pathlist_append(&branches,
8520 branchname, NULL);
8521 if (error)
8522 goto done;
8523 nbranches++;
8525 } else if (nbranches == 0) {
8526 for (i = 0; i < remote->nsend_branches; i++) {
8527 got_pathlist_append(&branches,
8528 remote->send_branches[i], NULL);
8532 if (send_all_tags) {
8533 error = got_ref_list(&all_tags, repo, "refs/tags",
8534 got_ref_cmp_by_name, NULL);
8535 if (error)
8536 goto done;
8537 TAILQ_FOREACH(re, &all_tags, entry) {
8538 const char *tagname = got_ref_get_name(re->ref);
8539 error = got_pathlist_append(&tags,
8540 tagname, NULL);
8541 if (error)
8542 goto done;
8543 ntags++;
8548 * To prevent accidents only branches in refs/heads/ can be deleted
8549 * with 'got send -d'.
8550 * Deleting anything else requires local repository access or Git.
8552 TAILQ_FOREACH(pe, &delete_args, entry) {
8553 const char *branchname = pe->path;
8554 char *s;
8555 struct got_pathlist_entry *new;
8556 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8557 s = strdup(branchname);
8558 if (s == NULL) {
8559 error = got_error_from_errno("strdup");
8560 goto done;
8562 } else {
8563 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8564 error = got_error_from_errno("asprintf");
8565 goto done;
8568 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8569 if (error || new == NULL /* duplicate */)
8570 free(s);
8571 if (error)
8572 goto done;
8573 ndelete_branches++;
8576 if (nbranches == 0 && ndelete_branches == 0) {
8577 struct got_reference *head_ref;
8578 if (worktree)
8579 error = got_ref_open(&head_ref, repo,
8580 got_worktree_get_head_ref_name(worktree), 0);
8581 else
8582 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8583 if (error)
8584 goto done;
8585 if (got_ref_is_symbolic(head_ref)) {
8586 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8587 got_ref_close(head_ref);
8588 if (error)
8589 goto done;
8590 } else
8591 ref = head_ref;
8592 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8593 NULL);
8594 if (error)
8595 goto done;
8596 nbranches++;
8599 if (verbosity >= 0)
8600 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8601 port ? ":" : "", port ? port : "");
8603 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8604 server_path, verbosity);
8605 if (error)
8606 goto done;
8608 memset(&spa, 0, sizeof(spa));
8609 spa.last_scaled_packsize[0] = '\0';
8610 spa.last_p_deltify = -1;
8611 spa.last_p_written = -1;
8612 spa.verbosity = verbosity;
8613 spa.delete_branches = &delete_branches;
8614 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8615 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8616 check_cancelled, NULL);
8617 if (spa.printed_something)
8618 putchar('\n');
8619 if (error)
8620 goto done;
8621 if (!spa.sent_something && verbosity >= 0)
8622 printf("Already up-to-date\n");
8623 done:
8624 if (sendpid > 0) {
8625 if (kill(sendpid, SIGTERM) == -1)
8626 error = got_error_from_errno("kill");
8627 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8628 error = got_error_from_errno("waitpid");
8630 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8631 error = got_error_from_errno("close");
8632 if (repo) {
8633 const struct got_error *close_err = got_repo_close(repo);
8634 if (error == NULL)
8635 error = close_err;
8637 if (worktree)
8638 got_worktree_close(worktree);
8639 if (ref)
8640 got_ref_close(ref);
8641 got_pathlist_free(&branches);
8642 got_pathlist_free(&tags);
8643 got_ref_list_free(&all_branches);
8644 got_ref_list_free(&all_tags);
8645 got_pathlist_free(&delete_args);
8646 TAILQ_FOREACH(pe, &delete_branches, entry)
8647 free((char *)pe->path);
8648 got_pathlist_free(&delete_branches);
8649 free(cwd);
8650 free(repo_path);
8651 free(proto);
8652 free(host);
8653 free(port);
8654 free(server_path);
8655 free(repo_name);
8656 return error;
8659 __dead static void
8660 usage_cherrypick(void)
8662 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8663 exit(1);
8666 static const struct got_error *
8667 cmd_cherrypick(int argc, char *argv[])
8669 const struct got_error *error = NULL;
8670 struct got_worktree *worktree = NULL;
8671 struct got_repository *repo = NULL;
8672 char *cwd = NULL, *commit_id_str = NULL;
8673 struct got_object_id *commit_id = NULL;
8674 struct got_commit_object *commit = NULL;
8675 struct got_object_qid *pid;
8676 int ch;
8677 struct got_update_progress_arg upa;
8679 while ((ch = getopt(argc, argv, "")) != -1) {
8680 switch (ch) {
8681 default:
8682 usage_cherrypick();
8683 /* NOTREACHED */
8687 argc -= optind;
8688 argv += optind;
8690 #ifndef PROFILE
8691 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8692 "unveil", NULL) == -1)
8693 err(1, "pledge");
8694 #endif
8695 if (argc != 1)
8696 usage_cherrypick();
8698 cwd = getcwd(NULL, 0);
8699 if (cwd == NULL) {
8700 error = got_error_from_errno("getcwd");
8701 goto done;
8703 error = got_worktree_open(&worktree, cwd);
8704 if (error) {
8705 if (error->code == GOT_ERR_NOT_WORKTREE)
8706 error = wrap_not_worktree_error(error, "cherrypick",
8707 cwd);
8708 goto done;
8711 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8712 NULL);
8713 if (error != NULL)
8714 goto done;
8716 error = apply_unveil(got_repo_get_path(repo), 0,
8717 got_worktree_get_root_path(worktree));
8718 if (error)
8719 goto done;
8721 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8722 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8723 if (error)
8724 goto done;
8725 error = got_object_id_str(&commit_id_str, commit_id);
8726 if (error)
8727 goto done;
8729 error = got_object_open_as_commit(&commit, repo, commit_id);
8730 if (error)
8731 goto done;
8732 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8733 memset(&upa, 0, sizeof(upa));
8734 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8735 commit_id, repo, update_progress, &upa, check_cancelled,
8736 NULL);
8737 if (error != NULL)
8738 goto done;
8740 if (upa.did_something)
8741 printf("Merged commit %s\n", commit_id_str);
8742 print_merge_progress_stats(&upa);
8743 done:
8744 if (commit)
8745 got_object_commit_close(commit);
8746 free(commit_id_str);
8747 if (worktree)
8748 got_worktree_close(worktree);
8749 if (repo) {
8750 const struct got_error *close_err = got_repo_close(repo);
8751 if (error == NULL)
8752 error = close_err;
8754 return error;
8757 __dead static void
8758 usage_backout(void)
8760 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8761 exit(1);
8764 static const struct got_error *
8765 cmd_backout(int argc, char *argv[])
8767 const struct got_error *error = NULL;
8768 struct got_worktree *worktree = NULL;
8769 struct got_repository *repo = NULL;
8770 char *cwd = NULL, *commit_id_str = NULL;
8771 struct got_object_id *commit_id = NULL;
8772 struct got_commit_object *commit = NULL;
8773 struct got_object_qid *pid;
8774 int ch;
8775 struct got_update_progress_arg upa;
8777 while ((ch = getopt(argc, argv, "")) != -1) {
8778 switch (ch) {
8779 default:
8780 usage_backout();
8781 /* NOTREACHED */
8785 argc -= optind;
8786 argv += optind;
8788 #ifndef PROFILE
8789 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8790 "unveil", NULL) == -1)
8791 err(1, "pledge");
8792 #endif
8793 if (argc != 1)
8794 usage_backout();
8796 cwd = getcwd(NULL, 0);
8797 if (cwd == NULL) {
8798 error = got_error_from_errno("getcwd");
8799 goto done;
8801 error = got_worktree_open(&worktree, cwd);
8802 if (error) {
8803 if (error->code == GOT_ERR_NOT_WORKTREE)
8804 error = wrap_not_worktree_error(error, "backout", cwd);
8805 goto done;
8808 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8809 NULL);
8810 if (error != NULL)
8811 goto done;
8813 error = apply_unveil(got_repo_get_path(repo), 0,
8814 got_worktree_get_root_path(worktree));
8815 if (error)
8816 goto done;
8818 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8819 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8820 if (error)
8821 goto done;
8822 error = got_object_id_str(&commit_id_str, commit_id);
8823 if (error)
8824 goto done;
8826 error = got_object_open_as_commit(&commit, repo, commit_id);
8827 if (error)
8828 goto done;
8829 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8830 if (pid == NULL) {
8831 error = got_error(GOT_ERR_ROOT_COMMIT);
8832 goto done;
8835 memset(&upa, 0, sizeof(upa));
8836 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8837 repo, update_progress, &upa, check_cancelled, NULL);
8838 if (error != NULL)
8839 goto done;
8841 if (upa.did_something)
8842 printf("Backed out commit %s\n", commit_id_str);
8843 print_merge_progress_stats(&upa);
8844 done:
8845 if (commit)
8846 got_object_commit_close(commit);
8847 free(commit_id_str);
8848 if (worktree)
8849 got_worktree_close(worktree);
8850 if (repo) {
8851 const struct got_error *close_err = got_repo_close(repo);
8852 if (error == NULL)
8853 error = close_err;
8855 return error;
8858 __dead static void
8859 usage_rebase(void)
8861 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8862 getprogname());
8863 exit(1);
8866 void
8867 trim_logmsg(char *logmsg, int limit)
8869 char *nl;
8870 size_t len;
8872 len = strlen(logmsg);
8873 if (len > limit)
8874 len = limit;
8875 logmsg[len] = '\0';
8876 nl = strchr(logmsg, '\n');
8877 if (nl)
8878 *nl = '\0';
8881 static const struct got_error *
8882 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8884 const struct got_error *err;
8885 char *logmsg0 = NULL;
8886 const char *s;
8888 err = got_object_commit_get_logmsg(&logmsg0, commit);
8889 if (err)
8890 return err;
8892 s = logmsg0;
8893 while (isspace((unsigned char)s[0]))
8894 s++;
8896 *logmsg = strdup(s);
8897 if (*logmsg == NULL) {
8898 err = got_error_from_errno("strdup");
8899 goto done;
8902 trim_logmsg(*logmsg, limit);
8903 done:
8904 free(logmsg0);
8905 return err;
8908 static const struct got_error *
8909 show_rebase_merge_conflict(struct got_object_id *id,
8910 struct got_repository *repo)
8912 const struct got_error *err;
8913 struct got_commit_object *commit = NULL;
8914 char *id_str = NULL, *logmsg = NULL;
8916 err = got_object_open_as_commit(&commit, repo, id);
8917 if (err)
8918 return err;
8920 err = got_object_id_str(&id_str, id);
8921 if (err)
8922 goto done;
8924 id_str[12] = '\0';
8926 err = get_short_logmsg(&logmsg, 42, commit);
8927 if (err)
8928 goto done;
8930 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8931 done:
8932 free(id_str);
8933 got_object_commit_close(commit);
8934 free(logmsg);
8935 return err;
8938 static const struct got_error *
8939 show_rebase_progress(struct got_commit_object *commit,
8940 struct got_object_id *old_id, struct got_object_id *new_id)
8942 const struct got_error *err;
8943 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8945 err = got_object_id_str(&old_id_str, old_id);
8946 if (err)
8947 goto done;
8949 if (new_id) {
8950 err = got_object_id_str(&new_id_str, new_id);
8951 if (err)
8952 goto done;
8955 old_id_str[12] = '\0';
8956 if (new_id_str)
8957 new_id_str[12] = '\0';
8959 err = get_short_logmsg(&logmsg, 42, commit);
8960 if (err)
8961 goto done;
8963 printf("%s -> %s: %s\n", old_id_str,
8964 new_id_str ? new_id_str : "no-op change", logmsg);
8965 done:
8966 free(old_id_str);
8967 free(new_id_str);
8968 free(logmsg);
8969 return err;
8972 static const struct got_error *
8973 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8974 struct got_reference *branch, struct got_reference *new_base_branch,
8975 struct got_reference *tmp_branch, struct got_repository *repo,
8976 int create_backup)
8978 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8979 return got_worktree_rebase_complete(worktree, fileindex,
8980 new_base_branch, tmp_branch, branch, repo, create_backup);
8983 static const struct got_error *
8984 rebase_commit(struct got_pathlist_head *merged_paths,
8985 struct got_worktree *worktree, struct got_fileindex *fileindex,
8986 struct got_reference *tmp_branch,
8987 struct got_object_id *commit_id, struct got_repository *repo)
8989 const struct got_error *error;
8990 struct got_commit_object *commit;
8991 struct got_object_id *new_commit_id;
8993 error = got_object_open_as_commit(&commit, repo, commit_id);
8994 if (error)
8995 return error;
8997 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8998 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8999 if (error) {
9000 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9001 goto done;
9002 error = show_rebase_progress(commit, commit_id, NULL);
9003 } else {
9004 error = show_rebase_progress(commit, commit_id, new_commit_id);
9005 free(new_commit_id);
9007 done:
9008 got_object_commit_close(commit);
9009 return error;
9012 struct check_path_prefix_arg {
9013 const char *path_prefix;
9014 size_t len;
9015 int errcode;
9018 static const struct got_error *
9019 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9020 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9021 struct got_object_id *id1, struct got_object_id *id2,
9022 const char *path1, const char *path2,
9023 mode_t mode1, mode_t mode2, struct got_repository *repo)
9025 struct check_path_prefix_arg *a = arg;
9027 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9028 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9029 return got_error(a->errcode);
9031 return NULL;
9034 static const struct got_error *
9035 check_path_prefix(struct got_object_id *parent_id,
9036 struct got_object_id *commit_id, const char *path_prefix,
9037 int errcode, struct got_repository *repo)
9039 const struct got_error *err;
9040 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9041 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9042 struct check_path_prefix_arg cpp_arg;
9044 if (got_path_is_root_dir(path_prefix))
9045 return NULL;
9047 err = got_object_open_as_commit(&commit, repo, commit_id);
9048 if (err)
9049 goto done;
9051 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9052 if (err)
9053 goto done;
9055 err = got_object_open_as_tree(&tree1, repo,
9056 got_object_commit_get_tree_id(parent_commit));
9057 if (err)
9058 goto done;
9060 err = got_object_open_as_tree(&tree2, repo,
9061 got_object_commit_get_tree_id(commit));
9062 if (err)
9063 goto done;
9065 cpp_arg.path_prefix = path_prefix;
9066 while (cpp_arg.path_prefix[0] == '/')
9067 cpp_arg.path_prefix++;
9068 cpp_arg.len = strlen(cpp_arg.path_prefix);
9069 cpp_arg.errcode = errcode;
9070 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9071 check_path_prefix_in_diff, &cpp_arg, 0);
9072 done:
9073 if (tree1)
9074 got_object_tree_close(tree1);
9075 if (tree2)
9076 got_object_tree_close(tree2);
9077 if (commit)
9078 got_object_commit_close(commit);
9079 if (parent_commit)
9080 got_object_commit_close(parent_commit);
9081 return err;
9084 static const struct got_error *
9085 collect_commits(struct got_object_id_queue *commits,
9086 struct got_object_id *initial_commit_id,
9087 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9088 const char *path_prefix, int path_prefix_errcode,
9089 struct got_repository *repo)
9091 const struct got_error *err = NULL;
9092 struct got_commit_graph *graph = NULL;
9093 struct got_object_id *parent_id = NULL;
9094 struct got_object_qid *qid;
9095 struct got_object_id *commit_id = initial_commit_id;
9097 err = got_commit_graph_open(&graph, "/", 1);
9098 if (err)
9099 return err;
9101 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9102 check_cancelled, NULL);
9103 if (err)
9104 goto done;
9105 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9106 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9107 check_cancelled, NULL);
9108 if (err) {
9109 if (err->code == GOT_ERR_ITER_COMPLETED) {
9110 err = got_error_msg(GOT_ERR_ANCESTRY,
9111 "ran out of commits to rebase before "
9112 "youngest common ancestor commit has "
9113 "been reached?!?");
9115 goto done;
9116 } else {
9117 err = check_path_prefix(parent_id, commit_id,
9118 path_prefix, path_prefix_errcode, repo);
9119 if (err)
9120 goto done;
9122 err = got_object_qid_alloc(&qid, commit_id);
9123 if (err)
9124 goto done;
9125 STAILQ_INSERT_HEAD(commits, qid, entry);
9126 commit_id = parent_id;
9129 done:
9130 got_commit_graph_close(graph);
9131 return err;
9134 static const struct got_error *
9135 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9137 const struct got_error *err = NULL;
9138 time_t committer_time;
9139 struct tm tm;
9140 char datebuf[11]; /* YYYY-MM-DD + NUL */
9141 char *author0 = NULL, *author, *smallerthan;
9142 char *logmsg0 = NULL, *logmsg, *newline;
9144 committer_time = got_object_commit_get_committer_time(commit);
9145 if (gmtime_r(&committer_time, &tm) == NULL)
9146 return got_error_from_errno("gmtime_r");
9147 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9148 return got_error(GOT_ERR_NO_SPACE);
9150 author0 = strdup(got_object_commit_get_author(commit));
9151 if (author0 == NULL)
9152 return got_error_from_errno("strdup");
9153 author = author0;
9154 smallerthan = strchr(author, '<');
9155 if (smallerthan && smallerthan[1] != '\0')
9156 author = smallerthan + 1;
9157 author[strcspn(author, "@>")] = '\0';
9159 err = got_object_commit_get_logmsg(&logmsg0, commit);
9160 if (err)
9161 goto done;
9162 logmsg = logmsg0;
9163 while (*logmsg == '\n')
9164 logmsg++;
9165 newline = strchr(logmsg, '\n');
9166 if (newline)
9167 *newline = '\0';
9169 if (asprintf(brief_str, "%s %s %s",
9170 datebuf, author, logmsg) == -1)
9171 err = got_error_from_errno("asprintf");
9172 done:
9173 free(author0);
9174 free(logmsg0);
9175 return err;
9178 static const struct got_error *
9179 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9180 struct got_repository *repo)
9182 const struct got_error *err;
9183 char *id_str;
9185 err = got_object_id_str(&id_str, id);
9186 if (err)
9187 return err;
9189 err = got_ref_delete(ref, repo);
9190 if (err)
9191 goto done;
9193 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9194 done:
9195 free(id_str);
9196 return err;
9199 static const struct got_error *
9200 print_backup_ref(const char *branch_name, const char *new_id_str,
9201 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9202 struct got_reflist_object_id_map *refs_idmap,
9203 struct got_repository *repo)
9205 const struct got_error *err = NULL;
9206 struct got_reflist_head *refs;
9207 char *refs_str = NULL;
9208 struct got_object_id *new_commit_id = NULL;
9209 struct got_commit_object *new_commit = NULL;
9210 char *new_commit_brief_str = NULL;
9211 struct got_object_id *yca_id = NULL;
9212 struct got_commit_object *yca_commit = NULL;
9213 char *yca_id_str = NULL, *yca_brief_str = NULL;
9214 char *custom_refs_str;
9216 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9217 return got_error_from_errno("asprintf");
9219 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9220 0, 0, refs_idmap, custom_refs_str);
9221 if (err)
9222 goto done;
9224 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9225 if (err)
9226 goto done;
9228 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9229 if (refs) {
9230 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9231 if (err)
9232 goto done;
9235 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9236 if (err)
9237 goto done;
9239 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9240 if (err)
9241 goto done;
9243 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9244 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9245 if (err)
9246 goto done;
9248 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9249 refs_str ? " (" : "", refs_str ? refs_str : "",
9250 refs_str ? ")" : "", new_commit_brief_str);
9251 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9252 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9253 free(refs_str);
9254 refs_str = NULL;
9256 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9257 if (err)
9258 goto done;
9260 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9261 if (err)
9262 goto done;
9264 err = got_object_id_str(&yca_id_str, yca_id);
9265 if (err)
9266 goto done;
9268 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9269 if (refs) {
9270 err = build_refs_str(&refs_str, refs, yca_id, repo);
9271 if (err)
9272 goto done;
9274 printf("history forked at %s%s%s%s\n %s\n",
9275 yca_id_str,
9276 refs_str ? " (" : "", refs_str ? refs_str : "",
9277 refs_str ? ")" : "", yca_brief_str);
9279 done:
9280 free(custom_refs_str);
9281 free(new_commit_id);
9282 free(refs_str);
9283 free(yca_id);
9284 free(yca_id_str);
9285 free(yca_brief_str);
9286 if (new_commit)
9287 got_object_commit_close(new_commit);
9288 if (yca_commit)
9289 got_object_commit_close(yca_commit);
9291 return NULL;
9294 static const struct got_error *
9295 process_backup_refs(const char *backup_ref_prefix,
9296 const char *wanted_branch_name,
9297 int delete, struct got_repository *repo)
9299 const struct got_error *err;
9300 struct got_reflist_head refs, backup_refs;
9301 struct got_reflist_entry *re;
9302 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9303 struct got_object_id *old_commit_id = NULL;
9304 char *branch_name = NULL;
9305 struct got_commit_object *old_commit = NULL;
9306 struct got_reflist_object_id_map *refs_idmap = NULL;
9307 int wanted_branch_found = 0;
9309 TAILQ_INIT(&refs);
9310 TAILQ_INIT(&backup_refs);
9312 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9313 if (err)
9314 return err;
9316 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9317 if (err)
9318 goto done;
9320 if (wanted_branch_name) {
9321 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9322 wanted_branch_name += 11;
9325 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9326 got_ref_cmp_by_commit_timestamp_descending, repo);
9327 if (err)
9328 goto done;
9330 TAILQ_FOREACH(re, &backup_refs, entry) {
9331 const char *refname = got_ref_get_name(re->ref);
9332 char *slash;
9334 err = check_cancelled(NULL);
9335 if (err)
9336 break;
9338 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9339 if (err)
9340 break;
9342 err = got_object_open_as_commit(&old_commit, repo,
9343 old_commit_id);
9344 if (err)
9345 break;
9347 if (strncmp(backup_ref_prefix, refname,
9348 backup_ref_prefix_len) == 0)
9349 refname += backup_ref_prefix_len;
9351 while (refname[0] == '/')
9352 refname++;
9354 branch_name = strdup(refname);
9355 if (branch_name == NULL) {
9356 err = got_error_from_errno("strdup");
9357 break;
9359 slash = strrchr(branch_name, '/');
9360 if (slash) {
9361 *slash = '\0';
9362 refname += strlen(branch_name) + 1;
9365 if (wanted_branch_name == NULL ||
9366 strcmp(wanted_branch_name, branch_name) == 0) {
9367 wanted_branch_found = 1;
9368 if (delete) {
9369 err = delete_backup_ref(re->ref,
9370 old_commit_id, repo);
9371 } else {
9372 err = print_backup_ref(branch_name, refname,
9373 old_commit_id, old_commit, refs_idmap,
9374 repo);
9376 if (err)
9377 break;
9380 free(old_commit_id);
9381 old_commit_id = NULL;
9382 free(branch_name);
9383 branch_name = NULL;
9384 got_object_commit_close(old_commit);
9385 old_commit = NULL;
9388 if (wanted_branch_name && !wanted_branch_found) {
9389 err = got_error_fmt(GOT_ERR_NOT_REF,
9390 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9392 done:
9393 if (refs_idmap)
9394 got_reflist_object_id_map_free(refs_idmap);
9395 got_ref_list_free(&refs);
9396 got_ref_list_free(&backup_refs);
9397 free(old_commit_id);
9398 free(branch_name);
9399 if (old_commit)
9400 got_object_commit_close(old_commit);
9401 return err;
9404 static const struct got_error *
9405 abort_progress(void *arg, unsigned char status, const char *path)
9408 * Unversioned files should not clutter progress output when
9409 * an operation is aborted.
9411 if (status == GOT_STATUS_UNVERSIONED)
9412 return NULL;
9414 return update_progress(arg, status, path);
9417 static const struct got_error *
9418 cmd_rebase(int argc, char *argv[])
9420 const struct got_error *error = NULL;
9421 struct got_worktree *worktree = NULL;
9422 struct got_repository *repo = NULL;
9423 struct got_fileindex *fileindex = NULL;
9424 char *cwd = NULL;
9425 struct got_reference *branch = NULL;
9426 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9427 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9428 struct got_object_id *resume_commit_id = NULL;
9429 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9430 struct got_commit_object *commit = NULL;
9431 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9432 int histedit_in_progress = 0, merge_in_progress = 0;
9433 int create_backup = 1, list_backups = 0, delete_backups = 0;
9434 struct got_object_id_queue commits;
9435 struct got_pathlist_head merged_paths;
9436 const struct got_object_id_queue *parent_ids;
9437 struct got_object_qid *qid, *pid;
9438 struct got_update_progress_arg upa;
9440 STAILQ_INIT(&commits);
9441 TAILQ_INIT(&merged_paths);
9442 memset(&upa, 0, sizeof(upa));
9444 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9445 switch (ch) {
9446 case 'a':
9447 abort_rebase = 1;
9448 break;
9449 case 'c':
9450 continue_rebase = 1;
9451 break;
9452 case 'l':
9453 list_backups = 1;
9454 break;
9455 case 'X':
9456 delete_backups = 1;
9457 break;
9458 default:
9459 usage_rebase();
9460 /* NOTREACHED */
9464 argc -= optind;
9465 argv += optind;
9467 #ifndef PROFILE
9468 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9469 "unveil", NULL) == -1)
9470 err(1, "pledge");
9471 #endif
9472 if (list_backups) {
9473 if (abort_rebase)
9474 option_conflict('l', 'a');
9475 if (continue_rebase)
9476 option_conflict('l', 'c');
9477 if (delete_backups)
9478 option_conflict('l', 'X');
9479 if (argc != 0 && argc != 1)
9480 usage_rebase();
9481 } else if (delete_backups) {
9482 if (abort_rebase)
9483 option_conflict('X', 'a');
9484 if (continue_rebase)
9485 option_conflict('X', 'c');
9486 if (list_backups)
9487 option_conflict('l', 'X');
9488 if (argc != 0 && argc != 1)
9489 usage_rebase();
9490 } else {
9491 if (abort_rebase && continue_rebase)
9492 usage_rebase();
9493 else if (abort_rebase || continue_rebase) {
9494 if (argc != 0)
9495 usage_rebase();
9496 } else if (argc != 1)
9497 usage_rebase();
9500 cwd = getcwd(NULL, 0);
9501 if (cwd == NULL) {
9502 error = got_error_from_errno("getcwd");
9503 goto done;
9505 error = got_worktree_open(&worktree, cwd);
9506 if (error) {
9507 if (list_backups || delete_backups) {
9508 if (error->code != GOT_ERR_NOT_WORKTREE)
9509 goto done;
9510 } else {
9511 if (error->code == GOT_ERR_NOT_WORKTREE)
9512 error = wrap_not_worktree_error(error,
9513 "rebase", cwd);
9514 goto done;
9518 error = got_repo_open(&repo,
9519 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9520 if (error != NULL)
9521 goto done;
9523 error = apply_unveil(got_repo_get_path(repo), 0,
9524 worktree ? got_worktree_get_root_path(worktree) : NULL);
9525 if (error)
9526 goto done;
9528 if (list_backups || delete_backups) {
9529 error = process_backup_refs(
9530 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9531 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9532 goto done; /* nothing else to do */
9535 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9536 worktree);
9537 if (error)
9538 goto done;
9539 if (histedit_in_progress) {
9540 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9541 goto done;
9544 error = got_worktree_merge_in_progress(&merge_in_progress,
9545 worktree, repo);
9546 if (error)
9547 goto done;
9548 if (merge_in_progress) {
9549 error = got_error(GOT_ERR_MERGE_BUSY);
9550 goto done;
9553 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9554 if (error)
9555 goto done;
9557 if (abort_rebase) {
9558 if (!rebase_in_progress) {
9559 error = got_error(GOT_ERR_NOT_REBASING);
9560 goto done;
9562 error = got_worktree_rebase_continue(&resume_commit_id,
9563 &new_base_branch, &tmp_branch, &branch, &fileindex,
9564 worktree, repo);
9565 if (error)
9566 goto done;
9567 printf("Switching work tree to %s\n",
9568 got_ref_get_symref_target(new_base_branch));
9569 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9570 new_base_branch, abort_progress, &upa);
9571 if (error)
9572 goto done;
9573 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9574 print_merge_progress_stats(&upa);
9575 goto done; /* nothing else to do */
9578 if (continue_rebase) {
9579 if (!rebase_in_progress) {
9580 error = got_error(GOT_ERR_NOT_REBASING);
9581 goto done;
9583 error = got_worktree_rebase_continue(&resume_commit_id,
9584 &new_base_branch, &tmp_branch, &branch, &fileindex,
9585 worktree, repo);
9586 if (error)
9587 goto done;
9589 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9590 resume_commit_id, repo);
9591 if (error)
9592 goto done;
9594 yca_id = got_object_id_dup(resume_commit_id);
9595 if (yca_id == NULL) {
9596 error = got_error_from_errno("got_object_id_dup");
9597 goto done;
9599 } else {
9600 error = got_ref_open(&branch, repo, argv[0], 0);
9601 if (error != NULL)
9602 goto done;
9605 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9606 if (error)
9607 goto done;
9609 if (!continue_rebase) {
9610 struct got_object_id *base_commit_id;
9612 base_commit_id = got_worktree_get_base_commit_id(worktree);
9613 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9614 base_commit_id, branch_head_commit_id, 1, repo,
9615 check_cancelled, NULL);
9616 if (error)
9617 goto done;
9618 if (yca_id == NULL) {
9619 error = got_error_msg(GOT_ERR_ANCESTRY,
9620 "specified branch shares no common ancestry "
9621 "with work tree's branch");
9622 goto done;
9625 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9626 if (error) {
9627 if (error->code != GOT_ERR_ANCESTRY)
9628 goto done;
9629 error = NULL;
9630 } else {
9631 struct got_pathlist_head paths;
9632 printf("%s is already based on %s\n",
9633 got_ref_get_name(branch),
9634 got_worktree_get_head_ref_name(worktree));
9635 error = switch_head_ref(branch, branch_head_commit_id,
9636 worktree, repo);
9637 if (error)
9638 goto done;
9639 error = got_worktree_set_base_commit_id(worktree, repo,
9640 branch_head_commit_id);
9641 if (error)
9642 goto done;
9643 TAILQ_INIT(&paths);
9644 error = got_pathlist_append(&paths, "", NULL);
9645 if (error)
9646 goto done;
9647 error = got_worktree_checkout_files(worktree,
9648 &paths, repo, update_progress, &upa,
9649 check_cancelled, NULL);
9650 got_pathlist_free(&paths);
9651 if (error)
9652 goto done;
9653 if (upa.did_something) {
9654 char *id_str;
9655 error = got_object_id_str(&id_str,
9656 branch_head_commit_id);
9657 if (error)
9658 goto done;
9659 printf("Updated to %s: %s\n",
9660 got_worktree_get_head_ref_name(worktree),
9661 id_str);
9662 free(id_str);
9663 } else
9664 printf("Already up-to-date\n");
9665 print_update_progress_stats(&upa);
9666 goto done;
9670 commit_id = branch_head_commit_id;
9671 error = got_object_open_as_commit(&commit, repo, commit_id);
9672 if (error)
9673 goto done;
9675 parent_ids = got_object_commit_get_parent_ids(commit);
9676 pid = STAILQ_FIRST(parent_ids);
9677 if (pid == NULL) {
9678 error = got_error(GOT_ERR_EMPTY_REBASE);
9679 goto done;
9681 error = collect_commits(&commits, commit_id, &pid->id,
9682 yca_id, got_worktree_get_path_prefix(worktree),
9683 GOT_ERR_REBASE_PATH, repo);
9684 got_object_commit_close(commit);
9685 commit = NULL;
9686 if (error)
9687 goto done;
9689 if (!continue_rebase) {
9690 error = got_worktree_rebase_prepare(&new_base_branch,
9691 &tmp_branch, &fileindex, worktree, branch, repo);
9692 if (error)
9693 goto done;
9696 if (STAILQ_EMPTY(&commits)) {
9697 if (continue_rebase) {
9698 error = rebase_complete(worktree, fileindex,
9699 branch, new_base_branch, tmp_branch, repo,
9700 create_backup);
9701 goto done;
9702 } else {
9703 /* Fast-forward the reference of the branch. */
9704 struct got_object_id *new_head_commit_id;
9705 char *id_str;
9706 error = got_ref_resolve(&new_head_commit_id, repo,
9707 new_base_branch);
9708 if (error)
9709 goto done;
9710 error = got_object_id_str(&id_str, new_head_commit_id);
9711 printf("Forwarding %s to commit %s\n",
9712 got_ref_get_name(branch), id_str);
9713 free(id_str);
9714 error = got_ref_change_ref(branch,
9715 new_head_commit_id);
9716 if (error)
9717 goto done;
9718 /* No backup needed since objects did not change. */
9719 create_backup = 0;
9723 pid = NULL;
9724 STAILQ_FOREACH(qid, &commits, entry) {
9726 commit_id = &qid->id;
9727 parent_id = pid ? &pid->id : yca_id;
9728 pid = qid;
9730 memset(&upa, 0, sizeof(upa));
9731 error = got_worktree_rebase_merge_files(&merged_paths,
9732 worktree, fileindex, parent_id, commit_id, repo,
9733 update_progress, &upa, check_cancelled, NULL);
9734 if (error)
9735 goto done;
9737 print_merge_progress_stats(&upa);
9738 if (upa.conflicts > 0 || upa.missing > 0 ||
9739 upa.not_deleted > 0 || upa.unversioned > 0) {
9740 if (upa.conflicts > 0) {
9741 error = show_rebase_merge_conflict(&qid->id,
9742 repo);
9743 if (error)
9744 goto done;
9746 got_worktree_rebase_pathlist_free(&merged_paths);
9747 break;
9750 error = rebase_commit(&merged_paths, worktree, fileindex,
9751 tmp_branch, commit_id, repo);
9752 got_worktree_rebase_pathlist_free(&merged_paths);
9753 if (error)
9754 goto done;
9757 if (upa.conflicts > 0 || upa.missing > 0 ||
9758 upa.not_deleted > 0 || upa.unversioned > 0) {
9759 error = got_worktree_rebase_postpone(worktree, fileindex);
9760 if (error)
9761 goto done;
9762 if (upa.conflicts > 0 && upa.missing == 0 &&
9763 upa.not_deleted == 0 && upa.unversioned == 0) {
9764 error = got_error_msg(GOT_ERR_CONFLICTS,
9765 "conflicts must be resolved before rebasing "
9766 "can continue");
9767 } else if (upa.conflicts > 0) {
9768 error = got_error_msg(GOT_ERR_CONFLICTS,
9769 "conflicts must be resolved before rebasing "
9770 "can continue; changes destined for some "
9771 "files were not yet merged and should be "
9772 "merged manually if required before the "
9773 "rebase operation is continued");
9774 } else {
9775 error = got_error_msg(GOT_ERR_CONFLICTS,
9776 "changes destined for some files were not "
9777 "yet merged and should be merged manually "
9778 "if required before the rebase operation "
9779 "is continued");
9781 } else
9782 error = rebase_complete(worktree, fileindex, branch,
9783 new_base_branch, tmp_branch, repo, create_backup);
9784 done:
9785 got_object_id_queue_free(&commits);
9786 free(branch_head_commit_id);
9787 free(resume_commit_id);
9788 free(yca_id);
9789 if (commit)
9790 got_object_commit_close(commit);
9791 if (branch)
9792 got_ref_close(branch);
9793 if (new_base_branch)
9794 got_ref_close(new_base_branch);
9795 if (tmp_branch)
9796 got_ref_close(tmp_branch);
9797 if (worktree)
9798 got_worktree_close(worktree);
9799 if (repo) {
9800 const struct got_error *close_err = got_repo_close(repo);
9801 if (error == NULL)
9802 error = close_err;
9804 return error;
9807 __dead static void
9808 usage_histedit(void)
9810 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9811 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9812 getprogname());
9813 exit(1);
9816 #define GOT_HISTEDIT_PICK 'p'
9817 #define GOT_HISTEDIT_EDIT 'e'
9818 #define GOT_HISTEDIT_FOLD 'f'
9819 #define GOT_HISTEDIT_DROP 'd'
9820 #define GOT_HISTEDIT_MESG 'm'
9822 static const struct got_histedit_cmd {
9823 unsigned char code;
9824 const char *name;
9825 const char *desc;
9826 } got_histedit_cmds[] = {
9827 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9828 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9829 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9830 "be used" },
9831 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9832 { GOT_HISTEDIT_MESG, "mesg",
9833 "single-line log message for commit above (open editor if empty)" },
9836 struct got_histedit_list_entry {
9837 TAILQ_ENTRY(got_histedit_list_entry) entry;
9838 struct got_object_id *commit_id;
9839 const struct got_histedit_cmd *cmd;
9840 char *logmsg;
9842 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9844 static const struct got_error *
9845 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9846 FILE *f, struct got_repository *repo)
9848 const struct got_error *err = NULL;
9849 char *logmsg = NULL, *id_str = NULL;
9850 struct got_commit_object *commit = NULL;
9851 int n;
9853 err = got_object_open_as_commit(&commit, repo, commit_id);
9854 if (err)
9855 goto done;
9857 err = get_short_logmsg(&logmsg, 34, commit);
9858 if (err)
9859 goto done;
9861 err = got_object_id_str(&id_str, commit_id);
9862 if (err)
9863 goto done;
9865 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9866 if (n < 0)
9867 err = got_ferror(f, GOT_ERR_IO);
9868 done:
9869 if (commit)
9870 got_object_commit_close(commit);
9871 free(id_str);
9872 free(logmsg);
9873 return err;
9876 static const struct got_error *
9877 histedit_write_commit_list(struct got_object_id_queue *commits,
9878 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9879 struct got_repository *repo)
9881 const struct got_error *err = NULL;
9882 struct got_object_qid *qid;
9883 const char *histedit_cmd = NULL;
9885 if (STAILQ_EMPTY(commits))
9886 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9888 STAILQ_FOREACH(qid, commits, entry) {
9889 histedit_cmd = got_histedit_cmds[0].name;
9890 if (edit_only)
9891 histedit_cmd = "edit";
9892 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9893 histedit_cmd = "fold";
9894 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9895 if (err)
9896 break;
9897 if (edit_logmsg_only) {
9898 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9899 if (n < 0) {
9900 err = got_ferror(f, GOT_ERR_IO);
9901 break;
9906 return err;
9909 static const struct got_error *
9910 write_cmd_list(FILE *f, const char *branch_name,
9911 struct got_object_id_queue *commits)
9913 const struct got_error *err = NULL;
9914 size_t i;
9915 int n;
9916 char *id_str;
9917 struct got_object_qid *qid;
9919 qid = STAILQ_FIRST(commits);
9920 err = got_object_id_str(&id_str, &qid->id);
9921 if (err)
9922 return err;
9924 n = fprintf(f,
9925 "# Editing the history of branch '%s' starting at\n"
9926 "# commit %s\n"
9927 "# Commits will be processed in order from top to "
9928 "bottom of this file.\n", branch_name, id_str);
9929 if (n < 0) {
9930 err = got_ferror(f, GOT_ERR_IO);
9931 goto done;
9934 n = fprintf(f, "# Available histedit commands:\n");
9935 if (n < 0) {
9936 err = got_ferror(f, GOT_ERR_IO);
9937 goto done;
9940 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9941 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9942 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9943 cmd->desc);
9944 if (n < 0) {
9945 err = got_ferror(f, GOT_ERR_IO);
9946 break;
9949 done:
9950 free(id_str);
9951 return err;
9954 static const struct got_error *
9955 histedit_syntax_error(int lineno)
9957 static char msg[42];
9958 int ret;
9960 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9961 lineno);
9962 if (ret == -1 || ret >= sizeof(msg))
9963 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9965 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9968 static const struct got_error *
9969 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9970 char *logmsg, struct got_repository *repo)
9972 const struct got_error *err;
9973 struct got_commit_object *folded_commit = NULL;
9974 char *id_str, *folded_logmsg = NULL;
9976 err = got_object_id_str(&id_str, hle->commit_id);
9977 if (err)
9978 return err;
9980 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9981 if (err)
9982 goto done;
9984 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9985 if (err)
9986 goto done;
9987 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9988 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9989 folded_logmsg) == -1) {
9990 err = got_error_from_errno("asprintf");
9992 done:
9993 if (folded_commit)
9994 got_object_commit_close(folded_commit);
9995 free(id_str);
9996 free(folded_logmsg);
9997 return err;
10000 static struct got_histedit_list_entry *
10001 get_folded_commits(struct got_histedit_list_entry *hle)
10003 struct got_histedit_list_entry *prev, *folded = NULL;
10005 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10006 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10007 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10008 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10009 folded = prev;
10010 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10013 return folded;
10016 static const struct got_error *
10017 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10018 struct got_repository *repo)
10020 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10021 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10022 const struct got_error *err = NULL;
10023 struct got_commit_object *commit = NULL;
10024 int logmsg_len;
10025 int fd;
10026 struct got_histedit_list_entry *folded = NULL;
10028 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10029 if (err)
10030 return err;
10032 folded = get_folded_commits(hle);
10033 if (folded) {
10034 while (folded != hle) {
10035 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10036 folded = TAILQ_NEXT(folded, entry);
10037 continue;
10039 err = append_folded_commit_msg(&new_msg, folded,
10040 logmsg, repo);
10041 if (err)
10042 goto done;
10043 free(logmsg);
10044 logmsg = new_msg;
10045 folded = TAILQ_NEXT(folded, entry);
10049 err = got_object_id_str(&id_str, hle->commit_id);
10050 if (err)
10051 goto done;
10052 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10053 if (err)
10054 goto done;
10055 logmsg_len = asprintf(&new_msg,
10056 "%s\n# original log message of commit %s: %s",
10057 logmsg ? logmsg : "", id_str, orig_logmsg);
10058 if (logmsg_len == -1) {
10059 err = got_error_from_errno("asprintf");
10060 goto done;
10062 free(logmsg);
10063 logmsg = new_msg;
10065 err = got_object_id_str(&id_str, hle->commit_id);
10066 if (err)
10067 goto done;
10069 err = got_opentemp_named_fd(&logmsg_path, &fd,
10070 GOT_TMPDIR_STR "/got-logmsg");
10071 if (err)
10072 goto done;
10074 write(fd, logmsg, logmsg_len);
10075 close(fd);
10077 err = get_editor(&editor);
10078 if (err)
10079 goto done;
10081 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10082 logmsg_len, 0);
10083 if (err) {
10084 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10085 goto done;
10086 err = NULL;
10087 hle->logmsg = strdup(new_msg);
10088 if (hle->logmsg == NULL)
10089 err = got_error_from_errno("strdup");
10091 done:
10092 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10093 err = got_error_from_errno2("unlink", logmsg_path);
10094 free(logmsg_path);
10095 free(logmsg);
10096 free(orig_logmsg);
10097 free(editor);
10098 if (commit)
10099 got_object_commit_close(commit);
10100 return err;
10103 static const struct got_error *
10104 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10105 FILE *f, struct got_repository *repo)
10107 const struct got_error *err = NULL;
10108 char *line = NULL, *p, *end;
10109 size_t i, size;
10110 ssize_t len;
10111 int lineno = 0;
10112 const struct got_histedit_cmd *cmd;
10113 struct got_object_id *commit_id = NULL;
10114 struct got_histedit_list_entry *hle = NULL;
10116 for (;;) {
10117 len = getline(&line, &size, f);
10118 if (len == -1) {
10119 const struct got_error *getline_err;
10120 if (feof(f))
10121 break;
10122 getline_err = got_error_from_errno("getline");
10123 err = got_ferror(f, getline_err->code);
10124 break;
10126 lineno++;
10127 p = line;
10128 while (isspace((unsigned char)p[0]))
10129 p++;
10130 if (p[0] == '#' || p[0] == '\0') {
10131 free(line);
10132 line = NULL;
10133 continue;
10135 cmd = NULL;
10136 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10137 cmd = &got_histedit_cmds[i];
10138 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10139 isspace((unsigned char)p[strlen(cmd->name)])) {
10140 p += strlen(cmd->name);
10141 break;
10143 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10144 p++;
10145 break;
10148 if (i == nitems(got_histedit_cmds)) {
10149 err = histedit_syntax_error(lineno);
10150 break;
10152 while (isspace((unsigned char)p[0]))
10153 p++;
10154 if (cmd->code == GOT_HISTEDIT_MESG) {
10155 if (hle == NULL || hle->logmsg != NULL) {
10156 err = got_error(GOT_ERR_HISTEDIT_CMD);
10157 break;
10159 if (p[0] == '\0') {
10160 err = histedit_edit_logmsg(hle, repo);
10161 if (err)
10162 break;
10163 } else {
10164 hle->logmsg = strdup(p);
10165 if (hle->logmsg == NULL) {
10166 err = got_error_from_errno("strdup");
10167 break;
10170 free(line);
10171 line = NULL;
10172 continue;
10173 } else {
10174 end = p;
10175 while (end[0] && !isspace((unsigned char)end[0]))
10176 end++;
10177 *end = '\0';
10179 err = got_object_resolve_id_str(&commit_id, repo, p);
10180 if (err) {
10181 /* override error code */
10182 err = histedit_syntax_error(lineno);
10183 break;
10186 hle = malloc(sizeof(*hle));
10187 if (hle == NULL) {
10188 err = got_error_from_errno("malloc");
10189 break;
10191 hle->cmd = cmd;
10192 hle->commit_id = commit_id;
10193 hle->logmsg = NULL;
10194 commit_id = NULL;
10195 free(line);
10196 line = NULL;
10197 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10200 free(line);
10201 free(commit_id);
10202 return err;
10205 static const struct got_error *
10206 histedit_check_script(struct got_histedit_list *histedit_cmds,
10207 struct got_object_id_queue *commits, struct got_repository *repo)
10209 const struct got_error *err = NULL;
10210 struct got_object_qid *qid;
10211 struct got_histedit_list_entry *hle;
10212 static char msg[92];
10213 char *id_str;
10215 if (TAILQ_EMPTY(histedit_cmds))
10216 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10217 "histedit script contains no commands");
10218 if (STAILQ_EMPTY(commits))
10219 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10221 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10222 struct got_histedit_list_entry *hle2;
10223 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10224 if (hle == hle2)
10225 continue;
10226 if (got_object_id_cmp(hle->commit_id,
10227 hle2->commit_id) != 0)
10228 continue;
10229 err = got_object_id_str(&id_str, hle->commit_id);
10230 if (err)
10231 return err;
10232 snprintf(msg, sizeof(msg), "commit %s is listed "
10233 "more than once in histedit script", id_str);
10234 free(id_str);
10235 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10239 STAILQ_FOREACH(qid, commits, entry) {
10240 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10241 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10242 break;
10244 if (hle == NULL) {
10245 err = got_object_id_str(&id_str, &qid->id);
10246 if (err)
10247 return err;
10248 snprintf(msg, sizeof(msg),
10249 "commit %s missing from histedit script", id_str);
10250 free(id_str);
10251 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10255 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10256 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10257 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10258 "last commit in histedit script cannot be folded");
10260 return NULL;
10263 static const struct got_error *
10264 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10265 const char *path, struct got_object_id_queue *commits,
10266 struct got_repository *repo)
10268 const struct got_error *err = NULL;
10269 char *editor;
10270 FILE *f = NULL;
10272 err = get_editor(&editor);
10273 if (err)
10274 return err;
10276 if (spawn_editor(editor, path) == -1) {
10277 err = got_error_from_errno("failed spawning editor");
10278 goto done;
10281 f = fopen(path, "re");
10282 if (f == NULL) {
10283 err = got_error_from_errno("fopen");
10284 goto done;
10286 err = histedit_parse_list(histedit_cmds, f, repo);
10287 if (err)
10288 goto done;
10290 err = histedit_check_script(histedit_cmds, commits, repo);
10291 done:
10292 if (f && fclose(f) == EOF && err == NULL)
10293 err = got_error_from_errno("fclose");
10294 free(editor);
10295 return err;
10298 static const struct got_error *
10299 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10300 struct got_object_id_queue *, const char *, const char *,
10301 struct got_repository *);
10303 static const struct got_error *
10304 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10305 struct got_object_id_queue *commits, const char *branch_name,
10306 int edit_logmsg_only, int fold_only, int edit_only,
10307 struct got_repository *repo)
10309 const struct got_error *err;
10310 FILE *f = NULL;
10311 char *path = NULL;
10313 err = got_opentemp_named(&path, &f, "got-histedit");
10314 if (err)
10315 return err;
10317 err = write_cmd_list(f, branch_name, commits);
10318 if (err)
10319 goto done;
10321 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10322 fold_only, edit_only, repo);
10323 if (err)
10324 goto done;
10326 if (edit_logmsg_only || fold_only || edit_only) {
10327 rewind(f);
10328 err = histedit_parse_list(histedit_cmds, f, repo);
10329 } else {
10330 if (fclose(f) == EOF) {
10331 err = got_error_from_errno("fclose");
10332 goto done;
10334 f = NULL;
10335 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10336 if (err) {
10337 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10338 err->code != GOT_ERR_HISTEDIT_CMD)
10339 goto done;
10340 err = histedit_edit_list_retry(histedit_cmds, err,
10341 commits, path, branch_name, repo);
10344 done:
10345 if (f && fclose(f) == EOF && err == NULL)
10346 err = got_error_from_errno("fclose");
10347 if (path && unlink(path) != 0 && err == NULL)
10348 err = got_error_from_errno2("unlink", path);
10349 free(path);
10350 return err;
10353 static const struct got_error *
10354 histedit_save_list(struct got_histedit_list *histedit_cmds,
10355 struct got_worktree *worktree, struct got_repository *repo)
10357 const struct got_error *err = NULL;
10358 char *path = NULL;
10359 FILE *f = NULL;
10360 struct got_histedit_list_entry *hle;
10361 struct got_commit_object *commit = NULL;
10363 err = got_worktree_get_histedit_script_path(&path, worktree);
10364 if (err)
10365 return err;
10367 f = fopen(path, "we");
10368 if (f == NULL) {
10369 err = got_error_from_errno2("fopen", path);
10370 goto done;
10372 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10373 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10374 repo);
10375 if (err)
10376 break;
10378 if (hle->logmsg) {
10379 int n = fprintf(f, "%c %s\n",
10380 GOT_HISTEDIT_MESG, hle->logmsg);
10381 if (n < 0) {
10382 err = got_ferror(f, GOT_ERR_IO);
10383 break;
10387 done:
10388 if (f && fclose(f) == EOF && err == NULL)
10389 err = got_error_from_errno("fclose");
10390 free(path);
10391 if (commit)
10392 got_object_commit_close(commit);
10393 return err;
10396 void
10397 histedit_free_list(struct got_histedit_list *histedit_cmds)
10399 struct got_histedit_list_entry *hle;
10401 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10402 TAILQ_REMOVE(histedit_cmds, hle, entry);
10403 free(hle);
10407 static const struct got_error *
10408 histedit_load_list(struct got_histedit_list *histedit_cmds,
10409 const char *path, struct got_repository *repo)
10411 const struct got_error *err = NULL;
10412 FILE *f = NULL;
10414 f = fopen(path, "re");
10415 if (f == NULL) {
10416 err = got_error_from_errno2("fopen", path);
10417 goto done;
10420 err = histedit_parse_list(histedit_cmds, f, repo);
10421 done:
10422 if (f && fclose(f) == EOF && err == NULL)
10423 err = got_error_from_errno("fclose");
10424 return err;
10427 static const struct got_error *
10428 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10429 const struct got_error *edit_err, struct got_object_id_queue *commits,
10430 const char *path, const char *branch_name, struct got_repository *repo)
10432 const struct got_error *err = NULL, *prev_err = edit_err;
10433 int resp = ' ';
10435 while (resp != 'c' && resp != 'r' && resp != 'a') {
10436 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10437 "or (a)bort: ", getprogname(), prev_err->msg);
10438 resp = getchar();
10439 if (resp == '\n')
10440 resp = getchar();
10441 if (resp == 'c') {
10442 histedit_free_list(histedit_cmds);
10443 err = histedit_run_editor(histedit_cmds, path, commits,
10444 repo);
10445 if (err) {
10446 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10447 err->code != GOT_ERR_HISTEDIT_CMD)
10448 break;
10449 prev_err = err;
10450 resp = ' ';
10451 continue;
10453 break;
10454 } else if (resp == 'r') {
10455 histedit_free_list(histedit_cmds);
10456 err = histedit_edit_script(histedit_cmds,
10457 commits, branch_name, 0, 0, 0, repo);
10458 if (err) {
10459 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10460 err->code != GOT_ERR_HISTEDIT_CMD)
10461 break;
10462 prev_err = err;
10463 resp = ' ';
10464 continue;
10466 break;
10467 } else if (resp == 'a') {
10468 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10469 break;
10470 } else
10471 printf("invalid response '%c'\n", resp);
10474 return err;
10477 static const struct got_error *
10478 histedit_complete(struct got_worktree *worktree,
10479 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10480 struct got_reference *branch, struct got_repository *repo)
10482 printf("Switching work tree to %s\n",
10483 got_ref_get_symref_target(branch));
10484 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10485 branch, repo);
10488 static const struct got_error *
10489 show_histedit_progress(struct got_commit_object *commit,
10490 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10492 const struct got_error *err;
10493 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10495 err = got_object_id_str(&old_id_str, hle->commit_id);
10496 if (err)
10497 goto done;
10499 if (new_id) {
10500 err = got_object_id_str(&new_id_str, new_id);
10501 if (err)
10502 goto done;
10505 old_id_str[12] = '\0';
10506 if (new_id_str)
10507 new_id_str[12] = '\0';
10509 if (hle->logmsg) {
10510 logmsg = strdup(hle->logmsg);
10511 if (logmsg == NULL) {
10512 err = got_error_from_errno("strdup");
10513 goto done;
10515 trim_logmsg(logmsg, 42);
10516 } else {
10517 err = get_short_logmsg(&logmsg, 42, commit);
10518 if (err)
10519 goto done;
10522 switch (hle->cmd->code) {
10523 case GOT_HISTEDIT_PICK:
10524 case GOT_HISTEDIT_EDIT:
10525 printf("%s -> %s: %s\n", old_id_str,
10526 new_id_str ? new_id_str : "no-op change", logmsg);
10527 break;
10528 case GOT_HISTEDIT_DROP:
10529 case GOT_HISTEDIT_FOLD:
10530 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10531 logmsg);
10532 break;
10533 default:
10534 break;
10536 done:
10537 free(old_id_str);
10538 free(new_id_str);
10539 return err;
10542 static const struct got_error *
10543 histedit_commit(struct got_pathlist_head *merged_paths,
10544 struct got_worktree *worktree, struct got_fileindex *fileindex,
10545 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10546 struct got_repository *repo)
10548 const struct got_error *err;
10549 struct got_commit_object *commit;
10550 struct got_object_id *new_commit_id;
10552 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10553 && hle->logmsg == NULL) {
10554 err = histedit_edit_logmsg(hle, repo);
10555 if (err)
10556 return err;
10559 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10560 if (err)
10561 return err;
10563 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10564 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10565 hle->logmsg, repo);
10566 if (err) {
10567 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10568 goto done;
10569 err = show_histedit_progress(commit, hle, NULL);
10570 } else {
10571 err = show_histedit_progress(commit, hle, new_commit_id);
10572 free(new_commit_id);
10574 done:
10575 got_object_commit_close(commit);
10576 return err;
10579 static const struct got_error *
10580 histedit_skip_commit(struct got_histedit_list_entry *hle,
10581 struct got_worktree *worktree, struct got_repository *repo)
10583 const struct got_error *error;
10584 struct got_commit_object *commit;
10586 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10587 repo);
10588 if (error)
10589 return error;
10591 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10592 if (error)
10593 return error;
10595 error = show_histedit_progress(commit, hle, NULL);
10596 got_object_commit_close(commit);
10597 return error;
10600 static const struct got_error *
10601 check_local_changes(void *arg, unsigned char status,
10602 unsigned char staged_status, const char *path,
10603 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10604 struct got_object_id *commit_id, int dirfd, const char *de_name)
10606 int *have_local_changes = arg;
10608 switch (status) {
10609 case GOT_STATUS_ADD:
10610 case GOT_STATUS_DELETE:
10611 case GOT_STATUS_MODIFY:
10612 case GOT_STATUS_CONFLICT:
10613 *have_local_changes = 1;
10614 return got_error(GOT_ERR_CANCELLED);
10615 default:
10616 break;
10619 switch (staged_status) {
10620 case GOT_STATUS_ADD:
10621 case GOT_STATUS_DELETE:
10622 case GOT_STATUS_MODIFY:
10623 *have_local_changes = 1;
10624 return got_error(GOT_ERR_CANCELLED);
10625 default:
10626 break;
10629 return NULL;
10632 static const struct got_error *
10633 cmd_histedit(int argc, char *argv[])
10635 const struct got_error *error = NULL;
10636 struct got_worktree *worktree = NULL;
10637 struct got_fileindex *fileindex = NULL;
10638 struct got_repository *repo = NULL;
10639 char *cwd = NULL;
10640 struct got_reference *branch = NULL;
10641 struct got_reference *tmp_branch = NULL;
10642 struct got_object_id *resume_commit_id = NULL;
10643 struct got_object_id *base_commit_id = NULL;
10644 struct got_object_id *head_commit_id = NULL;
10645 struct got_commit_object *commit = NULL;
10646 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10647 struct got_update_progress_arg upa;
10648 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10649 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10650 int list_backups = 0, delete_backups = 0;
10651 const char *edit_script_path = NULL;
10652 struct got_object_id_queue commits;
10653 struct got_pathlist_head merged_paths;
10654 const struct got_object_id_queue *parent_ids;
10655 struct got_object_qid *pid;
10656 struct got_histedit_list histedit_cmds;
10657 struct got_histedit_list_entry *hle;
10659 STAILQ_INIT(&commits);
10660 TAILQ_INIT(&histedit_cmds);
10661 TAILQ_INIT(&merged_paths);
10662 memset(&upa, 0, sizeof(upa));
10664 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10665 switch (ch) {
10666 case 'a':
10667 abort_edit = 1;
10668 break;
10669 case 'c':
10670 continue_edit = 1;
10671 break;
10672 case 'e':
10673 edit_only = 1;
10674 break;
10675 case 'f':
10676 fold_only = 1;
10677 break;
10678 case 'F':
10679 edit_script_path = optarg;
10680 break;
10681 case 'm':
10682 edit_logmsg_only = 1;
10683 break;
10684 case 'l':
10685 list_backups = 1;
10686 break;
10687 case 'X':
10688 delete_backups = 1;
10689 break;
10690 default:
10691 usage_histedit();
10692 /* NOTREACHED */
10696 argc -= optind;
10697 argv += optind;
10699 #ifndef PROFILE
10700 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10701 "unveil", NULL) == -1)
10702 err(1, "pledge");
10703 #endif
10704 if (abort_edit && continue_edit)
10705 option_conflict('a', 'c');
10706 if (edit_script_path && edit_logmsg_only)
10707 option_conflict('F', 'm');
10708 if (abort_edit && edit_logmsg_only)
10709 option_conflict('a', 'm');
10710 if (continue_edit && edit_logmsg_only)
10711 option_conflict('c', 'm');
10712 if (abort_edit && fold_only)
10713 option_conflict('a', 'f');
10714 if (continue_edit && fold_only)
10715 option_conflict('c', 'f');
10716 if (fold_only && edit_logmsg_only)
10717 option_conflict('f', 'm');
10718 if (edit_script_path && fold_only)
10719 option_conflict('F', 'f');
10720 if (abort_edit && edit_only)
10721 option_conflict('a', 'e');
10722 if (continue_edit && edit_only)
10723 option_conflict('c', 'e');
10724 if (edit_only && edit_logmsg_only)
10725 option_conflict('e', 'm');
10726 if (edit_script_path && edit_only)
10727 option_conflict('F', 'e');
10728 if (list_backups) {
10729 if (abort_edit)
10730 option_conflict('l', 'a');
10731 if (continue_edit)
10732 option_conflict('l', 'c');
10733 if (edit_script_path)
10734 option_conflict('l', 'F');
10735 if (edit_logmsg_only)
10736 option_conflict('l', 'm');
10737 if (fold_only)
10738 option_conflict('l', 'f');
10739 if (edit_only)
10740 option_conflict('l', 'e');
10741 if (delete_backups)
10742 option_conflict('l', 'X');
10743 if (argc != 0 && argc != 1)
10744 usage_histedit();
10745 } else if (delete_backups) {
10746 if (abort_edit)
10747 option_conflict('X', 'a');
10748 if (continue_edit)
10749 option_conflict('X', 'c');
10750 if (edit_script_path)
10751 option_conflict('X', 'F');
10752 if (edit_logmsg_only)
10753 option_conflict('X', 'm');
10754 if (fold_only)
10755 option_conflict('X', 'f');
10756 if (edit_only)
10757 option_conflict('X', 'e');
10758 if (list_backups)
10759 option_conflict('X', 'l');
10760 if (argc != 0 && argc != 1)
10761 usage_histedit();
10762 } else if (argc != 0)
10763 usage_histedit();
10766 * This command cannot apply unveil(2) in all cases because the
10767 * user may choose to run an editor to edit the histedit script
10768 * and to edit individual commit log messages.
10769 * unveil(2) traverses exec(2); if an editor is used we have to
10770 * apply unveil after edit script and log messages have been written.
10771 * XXX TODO: Make use of unveil(2) where possible.
10774 cwd = getcwd(NULL, 0);
10775 if (cwd == NULL) {
10776 error = got_error_from_errno("getcwd");
10777 goto done;
10779 error = got_worktree_open(&worktree, cwd);
10780 if (error) {
10781 if (list_backups || delete_backups) {
10782 if (error->code != GOT_ERR_NOT_WORKTREE)
10783 goto done;
10784 } else {
10785 if (error->code == GOT_ERR_NOT_WORKTREE)
10786 error = wrap_not_worktree_error(error,
10787 "histedit", cwd);
10788 goto done;
10792 if (list_backups || delete_backups) {
10793 error = got_repo_open(&repo,
10794 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10795 NULL);
10796 if (error != NULL)
10797 goto done;
10798 error = apply_unveil(got_repo_get_path(repo), 0,
10799 worktree ? got_worktree_get_root_path(worktree) : NULL);
10800 if (error)
10801 goto done;
10802 error = process_backup_refs(
10803 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10804 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10805 goto done; /* nothing else to do */
10808 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10809 NULL);
10810 if (error != NULL)
10811 goto done;
10813 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10814 if (error)
10815 goto done;
10816 if (rebase_in_progress) {
10817 error = got_error(GOT_ERR_REBASING);
10818 goto done;
10821 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10822 repo);
10823 if (error)
10824 goto done;
10825 if (merge_in_progress) {
10826 error = got_error(GOT_ERR_MERGE_BUSY);
10827 goto done;
10830 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10831 if (error)
10832 goto done;
10834 if (edit_in_progress && edit_logmsg_only) {
10835 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10836 "histedit operation is in progress in this "
10837 "work tree and must be continued or aborted "
10838 "before the -m option can be used");
10839 goto done;
10841 if (edit_in_progress && fold_only) {
10842 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10843 "histedit operation is in progress in this "
10844 "work tree and must be continued or aborted "
10845 "before the -f option can be used");
10846 goto done;
10848 if (edit_in_progress && edit_only) {
10849 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10850 "histedit operation is in progress in this "
10851 "work tree and must be continued or aborted "
10852 "before the -e option can be used");
10853 goto done;
10856 if (edit_in_progress && abort_edit) {
10857 error = got_worktree_histedit_continue(&resume_commit_id,
10858 &tmp_branch, &branch, &base_commit_id, &fileindex,
10859 worktree, repo);
10860 if (error)
10861 goto done;
10862 printf("Switching work tree to %s\n",
10863 got_ref_get_symref_target(branch));
10864 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10865 branch, base_commit_id, abort_progress, &upa);
10866 if (error)
10867 goto done;
10868 printf("Histedit of %s aborted\n",
10869 got_ref_get_symref_target(branch));
10870 print_merge_progress_stats(&upa);
10871 goto done; /* nothing else to do */
10872 } else if (abort_edit) {
10873 error = got_error(GOT_ERR_NOT_HISTEDIT);
10874 goto done;
10877 if (continue_edit) {
10878 char *path;
10880 if (!edit_in_progress) {
10881 error = got_error(GOT_ERR_NOT_HISTEDIT);
10882 goto done;
10885 error = got_worktree_get_histedit_script_path(&path, worktree);
10886 if (error)
10887 goto done;
10889 error = histedit_load_list(&histedit_cmds, path, repo);
10890 free(path);
10891 if (error)
10892 goto done;
10894 error = got_worktree_histedit_continue(&resume_commit_id,
10895 &tmp_branch, &branch, &base_commit_id, &fileindex,
10896 worktree, repo);
10897 if (error)
10898 goto done;
10900 error = got_ref_resolve(&head_commit_id, repo, branch);
10901 if (error)
10902 goto done;
10904 error = got_object_open_as_commit(&commit, repo,
10905 head_commit_id);
10906 if (error)
10907 goto done;
10908 parent_ids = got_object_commit_get_parent_ids(commit);
10909 pid = STAILQ_FIRST(parent_ids);
10910 if (pid == NULL) {
10911 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10912 goto done;
10914 error = collect_commits(&commits, head_commit_id, &pid->id,
10915 base_commit_id, got_worktree_get_path_prefix(worktree),
10916 GOT_ERR_HISTEDIT_PATH, repo);
10917 got_object_commit_close(commit);
10918 commit = NULL;
10919 if (error)
10920 goto done;
10921 } else {
10922 if (edit_in_progress) {
10923 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10924 goto done;
10927 error = got_ref_open(&branch, repo,
10928 got_worktree_get_head_ref_name(worktree), 0);
10929 if (error != NULL)
10930 goto done;
10932 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10933 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10934 "will not edit commit history of a branch outside "
10935 "the \"refs/heads/\" reference namespace");
10936 goto done;
10939 error = got_ref_resolve(&head_commit_id, repo, branch);
10940 got_ref_close(branch);
10941 branch = NULL;
10942 if (error)
10943 goto done;
10945 error = got_object_open_as_commit(&commit, repo,
10946 head_commit_id);
10947 if (error)
10948 goto done;
10949 parent_ids = got_object_commit_get_parent_ids(commit);
10950 pid = STAILQ_FIRST(parent_ids);
10951 if (pid == NULL) {
10952 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10953 goto done;
10955 error = collect_commits(&commits, head_commit_id, &pid->id,
10956 got_worktree_get_base_commit_id(worktree),
10957 got_worktree_get_path_prefix(worktree),
10958 GOT_ERR_HISTEDIT_PATH, repo);
10959 got_object_commit_close(commit);
10960 commit = NULL;
10961 if (error)
10962 goto done;
10964 if (STAILQ_EMPTY(&commits)) {
10965 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10966 goto done;
10969 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10970 &base_commit_id, &fileindex, worktree, repo);
10971 if (error)
10972 goto done;
10974 if (edit_script_path) {
10975 error = histedit_load_list(&histedit_cmds,
10976 edit_script_path, repo);
10977 if (error) {
10978 got_worktree_histedit_abort(worktree, fileindex,
10979 repo, branch, base_commit_id,
10980 abort_progress, &upa);
10981 print_merge_progress_stats(&upa);
10982 goto done;
10984 } else {
10985 const char *branch_name;
10986 branch_name = got_ref_get_symref_target(branch);
10987 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10988 branch_name += 11;
10989 error = histedit_edit_script(&histedit_cmds, &commits,
10990 branch_name, edit_logmsg_only, fold_only,
10991 edit_only, repo);
10992 if (error) {
10993 got_worktree_histedit_abort(worktree, fileindex,
10994 repo, branch, base_commit_id,
10995 abort_progress, &upa);
10996 print_merge_progress_stats(&upa);
10997 goto done;
11002 error = histedit_save_list(&histedit_cmds, worktree,
11003 repo);
11004 if (error) {
11005 got_worktree_histedit_abort(worktree, fileindex,
11006 repo, branch, base_commit_id,
11007 abort_progress, &upa);
11008 print_merge_progress_stats(&upa);
11009 goto done;
11014 error = histedit_check_script(&histedit_cmds, &commits, repo);
11015 if (error)
11016 goto done;
11018 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11019 if (resume_commit_id) {
11020 if (got_object_id_cmp(hle->commit_id,
11021 resume_commit_id) != 0)
11022 continue;
11024 resume_commit_id = NULL;
11025 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11026 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11027 error = histedit_skip_commit(hle, worktree,
11028 repo);
11029 if (error)
11030 goto done;
11031 } else {
11032 struct got_pathlist_head paths;
11033 int have_changes = 0;
11035 TAILQ_INIT(&paths);
11036 error = got_pathlist_append(&paths, "", NULL);
11037 if (error)
11038 goto done;
11039 error = got_worktree_status(worktree, &paths,
11040 repo, 0, check_local_changes, &have_changes,
11041 check_cancelled, NULL);
11042 got_pathlist_free(&paths);
11043 if (error) {
11044 if (error->code != GOT_ERR_CANCELLED)
11045 goto done;
11046 if (sigint_received || sigpipe_received)
11047 goto done;
11049 if (have_changes) {
11050 error = histedit_commit(NULL, worktree,
11051 fileindex, tmp_branch, hle, repo);
11052 if (error)
11053 goto done;
11054 } else {
11055 error = got_object_open_as_commit(
11056 &commit, repo, hle->commit_id);
11057 if (error)
11058 goto done;
11059 error = show_histedit_progress(commit,
11060 hle, NULL);
11061 got_object_commit_close(commit);
11062 commit = NULL;
11063 if (error)
11064 goto done;
11067 continue;
11070 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11071 error = histedit_skip_commit(hle, worktree, repo);
11072 if (error)
11073 goto done;
11074 continue;
11077 error = got_object_open_as_commit(&commit, repo,
11078 hle->commit_id);
11079 if (error)
11080 goto done;
11081 parent_ids = got_object_commit_get_parent_ids(commit);
11082 pid = STAILQ_FIRST(parent_ids);
11084 error = got_worktree_histedit_merge_files(&merged_paths,
11085 worktree, fileindex, &pid->id, hle->commit_id, repo,
11086 update_progress, &upa, check_cancelled, NULL);
11087 if (error)
11088 goto done;
11089 got_object_commit_close(commit);
11090 commit = NULL;
11092 print_merge_progress_stats(&upa);
11093 if (upa.conflicts > 0 || upa.missing > 0 ||
11094 upa.not_deleted > 0 || upa.unversioned > 0) {
11095 if (upa.conflicts > 0) {
11096 error = show_rebase_merge_conflict(
11097 hle->commit_id, repo);
11098 if (error)
11099 goto done;
11101 got_worktree_rebase_pathlist_free(&merged_paths);
11102 break;
11105 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11106 char *id_str;
11107 error = got_object_id_str(&id_str, hle->commit_id);
11108 if (error)
11109 goto done;
11110 printf("Stopping histedit for amending commit %s\n",
11111 id_str);
11112 free(id_str);
11113 got_worktree_rebase_pathlist_free(&merged_paths);
11114 error = got_worktree_histedit_postpone(worktree,
11115 fileindex);
11116 goto done;
11119 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11120 error = histedit_skip_commit(hle, worktree, repo);
11121 if (error)
11122 goto done;
11123 continue;
11126 error = histedit_commit(&merged_paths, worktree, fileindex,
11127 tmp_branch, hle, repo);
11128 got_worktree_rebase_pathlist_free(&merged_paths);
11129 if (error)
11130 goto done;
11133 if (upa.conflicts > 0 || upa.missing > 0 ||
11134 upa.not_deleted > 0 || upa.unversioned > 0) {
11135 error = got_worktree_histedit_postpone(worktree, fileindex);
11136 if (error)
11137 goto done;
11138 if (upa.conflicts > 0 && upa.missing == 0 &&
11139 upa.not_deleted == 0 && upa.unversioned == 0) {
11140 error = got_error_msg(GOT_ERR_CONFLICTS,
11141 "conflicts must be resolved before histedit "
11142 "can continue");
11143 } else if (upa.conflicts > 0) {
11144 error = got_error_msg(GOT_ERR_CONFLICTS,
11145 "conflicts must be resolved before histedit "
11146 "can continue; changes destined for some "
11147 "files were not yet merged and should be "
11148 "merged manually if required before the "
11149 "histedit operation is continued");
11150 } else {
11151 error = got_error_msg(GOT_ERR_CONFLICTS,
11152 "changes destined for some files were not "
11153 "yet merged and should be merged manually "
11154 "if required before the histedit operation "
11155 "is continued");
11157 } else
11158 error = histedit_complete(worktree, fileindex, tmp_branch,
11159 branch, repo);
11160 done:
11161 got_object_id_queue_free(&commits);
11162 histedit_free_list(&histedit_cmds);
11163 free(head_commit_id);
11164 free(base_commit_id);
11165 free(resume_commit_id);
11166 if (commit)
11167 got_object_commit_close(commit);
11168 if (branch)
11169 got_ref_close(branch);
11170 if (tmp_branch)
11171 got_ref_close(tmp_branch);
11172 if (worktree)
11173 got_worktree_close(worktree);
11174 if (repo) {
11175 const struct got_error *close_err = got_repo_close(repo);
11176 if (error == NULL)
11177 error = close_err;
11179 return error;
11182 __dead static void
11183 usage_integrate(void)
11185 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11186 exit(1);
11189 static const struct got_error *
11190 cmd_integrate(int argc, char *argv[])
11192 const struct got_error *error = NULL;
11193 struct got_repository *repo = NULL;
11194 struct got_worktree *worktree = NULL;
11195 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11196 const char *branch_arg = NULL;
11197 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11198 struct got_fileindex *fileindex = NULL;
11199 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11200 int ch;
11201 struct got_update_progress_arg upa;
11203 while ((ch = getopt(argc, argv, "")) != -1) {
11204 switch (ch) {
11205 default:
11206 usage_integrate();
11207 /* NOTREACHED */
11211 argc -= optind;
11212 argv += optind;
11214 if (argc != 1)
11215 usage_integrate();
11216 branch_arg = argv[0];
11217 #ifndef PROFILE
11218 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11219 "unveil", NULL) == -1)
11220 err(1, "pledge");
11221 #endif
11222 cwd = getcwd(NULL, 0);
11223 if (cwd == NULL) {
11224 error = got_error_from_errno("getcwd");
11225 goto done;
11228 error = got_worktree_open(&worktree, cwd);
11229 if (error) {
11230 if (error->code == GOT_ERR_NOT_WORKTREE)
11231 error = wrap_not_worktree_error(error, "integrate",
11232 cwd);
11233 goto done;
11236 error = check_rebase_or_histedit_in_progress(worktree);
11237 if (error)
11238 goto done;
11240 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11241 NULL);
11242 if (error != NULL)
11243 goto done;
11245 error = apply_unveil(got_repo_get_path(repo), 0,
11246 got_worktree_get_root_path(worktree));
11247 if (error)
11248 goto done;
11250 error = check_merge_in_progress(worktree, repo);
11251 if (error)
11252 goto done;
11254 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11255 error = got_error_from_errno("asprintf");
11256 goto done;
11259 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11260 &base_branch_ref, worktree, refname, repo);
11261 if (error)
11262 goto done;
11264 refname = strdup(got_ref_get_name(branch_ref));
11265 if (refname == NULL) {
11266 error = got_error_from_errno("strdup");
11267 got_worktree_integrate_abort(worktree, fileindex, repo,
11268 branch_ref, base_branch_ref);
11269 goto done;
11271 base_refname = strdup(got_ref_get_name(base_branch_ref));
11272 if (base_refname == NULL) {
11273 error = got_error_from_errno("strdup");
11274 got_worktree_integrate_abort(worktree, fileindex, repo,
11275 branch_ref, base_branch_ref);
11276 goto done;
11279 error = got_ref_resolve(&commit_id, repo, branch_ref);
11280 if (error)
11281 goto done;
11283 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11284 if (error)
11285 goto done;
11287 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11288 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11289 "specified branch has already been integrated");
11290 got_worktree_integrate_abort(worktree, fileindex, repo,
11291 branch_ref, base_branch_ref);
11292 goto done;
11295 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11296 if (error) {
11297 if (error->code == GOT_ERR_ANCESTRY)
11298 error = got_error(GOT_ERR_REBASE_REQUIRED);
11299 got_worktree_integrate_abort(worktree, fileindex, repo,
11300 branch_ref, base_branch_ref);
11301 goto done;
11304 memset(&upa, 0, sizeof(upa));
11305 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11306 branch_ref, base_branch_ref, update_progress, &upa,
11307 check_cancelled, NULL);
11308 if (error)
11309 goto done;
11311 printf("Integrated %s into %s\n", refname, base_refname);
11312 print_update_progress_stats(&upa);
11313 done:
11314 if (repo) {
11315 const struct got_error *close_err = got_repo_close(repo);
11316 if (error == NULL)
11317 error = close_err;
11319 if (worktree)
11320 got_worktree_close(worktree);
11321 free(cwd);
11322 free(base_commit_id);
11323 free(commit_id);
11324 free(refname);
11325 free(base_refname);
11326 return error;
11329 __dead static void
11330 usage_merge(void)
11332 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11333 getprogname());
11334 exit(1);
11337 static const struct got_error *
11338 cmd_merge(int argc, char *argv[])
11340 const struct got_error *error = NULL;
11341 struct got_worktree *worktree = NULL;
11342 struct got_repository *repo = NULL;
11343 struct got_fileindex *fileindex = NULL;
11344 char *cwd = NULL, *id_str = NULL, *author = NULL;
11345 struct got_reference *branch = NULL, *wt_branch = NULL;
11346 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11347 struct got_object_id *wt_branch_tip = NULL;
11348 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11349 int interrupt_merge = 0;
11350 struct got_update_progress_arg upa;
11351 struct got_object_id *merge_commit_id = NULL;
11352 char *branch_name = NULL;
11354 memset(&upa, 0, sizeof(upa));
11356 while ((ch = getopt(argc, argv, "acn")) != -1) {
11357 switch (ch) {
11358 case 'a':
11359 abort_merge = 1;
11360 break;
11361 case 'c':
11362 continue_merge = 1;
11363 break;
11364 case 'n':
11365 interrupt_merge = 1;
11366 break;
11367 default:
11368 usage_rebase();
11369 /* NOTREACHED */
11373 argc -= optind;
11374 argv += optind;
11376 #ifndef PROFILE
11377 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11378 "unveil", NULL) == -1)
11379 err(1, "pledge");
11380 #endif
11382 if (abort_merge && continue_merge)
11383 option_conflict('a', 'c');
11384 if (abort_merge || continue_merge) {
11385 if (argc != 0)
11386 usage_merge();
11387 } else if (argc != 1)
11388 usage_merge();
11390 cwd = getcwd(NULL, 0);
11391 if (cwd == NULL) {
11392 error = got_error_from_errno("getcwd");
11393 goto done;
11396 error = got_worktree_open(&worktree, cwd);
11397 if (error) {
11398 if (error->code == GOT_ERR_NOT_WORKTREE)
11399 error = wrap_not_worktree_error(error,
11400 "merge", cwd);
11401 goto done;
11404 error = got_repo_open(&repo,
11405 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11406 if (error != NULL)
11407 goto done;
11409 error = apply_unveil(got_repo_get_path(repo), 0,
11410 worktree ? got_worktree_get_root_path(worktree) : NULL);
11411 if (error)
11412 goto done;
11414 error = check_rebase_or_histedit_in_progress(worktree);
11415 if (error)
11416 goto done;
11418 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11419 repo);
11420 if (error)
11421 goto done;
11423 if (abort_merge) {
11424 if (!merge_in_progress) {
11425 error = got_error(GOT_ERR_NOT_MERGING);
11426 goto done;
11428 error = got_worktree_merge_continue(&branch_name,
11429 &branch_tip, &fileindex, worktree, repo);
11430 if (error)
11431 goto done;
11432 error = got_worktree_merge_abort(worktree, fileindex, repo,
11433 abort_progress, &upa);
11434 if (error)
11435 goto done;
11436 printf("Merge of %s aborted\n", branch_name);
11437 goto done; /* nothing else to do */
11440 error = get_author(&author, repo, worktree);
11441 if (error)
11442 goto done;
11444 if (continue_merge) {
11445 if (!merge_in_progress) {
11446 error = got_error(GOT_ERR_NOT_MERGING);
11447 goto done;
11449 error = got_worktree_merge_continue(&branch_name,
11450 &branch_tip, &fileindex, worktree, repo);
11451 if (error)
11452 goto done;
11453 } else {
11454 error = got_ref_open(&branch, repo, argv[0], 0);
11455 if (error != NULL)
11456 goto done;
11457 branch_name = strdup(got_ref_get_name(branch));
11458 if (branch_name == NULL) {
11459 error = got_error_from_errno("strdup");
11460 goto done;
11462 error = got_ref_resolve(&branch_tip, repo, branch);
11463 if (error)
11464 goto done;
11467 error = got_ref_open(&wt_branch, repo,
11468 got_worktree_get_head_ref_name(worktree), 0);
11469 if (error)
11470 goto done;
11471 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11472 if (error)
11473 goto done;
11474 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11475 wt_branch_tip, branch_tip, 0, repo,
11476 check_cancelled, NULL);
11477 if (error && error->code != GOT_ERR_ANCESTRY)
11478 goto done;
11480 if (!continue_merge) {
11481 error = check_path_prefix(wt_branch_tip, branch_tip,
11482 got_worktree_get_path_prefix(worktree),
11483 GOT_ERR_MERGE_PATH, repo);
11484 if (error)
11485 goto done;
11486 if (yca_id) {
11487 error = check_same_branch(wt_branch_tip, branch,
11488 yca_id, repo);
11489 if (error) {
11490 if (error->code != GOT_ERR_ANCESTRY)
11491 goto done;
11492 error = NULL;
11493 } else {
11494 static char msg[512];
11495 snprintf(msg, sizeof(msg),
11496 "cannot create a merge commit because "
11497 "%s is based on %s; %s can be integrated "
11498 "with 'got integrate' instead", branch_name,
11499 got_worktree_get_head_ref_name(worktree),
11500 branch_name);
11501 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11502 goto done;
11505 error = got_worktree_merge_prepare(&fileindex, worktree,
11506 branch, repo);
11507 if (error)
11508 goto done;
11510 error = got_worktree_merge_branch(worktree, fileindex,
11511 yca_id, branch_tip, repo, update_progress, &upa,
11512 check_cancelled, NULL);
11513 if (error)
11514 goto done;
11515 print_merge_progress_stats(&upa);
11516 if (!upa.did_something) {
11517 error = got_worktree_merge_abort(worktree, fileindex,
11518 repo, abort_progress, &upa);
11519 if (error)
11520 goto done;
11521 printf("Already up-to-date\n");
11522 goto done;
11526 if (interrupt_merge) {
11527 error = got_worktree_merge_postpone(worktree, fileindex);
11528 if (error)
11529 goto done;
11530 printf("Merge of %s interrupted on request\n", branch_name);
11531 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11532 upa.not_deleted > 0 || upa.unversioned > 0) {
11533 error = got_worktree_merge_postpone(worktree, fileindex);
11534 if (error)
11535 goto done;
11536 if (upa.conflicts > 0 && upa.missing == 0 &&
11537 upa.not_deleted == 0 && upa.unversioned == 0) {
11538 error = got_error_msg(GOT_ERR_CONFLICTS,
11539 "conflicts must be resolved before merging "
11540 "can continue");
11541 } else if (upa.conflicts > 0) {
11542 error = got_error_msg(GOT_ERR_CONFLICTS,
11543 "conflicts must be resolved before merging "
11544 "can continue; changes destined for some "
11545 "files were not yet merged and "
11546 "should be merged manually if required before the "
11547 "merge operation is continued");
11548 } else {
11549 error = got_error_msg(GOT_ERR_CONFLICTS,
11550 "changes destined for some "
11551 "files were not yet merged and should be "
11552 "merged manually if required before the "
11553 "merge operation is continued");
11555 goto done;
11556 } else {
11557 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11558 fileindex, author, NULL, 1, branch_tip, branch_name,
11559 repo, continue_merge ? print_status : NULL, NULL);
11560 if (error)
11561 goto done;
11562 error = got_worktree_merge_complete(worktree, fileindex, repo);
11563 if (error)
11564 goto done;
11565 error = got_object_id_str(&id_str, merge_commit_id);
11566 if (error)
11567 goto done;
11568 printf("Merged %s into %s: %s\n", branch_name,
11569 got_worktree_get_head_ref_name(worktree),
11570 id_str);
11573 done:
11574 free(id_str);
11575 free(merge_commit_id);
11576 free(author);
11577 free(branch_tip);
11578 free(branch_name);
11579 free(yca_id);
11580 if (branch)
11581 got_ref_close(branch);
11582 if (wt_branch)
11583 got_ref_close(wt_branch);
11584 if (worktree)
11585 got_worktree_close(worktree);
11586 if (repo) {
11587 const struct got_error *close_err = got_repo_close(repo);
11588 if (error == NULL)
11589 error = close_err;
11591 return error;
11594 __dead static void
11595 usage_stage(void)
11597 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11598 "[-S] [file-path ...]\n",
11599 getprogname());
11600 exit(1);
11603 static const struct got_error *
11604 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11605 const char *path, struct got_object_id *blob_id,
11606 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11607 int dirfd, const char *de_name)
11609 const struct got_error *err = NULL;
11610 char *id_str = NULL;
11612 if (staged_status != GOT_STATUS_ADD &&
11613 staged_status != GOT_STATUS_MODIFY &&
11614 staged_status != GOT_STATUS_DELETE)
11615 return NULL;
11617 if (staged_status == GOT_STATUS_ADD ||
11618 staged_status == GOT_STATUS_MODIFY)
11619 err = got_object_id_str(&id_str, staged_blob_id);
11620 else
11621 err = got_object_id_str(&id_str, blob_id);
11622 if (err)
11623 return err;
11625 printf("%s %c %s\n", id_str, staged_status, path);
11626 free(id_str);
11627 return NULL;
11630 static const struct got_error *
11631 cmd_stage(int argc, char *argv[])
11633 const struct got_error *error = NULL;
11634 struct got_repository *repo = NULL;
11635 struct got_worktree *worktree = NULL;
11636 char *cwd = NULL;
11637 struct got_pathlist_head paths;
11638 struct got_pathlist_entry *pe;
11639 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11640 FILE *patch_script_file = NULL;
11641 const char *patch_script_path = NULL;
11642 struct choose_patch_arg cpa;
11644 TAILQ_INIT(&paths);
11646 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11647 switch (ch) {
11648 case 'l':
11649 list_stage = 1;
11650 break;
11651 case 'p':
11652 pflag = 1;
11653 break;
11654 case 'F':
11655 patch_script_path = optarg;
11656 break;
11657 case 'S':
11658 allow_bad_symlinks = 1;
11659 break;
11660 default:
11661 usage_stage();
11662 /* NOTREACHED */
11666 argc -= optind;
11667 argv += optind;
11669 #ifndef PROFILE
11670 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11671 "unveil", NULL) == -1)
11672 err(1, "pledge");
11673 #endif
11674 if (list_stage && (pflag || patch_script_path))
11675 errx(1, "-l option cannot be used with other options");
11676 if (patch_script_path && !pflag)
11677 errx(1, "-F option can only be used together with -p option");
11679 cwd = getcwd(NULL, 0);
11680 if (cwd == NULL) {
11681 error = got_error_from_errno("getcwd");
11682 goto done;
11685 error = got_worktree_open(&worktree, cwd);
11686 if (error) {
11687 if (error->code == GOT_ERR_NOT_WORKTREE)
11688 error = wrap_not_worktree_error(error, "stage", cwd);
11689 goto done;
11692 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11693 NULL);
11694 if (error != NULL)
11695 goto done;
11697 if (patch_script_path) {
11698 patch_script_file = fopen(patch_script_path, "re");
11699 if (patch_script_file == NULL) {
11700 error = got_error_from_errno2("fopen",
11701 patch_script_path);
11702 goto done;
11705 error = apply_unveil(got_repo_get_path(repo), 0,
11706 got_worktree_get_root_path(worktree));
11707 if (error)
11708 goto done;
11710 error = check_merge_in_progress(worktree, repo);
11711 if (error)
11712 goto done;
11714 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11715 if (error)
11716 goto done;
11718 if (list_stage)
11719 error = got_worktree_status(worktree, &paths, repo, 0,
11720 print_stage, NULL, check_cancelled, NULL);
11721 else {
11722 cpa.patch_script_file = patch_script_file;
11723 cpa.action = "stage";
11724 error = got_worktree_stage(worktree, &paths,
11725 pflag ? NULL : print_status, NULL,
11726 pflag ? choose_patch : NULL, &cpa,
11727 allow_bad_symlinks, repo);
11729 done:
11730 if (patch_script_file && fclose(patch_script_file) == EOF &&
11731 error == NULL)
11732 error = got_error_from_errno2("fclose", patch_script_path);
11733 if (repo) {
11734 const struct got_error *close_err = got_repo_close(repo);
11735 if (error == NULL)
11736 error = close_err;
11738 if (worktree)
11739 got_worktree_close(worktree);
11740 TAILQ_FOREACH(pe, &paths, entry)
11741 free((char *)pe->path);
11742 got_pathlist_free(&paths);
11743 free(cwd);
11744 return error;
11747 __dead static void
11748 usage_unstage(void)
11750 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11751 "[file-path ...]\n",
11752 getprogname());
11753 exit(1);
11757 static const struct got_error *
11758 cmd_unstage(int argc, char *argv[])
11760 const struct got_error *error = NULL;
11761 struct got_repository *repo = NULL;
11762 struct got_worktree *worktree = NULL;
11763 char *cwd = NULL;
11764 struct got_pathlist_head paths;
11765 struct got_pathlist_entry *pe;
11766 int ch, pflag = 0;
11767 struct got_update_progress_arg upa;
11768 FILE *patch_script_file = NULL;
11769 const char *patch_script_path = NULL;
11770 struct choose_patch_arg cpa;
11772 TAILQ_INIT(&paths);
11774 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11775 switch (ch) {
11776 case 'p':
11777 pflag = 1;
11778 break;
11779 case 'F':
11780 patch_script_path = optarg;
11781 break;
11782 default:
11783 usage_unstage();
11784 /* NOTREACHED */
11788 argc -= optind;
11789 argv += optind;
11791 #ifndef PROFILE
11792 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11793 "unveil", NULL) == -1)
11794 err(1, "pledge");
11795 #endif
11796 if (patch_script_path && !pflag)
11797 errx(1, "-F option can only be used together with -p option");
11799 cwd = getcwd(NULL, 0);
11800 if (cwd == NULL) {
11801 error = got_error_from_errno("getcwd");
11802 goto done;
11805 error = got_worktree_open(&worktree, cwd);
11806 if (error) {
11807 if (error->code == GOT_ERR_NOT_WORKTREE)
11808 error = wrap_not_worktree_error(error, "unstage", cwd);
11809 goto done;
11812 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11813 NULL);
11814 if (error != NULL)
11815 goto done;
11817 if (patch_script_path) {
11818 patch_script_file = fopen(patch_script_path, "re");
11819 if (patch_script_file == NULL) {
11820 error = got_error_from_errno2("fopen",
11821 patch_script_path);
11822 goto done;
11826 error = apply_unveil(got_repo_get_path(repo), 0,
11827 got_worktree_get_root_path(worktree));
11828 if (error)
11829 goto done;
11831 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11832 if (error)
11833 goto done;
11835 cpa.patch_script_file = patch_script_file;
11836 cpa.action = "unstage";
11837 memset(&upa, 0, sizeof(upa));
11838 error = got_worktree_unstage(worktree, &paths, update_progress,
11839 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11840 if (!error)
11841 print_merge_progress_stats(&upa);
11842 done:
11843 if (patch_script_file && fclose(patch_script_file) == EOF &&
11844 error == NULL)
11845 error = got_error_from_errno2("fclose", patch_script_path);
11846 if (repo) {
11847 const struct got_error *close_err = got_repo_close(repo);
11848 if (error == NULL)
11849 error = close_err;
11851 if (worktree)
11852 got_worktree_close(worktree);
11853 TAILQ_FOREACH(pe, &paths, entry)
11854 free((char *)pe->path);
11855 got_pathlist_free(&paths);
11856 free(cwd);
11857 return error;
11860 __dead static void
11861 usage_cat(void)
11863 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11864 "arg1 [arg2 ...]\n", getprogname());
11865 exit(1);
11868 static const struct got_error *
11869 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11871 const struct got_error *err;
11872 struct got_blob_object *blob;
11874 err = got_object_open_as_blob(&blob, repo, id, 8192);
11875 if (err)
11876 return err;
11878 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11879 got_object_blob_close(blob);
11880 return err;
11883 static const struct got_error *
11884 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11886 const struct got_error *err;
11887 struct got_tree_object *tree;
11888 int nentries, i;
11890 err = got_object_open_as_tree(&tree, repo, id);
11891 if (err)
11892 return err;
11894 nentries = got_object_tree_get_nentries(tree);
11895 for (i = 0; i < nentries; i++) {
11896 struct got_tree_entry *te;
11897 char *id_str;
11898 if (sigint_received || sigpipe_received)
11899 break;
11900 te = got_object_tree_get_entry(tree, i);
11901 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11902 if (err)
11903 break;
11904 fprintf(outfile, "%s %.7o %s\n", id_str,
11905 got_tree_entry_get_mode(te),
11906 got_tree_entry_get_name(te));
11907 free(id_str);
11910 got_object_tree_close(tree);
11911 return err;
11914 static void
11915 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11917 long long h, m;
11918 char sign = '+';
11920 if (gmtoff < 0) {
11921 sign = '-';
11922 gmtoff = -gmtoff;
11925 h = (long long)gmtoff / 3600;
11926 m = ((long long)gmtoff - h*3600) / 60;
11927 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11930 static const struct got_error *
11931 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11933 const struct got_error *err;
11934 struct got_commit_object *commit;
11935 const struct got_object_id_queue *parent_ids;
11936 struct got_object_qid *pid;
11937 char *id_str = NULL;
11938 const char *logmsg = NULL;
11939 char gmtoff[6];
11941 err = got_object_open_as_commit(&commit, repo, id);
11942 if (err)
11943 return err;
11945 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11946 if (err)
11947 goto done;
11949 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11950 parent_ids = got_object_commit_get_parent_ids(commit);
11951 fprintf(outfile, "numparents %d\n",
11952 got_object_commit_get_nparents(commit));
11953 STAILQ_FOREACH(pid, parent_ids, entry) {
11954 char *pid_str;
11955 err = got_object_id_str(&pid_str, &pid->id);
11956 if (err)
11957 goto done;
11958 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11959 free(pid_str);
11961 format_gmtoff(gmtoff, sizeof(gmtoff),
11962 got_object_commit_get_author_gmtoff(commit));
11963 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11964 got_object_commit_get_author(commit),
11965 (long long)got_object_commit_get_author_time(commit),
11966 gmtoff);
11968 format_gmtoff(gmtoff, sizeof(gmtoff),
11969 got_object_commit_get_committer_gmtoff(commit));
11970 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11971 got_object_commit_get_author(commit),
11972 (long long)got_object_commit_get_committer_time(commit),
11973 gmtoff);
11975 logmsg = got_object_commit_get_logmsg_raw(commit);
11976 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11977 fprintf(outfile, "%s", logmsg);
11978 done:
11979 free(id_str);
11980 got_object_commit_close(commit);
11981 return err;
11984 static const struct got_error *
11985 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11987 const struct got_error *err;
11988 struct got_tag_object *tag;
11989 char *id_str = NULL;
11990 const char *tagmsg = NULL;
11991 char gmtoff[6];
11993 err = got_object_open_as_tag(&tag, repo, id);
11994 if (err)
11995 return err;
11997 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11998 if (err)
11999 goto done;
12001 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12003 switch (got_object_tag_get_object_type(tag)) {
12004 case GOT_OBJ_TYPE_BLOB:
12005 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12006 GOT_OBJ_LABEL_BLOB);
12007 break;
12008 case GOT_OBJ_TYPE_TREE:
12009 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12010 GOT_OBJ_LABEL_TREE);
12011 break;
12012 case GOT_OBJ_TYPE_COMMIT:
12013 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12014 GOT_OBJ_LABEL_COMMIT);
12015 break;
12016 case GOT_OBJ_TYPE_TAG:
12017 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12018 GOT_OBJ_LABEL_TAG);
12019 break;
12020 default:
12021 break;
12024 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12025 got_object_tag_get_name(tag));
12027 format_gmtoff(gmtoff, sizeof(gmtoff),
12028 got_object_tag_get_tagger_gmtoff(tag));
12029 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12030 got_object_tag_get_tagger(tag),
12031 (long long)got_object_tag_get_tagger_time(tag),
12032 gmtoff);
12034 tagmsg = got_object_tag_get_message(tag);
12035 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12036 fprintf(outfile, "%s", tagmsg);
12037 done:
12038 free(id_str);
12039 got_object_tag_close(tag);
12040 return err;
12043 static const struct got_error *
12044 cmd_cat(int argc, char *argv[])
12046 const struct got_error *error;
12047 struct got_repository *repo = NULL;
12048 struct got_worktree *worktree = NULL;
12049 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12050 const char *commit_id_str = NULL;
12051 struct got_object_id *id = NULL, *commit_id = NULL;
12052 struct got_commit_object *commit = NULL;
12053 int ch, obj_type, i, force_path = 0;
12054 struct got_reflist_head refs;
12056 TAILQ_INIT(&refs);
12058 #ifndef PROFILE
12059 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12060 NULL) == -1)
12061 err(1, "pledge");
12062 #endif
12064 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12065 switch (ch) {
12066 case 'c':
12067 commit_id_str = optarg;
12068 break;
12069 case 'r':
12070 repo_path = realpath(optarg, NULL);
12071 if (repo_path == NULL)
12072 return got_error_from_errno2("realpath",
12073 optarg);
12074 got_path_strip_trailing_slashes(repo_path);
12075 break;
12076 case 'P':
12077 force_path = 1;
12078 break;
12079 default:
12080 usage_cat();
12081 /* NOTREACHED */
12085 argc -= optind;
12086 argv += optind;
12088 cwd = getcwd(NULL, 0);
12089 if (cwd == NULL) {
12090 error = got_error_from_errno("getcwd");
12091 goto done;
12094 if (repo_path == NULL) {
12095 error = got_worktree_open(&worktree, cwd);
12096 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12097 goto done;
12098 if (worktree) {
12099 repo_path = strdup(
12100 got_worktree_get_repo_path(worktree));
12101 if (repo_path == NULL) {
12102 error = got_error_from_errno("strdup");
12103 goto done;
12106 /* Release work tree lock. */
12107 got_worktree_close(worktree);
12108 worktree = NULL;
12112 if (repo_path == NULL) {
12113 repo_path = strdup(cwd);
12114 if (repo_path == NULL)
12115 return got_error_from_errno("strdup");
12118 error = got_repo_open(&repo, repo_path, NULL);
12119 free(repo_path);
12120 if (error != NULL)
12121 goto done;
12123 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12124 if (error)
12125 goto done;
12127 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12128 if (error)
12129 goto done;
12131 if (commit_id_str == NULL)
12132 commit_id_str = GOT_REF_HEAD;
12133 error = got_repo_match_object_id(&commit_id, NULL,
12134 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12135 if (error)
12136 goto done;
12138 error = got_object_open_as_commit(&commit, repo, commit_id);
12139 if (error)
12140 goto done;
12142 for (i = 0; i < argc; i++) {
12143 if (force_path) {
12144 error = got_object_id_by_path(&id, repo, commit,
12145 argv[i]);
12146 if (error)
12147 break;
12148 } else {
12149 error = got_repo_match_object_id(&id, &label, argv[i],
12150 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12151 repo);
12152 if (error) {
12153 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12154 error->code != GOT_ERR_NOT_REF)
12155 break;
12156 error = got_object_id_by_path(&id, repo,
12157 commit, argv[i]);
12158 if (error)
12159 break;
12163 error = got_object_get_type(&obj_type, repo, id);
12164 if (error)
12165 break;
12167 switch (obj_type) {
12168 case GOT_OBJ_TYPE_BLOB:
12169 error = cat_blob(id, repo, stdout);
12170 break;
12171 case GOT_OBJ_TYPE_TREE:
12172 error = cat_tree(id, repo, stdout);
12173 break;
12174 case GOT_OBJ_TYPE_COMMIT:
12175 error = cat_commit(id, repo, stdout);
12176 break;
12177 case GOT_OBJ_TYPE_TAG:
12178 error = cat_tag(id, repo, stdout);
12179 break;
12180 default:
12181 error = got_error(GOT_ERR_OBJ_TYPE);
12182 break;
12184 if (error)
12185 break;
12186 free(label);
12187 label = NULL;
12188 free(id);
12189 id = NULL;
12191 done:
12192 free(label);
12193 free(id);
12194 free(commit_id);
12195 if (commit)
12196 got_object_commit_close(commit);
12197 if (worktree)
12198 got_worktree_close(worktree);
12199 if (repo) {
12200 const struct got_error *close_err = got_repo_close(repo);
12201 if (error == NULL)
12202 error = close_err;
12204 got_ref_list_free(&refs);
12205 return error;
12208 __dead static void
12209 usage_info(void)
12211 fprintf(stderr, "usage: %s info [path ...]\n",
12212 getprogname());
12213 exit(1);
12216 static const struct got_error *
12217 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12218 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12219 struct got_object_id *commit_id)
12221 const struct got_error *err = NULL;
12222 char *id_str = NULL;
12223 char datebuf[128];
12224 struct tm mytm, *tm;
12225 struct got_pathlist_head *paths = arg;
12226 struct got_pathlist_entry *pe;
12229 * Clear error indication from any of the path arguments which
12230 * would cause this file index entry to be displayed.
12232 TAILQ_FOREACH(pe, paths, entry) {
12233 if (got_path_cmp(path, pe->path, strlen(path),
12234 pe->path_len) == 0 ||
12235 got_path_is_child(path, pe->path, pe->path_len))
12236 pe->data = NULL; /* no error */
12239 printf(GOT_COMMIT_SEP_STR);
12240 if (S_ISLNK(mode))
12241 printf("symlink: %s\n", path);
12242 else if (S_ISREG(mode)) {
12243 printf("file: %s\n", path);
12244 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12245 } else if (S_ISDIR(mode))
12246 printf("directory: %s\n", path);
12247 else
12248 printf("something: %s\n", path);
12250 tm = localtime_r(&mtime, &mytm);
12251 if (tm == NULL)
12252 return NULL;
12253 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12254 return got_error(GOT_ERR_NO_SPACE);
12255 printf("timestamp: %s\n", datebuf);
12257 if (blob_id) {
12258 err = got_object_id_str(&id_str, blob_id);
12259 if (err)
12260 return err;
12261 printf("based on blob: %s\n", id_str);
12262 free(id_str);
12265 if (staged_blob_id) {
12266 err = got_object_id_str(&id_str, staged_blob_id);
12267 if (err)
12268 return err;
12269 printf("based on staged blob: %s\n", id_str);
12270 free(id_str);
12273 if (commit_id) {
12274 err = got_object_id_str(&id_str, commit_id);
12275 if (err)
12276 return err;
12277 printf("based on commit: %s\n", id_str);
12278 free(id_str);
12281 return NULL;
12284 static const struct got_error *
12285 cmd_info(int argc, char *argv[])
12287 const struct got_error *error = NULL;
12288 struct got_worktree *worktree = NULL;
12289 char *cwd = NULL, *id_str = NULL;
12290 struct got_pathlist_head paths;
12291 struct got_pathlist_entry *pe;
12292 char *uuidstr = NULL;
12293 int ch, show_files = 0;
12295 TAILQ_INIT(&paths);
12297 while ((ch = getopt(argc, argv, "")) != -1) {
12298 switch (ch) {
12299 default:
12300 usage_info();
12301 /* NOTREACHED */
12305 argc -= optind;
12306 argv += optind;
12308 #ifndef PROFILE
12309 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12310 NULL) == -1)
12311 err(1, "pledge");
12312 #endif
12313 cwd = getcwd(NULL, 0);
12314 if (cwd == NULL) {
12315 error = got_error_from_errno("getcwd");
12316 goto done;
12319 error = got_worktree_open(&worktree, cwd);
12320 if (error) {
12321 if (error->code == GOT_ERR_NOT_WORKTREE)
12322 error = wrap_not_worktree_error(error, "info", cwd);
12323 goto done;
12326 #ifndef PROFILE
12327 /* Remove "cpath" promise. */
12328 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12329 NULL) == -1)
12330 err(1, "pledge");
12331 #endif
12332 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12333 if (error)
12334 goto done;
12336 if (argc >= 1) {
12337 error = get_worktree_paths_from_argv(&paths, argc, argv,
12338 worktree);
12339 if (error)
12340 goto done;
12341 show_files = 1;
12344 error = got_object_id_str(&id_str,
12345 got_worktree_get_base_commit_id(worktree));
12346 if (error)
12347 goto done;
12349 error = got_worktree_get_uuid(&uuidstr, worktree);
12350 if (error)
12351 goto done;
12353 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12354 printf("work tree base commit: %s\n", id_str);
12355 printf("work tree path prefix: %s\n",
12356 got_worktree_get_path_prefix(worktree));
12357 printf("work tree branch reference: %s\n",
12358 got_worktree_get_head_ref_name(worktree));
12359 printf("work tree UUID: %s\n", uuidstr);
12360 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12362 if (show_files) {
12363 struct got_pathlist_entry *pe;
12364 TAILQ_FOREACH(pe, &paths, entry) {
12365 if (pe->path_len == 0)
12366 continue;
12368 * Assume this path will fail. This will be corrected
12369 * in print_path_info() in case the path does suceeed.
12371 pe->data = (void *)got_error_path(pe->path,
12372 GOT_ERR_BAD_PATH);
12374 error = got_worktree_path_info(worktree, &paths,
12375 print_path_info, &paths, check_cancelled, NULL);
12376 if (error)
12377 goto done;
12378 TAILQ_FOREACH(pe, &paths, entry) {
12379 if (pe->data != NULL) {
12380 error = pe->data; /* bad path */
12381 break;
12385 done:
12386 TAILQ_FOREACH(pe, &paths, entry)
12387 free((char *)pe->path);
12388 got_pathlist_free(&paths);
12389 free(cwd);
12390 free(id_str);
12391 free(uuidstr);
12392 return error;