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,
3823 int local_only)
3825 static const struct got_error *err = NULL;
3826 struct got_reflist_entry *re;
3827 char *s;
3828 const char *name;
3830 *refs_str = NULL;
3832 TAILQ_FOREACH(re, refs, entry) {
3833 struct got_tag_object *tag = NULL;
3834 struct got_object_id *ref_id;
3835 int cmp;
3837 name = got_ref_get_name(re->ref);
3838 if (strcmp(name, GOT_REF_HEAD) == 0)
3839 continue;
3840 if (strncmp(name, "refs/", 5) == 0)
3841 name += 5;
3842 if (strncmp(name, "got/", 4) == 0)
3843 continue;
3844 if (strncmp(name, "heads/", 6) == 0)
3845 name += 6;
3846 if (strncmp(name, "remotes/", 8) == 0) {
3847 if (local_only)
3848 continue;
3849 name += 8;
3850 s = strstr(name, "/" GOT_REF_HEAD);
3851 if (s != NULL && s[strlen(s)] == '\0')
3852 continue;
3854 err = got_ref_resolve(&ref_id, repo, re->ref);
3855 if (err)
3856 break;
3857 if (strncmp(name, "tags/", 5) == 0) {
3858 err = got_object_open_as_tag(&tag, repo, ref_id);
3859 if (err) {
3860 if (err->code != GOT_ERR_OBJ_TYPE) {
3861 free(ref_id);
3862 break;
3864 /* Ref points at something other than a tag. */
3865 err = NULL;
3866 tag = NULL;
3869 cmp = got_object_id_cmp(tag ?
3870 got_object_tag_get_object_id(tag) : ref_id, id);
3871 free(ref_id);
3872 if (tag)
3873 got_object_tag_close(tag);
3874 if (cmp != 0)
3875 continue;
3876 s = *refs_str;
3877 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3878 s ? ", " : "", name) == -1) {
3879 err = got_error_from_errno("asprintf");
3880 free(s);
3881 *refs_str = NULL;
3882 break;
3884 free(s);
3887 return err;
3890 static const struct got_error *
3891 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3892 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3894 const struct got_error *err = NULL;
3895 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3896 char *comma, *s, *nl;
3897 struct got_reflist_head *refs;
3898 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3899 struct tm tm;
3900 time_t committer_time;
3902 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3903 if (refs) {
3904 err = build_refs_str(&ref_str, refs, id, repo, 1);
3905 if (err)
3906 goto done;
3908 /* Display the first matching ref only. */
3909 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3910 *comma = '\0';
3913 if (ref_str == NULL) {
3914 err = got_object_id_str(&id_str, id);
3915 if (err)
3916 return err;
3919 committer_time = got_object_commit_get_committer_time(commit);
3920 if (gmtime_r(&committer_time, &tm) == NULL)
3921 return got_error_from_errno("gmtime_r");
3922 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
3923 return got_error(GOT_ERR_NO_SPACE);
3925 err = got_object_commit_get_logmsg(&logmsg0, commit);
3926 if (err)
3927 goto done;
3929 s = logmsg0;
3930 while (isspace((unsigned char)s[0]))
3931 s++;
3933 nl = strchr(s, '\n');
3934 if (nl) {
3935 *nl = '\0';
3938 if (ref_str)
3939 printf("%s%-7s %s\n", datebuf, ref_str, s);
3940 else
3941 printf("%s%.7s %s\n", datebuf, id_str, s);
3943 if (fflush(stdout) != 0 && err == NULL)
3944 err = got_error_from_errno("fflush");
3945 done:
3946 free(id_str);
3947 free(ref_str);
3948 free(logmsg0);
3949 return err;
3952 static const struct got_error *
3953 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3954 struct got_repository *repo, const char *path,
3955 struct got_pathlist_head *changed_paths, int show_patch,
3956 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3957 const char *custom_refs_str)
3959 const struct got_error *err = NULL;
3960 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3961 char datebuf[26];
3962 time_t committer_time;
3963 const char *author, *committer;
3964 char *refs_str = NULL;
3966 err = got_object_id_str(&id_str, id);
3967 if (err)
3968 return err;
3970 if (custom_refs_str == NULL) {
3971 struct got_reflist_head *refs;
3972 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3973 if (refs) {
3974 err = build_refs_str(&refs_str, refs, id, repo, 0);
3975 if (err)
3976 goto done;
3980 printf(GOT_COMMIT_SEP_STR);
3981 if (custom_refs_str)
3982 printf("commit %s (%s)\n", id_str, custom_refs_str);
3983 else
3984 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3985 refs_str ? refs_str : "", refs_str ? ")" : "");
3986 free(id_str);
3987 id_str = NULL;
3988 free(refs_str);
3989 refs_str = NULL;
3990 printf("from: %s\n", got_object_commit_get_author(commit));
3991 committer_time = got_object_commit_get_committer_time(commit);
3992 datestr = get_datestr(&committer_time, datebuf);
3993 if (datestr)
3994 printf("date: %s UTC\n", datestr);
3995 author = got_object_commit_get_author(commit);
3996 committer = got_object_commit_get_committer(commit);
3997 if (strcmp(author, committer) != 0)
3998 printf("via: %s\n", committer);
3999 if (got_object_commit_get_nparents(commit) > 1) {
4000 const struct got_object_id_queue *parent_ids;
4001 struct got_object_qid *qid;
4002 int n = 1;
4003 parent_ids = got_object_commit_get_parent_ids(commit);
4004 STAILQ_FOREACH(qid, parent_ids, entry) {
4005 err = got_object_id_str(&id_str, &qid->id);
4006 if (err)
4007 goto done;
4008 printf("parent %d: %s\n", n++, id_str);
4009 free(id_str);
4010 id_str = NULL;
4014 err = got_object_commit_get_logmsg(&logmsg0, commit);
4015 if (err)
4016 goto done;
4018 logmsg = logmsg0;
4019 do {
4020 line = strsep(&logmsg, "\n");
4021 if (line)
4022 printf(" %s\n", line);
4023 } while (line);
4024 free(logmsg0);
4026 if (changed_paths) {
4027 struct got_pathlist_entry *pe;
4028 TAILQ_FOREACH(pe, changed_paths, entry) {
4029 struct got_diff_changed_path *cp = pe->data;
4030 printf(" %c %s\n", cp->status, pe->path);
4032 printf("\n");
4034 if (show_patch) {
4035 err = print_patch(commit, id, path, diff_context, repo, stdout);
4036 if (err == 0)
4037 printf("\n");
4040 if (fflush(stdout) != 0 && err == NULL)
4041 err = got_error_from_errno("fflush");
4042 done:
4043 free(id_str);
4044 free(refs_str);
4045 return err;
4048 static const struct got_error *
4049 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4050 struct got_repository *repo, const char *path, int show_changed_paths,
4051 int show_patch, const char *search_pattern, int diff_context, int limit,
4052 int log_branches, int reverse_display_order,
4053 struct got_reflist_object_id_map *refs_idmap, int one_line,
4054 FILE *tmpfile)
4056 const struct got_error *err;
4057 struct got_commit_graph *graph;
4058 regex_t regex;
4059 int have_match;
4060 struct got_object_id_queue reversed_commits;
4061 struct got_object_qid *qid;
4062 struct got_commit_object *commit;
4063 struct got_pathlist_head changed_paths;
4064 struct got_pathlist_entry *pe;
4066 STAILQ_INIT(&reversed_commits);
4067 TAILQ_INIT(&changed_paths);
4069 if (search_pattern && regcomp(&regex, search_pattern,
4070 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4071 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4073 err = got_commit_graph_open(&graph, path, !log_branches);
4074 if (err)
4075 return err;
4076 err = got_commit_graph_iter_start(graph, root_id, repo,
4077 check_cancelled, NULL);
4078 if (err)
4079 goto done;
4080 for (;;) {
4081 struct got_object_id *id;
4083 if (sigint_received || sigpipe_received)
4084 break;
4086 err = got_commit_graph_iter_next(&id, graph, repo,
4087 check_cancelled, NULL);
4088 if (err) {
4089 if (err->code == GOT_ERR_ITER_COMPLETED)
4090 err = NULL;
4091 break;
4093 if (id == NULL)
4094 break;
4096 err = got_object_open_as_commit(&commit, repo, id);
4097 if (err)
4098 break;
4100 if (show_changed_paths && !reverse_display_order) {
4101 err = get_changed_paths(&changed_paths, commit, repo);
4102 if (err)
4103 break;
4106 if (search_pattern) {
4107 err = match_commit(&have_match, id, commit, &regex);
4108 if (err) {
4109 got_object_commit_close(commit);
4110 break;
4112 if (have_match == 0 && show_changed_paths)
4113 match_changed_paths(&have_match,
4114 &changed_paths, &regex);
4115 if (have_match == 0 && show_patch) {
4116 err = match_patch(&have_match, commit, id,
4117 path, diff_context, repo, &regex,
4118 tmpfile);
4119 if (err)
4120 break;
4122 if (have_match == 0) {
4123 got_object_commit_close(commit);
4124 TAILQ_FOREACH(pe, &changed_paths, entry) {
4125 free((char *)pe->path);
4126 free(pe->data);
4128 got_pathlist_free(&changed_paths);
4129 continue;
4133 if (reverse_display_order) {
4134 err = got_object_qid_alloc(&qid, id);
4135 if (err)
4136 break;
4137 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4138 got_object_commit_close(commit);
4139 } else {
4140 if (one_line)
4141 err = print_commit_oneline(commit, id,
4142 repo, refs_idmap);
4143 else
4144 err = print_commit(commit, id, repo, path,
4145 show_changed_paths ? &changed_paths : NULL,
4146 show_patch, diff_context, refs_idmap, NULL);
4147 got_object_commit_close(commit);
4148 if (err)
4149 break;
4151 if ((limit && --limit == 0) ||
4152 (end_id && got_object_id_cmp(id, end_id) == 0))
4153 break;
4155 TAILQ_FOREACH(pe, &changed_paths, entry) {
4156 free((char *)pe->path);
4157 free(pe->data);
4159 got_pathlist_free(&changed_paths);
4161 if (reverse_display_order) {
4162 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4163 err = got_object_open_as_commit(&commit, repo,
4164 &qid->id);
4165 if (err)
4166 break;
4167 if (show_changed_paths) {
4168 err = get_changed_paths(&changed_paths,
4169 commit, repo);
4170 if (err)
4171 break;
4173 if (one_line)
4174 err = print_commit_oneline(commit, &qid->id,
4175 repo, refs_idmap);
4176 else
4177 err = print_commit(commit, &qid->id, repo, path,
4178 show_changed_paths ? &changed_paths : NULL,
4179 show_patch, diff_context, refs_idmap, NULL);
4180 got_object_commit_close(commit);
4181 if (err)
4182 break;
4183 TAILQ_FOREACH(pe, &changed_paths, entry) {
4184 free((char *)pe->path);
4185 free(pe->data);
4187 got_pathlist_free(&changed_paths);
4190 done:
4191 while (!STAILQ_EMPTY(&reversed_commits)) {
4192 qid = STAILQ_FIRST(&reversed_commits);
4193 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4194 got_object_qid_free(qid);
4196 TAILQ_FOREACH(pe, &changed_paths, entry) {
4197 free((char *)pe->path);
4198 free(pe->data);
4200 got_pathlist_free(&changed_paths);
4201 if (search_pattern)
4202 regfree(&regex);
4203 got_commit_graph_close(graph);
4204 return err;
4207 __dead static void
4208 usage_log(void)
4210 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4211 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4212 "[-r repository-path] [-R] [path]\n", getprogname());
4213 exit(1);
4216 static int
4217 get_default_log_limit(void)
4219 const char *got_default_log_limit;
4220 long long n;
4221 const char *errstr;
4223 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4224 if (got_default_log_limit == NULL)
4225 return 0;
4226 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4227 if (errstr != NULL)
4228 return 0;
4229 return n;
4232 static const struct got_error *
4233 cmd_log(int argc, char *argv[])
4235 const struct got_error *error;
4236 struct got_repository *repo = NULL;
4237 struct got_worktree *worktree = NULL;
4238 struct got_object_id *start_id = NULL, *end_id = NULL;
4239 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4240 const char *start_commit = NULL, *end_commit = NULL;
4241 const char *search_pattern = NULL;
4242 int diff_context = -1, ch;
4243 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4244 int reverse_display_order = 0, one_line = 0;
4245 const char *errstr;
4246 struct got_reflist_head refs;
4247 struct got_reflist_object_id_map *refs_idmap = NULL;
4248 FILE *tmpfile = NULL;
4250 TAILQ_INIT(&refs);
4252 #ifndef PROFILE
4253 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4254 NULL)
4255 == -1)
4256 err(1, "pledge");
4257 #endif
4259 limit = get_default_log_limit();
4261 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4262 switch (ch) {
4263 case 'p':
4264 show_patch = 1;
4265 break;
4266 case 'P':
4267 show_changed_paths = 1;
4268 break;
4269 case 'c':
4270 start_commit = optarg;
4271 break;
4272 case 'C':
4273 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4274 &errstr);
4275 if (errstr != NULL)
4276 errx(1, "number of context lines is %s: %s",
4277 errstr, optarg);
4278 break;
4279 case 'l':
4280 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4281 if (errstr != NULL)
4282 errx(1, "number of commits is %s: %s",
4283 errstr, optarg);
4284 break;
4285 case 'b':
4286 log_branches = 1;
4287 break;
4288 case 'r':
4289 repo_path = realpath(optarg, NULL);
4290 if (repo_path == NULL)
4291 return got_error_from_errno2("realpath",
4292 optarg);
4293 got_path_strip_trailing_slashes(repo_path);
4294 break;
4295 case 'R':
4296 reverse_display_order = 1;
4297 break;
4298 case 's':
4299 one_line = 1;
4300 break;
4301 case 'S':
4302 search_pattern = optarg;
4303 break;
4304 case 'x':
4305 end_commit = optarg;
4306 break;
4307 default:
4308 usage_log();
4309 /* NOTREACHED */
4313 argc -= optind;
4314 argv += optind;
4316 if (diff_context == -1)
4317 diff_context = 3;
4318 else if (!show_patch)
4319 errx(1, "-C requires -p");
4321 if (one_line && (show_patch || show_changed_paths))
4322 errx(1, "cannot use -s with -p or -P");
4324 cwd = getcwd(NULL, 0);
4325 if (cwd == NULL) {
4326 error = got_error_from_errno("getcwd");
4327 goto done;
4330 if (repo_path == NULL) {
4331 error = got_worktree_open(&worktree, cwd);
4332 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4333 goto done;
4334 error = NULL;
4337 if (argc == 1) {
4338 if (worktree) {
4339 error = got_worktree_resolve_path(&path, worktree,
4340 argv[0]);
4341 if (error)
4342 goto done;
4343 } else {
4344 path = strdup(argv[0]);
4345 if (path == NULL) {
4346 error = got_error_from_errno("strdup");
4347 goto done;
4350 } else if (argc != 0)
4351 usage_log();
4353 if (repo_path == NULL) {
4354 repo_path = worktree ?
4355 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4357 if (repo_path == NULL) {
4358 error = got_error_from_errno("strdup");
4359 goto done;
4362 error = got_repo_open(&repo, repo_path, NULL);
4363 if (error != NULL)
4364 goto done;
4366 error = apply_unveil(got_repo_get_path(repo), 1,
4367 worktree ? got_worktree_get_root_path(worktree) : NULL);
4368 if (error)
4369 goto done;
4371 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4372 if (error)
4373 goto done;
4375 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4376 if (error)
4377 goto done;
4379 if (start_commit == NULL) {
4380 struct got_reference *head_ref;
4381 struct got_commit_object *commit = NULL;
4382 error = got_ref_open(&head_ref, repo,
4383 worktree ? got_worktree_get_head_ref_name(worktree)
4384 : GOT_REF_HEAD, 0);
4385 if (error != NULL)
4386 goto done;
4387 error = got_ref_resolve(&start_id, repo, head_ref);
4388 got_ref_close(head_ref);
4389 if (error != NULL)
4390 goto done;
4391 error = got_object_open_as_commit(&commit, repo,
4392 start_id);
4393 if (error != NULL)
4394 goto done;
4395 got_object_commit_close(commit);
4396 } else {
4397 error = got_repo_match_object_id(&start_id, NULL,
4398 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4399 if (error != NULL)
4400 goto done;
4402 if (end_commit != NULL) {
4403 error = got_repo_match_object_id(&end_id, NULL,
4404 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4405 if (error != NULL)
4406 goto done;
4409 if (worktree) {
4411 * If a path was specified on the command line it was resolved
4412 * to a path in the work tree above. Prepend the work tree's
4413 * path prefix to obtain the corresponding in-repository path.
4415 if (path) {
4416 const char *prefix;
4417 prefix = got_worktree_get_path_prefix(worktree);
4418 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4419 (path[0] != '\0') ? "/" : "", path) == -1) {
4420 error = got_error_from_errno("asprintf");
4421 goto done;
4424 } else
4425 error = got_repo_map_path(&in_repo_path, repo,
4426 path ? path : "");
4427 if (error != NULL)
4428 goto done;
4429 if (in_repo_path) {
4430 free(path);
4431 path = in_repo_path;
4434 if (worktree) {
4435 /* Release work tree lock. */
4436 got_worktree_close(worktree);
4437 worktree = NULL;
4440 if (search_pattern && show_patch) {
4441 tmpfile = got_opentemp();
4442 if (tmpfile == NULL) {
4443 error = got_error_from_errno("got_opentemp");
4444 goto done;
4448 error = print_commits(start_id, end_id, repo, path ? path : "",
4449 show_changed_paths, show_patch, search_pattern, diff_context,
4450 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4451 tmpfile);
4452 done:
4453 free(path);
4454 free(repo_path);
4455 free(cwd);
4456 if (worktree)
4457 got_worktree_close(worktree);
4458 if (repo) {
4459 const struct got_error *close_err = got_repo_close(repo);
4460 if (error == NULL)
4461 error = close_err;
4463 if (refs_idmap)
4464 got_reflist_object_id_map_free(refs_idmap);
4465 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4466 error = got_error_from_errno("fclose");
4467 got_ref_list_free(&refs);
4468 return error;
4471 __dead static void
4472 usage_diff(void)
4474 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4475 "[-r repository-path] [-s] [-w] [-P] "
4476 "[object1 object2 | path ...]\n", getprogname());
4477 exit(1);
4480 struct print_diff_arg {
4481 struct got_repository *repo;
4482 struct got_worktree *worktree;
4483 int diff_context;
4484 const char *id_str;
4485 int header_shown;
4486 int diff_staged;
4487 int ignore_whitespace;
4488 int force_text_diff;
4492 * Create a file which contains the target path of a symlink so we can feed
4493 * it as content to the diff engine.
4495 static const struct got_error *
4496 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4497 const char *abspath)
4499 const struct got_error *err = NULL;
4500 char target_path[PATH_MAX];
4501 ssize_t target_len, outlen;
4503 *fd = -1;
4505 if (dirfd != -1) {
4506 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4507 if (target_len == -1)
4508 return got_error_from_errno2("readlinkat", abspath);
4509 } else {
4510 target_len = readlink(abspath, target_path, PATH_MAX);
4511 if (target_len == -1)
4512 return got_error_from_errno2("readlink", abspath);
4515 *fd = got_opentempfd();
4516 if (*fd == -1)
4517 return got_error_from_errno("got_opentempfd");
4519 outlen = write(*fd, target_path, target_len);
4520 if (outlen == -1) {
4521 err = got_error_from_errno("got_opentempfd");
4522 goto done;
4525 if (lseek(*fd, 0, SEEK_SET) == -1) {
4526 err = got_error_from_errno2("lseek", abspath);
4527 goto done;
4529 done:
4530 if (err) {
4531 close(*fd);
4532 *fd = -1;
4534 return err;
4537 static const struct got_error *
4538 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4539 const char *path, struct got_object_id *blob_id,
4540 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4541 int dirfd, const char *de_name)
4543 struct print_diff_arg *a = arg;
4544 const struct got_error *err = NULL;
4545 struct got_blob_object *blob1 = NULL;
4546 int fd = -1;
4547 FILE *f1 = NULL, *f2 = NULL;
4548 char *abspath = NULL, *label1 = NULL;
4549 struct stat sb;
4550 off_t size1 = 0;
4552 if (a->diff_staged) {
4553 if (staged_status != GOT_STATUS_MODIFY &&
4554 staged_status != GOT_STATUS_ADD &&
4555 staged_status != GOT_STATUS_DELETE)
4556 return NULL;
4557 } else {
4558 if (staged_status == GOT_STATUS_DELETE)
4559 return NULL;
4560 if (status == GOT_STATUS_NONEXISTENT)
4561 return got_error_set_errno(ENOENT, path);
4562 if (status != GOT_STATUS_MODIFY &&
4563 status != GOT_STATUS_ADD &&
4564 status != GOT_STATUS_DELETE &&
4565 status != GOT_STATUS_CONFLICT)
4566 return NULL;
4569 if (!a->header_shown) {
4570 printf("diff %s %s%s\n", a->id_str,
4571 got_worktree_get_root_path(a->worktree),
4572 a->diff_staged ? " (staged changes)" : "");
4573 a->header_shown = 1;
4576 if (a->diff_staged) {
4577 const char *label1 = NULL, *label2 = NULL;
4578 switch (staged_status) {
4579 case GOT_STATUS_MODIFY:
4580 label1 = path;
4581 label2 = path;
4582 break;
4583 case GOT_STATUS_ADD:
4584 label2 = path;
4585 break;
4586 case GOT_STATUS_DELETE:
4587 label1 = path;
4588 break;
4589 default:
4590 return got_error(GOT_ERR_FILE_STATUS);
4592 f1 = got_opentemp();
4593 if (f1 == NULL) {
4594 err = got_error_from_errno("got_opentemp");
4595 goto done;
4597 f2 = got_opentemp();
4598 if (f2 == NULL) {
4599 err = got_error_from_errno("got_opentemp");
4600 goto done;
4602 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4603 blob_id, staged_blob_id, label1, label2, a->diff_context,
4604 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4605 goto done;
4608 if (staged_status == GOT_STATUS_ADD ||
4609 staged_status == GOT_STATUS_MODIFY) {
4610 char *id_str;
4611 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4612 8192);
4613 if (err)
4614 goto done;
4615 err = got_object_id_str(&id_str, staged_blob_id);
4616 if (err)
4617 goto done;
4618 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4619 err = got_error_from_errno("asprintf");
4620 free(id_str);
4621 goto done;
4623 free(id_str);
4624 } else if (status != GOT_STATUS_ADD) {
4625 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4626 if (err)
4627 goto done;
4630 if (status != GOT_STATUS_DELETE) {
4631 if (asprintf(&abspath, "%s/%s",
4632 got_worktree_get_root_path(a->worktree), path) == -1) {
4633 err = got_error_from_errno("asprintf");
4634 goto done;
4637 if (dirfd != -1) {
4638 fd = openat(dirfd, de_name,
4639 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4640 if (fd == -1) {
4641 if (!got_err_open_nofollow_on_symlink()) {
4642 err = got_error_from_errno2("openat",
4643 abspath);
4644 goto done;
4646 err = get_symlink_target_file(&fd, dirfd,
4647 de_name, abspath);
4648 if (err)
4649 goto done;
4651 } else {
4652 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4653 if (fd == -1) {
4654 if (!got_err_open_nofollow_on_symlink()) {
4655 err = got_error_from_errno2("open",
4656 abspath);
4657 goto done;
4659 err = get_symlink_target_file(&fd, dirfd,
4660 de_name, abspath);
4661 if (err)
4662 goto done;
4665 if (fstat(fd, &sb) == -1) {
4666 err = got_error_from_errno2("fstat", abspath);
4667 goto done;
4669 f2 = fdopen(fd, "r");
4670 if (f2 == NULL) {
4671 err = got_error_from_errno2("fdopen", abspath);
4672 goto done;
4674 fd = -1;
4675 } else
4676 sb.st_size = 0;
4678 if (blob1) {
4679 f1 = got_opentemp();
4680 if (f1 == NULL) {
4681 err = got_error_from_errno("got_opentemp");
4682 goto done;
4684 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4685 blob1);
4686 if (err)
4687 goto done;
4690 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4691 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4692 stdout);
4693 done:
4694 if (blob1)
4695 got_object_blob_close(blob1);
4696 if (f1 && fclose(f1) == EOF && err == NULL)
4697 err = got_error_from_errno("fclose");
4698 if (f2 && fclose(f2) == EOF && err == NULL)
4699 err = got_error_from_errno("fclose");
4700 if (fd != -1 && close(fd) == -1 && err == NULL)
4701 err = got_error_from_errno("close");
4702 free(abspath);
4703 return err;
4706 static const struct got_error *
4707 cmd_diff(int argc, char *argv[])
4709 const struct got_error *error;
4710 struct got_repository *repo = NULL;
4711 struct got_worktree *worktree = NULL;
4712 char *cwd = NULL, *repo_path = NULL;
4713 const char *commit_args[2] = { NULL, NULL };
4714 int ncommit_args = 0;
4715 struct got_object_id *ids[2] = { NULL, NULL };
4716 char *labels[2] = { NULL, NULL };
4717 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4718 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4719 int force_text_diff = 0, force_path = 0, rflag = 0;
4720 const char *errstr;
4721 struct got_reflist_head refs;
4722 struct got_pathlist_head paths;
4723 struct got_pathlist_entry *pe;
4724 FILE *f1 = NULL, *f2 = NULL;
4726 TAILQ_INIT(&refs);
4727 TAILQ_INIT(&paths);
4729 #ifndef PROFILE
4730 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4731 NULL) == -1)
4732 err(1, "pledge");
4733 #endif
4735 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4736 switch (ch) {
4737 case 'a':
4738 force_text_diff = 1;
4739 break;
4740 case 'c':
4741 if (ncommit_args >= 2)
4742 errx(1, "too many -c options used");
4743 commit_args[ncommit_args++] = optarg;
4744 break;
4745 case 'C':
4746 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4747 &errstr);
4748 if (errstr != NULL)
4749 errx(1, "number of context lines is %s: %s",
4750 errstr, optarg);
4751 break;
4752 case 'r':
4753 repo_path = realpath(optarg, NULL);
4754 if (repo_path == NULL)
4755 return got_error_from_errno2("realpath",
4756 optarg);
4757 got_path_strip_trailing_slashes(repo_path);
4758 rflag = 1;
4759 break;
4760 case 's':
4761 diff_staged = 1;
4762 break;
4763 case 'w':
4764 ignore_whitespace = 1;
4765 break;
4766 case 'P':
4767 force_path = 1;
4768 break;
4769 default:
4770 usage_diff();
4771 /* NOTREACHED */
4775 argc -= optind;
4776 argv += optind;
4778 cwd = getcwd(NULL, 0);
4779 if (cwd == NULL) {
4780 error = got_error_from_errno("getcwd");
4781 goto done;
4784 if (repo_path == NULL) {
4785 error = got_worktree_open(&worktree, cwd);
4786 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4787 goto done;
4788 else
4789 error = NULL;
4790 if (worktree) {
4791 repo_path =
4792 strdup(got_worktree_get_repo_path(worktree));
4793 if (repo_path == NULL) {
4794 error = got_error_from_errno("strdup");
4795 goto done;
4797 } else {
4798 repo_path = strdup(cwd);
4799 if (repo_path == NULL) {
4800 error = got_error_from_errno("strdup");
4801 goto done;
4806 error = got_repo_open(&repo, repo_path, NULL);
4807 free(repo_path);
4808 if (error != NULL)
4809 goto done;
4811 if (rflag || worktree == NULL || ncommit_args > 0) {
4812 if (force_path) {
4813 error = got_error_msg(GOT_ERR_NOT_IMPL,
4814 "-P option can only be used when diffing "
4815 "a work tree");
4816 goto done;
4818 if (diff_staged) {
4819 error = got_error_msg(GOT_ERR_NOT_IMPL,
4820 "-s option can only be used when diffing "
4821 "a work tree");
4822 goto done;
4826 error = apply_unveil(got_repo_get_path(repo), 1,
4827 worktree ? got_worktree_get_root_path(worktree) : NULL);
4828 if (error)
4829 goto done;
4831 if ((!force_path && argc == 2) || ncommit_args > 0) {
4832 int obj_type = (ncommit_args > 0 ?
4833 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4834 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4835 NULL);
4836 if (error)
4837 goto done;
4838 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4839 const char *arg;
4840 if (ncommit_args > 0)
4841 arg = commit_args[i];
4842 else
4843 arg = argv[i];
4844 error = got_repo_match_object_id(&ids[i], &labels[i],
4845 arg, obj_type, &refs, repo);
4846 if (error) {
4847 if (error->code != GOT_ERR_NOT_REF &&
4848 error->code != GOT_ERR_NO_OBJ)
4849 goto done;
4850 if (ncommit_args > 0)
4851 goto done;
4852 error = NULL;
4853 break;
4858 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4859 struct print_diff_arg arg;
4860 char *id_str;
4862 if (worktree == NULL) {
4863 if (argc == 2 && ids[0] == NULL) {
4864 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4865 goto done;
4866 } else if (argc == 2 && ids[1] == NULL) {
4867 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4868 goto done;
4869 } else if (argc > 0) {
4870 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4871 "%s", "specified paths cannot be resolved");
4872 goto done;
4873 } else {
4874 error = got_error(GOT_ERR_NOT_WORKTREE);
4875 goto done;
4879 error = get_worktree_paths_from_argv(&paths, argc, argv,
4880 worktree);
4881 if (error)
4882 goto done;
4884 error = got_object_id_str(&id_str,
4885 got_worktree_get_base_commit_id(worktree));
4886 if (error)
4887 goto done;
4888 arg.repo = repo;
4889 arg.worktree = worktree;
4890 arg.diff_context = diff_context;
4891 arg.id_str = id_str;
4892 arg.header_shown = 0;
4893 arg.diff_staged = diff_staged;
4894 arg.ignore_whitespace = ignore_whitespace;
4895 arg.force_text_diff = force_text_diff;
4897 error = got_worktree_status(worktree, &paths, repo, 0,
4898 print_diff, &arg, check_cancelled, NULL);
4899 free(id_str);
4900 goto done;
4903 if (ncommit_args == 1) {
4904 struct got_commit_object *commit;
4905 error = got_object_open_as_commit(&commit, repo, ids[0]);
4906 if (error)
4907 goto done;
4909 labels[1] = labels[0];
4910 ids[1] = ids[0];
4911 if (got_object_commit_get_nparents(commit) > 0) {
4912 const struct got_object_id_queue *pids;
4913 struct got_object_qid *pid;
4914 pids = got_object_commit_get_parent_ids(commit);
4915 pid = STAILQ_FIRST(pids);
4916 ids[0] = got_object_id_dup(&pid->id);
4917 if (ids[0] == NULL) {
4918 error = got_error_from_errno(
4919 "got_object_id_dup");
4920 got_object_commit_close(commit);
4921 goto done;
4923 error = got_object_id_str(&labels[0], ids[0]);
4924 if (error) {
4925 got_object_commit_close(commit);
4926 goto done;
4928 } else {
4929 ids[0] = NULL;
4930 labels[0] = strdup("/dev/null");
4931 if (labels[0] == NULL) {
4932 error = got_error_from_errno("strdup");
4933 got_object_commit_close(commit);
4934 goto done;
4938 got_object_commit_close(commit);
4941 if (ncommit_args == 0 && argc > 2) {
4942 error = got_error_msg(GOT_ERR_BAD_PATH,
4943 "path arguments cannot be used when diffing two objects");
4944 goto done;
4947 if (ids[0]) {
4948 error = got_object_get_type(&type1, repo, ids[0]);
4949 if (error)
4950 goto done;
4953 error = got_object_get_type(&type2, repo, ids[1]);
4954 if (error)
4955 goto done;
4956 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4957 error = got_error(GOT_ERR_OBJ_TYPE);
4958 goto done;
4960 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4961 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4962 "path arguments cannot be used when diffing blobs");
4963 goto done;
4966 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4967 char *in_repo_path;
4968 struct got_pathlist_entry *new;
4969 if (worktree) {
4970 const char *prefix;
4971 char *p;
4972 error = got_worktree_resolve_path(&p, worktree,
4973 argv[i]);
4974 if (error)
4975 goto done;
4976 prefix = got_worktree_get_path_prefix(worktree);
4977 while (prefix[0] == '/')
4978 prefix++;
4979 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4980 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4981 p) == -1) {
4982 error = got_error_from_errno("asprintf");
4983 free(p);
4984 goto done;
4986 free(p);
4987 } else {
4988 char *mapped_path, *s;
4989 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4990 if (error)
4991 goto done;
4992 s = mapped_path;
4993 while (s[0] == '/')
4994 s++;
4995 in_repo_path = strdup(s);
4996 if (in_repo_path == NULL) {
4997 error = got_error_from_errno("asprintf");
4998 free(mapped_path);
4999 goto done;
5001 free(mapped_path);
5004 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5005 if (error || new == NULL /* duplicate */)
5006 free(in_repo_path);
5007 if (error)
5008 goto done;
5011 if (worktree) {
5012 /* Release work tree lock. */
5013 got_worktree_close(worktree);
5014 worktree = NULL;
5017 f1 = got_opentemp();
5018 if (f1 == NULL) {
5019 error = got_error_from_errno("got_opentemp");
5020 goto done;
5023 f2 = got_opentemp();
5024 if (f2 == NULL) {
5025 error = got_error_from_errno("got_opentemp");
5026 goto done;
5029 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5030 case GOT_OBJ_TYPE_BLOB:
5031 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5032 ids[0], ids[1], NULL, NULL, diff_context,
5033 ignore_whitespace, force_text_diff, repo, stdout);
5034 break;
5035 case GOT_OBJ_TYPE_TREE:
5036 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5037 ids[0], ids[1], &paths, "", "", diff_context,
5038 ignore_whitespace, force_text_diff, repo, stdout);
5039 break;
5040 case GOT_OBJ_TYPE_COMMIT:
5041 printf("diff %s %s\n", labels[0], labels[1]);
5042 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5043 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5044 force_text_diff, repo, stdout);
5045 break;
5046 default:
5047 error = got_error(GOT_ERR_OBJ_TYPE);
5049 done:
5050 free(labels[0]);
5051 free(labels[1]);
5052 free(ids[0]);
5053 free(ids[1]);
5054 if (worktree)
5055 got_worktree_close(worktree);
5056 if (repo) {
5057 const struct got_error *close_err = got_repo_close(repo);
5058 if (error == NULL)
5059 error = close_err;
5061 TAILQ_FOREACH(pe, &paths, entry)
5062 free((char *)pe->path);
5063 got_pathlist_free(&paths);
5064 got_ref_list_free(&refs);
5065 if (f1 && fclose(f1) == EOF && error == NULL)
5066 error = got_error_from_errno("fclose");
5067 if (f2 && fclose(f2) == EOF && error == NULL)
5068 error = got_error_from_errno("fclose");
5069 return error;
5072 __dead static void
5073 usage_blame(void)
5075 fprintf(stderr,
5076 "usage: %s blame [-c commit] [-r repository-path] path\n",
5077 getprogname());
5078 exit(1);
5081 struct blame_line {
5082 int annotated;
5083 char *id_str;
5084 char *committer;
5085 char datebuf[11]; /* YYYY-MM-DD + NUL */
5088 struct blame_cb_args {
5089 struct blame_line *lines;
5090 int nlines;
5091 int nlines_prec;
5092 int lineno_cur;
5093 off_t *line_offsets;
5094 FILE *f;
5095 struct got_repository *repo;
5098 static const struct got_error *
5099 blame_cb(void *arg, int nlines, int lineno,
5100 struct got_commit_object *commit, struct got_object_id *id)
5102 const struct got_error *err = NULL;
5103 struct blame_cb_args *a = arg;
5104 struct blame_line *bline;
5105 char *line = NULL;
5106 size_t linesize = 0;
5107 off_t offset;
5108 struct tm tm;
5109 time_t committer_time;
5111 if (nlines != a->nlines ||
5112 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5113 return got_error(GOT_ERR_RANGE);
5115 if (sigint_received)
5116 return got_error(GOT_ERR_ITER_COMPLETED);
5118 if (lineno == -1)
5119 return NULL; /* no change in this commit */
5121 /* Annotate this line. */
5122 bline = &a->lines[lineno - 1];
5123 if (bline->annotated)
5124 return NULL;
5125 err = got_object_id_str(&bline->id_str, id);
5126 if (err)
5127 return err;
5129 bline->committer = strdup(got_object_commit_get_committer(commit));
5130 if (bline->committer == NULL) {
5131 err = got_error_from_errno("strdup");
5132 goto done;
5135 committer_time = got_object_commit_get_committer_time(commit);
5136 if (gmtime_r(&committer_time, &tm) == NULL)
5137 return got_error_from_errno("gmtime_r");
5138 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5139 &tm) == 0) {
5140 err = got_error(GOT_ERR_NO_SPACE);
5141 goto done;
5143 bline->annotated = 1;
5145 /* Print lines annotated so far. */
5146 bline = &a->lines[a->lineno_cur - 1];
5147 if (!bline->annotated)
5148 goto done;
5150 offset = a->line_offsets[a->lineno_cur - 1];
5151 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5152 err = got_error_from_errno("fseeko");
5153 goto done;
5156 while (bline->annotated) {
5157 char *smallerthan, *at, *nl, *committer;
5158 size_t len;
5160 if (getline(&line, &linesize, a->f) == -1) {
5161 if (ferror(a->f))
5162 err = got_error_from_errno("getline");
5163 break;
5166 committer = bline->committer;
5167 smallerthan = strchr(committer, '<');
5168 if (smallerthan && smallerthan[1] != '\0')
5169 committer = smallerthan + 1;
5170 at = strchr(committer, '@');
5171 if (at)
5172 *at = '\0';
5173 len = strlen(committer);
5174 if (len >= 9)
5175 committer[8] = '\0';
5177 nl = strchr(line, '\n');
5178 if (nl)
5179 *nl = '\0';
5180 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5181 bline->id_str, bline->datebuf, committer, line);
5183 a->lineno_cur++;
5184 bline = &a->lines[a->lineno_cur - 1];
5186 done:
5187 free(line);
5188 return err;
5191 static const struct got_error *
5192 cmd_blame(int argc, char *argv[])
5194 const struct got_error *error;
5195 struct got_repository *repo = NULL;
5196 struct got_worktree *worktree = NULL;
5197 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5198 char *link_target = NULL;
5199 struct got_object_id *obj_id = NULL;
5200 struct got_object_id *commit_id = NULL;
5201 struct got_commit_object *commit = NULL;
5202 struct got_blob_object *blob = NULL;
5203 char *commit_id_str = NULL;
5204 struct blame_cb_args bca;
5205 int ch, obj_type, i;
5206 off_t filesize;
5208 memset(&bca, 0, sizeof(bca));
5210 #ifndef PROFILE
5211 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5212 NULL) == -1)
5213 err(1, "pledge");
5214 #endif
5216 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5217 switch (ch) {
5218 case 'c':
5219 commit_id_str = optarg;
5220 break;
5221 case 'r':
5222 repo_path = realpath(optarg, NULL);
5223 if (repo_path == NULL)
5224 return got_error_from_errno2("realpath",
5225 optarg);
5226 got_path_strip_trailing_slashes(repo_path);
5227 break;
5228 default:
5229 usage_blame();
5230 /* NOTREACHED */
5234 argc -= optind;
5235 argv += optind;
5237 if (argc == 1)
5238 path = argv[0];
5239 else
5240 usage_blame();
5242 cwd = getcwd(NULL, 0);
5243 if (cwd == NULL) {
5244 error = got_error_from_errno("getcwd");
5245 goto done;
5247 if (repo_path == NULL) {
5248 error = got_worktree_open(&worktree, cwd);
5249 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5250 goto done;
5251 else
5252 error = NULL;
5253 if (worktree) {
5254 repo_path =
5255 strdup(got_worktree_get_repo_path(worktree));
5256 if (repo_path == NULL) {
5257 error = got_error_from_errno("strdup");
5258 if (error)
5259 goto done;
5261 } else {
5262 repo_path = strdup(cwd);
5263 if (repo_path == NULL) {
5264 error = got_error_from_errno("strdup");
5265 goto done;
5270 error = got_repo_open(&repo, repo_path, NULL);
5271 if (error != NULL)
5272 goto done;
5274 if (worktree) {
5275 const char *prefix = got_worktree_get_path_prefix(worktree);
5276 char *p;
5278 error = got_worktree_resolve_path(&p, worktree, path);
5279 if (error)
5280 goto done;
5281 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5282 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5283 p) == -1) {
5284 error = got_error_from_errno("asprintf");
5285 free(p);
5286 goto done;
5288 free(p);
5289 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5290 } else {
5291 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5292 if (error)
5293 goto done;
5294 error = got_repo_map_path(&in_repo_path, repo, path);
5296 if (error)
5297 goto done;
5299 if (commit_id_str == NULL) {
5300 struct got_reference *head_ref;
5301 error = got_ref_open(&head_ref, repo, worktree ?
5302 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5303 if (error != NULL)
5304 goto done;
5305 error = got_ref_resolve(&commit_id, repo, head_ref);
5306 got_ref_close(head_ref);
5307 if (error != NULL)
5308 goto done;
5309 } else {
5310 struct got_reflist_head refs;
5311 TAILQ_INIT(&refs);
5312 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5313 NULL);
5314 if (error)
5315 goto done;
5316 error = got_repo_match_object_id(&commit_id, NULL,
5317 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5318 got_ref_list_free(&refs);
5319 if (error)
5320 goto done;
5323 if (worktree) {
5324 /* Release work tree lock. */
5325 got_worktree_close(worktree);
5326 worktree = NULL;
5329 error = got_object_open_as_commit(&commit, repo, commit_id);
5330 if (error)
5331 goto done;
5333 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5334 commit, repo);
5335 if (error)
5336 goto done;
5338 error = got_object_id_by_path(&obj_id, repo, commit,
5339 link_target ? link_target : in_repo_path);
5340 if (error)
5341 goto done;
5343 error = got_object_get_type(&obj_type, repo, obj_id);
5344 if (error)
5345 goto done;
5347 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5348 error = got_error_path(link_target ? link_target : in_repo_path,
5349 GOT_ERR_OBJ_TYPE);
5350 goto done;
5353 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5354 if (error)
5355 goto done;
5356 bca.f = got_opentemp();
5357 if (bca.f == NULL) {
5358 error = got_error_from_errno("got_opentemp");
5359 goto done;
5361 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5362 &bca.line_offsets, bca.f, blob);
5363 if (error || bca.nlines == 0)
5364 goto done;
5366 /* Don't include \n at EOF in the blame line count. */
5367 if (bca.line_offsets[bca.nlines - 1] == filesize)
5368 bca.nlines--;
5370 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5371 if (bca.lines == NULL) {
5372 error = got_error_from_errno("calloc");
5373 goto done;
5375 bca.lineno_cur = 1;
5376 bca.nlines_prec = 0;
5377 i = bca.nlines;
5378 while (i > 0) {
5379 i /= 10;
5380 bca.nlines_prec++;
5382 bca.repo = repo;
5384 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5385 repo, blame_cb, &bca, check_cancelled, NULL);
5386 done:
5387 free(in_repo_path);
5388 free(link_target);
5389 free(repo_path);
5390 free(cwd);
5391 free(commit_id);
5392 free(obj_id);
5393 if (commit)
5394 got_object_commit_close(commit);
5395 if (blob)
5396 got_object_blob_close(blob);
5397 if (worktree)
5398 got_worktree_close(worktree);
5399 if (repo) {
5400 const struct got_error *close_err = got_repo_close(repo);
5401 if (error == NULL)
5402 error = close_err;
5404 if (bca.lines) {
5405 for (i = 0; i < bca.nlines; i++) {
5406 struct blame_line *bline = &bca.lines[i];
5407 free(bline->id_str);
5408 free(bline->committer);
5410 free(bca.lines);
5412 free(bca.line_offsets);
5413 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5414 error = got_error_from_errno("fclose");
5415 return error;
5418 __dead static void
5419 usage_tree(void)
5421 fprintf(stderr,
5422 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5423 getprogname());
5424 exit(1);
5427 static const struct got_error *
5428 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5429 const char *root_path, struct got_repository *repo)
5431 const struct got_error *err = NULL;
5432 int is_root_path = (strcmp(path, root_path) == 0);
5433 const char *modestr = "";
5434 mode_t mode = got_tree_entry_get_mode(te);
5435 char *link_target = NULL;
5437 path += strlen(root_path);
5438 while (path[0] == '/')
5439 path++;
5441 if (got_object_tree_entry_is_submodule(te))
5442 modestr = "$";
5443 else if (S_ISLNK(mode)) {
5444 int i;
5446 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5447 if (err)
5448 return err;
5449 for (i = 0; i < strlen(link_target); i++) {
5450 if (!isprint((unsigned char)link_target[i]))
5451 link_target[i] = '?';
5454 modestr = "@";
5456 else if (S_ISDIR(mode))
5457 modestr = "/";
5458 else if (mode & S_IXUSR)
5459 modestr = "*";
5461 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5462 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5463 link_target ? " -> ": "", link_target ? link_target : "");
5465 free(link_target);
5466 return NULL;
5469 static const struct got_error *
5470 print_tree(const char *path, struct got_commit_object *commit,
5471 int show_ids, int recurse, const char *root_path,
5472 struct got_repository *repo)
5474 const struct got_error *err = NULL;
5475 struct got_object_id *tree_id = NULL;
5476 struct got_tree_object *tree = NULL;
5477 int nentries, i;
5479 err = got_object_id_by_path(&tree_id, repo, commit, path);
5480 if (err)
5481 goto done;
5483 err = got_object_open_as_tree(&tree, repo, tree_id);
5484 if (err)
5485 goto done;
5486 nentries = got_object_tree_get_nentries(tree);
5487 for (i = 0; i < nentries; i++) {
5488 struct got_tree_entry *te;
5489 char *id = NULL;
5491 if (sigint_received || sigpipe_received)
5492 break;
5494 te = got_object_tree_get_entry(tree, i);
5495 if (show_ids) {
5496 char *id_str;
5497 err = got_object_id_str(&id_str,
5498 got_tree_entry_get_id(te));
5499 if (err)
5500 goto done;
5501 if (asprintf(&id, "%s ", id_str) == -1) {
5502 err = got_error_from_errno("asprintf");
5503 free(id_str);
5504 goto done;
5506 free(id_str);
5508 err = print_entry(te, id, path, root_path, repo);
5509 free(id);
5510 if (err)
5511 goto done;
5513 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5514 char *child_path;
5515 if (asprintf(&child_path, "%s%s%s", path,
5516 path[0] == '/' && path[1] == '\0' ? "" : "/",
5517 got_tree_entry_get_name(te)) == -1) {
5518 err = got_error_from_errno("asprintf");
5519 goto done;
5521 err = print_tree(child_path, commit, show_ids, 1,
5522 root_path, repo);
5523 free(child_path);
5524 if (err)
5525 goto done;
5528 done:
5529 if (tree)
5530 got_object_tree_close(tree);
5531 free(tree_id);
5532 return err;
5535 static const struct got_error *
5536 cmd_tree(int argc, char *argv[])
5538 const struct got_error *error;
5539 struct got_repository *repo = NULL;
5540 struct got_worktree *worktree = NULL;
5541 const char *path, *refname = NULL;
5542 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5543 struct got_object_id *commit_id = NULL;
5544 struct got_commit_object *commit = NULL;
5545 char *commit_id_str = NULL;
5546 int show_ids = 0, recurse = 0;
5547 int ch;
5549 #ifndef PROFILE
5550 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5551 NULL) == -1)
5552 err(1, "pledge");
5553 #endif
5555 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5556 switch (ch) {
5557 case 'c':
5558 commit_id_str = optarg;
5559 break;
5560 case 'r':
5561 repo_path = realpath(optarg, NULL);
5562 if (repo_path == NULL)
5563 return got_error_from_errno2("realpath",
5564 optarg);
5565 got_path_strip_trailing_slashes(repo_path);
5566 break;
5567 case 'i':
5568 show_ids = 1;
5569 break;
5570 case 'R':
5571 recurse = 1;
5572 break;
5573 default:
5574 usage_tree();
5575 /* NOTREACHED */
5579 argc -= optind;
5580 argv += optind;
5582 if (argc == 1)
5583 path = argv[0];
5584 else if (argc > 1)
5585 usage_tree();
5586 else
5587 path = NULL;
5589 cwd = getcwd(NULL, 0);
5590 if (cwd == NULL) {
5591 error = got_error_from_errno("getcwd");
5592 goto done;
5594 if (repo_path == NULL) {
5595 error = got_worktree_open(&worktree, cwd);
5596 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5597 goto done;
5598 else
5599 error = NULL;
5600 if (worktree) {
5601 repo_path =
5602 strdup(got_worktree_get_repo_path(worktree));
5603 if (repo_path == NULL)
5604 error = got_error_from_errno("strdup");
5605 if (error)
5606 goto done;
5607 } else {
5608 repo_path = strdup(cwd);
5609 if (repo_path == NULL) {
5610 error = got_error_from_errno("strdup");
5611 goto done;
5616 error = got_repo_open(&repo, repo_path, NULL);
5617 if (error != NULL)
5618 goto done;
5620 if (worktree) {
5621 const char *prefix = got_worktree_get_path_prefix(worktree);
5622 char *p;
5624 if (path == NULL)
5625 path = "";
5626 error = got_worktree_resolve_path(&p, worktree, path);
5627 if (error)
5628 goto done;
5629 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5630 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5631 p) == -1) {
5632 error = got_error_from_errno("asprintf");
5633 free(p);
5634 goto done;
5636 free(p);
5637 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5638 if (error)
5639 goto done;
5640 } else {
5641 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5642 if (error)
5643 goto done;
5644 if (path == NULL)
5645 path = "/";
5646 error = got_repo_map_path(&in_repo_path, repo, path);
5647 if (error != NULL)
5648 goto done;
5651 if (commit_id_str == NULL) {
5652 struct got_reference *head_ref;
5653 if (worktree)
5654 refname = got_worktree_get_head_ref_name(worktree);
5655 else
5656 refname = GOT_REF_HEAD;
5657 error = got_ref_open(&head_ref, repo, refname, 0);
5658 if (error != NULL)
5659 goto done;
5660 error = got_ref_resolve(&commit_id, repo, head_ref);
5661 got_ref_close(head_ref);
5662 if (error != NULL)
5663 goto done;
5664 } else {
5665 struct got_reflist_head refs;
5666 TAILQ_INIT(&refs);
5667 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5668 NULL);
5669 if (error)
5670 goto done;
5671 error = got_repo_match_object_id(&commit_id, NULL,
5672 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5673 got_ref_list_free(&refs);
5674 if (error)
5675 goto done;
5678 if (worktree) {
5679 /* Release work tree lock. */
5680 got_worktree_close(worktree);
5681 worktree = NULL;
5684 error = got_object_open_as_commit(&commit, repo, commit_id);
5685 if (error)
5686 goto done;
5688 error = print_tree(in_repo_path, commit, show_ids, recurse,
5689 in_repo_path, repo);
5690 done:
5691 free(in_repo_path);
5692 free(repo_path);
5693 free(cwd);
5694 free(commit_id);
5695 if (commit)
5696 got_object_commit_close(commit);
5697 if (worktree)
5698 got_worktree_close(worktree);
5699 if (repo) {
5700 const struct got_error *close_err = got_repo_close(repo);
5701 if (error == NULL)
5702 error = close_err;
5704 return error;
5707 __dead static void
5708 usage_status(void)
5710 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5711 "[-S status-codes] [path ...]\n", getprogname());
5712 exit(1);
5715 struct got_status_arg {
5716 char *status_codes;
5717 int suppress;
5720 static const struct got_error *
5721 print_status(void *arg, unsigned char status, unsigned char staged_status,
5722 const char *path, struct got_object_id *blob_id,
5723 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5724 int dirfd, const char *de_name)
5726 struct got_status_arg *st = arg;
5728 if (status == staged_status && (status == GOT_STATUS_DELETE))
5729 status = GOT_STATUS_NO_CHANGE;
5730 if (st != NULL && st->status_codes) {
5731 size_t ncodes = strlen(st->status_codes);
5732 int i, j = 0;
5734 for (i = 0; i < ncodes ; i++) {
5735 if (st->suppress) {
5736 if (status == st->status_codes[i] ||
5737 staged_status == st->status_codes[i]) {
5738 j++;
5739 continue;
5741 } else {
5742 if (status == st->status_codes[i] ||
5743 staged_status == st->status_codes[i])
5744 break;
5748 if (st->suppress && j == 0)
5749 goto print;
5751 if (i == ncodes)
5752 return NULL;
5754 print:
5755 printf("%c%c %s\n", status, staged_status, path);
5756 return NULL;
5759 static const struct got_error *
5760 cmd_status(int argc, char *argv[])
5762 const struct got_error *error = NULL;
5763 struct got_repository *repo = NULL;
5764 struct got_worktree *worktree = NULL;
5765 struct got_status_arg st;
5766 char *cwd = NULL;
5767 struct got_pathlist_head paths;
5768 struct got_pathlist_entry *pe;
5769 int ch, i, no_ignores = 0;
5771 TAILQ_INIT(&paths);
5773 memset(&st, 0, sizeof(st));
5774 st.status_codes = NULL;
5775 st.suppress = 0;
5777 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5778 switch (ch) {
5779 case 'I':
5780 no_ignores = 1;
5781 break;
5782 case 'S':
5783 if (st.status_codes != NULL && st.suppress == 0)
5784 option_conflict('S', 's');
5785 st.suppress = 1;
5786 /* fallthrough */
5787 case 's':
5788 for (i = 0; i < strlen(optarg); i++) {
5789 switch (optarg[i]) {
5790 case GOT_STATUS_MODIFY:
5791 case GOT_STATUS_ADD:
5792 case GOT_STATUS_DELETE:
5793 case GOT_STATUS_CONFLICT:
5794 case GOT_STATUS_MISSING:
5795 case GOT_STATUS_OBSTRUCTED:
5796 case GOT_STATUS_UNVERSIONED:
5797 case GOT_STATUS_MODE_CHANGE:
5798 case GOT_STATUS_NONEXISTENT:
5799 break;
5800 default:
5801 errx(1, "invalid status code '%c'",
5802 optarg[i]);
5805 if (ch == 's' && st.suppress)
5806 option_conflict('s', 'S');
5807 st.status_codes = optarg;
5808 break;
5809 default:
5810 usage_status();
5811 /* NOTREACHED */
5815 argc -= optind;
5816 argv += optind;
5818 #ifndef PROFILE
5819 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5820 NULL) == -1)
5821 err(1, "pledge");
5822 #endif
5823 cwd = getcwd(NULL, 0);
5824 if (cwd == NULL) {
5825 error = got_error_from_errno("getcwd");
5826 goto done;
5829 error = got_worktree_open(&worktree, cwd);
5830 if (error) {
5831 if (error->code == GOT_ERR_NOT_WORKTREE)
5832 error = wrap_not_worktree_error(error, "status", cwd);
5833 goto done;
5836 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5837 NULL);
5838 if (error != NULL)
5839 goto done;
5841 error = apply_unveil(got_repo_get_path(repo), 1,
5842 got_worktree_get_root_path(worktree));
5843 if (error)
5844 goto done;
5846 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5847 if (error)
5848 goto done;
5850 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5851 print_status, &st, check_cancelled, NULL);
5852 done:
5853 TAILQ_FOREACH(pe, &paths, entry)
5854 free((char *)pe->path);
5855 got_pathlist_free(&paths);
5856 free(cwd);
5857 return error;
5860 __dead static void
5861 usage_ref(void)
5863 fprintf(stderr,
5864 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5865 "[-s reference] [-d] [name]\n",
5866 getprogname());
5867 exit(1);
5870 static const struct got_error *
5871 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5873 static const struct got_error *err = NULL;
5874 struct got_reflist_head refs;
5875 struct got_reflist_entry *re;
5877 TAILQ_INIT(&refs);
5878 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5879 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5880 repo);
5881 if (err)
5882 return err;
5884 TAILQ_FOREACH(re, &refs, entry) {
5885 char *refstr;
5886 refstr = got_ref_to_str(re->ref);
5887 if (refstr == NULL) {
5888 err = got_error_from_errno("got_ref_to_str");
5889 break;
5891 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5892 free(refstr);
5895 got_ref_list_free(&refs);
5896 return err;
5899 static const struct got_error *
5900 delete_ref_by_name(struct got_repository *repo, const char *refname)
5902 const struct got_error *err;
5903 struct got_reference *ref;
5905 err = got_ref_open(&ref, repo, refname, 0);
5906 if (err)
5907 return err;
5909 err = delete_ref(repo, ref);
5910 got_ref_close(ref);
5911 return err;
5914 static const struct got_error *
5915 add_ref(struct got_repository *repo, const char *refname, const char *target)
5917 const struct got_error *err = NULL;
5918 struct got_object_id *id = NULL;
5919 struct got_reference *ref = NULL;
5920 struct got_reflist_head refs;
5923 * Don't let the user create a reference name with a leading '-'.
5924 * While technically a valid reference name, this case is usually
5925 * an unintended typo.
5927 if (refname[0] == '-')
5928 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5930 TAILQ_INIT(&refs);
5931 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5932 if (err)
5933 goto done;
5934 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5935 &refs, repo);
5936 got_ref_list_free(&refs);
5937 if (err)
5938 goto done;
5940 err = got_ref_alloc(&ref, refname, id);
5941 if (err)
5942 goto done;
5944 err = got_ref_write(ref, repo);
5945 done:
5946 if (ref)
5947 got_ref_close(ref);
5948 free(id);
5949 return err;
5952 static const struct got_error *
5953 add_symref(struct got_repository *repo, const char *refname, const char *target)
5955 const struct got_error *err = NULL;
5956 struct got_reference *ref = NULL;
5957 struct got_reference *target_ref = NULL;
5960 * Don't let the user create a reference name with a leading '-'.
5961 * While technically a valid reference name, this case is usually
5962 * an unintended typo.
5964 if (refname[0] == '-')
5965 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5967 err = got_ref_open(&target_ref, repo, target, 0);
5968 if (err)
5969 return err;
5971 err = got_ref_alloc_symref(&ref, refname, target_ref);
5972 if (err)
5973 goto done;
5975 err = got_ref_write(ref, repo);
5976 done:
5977 if (target_ref)
5978 got_ref_close(target_ref);
5979 if (ref)
5980 got_ref_close(ref);
5981 return err;
5984 static const struct got_error *
5985 cmd_ref(int argc, char *argv[])
5987 const struct got_error *error = NULL;
5988 struct got_repository *repo = NULL;
5989 struct got_worktree *worktree = NULL;
5990 char *cwd = NULL, *repo_path = NULL;
5991 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5992 const char *obj_arg = NULL, *symref_target= NULL;
5993 char *refname = NULL;
5995 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5996 switch (ch) {
5997 case 'c':
5998 obj_arg = optarg;
5999 break;
6000 case 'd':
6001 do_delete = 1;
6002 break;
6003 case 'r':
6004 repo_path = realpath(optarg, NULL);
6005 if (repo_path == NULL)
6006 return got_error_from_errno2("realpath",
6007 optarg);
6008 got_path_strip_trailing_slashes(repo_path);
6009 break;
6010 case 'l':
6011 do_list = 1;
6012 break;
6013 case 's':
6014 symref_target = optarg;
6015 break;
6016 case 't':
6017 sort_by_time = 1;
6018 break;
6019 default:
6020 usage_ref();
6021 /* NOTREACHED */
6025 if (obj_arg && do_list)
6026 option_conflict('c', 'l');
6027 if (obj_arg && do_delete)
6028 option_conflict('c', 'd');
6029 if (obj_arg && symref_target)
6030 option_conflict('c', 's');
6031 if (symref_target && do_delete)
6032 option_conflict('s', 'd');
6033 if (symref_target && do_list)
6034 option_conflict('s', 'l');
6035 if (do_delete && do_list)
6036 option_conflict('d', 'l');
6037 if (sort_by_time && !do_list)
6038 errx(1, "-t option requires -l option");
6040 argc -= optind;
6041 argv += optind;
6043 if (do_list) {
6044 if (argc != 0 && argc != 1)
6045 usage_ref();
6046 if (argc == 1) {
6047 refname = strdup(argv[0]);
6048 if (refname == NULL) {
6049 error = got_error_from_errno("strdup");
6050 goto done;
6053 } else {
6054 if (argc != 1)
6055 usage_ref();
6056 refname = strdup(argv[0]);
6057 if (refname == NULL) {
6058 error = got_error_from_errno("strdup");
6059 goto done;
6063 if (refname)
6064 got_path_strip_trailing_slashes(refname);
6066 #ifndef PROFILE
6067 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6068 "sendfd unveil", NULL) == -1)
6069 err(1, "pledge");
6070 #endif
6071 cwd = getcwd(NULL, 0);
6072 if (cwd == NULL) {
6073 error = got_error_from_errno("getcwd");
6074 goto done;
6077 if (repo_path == NULL) {
6078 error = got_worktree_open(&worktree, cwd);
6079 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6080 goto done;
6081 else
6082 error = NULL;
6083 if (worktree) {
6084 repo_path =
6085 strdup(got_worktree_get_repo_path(worktree));
6086 if (repo_path == NULL)
6087 error = got_error_from_errno("strdup");
6088 if (error)
6089 goto done;
6090 } else {
6091 repo_path = strdup(cwd);
6092 if (repo_path == NULL) {
6093 error = got_error_from_errno("strdup");
6094 goto done;
6099 error = got_repo_open(&repo, repo_path, NULL);
6100 if (error != NULL)
6101 goto done;
6103 #ifndef PROFILE
6104 if (do_list) {
6105 /* Remove "cpath" promise. */
6106 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6107 NULL) == -1)
6108 err(1, "pledge");
6110 #endif
6112 error = apply_unveil(got_repo_get_path(repo), do_list,
6113 worktree ? got_worktree_get_root_path(worktree) : NULL);
6114 if (error)
6115 goto done;
6117 if (do_list)
6118 error = list_refs(repo, refname, sort_by_time);
6119 else if (do_delete)
6120 error = delete_ref_by_name(repo, refname);
6121 else if (symref_target)
6122 error = add_symref(repo, refname, symref_target);
6123 else {
6124 if (obj_arg == NULL)
6125 usage_ref();
6126 error = add_ref(repo, refname, obj_arg);
6128 done:
6129 free(refname);
6130 if (repo) {
6131 const struct got_error *close_err = got_repo_close(repo);
6132 if (error == NULL)
6133 error = close_err;
6135 if (worktree)
6136 got_worktree_close(worktree);
6137 free(cwd);
6138 free(repo_path);
6139 return error;
6142 __dead static void
6143 usage_branch(void)
6145 fprintf(stderr,
6146 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6147 "[-n] [name]\n", getprogname());
6148 exit(1);
6151 static const struct got_error *
6152 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6153 struct got_reference *ref)
6155 const struct got_error *err = NULL;
6156 const char *refname, *marker = " ";
6157 char *refstr;
6159 refname = got_ref_get_name(ref);
6160 if (worktree && strcmp(refname,
6161 got_worktree_get_head_ref_name(worktree)) == 0) {
6162 struct got_object_id *id = NULL;
6164 err = got_ref_resolve(&id, repo, ref);
6165 if (err)
6166 return err;
6167 if (got_object_id_cmp(id,
6168 got_worktree_get_base_commit_id(worktree)) == 0)
6169 marker = "* ";
6170 else
6171 marker = "~ ";
6172 free(id);
6175 if (strncmp(refname, "refs/heads/", 11) == 0)
6176 refname += 11;
6177 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6178 refname += 18;
6179 if (strncmp(refname, "refs/remotes/", 13) == 0)
6180 refname += 13;
6182 refstr = got_ref_to_str(ref);
6183 if (refstr == NULL)
6184 return got_error_from_errno("got_ref_to_str");
6186 printf("%s%s: %s\n", marker, refname, refstr);
6187 free(refstr);
6188 return NULL;
6191 static const struct got_error *
6192 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6194 const char *refname;
6196 if (worktree == NULL)
6197 return got_error(GOT_ERR_NOT_WORKTREE);
6199 refname = got_worktree_get_head_ref_name(worktree);
6201 if (strncmp(refname, "refs/heads/", 11) == 0)
6202 refname += 11;
6203 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6204 refname += 18;
6206 printf("%s\n", refname);
6208 return NULL;
6211 static const struct got_error *
6212 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6213 int sort_by_time)
6215 static const struct got_error *err = NULL;
6216 struct got_reflist_head refs;
6217 struct got_reflist_entry *re;
6218 struct got_reference *temp_ref = NULL;
6219 int rebase_in_progress, histedit_in_progress;
6221 TAILQ_INIT(&refs);
6223 if (worktree) {
6224 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6225 worktree);
6226 if (err)
6227 return err;
6229 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6230 worktree);
6231 if (err)
6232 return err;
6234 if (rebase_in_progress || histedit_in_progress) {
6235 err = got_ref_open(&temp_ref, repo,
6236 got_worktree_get_head_ref_name(worktree), 0);
6237 if (err)
6238 return err;
6239 list_branch(repo, worktree, temp_ref);
6240 got_ref_close(temp_ref);
6244 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6245 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6246 repo);
6247 if (err)
6248 return err;
6250 TAILQ_FOREACH(re, &refs, entry)
6251 list_branch(repo, worktree, re->ref);
6253 got_ref_list_free(&refs);
6255 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6256 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6257 repo);
6258 if (err)
6259 return err;
6261 TAILQ_FOREACH(re, &refs, entry)
6262 list_branch(repo, worktree, re->ref);
6264 got_ref_list_free(&refs);
6266 return NULL;
6269 static const struct got_error *
6270 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6271 const char *branch_name)
6273 const struct got_error *err = NULL;
6274 struct got_reference *ref = NULL;
6275 char *refname, *remote_refname = NULL;
6277 if (strncmp(branch_name, "refs/", 5) == 0)
6278 branch_name += 5;
6279 if (strncmp(branch_name, "heads/", 6) == 0)
6280 branch_name += 6;
6281 else if (strncmp(branch_name, "remotes/", 8) == 0)
6282 branch_name += 8;
6284 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6285 return got_error_from_errno("asprintf");
6287 if (asprintf(&remote_refname, "refs/remotes/%s",
6288 branch_name) == -1) {
6289 err = got_error_from_errno("asprintf");
6290 goto done;
6293 err = got_ref_open(&ref, repo, refname, 0);
6294 if (err) {
6295 const struct got_error *err2;
6296 if (err->code != GOT_ERR_NOT_REF)
6297 goto done;
6299 * Keep 'err' intact such that if neither branch exists
6300 * we report "refs/heads" rather than "refs/remotes" in
6301 * our error message.
6303 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6304 if (err2)
6305 goto done;
6306 err = NULL;
6309 if (worktree &&
6310 strcmp(got_worktree_get_head_ref_name(worktree),
6311 got_ref_get_name(ref)) == 0) {
6312 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6313 "will not delete this work tree's current branch");
6314 goto done;
6317 err = delete_ref(repo, ref);
6318 done:
6319 if (ref)
6320 got_ref_close(ref);
6321 free(refname);
6322 free(remote_refname);
6323 return err;
6326 static const struct got_error *
6327 add_branch(struct got_repository *repo, const char *branch_name,
6328 struct got_object_id *base_commit_id)
6330 const struct got_error *err = NULL;
6331 struct got_reference *ref = NULL;
6332 char *base_refname = NULL, *refname = NULL;
6335 * Don't let the user create a branch name with a leading '-'.
6336 * While technically a valid reference name, this case is usually
6337 * an unintended typo.
6339 if (branch_name[0] == '-')
6340 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6342 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6343 branch_name += 11;
6345 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6346 err = got_error_from_errno("asprintf");
6347 goto done;
6350 err = got_ref_open(&ref, repo, refname, 0);
6351 if (err == NULL) {
6352 err = got_error(GOT_ERR_BRANCH_EXISTS);
6353 goto done;
6354 } else if (err->code != GOT_ERR_NOT_REF)
6355 goto done;
6357 err = got_ref_alloc(&ref, refname, base_commit_id);
6358 if (err)
6359 goto done;
6361 err = got_ref_write(ref, repo);
6362 done:
6363 if (ref)
6364 got_ref_close(ref);
6365 free(base_refname);
6366 free(refname);
6367 return err;
6370 static const struct got_error *
6371 cmd_branch(int argc, char *argv[])
6373 const struct got_error *error = NULL;
6374 struct got_repository *repo = NULL;
6375 struct got_worktree *worktree = NULL;
6376 char *cwd = NULL, *repo_path = NULL;
6377 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6378 const char *delref = NULL, *commit_id_arg = NULL;
6379 struct got_reference *ref = NULL;
6380 struct got_pathlist_head paths;
6381 struct got_pathlist_entry *pe;
6382 struct got_object_id *commit_id = NULL;
6383 char *commit_id_str = NULL;
6385 TAILQ_INIT(&paths);
6387 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6388 switch (ch) {
6389 case 'c':
6390 commit_id_arg = optarg;
6391 break;
6392 case 'd':
6393 delref = optarg;
6394 break;
6395 case 'r':
6396 repo_path = realpath(optarg, NULL);
6397 if (repo_path == NULL)
6398 return got_error_from_errno2("realpath",
6399 optarg);
6400 got_path_strip_trailing_slashes(repo_path);
6401 break;
6402 case 'l':
6403 do_list = 1;
6404 break;
6405 case 'n':
6406 do_update = 0;
6407 break;
6408 case 't':
6409 sort_by_time = 1;
6410 break;
6411 default:
6412 usage_branch();
6413 /* NOTREACHED */
6417 if (do_list && delref)
6418 option_conflict('l', 'd');
6419 if (sort_by_time && !do_list)
6420 errx(1, "-t option requires -l option");
6422 argc -= optind;
6423 argv += optind;
6425 if (!do_list && !delref && argc == 0)
6426 do_show = 1;
6428 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6429 errx(1, "-c option can only be used when creating a branch");
6431 if (do_list || delref) {
6432 if (argc > 0)
6433 usage_branch();
6434 } else if (!do_show && argc != 1)
6435 usage_branch();
6437 #ifndef PROFILE
6438 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6439 "sendfd unveil", NULL) == -1)
6440 err(1, "pledge");
6441 #endif
6442 cwd = getcwd(NULL, 0);
6443 if (cwd == NULL) {
6444 error = got_error_from_errno("getcwd");
6445 goto done;
6448 if (repo_path == NULL) {
6449 error = got_worktree_open(&worktree, cwd);
6450 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6451 goto done;
6452 else
6453 error = NULL;
6454 if (worktree) {
6455 repo_path =
6456 strdup(got_worktree_get_repo_path(worktree));
6457 if (repo_path == NULL)
6458 error = got_error_from_errno("strdup");
6459 if (error)
6460 goto done;
6461 } else {
6462 repo_path = strdup(cwd);
6463 if (repo_path == NULL) {
6464 error = got_error_from_errno("strdup");
6465 goto done;
6470 error = got_repo_open(&repo, repo_path, NULL);
6471 if (error != NULL)
6472 goto done;
6474 #ifndef PROFILE
6475 if (do_list || do_show) {
6476 /* Remove "cpath" promise. */
6477 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6478 NULL) == -1)
6479 err(1, "pledge");
6481 #endif
6483 error = apply_unveil(got_repo_get_path(repo), do_list,
6484 worktree ? got_worktree_get_root_path(worktree) : NULL);
6485 if (error)
6486 goto done;
6488 if (do_show)
6489 error = show_current_branch(repo, worktree);
6490 else if (do_list)
6491 error = list_branches(repo, worktree, sort_by_time);
6492 else if (delref)
6493 error = delete_branch(repo, worktree, delref);
6494 else {
6495 struct got_reflist_head refs;
6496 TAILQ_INIT(&refs);
6497 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6498 NULL);
6499 if (error)
6500 goto done;
6501 if (commit_id_arg == NULL)
6502 commit_id_arg = worktree ?
6503 got_worktree_get_head_ref_name(worktree) :
6504 GOT_REF_HEAD;
6505 error = got_repo_match_object_id(&commit_id, NULL,
6506 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6507 got_ref_list_free(&refs);
6508 if (error)
6509 goto done;
6510 error = add_branch(repo, argv[0], commit_id);
6511 if (error)
6512 goto done;
6513 if (worktree && do_update) {
6514 struct got_update_progress_arg upa;
6515 char *branch_refname = NULL;
6517 error = got_object_id_str(&commit_id_str, commit_id);
6518 if (error)
6519 goto done;
6520 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6521 worktree);
6522 if (error)
6523 goto done;
6524 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6525 == -1) {
6526 error = got_error_from_errno("asprintf");
6527 goto done;
6529 error = got_ref_open(&ref, repo, branch_refname, 0);
6530 free(branch_refname);
6531 if (error)
6532 goto done;
6533 error = switch_head_ref(ref, commit_id, worktree,
6534 repo);
6535 if (error)
6536 goto done;
6537 error = got_worktree_set_base_commit_id(worktree, repo,
6538 commit_id);
6539 if (error)
6540 goto done;
6541 memset(&upa, 0, sizeof(upa));
6542 error = got_worktree_checkout_files(worktree, &paths,
6543 repo, update_progress, &upa, check_cancelled,
6544 NULL);
6545 if (error)
6546 goto done;
6547 if (upa.did_something) {
6548 printf("Updated to %s: %s\n",
6549 got_worktree_get_head_ref_name(worktree),
6550 commit_id_str);
6552 print_update_progress_stats(&upa);
6555 done:
6556 if (ref)
6557 got_ref_close(ref);
6558 if (repo) {
6559 const struct got_error *close_err = got_repo_close(repo);
6560 if (error == NULL)
6561 error = close_err;
6563 if (worktree)
6564 got_worktree_close(worktree);
6565 free(cwd);
6566 free(repo_path);
6567 free(commit_id);
6568 free(commit_id_str);
6569 TAILQ_FOREACH(pe, &paths, entry)
6570 free((char *)pe->path);
6571 got_pathlist_free(&paths);
6572 return error;
6576 __dead static void
6577 usage_tag(void)
6579 fprintf(stderr,
6580 "usage: %s tag [-c commit] [-r repository] [-l] "
6581 "[-m message] name\n", getprogname());
6582 exit(1);
6585 #if 0
6586 static const struct got_error *
6587 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6589 const struct got_error *err = NULL;
6590 struct got_reflist_entry *re, *se, *new;
6591 struct got_object_id *re_id, *se_id;
6592 struct got_tag_object *re_tag, *se_tag;
6593 time_t re_time, se_time;
6595 STAILQ_FOREACH(re, tags, entry) {
6596 se = STAILQ_FIRST(sorted);
6597 if (se == NULL) {
6598 err = got_reflist_entry_dup(&new, re);
6599 if (err)
6600 return err;
6601 STAILQ_INSERT_HEAD(sorted, new, entry);
6602 continue;
6603 } else {
6604 err = got_ref_resolve(&re_id, repo, re->ref);
6605 if (err)
6606 break;
6607 err = got_object_open_as_tag(&re_tag, repo, re_id);
6608 free(re_id);
6609 if (err)
6610 break;
6611 re_time = got_object_tag_get_tagger_time(re_tag);
6612 got_object_tag_close(re_tag);
6615 while (se) {
6616 err = got_ref_resolve(&se_id, repo, re->ref);
6617 if (err)
6618 break;
6619 err = got_object_open_as_tag(&se_tag, repo, se_id);
6620 free(se_id);
6621 if (err)
6622 break;
6623 se_time = got_object_tag_get_tagger_time(se_tag);
6624 got_object_tag_close(se_tag);
6626 if (se_time > re_time) {
6627 err = got_reflist_entry_dup(&new, re);
6628 if (err)
6629 return err;
6630 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6631 break;
6633 se = STAILQ_NEXT(se, entry);
6634 continue;
6637 done:
6638 return err;
6640 #endif
6642 static const struct got_error *
6643 list_tags(struct got_repository *repo)
6645 static const struct got_error *err = NULL;
6646 struct got_reflist_head refs;
6647 struct got_reflist_entry *re;
6649 TAILQ_INIT(&refs);
6651 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6652 if (err)
6653 return err;
6655 TAILQ_FOREACH(re, &refs, entry) {
6656 const char *refname;
6657 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6658 char datebuf[26];
6659 const char *tagger;
6660 time_t tagger_time;
6661 struct got_object_id *id;
6662 struct got_tag_object *tag;
6663 struct got_commit_object *commit = NULL;
6665 refname = got_ref_get_name(re->ref);
6666 if (strncmp(refname, "refs/tags/", 10) != 0)
6667 continue;
6668 refname += 10;
6669 refstr = got_ref_to_str(re->ref);
6670 if (refstr == NULL) {
6671 err = got_error_from_errno("got_ref_to_str");
6672 break;
6674 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6675 free(refstr);
6677 err = got_ref_resolve(&id, repo, re->ref);
6678 if (err)
6679 break;
6680 err = got_object_open_as_tag(&tag, repo, id);
6681 if (err) {
6682 if (err->code != GOT_ERR_OBJ_TYPE) {
6683 free(id);
6684 break;
6686 /* "lightweight" tag */
6687 err = got_object_open_as_commit(&commit, repo, id);
6688 if (err) {
6689 free(id);
6690 break;
6692 tagger = got_object_commit_get_committer(commit);
6693 tagger_time =
6694 got_object_commit_get_committer_time(commit);
6695 err = got_object_id_str(&id_str, id);
6696 free(id);
6697 if (err)
6698 break;
6699 } else {
6700 free(id);
6701 tagger = got_object_tag_get_tagger(tag);
6702 tagger_time = got_object_tag_get_tagger_time(tag);
6703 err = got_object_id_str(&id_str,
6704 got_object_tag_get_object_id(tag));
6705 if (err)
6706 break;
6708 printf("from: %s\n", tagger);
6709 datestr = get_datestr(&tagger_time, datebuf);
6710 if (datestr)
6711 printf("date: %s UTC\n", datestr);
6712 if (commit)
6713 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6714 else {
6715 switch (got_object_tag_get_object_type(tag)) {
6716 case GOT_OBJ_TYPE_BLOB:
6717 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6718 id_str);
6719 break;
6720 case GOT_OBJ_TYPE_TREE:
6721 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6722 id_str);
6723 break;
6724 case GOT_OBJ_TYPE_COMMIT:
6725 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6726 id_str);
6727 break;
6728 case GOT_OBJ_TYPE_TAG:
6729 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6730 id_str);
6731 break;
6732 default:
6733 break;
6736 free(id_str);
6737 if (commit) {
6738 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6739 if (err)
6740 break;
6741 got_object_commit_close(commit);
6742 } else {
6743 tagmsg0 = strdup(got_object_tag_get_message(tag));
6744 got_object_tag_close(tag);
6745 if (tagmsg0 == NULL) {
6746 err = got_error_from_errno("strdup");
6747 break;
6751 tagmsg = tagmsg0;
6752 do {
6753 line = strsep(&tagmsg, "\n");
6754 if (line)
6755 printf(" %s\n", line);
6756 } while (line);
6757 free(tagmsg0);
6760 got_ref_list_free(&refs);
6761 return NULL;
6764 static const struct got_error *
6765 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6766 const char *tag_name, const char *repo_path)
6768 const struct got_error *err = NULL;
6769 char *template = NULL, *initial_content = NULL;
6770 char *editor = NULL;
6771 int initial_content_len;
6772 int fd = -1;
6774 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6775 err = got_error_from_errno("asprintf");
6776 goto done;
6779 initial_content_len = asprintf(&initial_content,
6780 "\n# tagging commit %s as %s\n",
6781 commit_id_str, tag_name);
6782 if (initial_content_len == -1) {
6783 err = got_error_from_errno("asprintf");
6784 goto done;
6787 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6788 if (err)
6789 goto done;
6791 if (write(fd, initial_content, initial_content_len) == -1) {
6792 err = got_error_from_errno2("write", *tagmsg_path);
6793 goto done;
6796 err = get_editor(&editor);
6797 if (err)
6798 goto done;
6799 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6800 initial_content_len, 1);
6801 done:
6802 free(initial_content);
6803 free(template);
6804 free(editor);
6806 if (fd != -1 && close(fd) == -1 && err == NULL)
6807 err = got_error_from_errno2("close", *tagmsg_path);
6809 /* Editor is done; we can now apply unveil(2) */
6810 if (err == NULL)
6811 err = apply_unveil(repo_path, 0, NULL);
6812 if (err) {
6813 free(*tagmsg);
6814 *tagmsg = NULL;
6816 return err;
6819 static const struct got_error *
6820 add_tag(struct got_repository *repo, const char *tagger,
6821 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6823 const struct got_error *err = NULL;
6824 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6825 char *label = NULL, *commit_id_str = NULL;
6826 struct got_reference *ref = NULL;
6827 char *refname = NULL, *tagmsg = NULL;
6828 char *tagmsg_path = NULL, *tag_id_str = NULL;
6829 int preserve_tagmsg = 0;
6830 struct got_reflist_head refs;
6832 TAILQ_INIT(&refs);
6835 * Don't let the user create a tag name with a leading '-'.
6836 * While technically a valid reference name, this case is usually
6837 * an unintended typo.
6839 if (tag_name[0] == '-')
6840 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6842 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6843 if (err)
6844 goto done;
6846 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6847 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6848 if (err)
6849 goto done;
6851 err = got_object_id_str(&commit_id_str, commit_id);
6852 if (err)
6853 goto done;
6855 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6856 refname = strdup(tag_name);
6857 if (refname == NULL) {
6858 err = got_error_from_errno("strdup");
6859 goto done;
6861 tag_name += 10;
6862 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6863 err = got_error_from_errno("asprintf");
6864 goto done;
6867 err = got_ref_open(&ref, repo, refname, 0);
6868 if (err == NULL) {
6869 err = got_error(GOT_ERR_TAG_EXISTS);
6870 goto done;
6871 } else if (err->code != GOT_ERR_NOT_REF)
6872 goto done;
6874 if (tagmsg_arg == NULL) {
6875 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6876 tag_name, got_repo_get_path(repo));
6877 if (err) {
6878 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6879 tagmsg_path != NULL)
6880 preserve_tagmsg = 1;
6881 goto done;
6885 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6886 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6887 if (err) {
6888 if (tagmsg_path)
6889 preserve_tagmsg = 1;
6890 goto done;
6893 err = got_ref_alloc(&ref, refname, tag_id);
6894 if (err) {
6895 if (tagmsg_path)
6896 preserve_tagmsg = 1;
6897 goto done;
6900 err = got_ref_write(ref, repo);
6901 if (err) {
6902 if (tagmsg_path)
6903 preserve_tagmsg = 1;
6904 goto done;
6907 err = got_object_id_str(&tag_id_str, tag_id);
6908 if (err) {
6909 if (tagmsg_path)
6910 preserve_tagmsg = 1;
6911 goto done;
6913 printf("Created tag %s\n", tag_id_str);
6914 done:
6915 if (preserve_tagmsg) {
6916 fprintf(stderr, "%s: tag message preserved in %s\n",
6917 getprogname(), tagmsg_path);
6918 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6919 err = got_error_from_errno2("unlink", tagmsg_path);
6920 free(tag_id_str);
6921 if (ref)
6922 got_ref_close(ref);
6923 free(commit_id);
6924 free(commit_id_str);
6925 free(refname);
6926 free(tagmsg);
6927 free(tagmsg_path);
6928 got_ref_list_free(&refs);
6929 return err;
6932 static const struct got_error *
6933 cmd_tag(int argc, char *argv[])
6935 const struct got_error *error = NULL;
6936 struct got_repository *repo = NULL;
6937 struct got_worktree *worktree = NULL;
6938 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6939 char *gitconfig_path = NULL, *tagger = NULL;
6940 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6941 int ch, do_list = 0;
6943 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6944 switch (ch) {
6945 case 'c':
6946 commit_id_arg = optarg;
6947 break;
6948 case 'm':
6949 tagmsg = optarg;
6950 break;
6951 case 'r':
6952 repo_path = realpath(optarg, NULL);
6953 if (repo_path == NULL)
6954 return got_error_from_errno2("realpath",
6955 optarg);
6956 got_path_strip_trailing_slashes(repo_path);
6957 break;
6958 case 'l':
6959 do_list = 1;
6960 break;
6961 default:
6962 usage_tag();
6963 /* NOTREACHED */
6967 argc -= optind;
6968 argv += optind;
6970 if (do_list) {
6971 if (commit_id_arg != NULL)
6972 errx(1,
6973 "-c option can only be used when creating a tag");
6974 if (tagmsg)
6975 option_conflict('l', 'm');
6976 if (argc > 0)
6977 usage_tag();
6978 } else if (argc != 1)
6979 usage_tag();
6981 tag_name = argv[0];
6983 #ifndef PROFILE
6984 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6985 "sendfd unveil", NULL) == -1)
6986 err(1, "pledge");
6987 #endif
6988 cwd = getcwd(NULL, 0);
6989 if (cwd == NULL) {
6990 error = got_error_from_errno("getcwd");
6991 goto done;
6994 if (repo_path == NULL) {
6995 error = got_worktree_open(&worktree, cwd);
6996 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6997 goto done;
6998 else
6999 error = NULL;
7000 if (worktree) {
7001 repo_path =
7002 strdup(got_worktree_get_repo_path(worktree));
7003 if (repo_path == NULL)
7004 error = got_error_from_errno("strdup");
7005 if (error)
7006 goto done;
7007 } else {
7008 repo_path = strdup(cwd);
7009 if (repo_path == NULL) {
7010 error = got_error_from_errno("strdup");
7011 goto done;
7016 if (do_list) {
7017 if (worktree) {
7018 /* Release work tree lock. */
7019 got_worktree_close(worktree);
7020 worktree = NULL;
7022 error = got_repo_open(&repo, repo_path, NULL);
7023 if (error != NULL)
7024 goto done;
7025 #ifndef PROFILE
7026 /* Remove "cpath" promise. */
7027 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7028 NULL) == -1)
7029 err(1, "pledge");
7030 #endif
7031 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7032 if (error)
7033 goto done;
7034 error = list_tags(repo);
7035 } else {
7036 error = get_gitconfig_path(&gitconfig_path);
7037 if (error)
7038 goto done;
7039 error = got_repo_open(&repo, repo_path, gitconfig_path);
7040 if (error != NULL)
7041 goto done;
7043 error = get_author(&tagger, repo, worktree);
7044 if (error)
7045 goto done;
7046 if (worktree) {
7047 /* Release work tree lock. */
7048 got_worktree_close(worktree);
7049 worktree = NULL;
7052 if (tagmsg) {
7053 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7054 if (error)
7055 goto done;
7058 if (commit_id_arg == NULL) {
7059 struct got_reference *head_ref;
7060 struct got_object_id *commit_id;
7061 error = got_ref_open(&head_ref, repo,
7062 worktree ? got_worktree_get_head_ref_name(worktree)
7063 : GOT_REF_HEAD, 0);
7064 if (error)
7065 goto done;
7066 error = got_ref_resolve(&commit_id, repo, head_ref);
7067 got_ref_close(head_ref);
7068 if (error)
7069 goto done;
7070 error = got_object_id_str(&commit_id_str, commit_id);
7071 free(commit_id);
7072 if (error)
7073 goto done;
7076 error = add_tag(repo, tagger, tag_name,
7077 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7079 done:
7080 if (repo) {
7081 const struct got_error *close_err = got_repo_close(repo);
7082 if (error == NULL)
7083 error = close_err;
7085 if (worktree)
7086 got_worktree_close(worktree);
7087 free(cwd);
7088 free(repo_path);
7089 free(gitconfig_path);
7090 free(commit_id_str);
7091 free(tagger);
7092 return error;
7095 __dead static void
7096 usage_add(void)
7098 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7099 getprogname());
7100 exit(1);
7103 static const struct got_error *
7104 add_progress(void *arg, unsigned char status, const char *path)
7106 while (path[0] == '/')
7107 path++;
7108 printf("%c %s\n", status, path);
7109 return NULL;
7112 static const struct got_error *
7113 cmd_add(int argc, char *argv[])
7115 const struct got_error *error = NULL;
7116 struct got_repository *repo = NULL;
7117 struct got_worktree *worktree = NULL;
7118 char *cwd = NULL;
7119 struct got_pathlist_head paths;
7120 struct got_pathlist_entry *pe;
7121 int ch, can_recurse = 0, no_ignores = 0;
7123 TAILQ_INIT(&paths);
7125 while ((ch = getopt(argc, argv, "IR")) != -1) {
7126 switch (ch) {
7127 case 'I':
7128 no_ignores = 1;
7129 break;
7130 case 'R':
7131 can_recurse = 1;
7132 break;
7133 default:
7134 usage_add();
7135 /* NOTREACHED */
7139 argc -= optind;
7140 argv += optind;
7142 #ifndef PROFILE
7143 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7144 NULL) == -1)
7145 err(1, "pledge");
7146 #endif
7147 if (argc < 1)
7148 usage_add();
7150 cwd = getcwd(NULL, 0);
7151 if (cwd == NULL) {
7152 error = got_error_from_errno("getcwd");
7153 goto done;
7156 error = got_worktree_open(&worktree, cwd);
7157 if (error) {
7158 if (error->code == GOT_ERR_NOT_WORKTREE)
7159 error = wrap_not_worktree_error(error, "add", cwd);
7160 goto done;
7163 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7164 NULL);
7165 if (error != NULL)
7166 goto done;
7168 error = apply_unveil(got_repo_get_path(repo), 1,
7169 got_worktree_get_root_path(worktree));
7170 if (error)
7171 goto done;
7173 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7174 if (error)
7175 goto done;
7177 if (!can_recurse) {
7178 char *ondisk_path;
7179 struct stat sb;
7180 TAILQ_FOREACH(pe, &paths, entry) {
7181 if (asprintf(&ondisk_path, "%s/%s",
7182 got_worktree_get_root_path(worktree),
7183 pe->path) == -1) {
7184 error = got_error_from_errno("asprintf");
7185 goto done;
7187 if (lstat(ondisk_path, &sb) == -1) {
7188 if (errno == ENOENT) {
7189 free(ondisk_path);
7190 continue;
7192 error = got_error_from_errno2("lstat",
7193 ondisk_path);
7194 free(ondisk_path);
7195 goto done;
7197 free(ondisk_path);
7198 if (S_ISDIR(sb.st_mode)) {
7199 error = got_error_msg(GOT_ERR_BAD_PATH,
7200 "adding directories requires -R option");
7201 goto done;
7206 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7207 NULL, repo, no_ignores);
7208 done:
7209 if (repo) {
7210 const struct got_error *close_err = got_repo_close(repo);
7211 if (error == NULL)
7212 error = close_err;
7214 if (worktree)
7215 got_worktree_close(worktree);
7216 TAILQ_FOREACH(pe, &paths, entry)
7217 free((char *)pe->path);
7218 got_pathlist_free(&paths);
7219 free(cwd);
7220 return error;
7223 __dead static void
7224 usage_remove(void)
7226 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7227 "path ...\n", getprogname());
7228 exit(1);
7231 static const struct got_error *
7232 print_remove_status(void *arg, unsigned char status,
7233 unsigned char staged_status, const char *path)
7235 while (path[0] == '/')
7236 path++;
7237 if (status == GOT_STATUS_NONEXISTENT)
7238 return NULL;
7239 if (status == staged_status && (status == GOT_STATUS_DELETE))
7240 status = GOT_STATUS_NO_CHANGE;
7241 printf("%c%c %s\n", status, staged_status, path);
7242 return NULL;
7245 static const struct got_error *
7246 cmd_remove(int argc, char *argv[])
7248 const struct got_error *error = NULL;
7249 struct got_worktree *worktree = NULL;
7250 struct got_repository *repo = NULL;
7251 const char *status_codes = NULL;
7252 char *cwd = NULL;
7253 struct got_pathlist_head paths;
7254 struct got_pathlist_entry *pe;
7255 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7256 int ignore_missing_paths = 0;
7258 TAILQ_INIT(&paths);
7260 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7261 switch (ch) {
7262 case 'f':
7263 delete_local_mods = 1;
7264 ignore_missing_paths = 1;
7265 break;
7266 case 'k':
7267 keep_on_disk = 1;
7268 break;
7269 case 'R':
7270 can_recurse = 1;
7271 break;
7272 case 's':
7273 for (i = 0; i < strlen(optarg); i++) {
7274 switch (optarg[i]) {
7275 case GOT_STATUS_MODIFY:
7276 delete_local_mods = 1;
7277 break;
7278 case GOT_STATUS_MISSING:
7279 ignore_missing_paths = 1;
7280 break;
7281 default:
7282 errx(1, "invalid status code '%c'",
7283 optarg[i]);
7286 status_codes = optarg;
7287 break;
7288 default:
7289 usage_remove();
7290 /* NOTREACHED */
7294 argc -= optind;
7295 argv += optind;
7297 #ifndef PROFILE
7298 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7299 NULL) == -1)
7300 err(1, "pledge");
7301 #endif
7302 if (argc < 1)
7303 usage_remove();
7305 cwd = getcwd(NULL, 0);
7306 if (cwd == NULL) {
7307 error = got_error_from_errno("getcwd");
7308 goto done;
7310 error = got_worktree_open(&worktree, cwd);
7311 if (error) {
7312 if (error->code == GOT_ERR_NOT_WORKTREE)
7313 error = wrap_not_worktree_error(error, "remove", cwd);
7314 goto done;
7317 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7318 NULL);
7319 if (error)
7320 goto done;
7322 error = apply_unveil(got_repo_get_path(repo), 1,
7323 got_worktree_get_root_path(worktree));
7324 if (error)
7325 goto done;
7327 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7328 if (error)
7329 goto done;
7331 if (!can_recurse) {
7332 char *ondisk_path;
7333 struct stat sb;
7334 TAILQ_FOREACH(pe, &paths, entry) {
7335 if (asprintf(&ondisk_path, "%s/%s",
7336 got_worktree_get_root_path(worktree),
7337 pe->path) == -1) {
7338 error = got_error_from_errno("asprintf");
7339 goto done;
7341 if (lstat(ondisk_path, &sb) == -1) {
7342 if (errno == ENOENT) {
7343 free(ondisk_path);
7344 continue;
7346 error = got_error_from_errno2("lstat",
7347 ondisk_path);
7348 free(ondisk_path);
7349 goto done;
7351 free(ondisk_path);
7352 if (S_ISDIR(sb.st_mode)) {
7353 error = got_error_msg(GOT_ERR_BAD_PATH,
7354 "removing directories requires -R option");
7355 goto done;
7360 error = got_worktree_schedule_delete(worktree, &paths,
7361 delete_local_mods, status_codes, print_remove_status, NULL,
7362 repo, keep_on_disk, ignore_missing_paths);
7363 done:
7364 if (repo) {
7365 const struct got_error *close_err = got_repo_close(repo);
7366 if (error == NULL)
7367 error = close_err;
7369 if (worktree)
7370 got_worktree_close(worktree);
7371 TAILQ_FOREACH(pe, &paths, entry)
7372 free((char *)pe->path);
7373 got_pathlist_free(&paths);
7374 free(cwd);
7375 return error;
7378 __dead static void
7379 usage_patch(void)
7381 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7382 "[-R] [patchfile]\n", getprogname());
7383 exit(1);
7386 static const struct got_error *
7387 patch_from_stdin(int *patchfd)
7389 const struct got_error *err = NULL;
7390 ssize_t r;
7391 char *path, buf[BUFSIZ];
7392 sig_t sighup, sigint, sigquit;
7394 err = got_opentemp_named_fd(&path, patchfd,
7395 GOT_TMPDIR_STR "/got-patch");
7396 if (err)
7397 return err;
7398 unlink(path);
7399 free(path);
7401 sighup = signal(SIGHUP, SIG_DFL);
7402 sigint = signal(SIGINT, SIG_DFL);
7403 sigquit = signal(SIGQUIT, SIG_DFL);
7405 for (;;) {
7406 r = read(0, buf, sizeof(buf));
7407 if (r == -1) {
7408 err = got_error_from_errno("read");
7409 break;
7411 if (r == 0)
7412 break;
7413 if (write(*patchfd, buf, r) == -1) {
7414 err = got_error_from_errno("write");
7415 break;
7419 signal(SIGHUP, sighup);
7420 signal(SIGINT, sigint);
7421 signal(SIGQUIT, sigquit);
7423 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7424 err = got_error_from_errno("lseek");
7426 if (err != NULL) {
7427 close(*patchfd);
7428 *patchfd = -1;
7431 return err;
7434 static const struct got_error *
7435 patch_progress(void *arg, const char *old, const char *new,
7436 unsigned char status, const struct got_error *error, long old_from,
7437 long old_lines, long new_from, long new_lines, long offset,
7438 const struct got_error *hunk_err)
7440 const char *path = new == NULL ? old : new;
7442 while (*path == '/')
7443 path++;
7445 if (status != 0)
7446 printf("%c %s\n", status, path);
7448 if (error != NULL)
7449 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7451 if (offset != 0 || hunk_err != NULL) {
7452 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7453 old_lines, new_from, new_lines);
7454 if (hunk_err != NULL)
7455 printf("%s\n", hunk_err->msg);
7456 else
7457 printf("applied with offset %ld\n", offset);
7460 return NULL;
7463 static const struct got_error *
7464 cmd_patch(int argc, char *argv[])
7466 const struct got_error *error = NULL, *close_error = NULL;
7467 struct got_worktree *worktree = NULL;
7468 struct got_repository *repo = NULL;
7469 const char *errstr;
7470 char *cwd = NULL;
7471 int ch, nop = 0, strip = -1, reverse = 0;
7472 int patchfd;
7474 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7475 switch (ch) {
7476 case 'n':
7477 nop = 1;
7478 break;
7479 case 'p':
7480 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7481 if (errstr != NULL)
7482 errx(1, "pathname strip count is %s: %s",
7483 errstr, optarg);
7484 break;
7485 case 'R':
7486 reverse = 1;
7487 break;
7488 default:
7489 usage_patch();
7490 /* NOTREACHED */
7494 argc -= optind;
7495 argv += optind;
7497 if (argc == 0) {
7498 error = patch_from_stdin(&patchfd);
7499 if (error)
7500 return error;
7501 } else if (argc == 1) {
7502 patchfd = open(argv[0], O_RDONLY);
7503 if (patchfd == -1) {
7504 error = got_error_from_errno2("open", argv[0]);
7505 return error;
7507 } else
7508 usage_patch();
7510 if ((cwd = getcwd(NULL, 0)) == NULL) {
7511 error = got_error_from_errno("getcwd");
7512 goto done;
7515 error = got_worktree_open(&worktree, cwd);
7516 if (error != NULL)
7517 goto done;
7519 const char *repo_path = got_worktree_get_repo_path(worktree);
7520 error = got_repo_open(&repo, repo_path, NULL);
7521 if (error != NULL)
7522 goto done;
7524 error = apply_unveil(got_repo_get_path(repo), 0,
7525 got_worktree_get_root_path(worktree));
7526 if (error != NULL)
7527 goto done;
7529 #ifndef PROFILE
7530 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7531 NULL) == -1)
7532 err(1, "pledge");
7533 #endif
7535 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7536 &patch_progress, NULL, check_cancelled, NULL);
7538 done:
7539 if (repo) {
7540 close_error = got_repo_close(repo);
7541 if (error == NULL)
7542 error = close_error;
7544 if (worktree != NULL) {
7545 close_error = got_worktree_close(worktree);
7546 if (error == NULL)
7547 error = close_error;
7549 free(cwd);
7550 return error;
7553 __dead static void
7554 usage_revert(void)
7556 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7557 "path ...\n", getprogname());
7558 exit(1);
7561 static const struct got_error *
7562 revert_progress(void *arg, unsigned char status, const char *path)
7564 if (status == GOT_STATUS_UNVERSIONED)
7565 return NULL;
7567 while (path[0] == '/')
7568 path++;
7569 printf("%c %s\n", status, path);
7570 return NULL;
7573 struct choose_patch_arg {
7574 FILE *patch_script_file;
7575 const char *action;
7578 static const struct got_error *
7579 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7580 int nchanges, const char *action)
7582 const struct got_error *err;
7583 char *line = NULL;
7584 size_t linesize = 0;
7585 ssize_t linelen;
7587 switch (status) {
7588 case GOT_STATUS_ADD:
7589 printf("A %s\n%s this addition? [y/n] ", path, action);
7590 break;
7591 case GOT_STATUS_DELETE:
7592 printf("D %s\n%s this deletion? [y/n] ", path, action);
7593 break;
7594 case GOT_STATUS_MODIFY:
7595 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7596 return got_error_from_errno("fseek");
7597 printf(GOT_COMMIT_SEP_STR);
7598 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7599 printf("%s", line);
7600 if (linelen == -1 && ferror(patch_file)) {
7601 err = got_error_from_errno("getline");
7602 free(line);
7603 return err;
7605 free(line);
7606 printf(GOT_COMMIT_SEP_STR);
7607 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7608 path, n, nchanges, action);
7609 break;
7610 default:
7611 return got_error_path(path, GOT_ERR_FILE_STATUS);
7614 return NULL;
7617 static const struct got_error *
7618 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7619 FILE *patch_file, int n, int nchanges)
7621 const struct got_error *err = NULL;
7622 char *line = NULL;
7623 size_t linesize = 0;
7624 ssize_t linelen;
7625 int resp = ' ';
7626 struct choose_patch_arg *a = arg;
7628 *choice = GOT_PATCH_CHOICE_NONE;
7630 if (a->patch_script_file) {
7631 char *nl;
7632 err = show_change(status, path, patch_file, n, nchanges,
7633 a->action);
7634 if (err)
7635 return err;
7636 linelen = getline(&line, &linesize, a->patch_script_file);
7637 if (linelen == -1) {
7638 if (ferror(a->patch_script_file))
7639 return got_error_from_errno("getline");
7640 return NULL;
7642 nl = strchr(line, '\n');
7643 if (nl)
7644 *nl = '\0';
7645 if (strcmp(line, "y") == 0) {
7646 *choice = GOT_PATCH_CHOICE_YES;
7647 printf("y\n");
7648 } else if (strcmp(line, "n") == 0) {
7649 *choice = GOT_PATCH_CHOICE_NO;
7650 printf("n\n");
7651 } else if (strcmp(line, "q") == 0 &&
7652 status == GOT_STATUS_MODIFY) {
7653 *choice = GOT_PATCH_CHOICE_QUIT;
7654 printf("q\n");
7655 } else
7656 printf("invalid response '%s'\n", line);
7657 free(line);
7658 return NULL;
7661 while (resp != 'y' && resp != 'n' && resp != 'q') {
7662 err = show_change(status, path, patch_file, n, nchanges,
7663 a->action);
7664 if (err)
7665 return err;
7666 resp = getchar();
7667 if (resp == '\n')
7668 resp = getchar();
7669 if (status == GOT_STATUS_MODIFY) {
7670 if (resp != 'y' && resp != 'n' && resp != 'q') {
7671 printf("invalid response '%c'\n", resp);
7672 resp = ' ';
7674 } else if (resp != 'y' && resp != 'n') {
7675 printf("invalid response '%c'\n", resp);
7676 resp = ' ';
7680 if (resp == 'y')
7681 *choice = GOT_PATCH_CHOICE_YES;
7682 else if (resp == 'n')
7683 *choice = GOT_PATCH_CHOICE_NO;
7684 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7685 *choice = GOT_PATCH_CHOICE_QUIT;
7687 return NULL;
7690 static const struct got_error *
7691 cmd_revert(int argc, char *argv[])
7693 const struct got_error *error = NULL;
7694 struct got_worktree *worktree = NULL;
7695 struct got_repository *repo = NULL;
7696 char *cwd = NULL, *path = NULL;
7697 struct got_pathlist_head paths;
7698 struct got_pathlist_entry *pe;
7699 int ch, can_recurse = 0, pflag = 0;
7700 FILE *patch_script_file = NULL;
7701 const char *patch_script_path = NULL;
7702 struct choose_patch_arg cpa;
7704 TAILQ_INIT(&paths);
7706 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7707 switch (ch) {
7708 case 'p':
7709 pflag = 1;
7710 break;
7711 case 'F':
7712 patch_script_path = optarg;
7713 break;
7714 case 'R':
7715 can_recurse = 1;
7716 break;
7717 default:
7718 usage_revert();
7719 /* NOTREACHED */
7723 argc -= optind;
7724 argv += optind;
7726 #ifndef PROFILE
7727 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7728 "unveil", NULL) == -1)
7729 err(1, "pledge");
7730 #endif
7731 if (argc < 1)
7732 usage_revert();
7733 if (patch_script_path && !pflag)
7734 errx(1, "-F option can only be used together with -p option");
7736 cwd = getcwd(NULL, 0);
7737 if (cwd == NULL) {
7738 error = got_error_from_errno("getcwd");
7739 goto done;
7741 error = got_worktree_open(&worktree, cwd);
7742 if (error) {
7743 if (error->code == GOT_ERR_NOT_WORKTREE)
7744 error = wrap_not_worktree_error(error, "revert", cwd);
7745 goto done;
7748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7749 NULL);
7750 if (error != NULL)
7751 goto done;
7753 if (patch_script_path) {
7754 patch_script_file = fopen(patch_script_path, "re");
7755 if (patch_script_file == NULL) {
7756 error = got_error_from_errno2("fopen",
7757 patch_script_path);
7758 goto done;
7761 error = apply_unveil(got_repo_get_path(repo), 1,
7762 got_worktree_get_root_path(worktree));
7763 if (error)
7764 goto done;
7766 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7767 if (error)
7768 goto done;
7770 if (!can_recurse) {
7771 char *ondisk_path;
7772 struct stat sb;
7773 TAILQ_FOREACH(pe, &paths, entry) {
7774 if (asprintf(&ondisk_path, "%s/%s",
7775 got_worktree_get_root_path(worktree),
7776 pe->path) == -1) {
7777 error = got_error_from_errno("asprintf");
7778 goto done;
7780 if (lstat(ondisk_path, &sb) == -1) {
7781 if (errno == ENOENT) {
7782 free(ondisk_path);
7783 continue;
7785 error = got_error_from_errno2("lstat",
7786 ondisk_path);
7787 free(ondisk_path);
7788 goto done;
7790 free(ondisk_path);
7791 if (S_ISDIR(sb.st_mode)) {
7792 error = got_error_msg(GOT_ERR_BAD_PATH,
7793 "reverting directories requires -R option");
7794 goto done;
7799 cpa.patch_script_file = patch_script_file;
7800 cpa.action = "revert";
7801 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7802 pflag ? choose_patch : NULL, &cpa, repo);
7803 done:
7804 if (patch_script_file && fclose(patch_script_file) == EOF &&
7805 error == NULL)
7806 error = got_error_from_errno2("fclose", patch_script_path);
7807 if (repo) {
7808 const struct got_error *close_err = got_repo_close(repo);
7809 if (error == NULL)
7810 error = close_err;
7812 if (worktree)
7813 got_worktree_close(worktree);
7814 free(path);
7815 free(cwd);
7816 return error;
7819 __dead static void
7820 usage_commit(void)
7822 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7823 "[path ...]\n", getprogname());
7824 exit(1);
7827 struct collect_commit_logmsg_arg {
7828 const char *cmdline_log;
7829 const char *prepared_log;
7830 int non_interactive;
7831 const char *editor;
7832 const char *worktree_path;
7833 const char *branch_name;
7834 const char *repo_path;
7835 char *logmsg_path;
7839 static const struct got_error *
7840 read_prepared_logmsg(char **logmsg, const char *path)
7842 const struct got_error *err = NULL;
7843 FILE *f = NULL;
7844 struct stat sb;
7845 size_t r;
7847 *logmsg = NULL;
7848 memset(&sb, 0, sizeof(sb));
7850 f = fopen(path, "re");
7851 if (f == NULL)
7852 return got_error_from_errno2("fopen", path);
7854 if (fstat(fileno(f), &sb) == -1) {
7855 err = got_error_from_errno2("fstat", path);
7856 goto done;
7858 if (sb.st_size == 0) {
7859 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7860 goto done;
7863 *logmsg = malloc(sb.st_size + 1);
7864 if (*logmsg == NULL) {
7865 err = got_error_from_errno("malloc");
7866 goto done;
7869 r = fread(*logmsg, 1, sb.st_size, f);
7870 if (r != sb.st_size) {
7871 if (ferror(f))
7872 err = got_error_from_errno2("fread", path);
7873 else
7874 err = got_error(GOT_ERR_IO);
7875 goto done;
7877 (*logmsg)[sb.st_size] = '\0';
7878 done:
7879 if (fclose(f) == EOF && err == NULL)
7880 err = got_error_from_errno2("fclose", path);
7881 if (err) {
7882 free(*logmsg);
7883 *logmsg = NULL;
7885 return err;
7889 static const struct got_error *
7890 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7891 void *arg)
7893 char *initial_content = NULL;
7894 struct got_pathlist_entry *pe;
7895 const struct got_error *err = NULL;
7896 char *template = NULL;
7897 struct collect_commit_logmsg_arg *a = arg;
7898 int initial_content_len;
7899 int fd = -1;
7900 size_t len;
7902 /* if a message was specified on the command line, just use it */
7903 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7904 len = strlen(a->cmdline_log) + 1;
7905 *logmsg = malloc(len + 1);
7906 if (*logmsg == NULL)
7907 return got_error_from_errno("malloc");
7908 strlcpy(*logmsg, a->cmdline_log, len);
7909 return NULL;
7910 } else if (a->prepared_log != NULL && a->non_interactive)
7911 return read_prepared_logmsg(logmsg, a->prepared_log);
7913 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7914 return got_error_from_errno("asprintf");
7916 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7917 if (err)
7918 goto done;
7920 if (a->prepared_log) {
7921 char *msg;
7922 err = read_prepared_logmsg(&msg, a->prepared_log);
7923 if (err)
7924 goto done;
7925 if (write(fd, msg, strlen(msg)) == -1) {
7926 err = got_error_from_errno2("write", a->logmsg_path);
7927 free(msg);
7928 goto done;
7930 free(msg);
7933 initial_content_len = asprintf(&initial_content,
7934 "\n# changes to be committed on branch %s:\n",
7935 a->branch_name);
7936 if (initial_content_len == -1) {
7937 err = got_error_from_errno("asprintf");
7938 goto done;
7941 if (write(fd, initial_content, initial_content_len) == -1) {
7942 err = got_error_from_errno2("write", a->logmsg_path);
7943 goto done;
7946 TAILQ_FOREACH(pe, commitable_paths, entry) {
7947 struct got_commitable *ct = pe->data;
7948 dprintf(fd, "# %c %s\n",
7949 got_commitable_get_status(ct),
7950 got_commitable_get_path(ct));
7953 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7954 initial_content_len, a->prepared_log ? 0 : 1);
7955 done:
7956 free(initial_content);
7957 free(template);
7959 if (fd != -1 && close(fd) == -1 && err == NULL)
7960 err = got_error_from_errno2("close", a->logmsg_path);
7962 /* Editor is done; we can now apply unveil(2) */
7963 if (err == NULL)
7964 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7965 if (err) {
7966 free(*logmsg);
7967 *logmsg = NULL;
7969 return err;
7972 static const struct got_error *
7973 cmd_commit(int argc, char *argv[])
7975 const struct got_error *error = NULL;
7976 struct got_worktree *worktree = NULL;
7977 struct got_repository *repo = NULL;
7978 char *cwd = NULL, *id_str = NULL;
7979 struct got_object_id *id = NULL;
7980 const char *logmsg = NULL;
7981 char *prepared_logmsg = NULL;
7982 struct collect_commit_logmsg_arg cl_arg;
7983 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7984 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7985 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7986 struct got_pathlist_head paths;
7988 TAILQ_INIT(&paths);
7989 cl_arg.logmsg_path = NULL;
7991 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7992 switch (ch) {
7993 case 'F':
7994 if (logmsg != NULL)
7995 option_conflict('F', 'm');
7996 prepared_logmsg = realpath(optarg, NULL);
7997 if (prepared_logmsg == NULL)
7998 return got_error_from_errno2("realpath",
7999 optarg);
8000 break;
8001 case 'm':
8002 if (prepared_logmsg)
8003 option_conflict('m', 'F');
8004 logmsg = optarg;
8005 break;
8006 case 'N':
8007 non_interactive = 1;
8008 break;
8009 case 'S':
8010 allow_bad_symlinks = 1;
8011 break;
8012 default:
8013 usage_commit();
8014 /* NOTREACHED */
8018 argc -= optind;
8019 argv += optind;
8021 #ifndef PROFILE
8022 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8023 "unveil", NULL) == -1)
8024 err(1, "pledge");
8025 #endif
8026 cwd = getcwd(NULL, 0);
8027 if (cwd == NULL) {
8028 error = got_error_from_errno("getcwd");
8029 goto done;
8031 error = got_worktree_open(&worktree, cwd);
8032 if (error) {
8033 if (error->code == GOT_ERR_NOT_WORKTREE)
8034 error = wrap_not_worktree_error(error, "commit", cwd);
8035 goto done;
8038 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8039 if (error)
8040 goto done;
8041 if (rebase_in_progress) {
8042 error = got_error(GOT_ERR_REBASING);
8043 goto done;
8046 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8047 worktree);
8048 if (error)
8049 goto done;
8051 error = get_gitconfig_path(&gitconfig_path);
8052 if (error)
8053 goto done;
8054 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8055 gitconfig_path);
8056 if (error != NULL)
8057 goto done;
8059 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8060 if (error)
8061 goto done;
8062 if (merge_in_progress) {
8063 error = got_error(GOT_ERR_MERGE_BUSY);
8064 goto done;
8067 error = get_author(&author, repo, worktree);
8068 if (error)
8069 return error;
8072 * unveil(2) traverses exec(2); if an editor is used we have
8073 * to apply unveil after the log message has been written.
8075 if (logmsg == NULL || strlen(logmsg) == 0)
8076 error = get_editor(&editor);
8077 else
8078 error = apply_unveil(got_repo_get_path(repo), 0,
8079 got_worktree_get_root_path(worktree));
8080 if (error)
8081 goto done;
8083 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8084 if (error)
8085 goto done;
8087 cl_arg.editor = editor;
8088 cl_arg.cmdline_log = logmsg;
8089 cl_arg.prepared_log = prepared_logmsg;
8090 cl_arg.non_interactive = non_interactive;
8091 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8092 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8093 if (!histedit_in_progress) {
8094 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8095 error = got_error(GOT_ERR_COMMIT_BRANCH);
8096 goto done;
8098 cl_arg.branch_name += 11;
8100 cl_arg.repo_path = got_repo_get_path(repo);
8101 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8102 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8103 print_status, NULL, repo);
8104 if (error) {
8105 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8106 cl_arg.logmsg_path != NULL)
8107 preserve_logmsg = 1;
8108 goto done;
8111 error = got_object_id_str(&id_str, id);
8112 if (error)
8113 goto done;
8114 printf("Created commit %s\n", id_str);
8115 done:
8116 if (preserve_logmsg) {
8117 fprintf(stderr, "%s: log message preserved in %s\n",
8118 getprogname(), cl_arg.logmsg_path);
8119 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8120 error == NULL)
8121 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8122 free(cl_arg.logmsg_path);
8123 if (repo) {
8124 const struct got_error *close_err = got_repo_close(repo);
8125 if (error == NULL)
8126 error = close_err;
8128 if (worktree)
8129 got_worktree_close(worktree);
8130 free(cwd);
8131 free(id_str);
8132 free(gitconfig_path);
8133 free(editor);
8134 free(author);
8135 free(prepared_logmsg);
8136 return error;
8139 __dead static void
8140 usage_send(void)
8142 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8143 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8144 "[remote-repository]\n", getprogname());
8145 exit(1);
8148 static void
8149 print_load_info(int print_colored, int print_found, int print_trees,
8150 int ncolored, int nfound, int ntrees)
8152 if (print_colored) {
8153 printf("%d commit%s colored", ncolored,
8154 ncolored == 1 ? "" : "s");
8156 if (print_found) {
8157 printf("%s%d object%s found",
8158 ncolored > 0 ? "; " : "",
8159 nfound, nfound == 1 ? "" : "s");
8161 if (print_trees) {
8162 printf("; %d tree%s scanned", ntrees,
8163 ntrees == 1 ? "" : "s");
8167 struct got_send_progress_arg {
8168 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8169 int verbosity;
8170 int last_ncolored;
8171 int last_nfound;
8172 int last_ntrees;
8173 int loading_done;
8174 int last_ncommits;
8175 int last_nobj_total;
8176 int last_p_deltify;
8177 int last_p_written;
8178 int last_p_sent;
8179 int printed_something;
8180 int sent_something;
8181 struct got_pathlist_head *delete_branches;
8184 static const struct got_error *
8185 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8186 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8187 int nobj_written, off_t bytes_sent, const char *refname, int success)
8189 struct got_send_progress_arg *a = arg;
8190 char scaled_packsize[FMT_SCALED_STRSIZE];
8191 char scaled_sent[FMT_SCALED_STRSIZE];
8192 int p_deltify = 0, p_written = 0, p_sent = 0;
8193 int print_colored = 0, print_found = 0, print_trees = 0;
8194 int print_searching = 0, print_total = 0;
8195 int print_deltify = 0, print_written = 0, print_sent = 0;
8197 if (a->verbosity < 0)
8198 return NULL;
8200 if (refname) {
8201 const char *status = success ? "accepted" : "rejected";
8203 if (success) {
8204 struct got_pathlist_entry *pe;
8205 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8206 const char *branchname = pe->path;
8207 if (got_path_cmp(branchname, refname,
8208 strlen(branchname), strlen(refname)) == 0) {
8209 status = "deleted";
8210 a->sent_something = 1;
8211 break;
8216 if (a->printed_something)
8217 putchar('\n');
8218 printf("Server has %s %s", status, refname);
8219 a->printed_something = 1;
8220 return NULL;
8223 if (a->last_ncolored != ncolored) {
8224 print_colored = 1;
8225 a->last_ncolored = ncolored;
8228 if (a->last_nfound != nfound) {
8229 print_colored = 1;
8230 print_found = 1;
8231 a->last_nfound = nfound;
8234 if (a->last_ntrees != ntrees) {
8235 print_colored = 1;
8236 print_found = 1;
8237 print_trees = 1;
8238 a->last_ntrees = ntrees;
8241 if ((print_colored || print_found || print_trees) &&
8242 !a->loading_done) {
8243 printf("\r");
8244 print_load_info(print_colored, print_found, print_trees,
8245 ncolored, nfound, ntrees);
8246 a->printed_something = 1;
8247 fflush(stdout);
8248 return NULL;
8249 } else if (!a->loading_done) {
8250 printf("\r");
8251 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8252 printf("\n");
8253 a->loading_done = 1;
8256 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8257 return got_error_from_errno("fmt_scaled");
8258 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8259 return got_error_from_errno("fmt_scaled");
8261 if (a->last_ncommits != ncommits) {
8262 print_searching = 1;
8263 a->last_ncommits = ncommits;
8266 if (a->last_nobj_total != nobj_total) {
8267 print_searching = 1;
8268 print_total = 1;
8269 a->last_nobj_total = nobj_total;
8272 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8273 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8274 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8275 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8276 return got_error(GOT_ERR_NO_SPACE);
8279 if (nobj_deltify > 0 || nobj_written > 0) {
8280 if (nobj_deltify > 0) {
8281 p_deltify = (nobj_deltify * 100) / nobj_total;
8282 if (p_deltify != a->last_p_deltify) {
8283 a->last_p_deltify = p_deltify;
8284 print_searching = 1;
8285 print_total = 1;
8286 print_deltify = 1;
8289 if (nobj_written > 0) {
8290 p_written = (nobj_written * 100) / nobj_total;
8291 if (p_written != a->last_p_written) {
8292 a->last_p_written = p_written;
8293 print_searching = 1;
8294 print_total = 1;
8295 print_deltify = 1;
8296 print_written = 1;
8301 if (bytes_sent > 0) {
8302 p_sent = (bytes_sent * 100) / packfile_size;
8303 if (p_sent != a->last_p_sent) {
8304 a->last_p_sent = p_sent;
8305 print_searching = 1;
8306 print_total = 1;
8307 print_deltify = 1;
8308 print_written = 1;
8309 print_sent = 1;
8311 a->sent_something = 1;
8314 if (print_searching || print_total || print_deltify || print_written ||
8315 print_sent)
8316 printf("\r");
8317 if (print_searching)
8318 printf("packing %d reference%s", ncommits,
8319 ncommits == 1 ? "" : "s");
8320 if (print_total)
8321 printf("; %d object%s", nobj_total,
8322 nobj_total == 1 ? "" : "s");
8323 if (print_deltify)
8324 printf("; deltify: %d%%", p_deltify);
8325 if (print_sent)
8326 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8327 scaled_packsize, p_sent);
8328 else if (print_written)
8329 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8330 scaled_packsize, p_written);
8331 if (print_searching || print_total || print_deltify ||
8332 print_written || print_sent) {
8333 a->printed_something = 1;
8334 fflush(stdout);
8336 return NULL;
8339 static const struct got_error *
8340 cmd_send(int argc, char *argv[])
8342 const struct got_error *error = NULL;
8343 char *cwd = NULL, *repo_path = NULL;
8344 const char *remote_name;
8345 char *proto = NULL, *host = NULL, *port = NULL;
8346 char *repo_name = NULL, *server_path = NULL;
8347 const struct got_remote_repo *remotes, *remote = NULL;
8348 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8349 struct got_repository *repo = NULL;
8350 struct got_worktree *worktree = NULL;
8351 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8352 struct got_pathlist_head branches;
8353 struct got_pathlist_head tags;
8354 struct got_reflist_head all_branches;
8355 struct got_reflist_head all_tags;
8356 struct got_pathlist_head delete_args;
8357 struct got_pathlist_head delete_branches;
8358 struct got_reflist_entry *re;
8359 struct got_pathlist_entry *pe;
8360 int i, ch, sendfd = -1, sendstatus;
8361 pid_t sendpid = -1;
8362 struct got_send_progress_arg spa;
8363 int verbosity = 0, overwrite_refs = 0;
8364 int send_all_branches = 0, send_all_tags = 0;
8365 struct got_reference *ref = NULL;
8367 TAILQ_INIT(&branches);
8368 TAILQ_INIT(&tags);
8369 TAILQ_INIT(&all_branches);
8370 TAILQ_INIT(&all_tags);
8371 TAILQ_INIT(&delete_args);
8372 TAILQ_INIT(&delete_branches);
8374 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8375 switch (ch) {
8376 case 'a':
8377 send_all_branches = 1;
8378 break;
8379 case 'b':
8380 error = got_pathlist_append(&branches, optarg, NULL);
8381 if (error)
8382 return error;
8383 nbranches++;
8384 break;
8385 case 'd':
8386 error = got_pathlist_append(&delete_args, optarg, NULL);
8387 if (error)
8388 return error;
8389 break;
8390 case 'f':
8391 overwrite_refs = 1;
8392 break;
8393 case 'r':
8394 repo_path = realpath(optarg, NULL);
8395 if (repo_path == NULL)
8396 return got_error_from_errno2("realpath",
8397 optarg);
8398 got_path_strip_trailing_slashes(repo_path);
8399 break;
8400 case 't':
8401 error = got_pathlist_append(&tags, optarg, NULL);
8402 if (error)
8403 return error;
8404 ntags++;
8405 break;
8406 case 'T':
8407 send_all_tags = 1;
8408 break;
8409 case 'v':
8410 if (verbosity < 0)
8411 verbosity = 0;
8412 else if (verbosity < 3)
8413 verbosity++;
8414 break;
8415 case 'q':
8416 verbosity = -1;
8417 break;
8418 default:
8419 usage_send();
8420 /* NOTREACHED */
8423 argc -= optind;
8424 argv += optind;
8426 if (send_all_branches && !TAILQ_EMPTY(&branches))
8427 option_conflict('a', 'b');
8428 if (send_all_tags && !TAILQ_EMPTY(&tags))
8429 option_conflict('T', 't');
8432 if (argc == 0)
8433 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8434 else if (argc == 1)
8435 remote_name = argv[0];
8436 else
8437 usage_send();
8439 cwd = getcwd(NULL, 0);
8440 if (cwd == NULL) {
8441 error = got_error_from_errno("getcwd");
8442 goto done;
8445 if (repo_path == NULL) {
8446 error = got_worktree_open(&worktree, cwd);
8447 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8448 goto done;
8449 else
8450 error = NULL;
8451 if (worktree) {
8452 repo_path =
8453 strdup(got_worktree_get_repo_path(worktree));
8454 if (repo_path == NULL)
8455 error = got_error_from_errno("strdup");
8456 if (error)
8457 goto done;
8458 } else {
8459 repo_path = strdup(cwd);
8460 if (repo_path == NULL) {
8461 error = got_error_from_errno("strdup");
8462 goto done;
8467 error = got_repo_open(&repo, repo_path, NULL);
8468 if (error)
8469 goto done;
8471 if (worktree) {
8472 worktree_conf = got_worktree_get_gotconfig(worktree);
8473 if (worktree_conf) {
8474 got_gotconfig_get_remotes(&nremotes, &remotes,
8475 worktree_conf);
8476 for (i = 0; i < nremotes; i++) {
8477 if (strcmp(remotes[i].name, remote_name) == 0) {
8478 remote = &remotes[i];
8479 break;
8484 if (remote == NULL) {
8485 repo_conf = got_repo_get_gotconfig(repo);
8486 if (repo_conf) {
8487 got_gotconfig_get_remotes(&nremotes, &remotes,
8488 repo_conf);
8489 for (i = 0; i < nremotes; i++) {
8490 if (strcmp(remotes[i].name, remote_name) == 0) {
8491 remote = &remotes[i];
8492 break;
8497 if (remote == NULL) {
8498 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8499 for (i = 0; i < nremotes; i++) {
8500 if (strcmp(remotes[i].name, remote_name) == 0) {
8501 remote = &remotes[i];
8502 break;
8506 if (remote == NULL) {
8507 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8508 goto done;
8511 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8512 &repo_name, remote->send_url);
8513 if (error)
8514 goto done;
8516 if (strcmp(proto, "git") == 0) {
8517 #ifndef PROFILE
8518 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8519 "sendfd dns inet unveil", NULL) == -1)
8520 err(1, "pledge");
8521 #endif
8522 } else if (strcmp(proto, "git+ssh") == 0 ||
8523 strcmp(proto, "ssh") == 0) {
8524 #ifndef PROFILE
8525 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8526 "sendfd unveil", NULL) == -1)
8527 err(1, "pledge");
8528 #endif
8529 } else if (strcmp(proto, "http") == 0 ||
8530 strcmp(proto, "git+http") == 0) {
8531 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8532 goto done;
8533 } else {
8534 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8535 goto done;
8538 error = got_dial_apply_unveil(proto);
8539 if (error)
8540 goto done;
8542 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8543 if (error)
8544 goto done;
8546 if (send_all_branches) {
8547 error = got_ref_list(&all_branches, repo, "refs/heads",
8548 got_ref_cmp_by_name, NULL);
8549 if (error)
8550 goto done;
8551 TAILQ_FOREACH(re, &all_branches, entry) {
8552 const char *branchname = got_ref_get_name(re->ref);
8553 error = got_pathlist_append(&branches,
8554 branchname, NULL);
8555 if (error)
8556 goto done;
8557 nbranches++;
8559 } else if (nbranches == 0) {
8560 for (i = 0; i < remote->nsend_branches; i++) {
8561 got_pathlist_append(&branches,
8562 remote->send_branches[i], NULL);
8566 if (send_all_tags) {
8567 error = got_ref_list(&all_tags, repo, "refs/tags",
8568 got_ref_cmp_by_name, NULL);
8569 if (error)
8570 goto done;
8571 TAILQ_FOREACH(re, &all_tags, entry) {
8572 const char *tagname = got_ref_get_name(re->ref);
8573 error = got_pathlist_append(&tags,
8574 tagname, NULL);
8575 if (error)
8576 goto done;
8577 ntags++;
8582 * To prevent accidents only branches in refs/heads/ can be deleted
8583 * with 'got send -d'.
8584 * Deleting anything else requires local repository access or Git.
8586 TAILQ_FOREACH(pe, &delete_args, entry) {
8587 const char *branchname = pe->path;
8588 char *s;
8589 struct got_pathlist_entry *new;
8590 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8591 s = strdup(branchname);
8592 if (s == NULL) {
8593 error = got_error_from_errno("strdup");
8594 goto done;
8596 } else {
8597 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8598 error = got_error_from_errno("asprintf");
8599 goto done;
8602 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8603 if (error || new == NULL /* duplicate */)
8604 free(s);
8605 if (error)
8606 goto done;
8607 ndelete_branches++;
8610 if (nbranches == 0 && ndelete_branches == 0) {
8611 struct got_reference *head_ref;
8612 if (worktree)
8613 error = got_ref_open(&head_ref, repo,
8614 got_worktree_get_head_ref_name(worktree), 0);
8615 else
8616 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8617 if (error)
8618 goto done;
8619 if (got_ref_is_symbolic(head_ref)) {
8620 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8621 got_ref_close(head_ref);
8622 if (error)
8623 goto done;
8624 } else
8625 ref = head_ref;
8626 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8627 NULL);
8628 if (error)
8629 goto done;
8630 nbranches++;
8633 if (verbosity >= 0)
8634 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8635 port ? ":" : "", port ? port : "");
8637 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8638 server_path, verbosity);
8639 if (error)
8640 goto done;
8642 memset(&spa, 0, sizeof(spa));
8643 spa.last_scaled_packsize[0] = '\0';
8644 spa.last_p_deltify = -1;
8645 spa.last_p_written = -1;
8646 spa.verbosity = verbosity;
8647 spa.delete_branches = &delete_branches;
8648 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8649 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8650 check_cancelled, NULL);
8651 if (spa.printed_something)
8652 putchar('\n');
8653 if (error)
8654 goto done;
8655 if (!spa.sent_something && verbosity >= 0)
8656 printf("Already up-to-date\n");
8657 done:
8658 if (sendpid > 0) {
8659 if (kill(sendpid, SIGTERM) == -1)
8660 error = got_error_from_errno("kill");
8661 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8662 error = got_error_from_errno("waitpid");
8664 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8665 error = got_error_from_errno("close");
8666 if (repo) {
8667 const struct got_error *close_err = got_repo_close(repo);
8668 if (error == NULL)
8669 error = close_err;
8671 if (worktree)
8672 got_worktree_close(worktree);
8673 if (ref)
8674 got_ref_close(ref);
8675 got_pathlist_free(&branches);
8676 got_pathlist_free(&tags);
8677 got_ref_list_free(&all_branches);
8678 got_ref_list_free(&all_tags);
8679 got_pathlist_free(&delete_args);
8680 TAILQ_FOREACH(pe, &delete_branches, entry)
8681 free((char *)pe->path);
8682 got_pathlist_free(&delete_branches);
8683 free(cwd);
8684 free(repo_path);
8685 free(proto);
8686 free(host);
8687 free(port);
8688 free(server_path);
8689 free(repo_name);
8690 return error;
8693 __dead static void
8694 usage_cherrypick(void)
8696 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8697 exit(1);
8700 static const struct got_error *
8701 cmd_cherrypick(int argc, char *argv[])
8703 const struct got_error *error = NULL;
8704 struct got_worktree *worktree = NULL;
8705 struct got_repository *repo = NULL;
8706 char *cwd = NULL, *commit_id_str = NULL;
8707 struct got_object_id *commit_id = NULL;
8708 struct got_commit_object *commit = NULL;
8709 struct got_object_qid *pid;
8710 int ch;
8711 struct got_update_progress_arg upa;
8713 while ((ch = getopt(argc, argv, "")) != -1) {
8714 switch (ch) {
8715 default:
8716 usage_cherrypick();
8717 /* NOTREACHED */
8721 argc -= optind;
8722 argv += optind;
8724 #ifndef PROFILE
8725 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8726 "unveil", NULL) == -1)
8727 err(1, "pledge");
8728 #endif
8729 if (argc != 1)
8730 usage_cherrypick();
8732 cwd = getcwd(NULL, 0);
8733 if (cwd == NULL) {
8734 error = got_error_from_errno("getcwd");
8735 goto done;
8737 error = got_worktree_open(&worktree, cwd);
8738 if (error) {
8739 if (error->code == GOT_ERR_NOT_WORKTREE)
8740 error = wrap_not_worktree_error(error, "cherrypick",
8741 cwd);
8742 goto done;
8745 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8746 NULL);
8747 if (error != NULL)
8748 goto done;
8750 error = apply_unveil(got_repo_get_path(repo), 0,
8751 got_worktree_get_root_path(worktree));
8752 if (error)
8753 goto done;
8755 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8756 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8757 if (error)
8758 goto done;
8759 error = got_object_id_str(&commit_id_str, commit_id);
8760 if (error)
8761 goto done;
8763 error = got_object_open_as_commit(&commit, repo, commit_id);
8764 if (error)
8765 goto done;
8766 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8767 memset(&upa, 0, sizeof(upa));
8768 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8769 commit_id, repo, update_progress, &upa, check_cancelled,
8770 NULL);
8771 if (error != NULL)
8772 goto done;
8774 if (upa.did_something)
8775 printf("Merged commit %s\n", commit_id_str);
8776 print_merge_progress_stats(&upa);
8777 done:
8778 if (commit)
8779 got_object_commit_close(commit);
8780 free(commit_id_str);
8781 if (worktree)
8782 got_worktree_close(worktree);
8783 if (repo) {
8784 const struct got_error *close_err = got_repo_close(repo);
8785 if (error == NULL)
8786 error = close_err;
8788 return error;
8791 __dead static void
8792 usage_backout(void)
8794 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8795 exit(1);
8798 static const struct got_error *
8799 cmd_backout(int argc, char *argv[])
8801 const struct got_error *error = NULL;
8802 struct got_worktree *worktree = NULL;
8803 struct got_repository *repo = NULL;
8804 char *cwd = NULL, *commit_id_str = NULL;
8805 struct got_object_id *commit_id = NULL;
8806 struct got_commit_object *commit = NULL;
8807 struct got_object_qid *pid;
8808 int ch;
8809 struct got_update_progress_arg upa;
8811 while ((ch = getopt(argc, argv, "")) != -1) {
8812 switch (ch) {
8813 default:
8814 usage_backout();
8815 /* NOTREACHED */
8819 argc -= optind;
8820 argv += optind;
8822 #ifndef PROFILE
8823 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8824 "unveil", NULL) == -1)
8825 err(1, "pledge");
8826 #endif
8827 if (argc != 1)
8828 usage_backout();
8830 cwd = getcwd(NULL, 0);
8831 if (cwd == NULL) {
8832 error = got_error_from_errno("getcwd");
8833 goto done;
8835 error = got_worktree_open(&worktree, cwd);
8836 if (error) {
8837 if (error->code == GOT_ERR_NOT_WORKTREE)
8838 error = wrap_not_worktree_error(error, "backout", cwd);
8839 goto done;
8842 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8843 NULL);
8844 if (error != NULL)
8845 goto done;
8847 error = apply_unveil(got_repo_get_path(repo), 0,
8848 got_worktree_get_root_path(worktree));
8849 if (error)
8850 goto done;
8852 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8853 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8854 if (error)
8855 goto done;
8856 error = got_object_id_str(&commit_id_str, commit_id);
8857 if (error)
8858 goto done;
8860 error = got_object_open_as_commit(&commit, repo, commit_id);
8861 if (error)
8862 goto done;
8863 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8864 if (pid == NULL) {
8865 error = got_error(GOT_ERR_ROOT_COMMIT);
8866 goto done;
8869 memset(&upa, 0, sizeof(upa));
8870 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8871 repo, update_progress, &upa, check_cancelled, NULL);
8872 if (error != NULL)
8873 goto done;
8875 if (upa.did_something)
8876 printf("Backed out commit %s\n", commit_id_str);
8877 print_merge_progress_stats(&upa);
8878 done:
8879 if (commit)
8880 got_object_commit_close(commit);
8881 free(commit_id_str);
8882 if (worktree)
8883 got_worktree_close(worktree);
8884 if (repo) {
8885 const struct got_error *close_err = got_repo_close(repo);
8886 if (error == NULL)
8887 error = close_err;
8889 return error;
8892 __dead static void
8893 usage_rebase(void)
8895 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8896 getprogname());
8897 exit(1);
8900 void
8901 trim_logmsg(char *logmsg, int limit)
8903 char *nl;
8904 size_t len;
8906 len = strlen(logmsg);
8907 if (len > limit)
8908 len = limit;
8909 logmsg[len] = '\0';
8910 nl = strchr(logmsg, '\n');
8911 if (nl)
8912 *nl = '\0';
8915 static const struct got_error *
8916 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8918 const struct got_error *err;
8919 char *logmsg0 = NULL;
8920 const char *s;
8922 err = got_object_commit_get_logmsg(&logmsg0, commit);
8923 if (err)
8924 return err;
8926 s = logmsg0;
8927 while (isspace((unsigned char)s[0]))
8928 s++;
8930 *logmsg = strdup(s);
8931 if (*logmsg == NULL) {
8932 err = got_error_from_errno("strdup");
8933 goto done;
8936 trim_logmsg(*logmsg, limit);
8937 done:
8938 free(logmsg0);
8939 return err;
8942 static const struct got_error *
8943 show_rebase_merge_conflict(struct got_object_id *id,
8944 struct got_repository *repo)
8946 const struct got_error *err;
8947 struct got_commit_object *commit = NULL;
8948 char *id_str = NULL, *logmsg = NULL;
8950 err = got_object_open_as_commit(&commit, repo, id);
8951 if (err)
8952 return err;
8954 err = got_object_id_str(&id_str, id);
8955 if (err)
8956 goto done;
8958 id_str[12] = '\0';
8960 err = get_short_logmsg(&logmsg, 42, commit);
8961 if (err)
8962 goto done;
8964 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8965 done:
8966 free(id_str);
8967 got_object_commit_close(commit);
8968 free(logmsg);
8969 return err;
8972 static const struct got_error *
8973 show_rebase_progress(struct got_commit_object *commit,
8974 struct got_object_id *old_id, struct got_object_id *new_id)
8976 const struct got_error *err;
8977 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8979 err = got_object_id_str(&old_id_str, old_id);
8980 if (err)
8981 goto done;
8983 if (new_id) {
8984 err = got_object_id_str(&new_id_str, new_id);
8985 if (err)
8986 goto done;
8989 old_id_str[12] = '\0';
8990 if (new_id_str)
8991 new_id_str[12] = '\0';
8993 err = get_short_logmsg(&logmsg, 42, commit);
8994 if (err)
8995 goto done;
8997 printf("%s -> %s: %s\n", old_id_str,
8998 new_id_str ? new_id_str : "no-op change", logmsg);
8999 done:
9000 free(old_id_str);
9001 free(new_id_str);
9002 free(logmsg);
9003 return err;
9006 static const struct got_error *
9007 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9008 struct got_reference *branch, struct got_reference *new_base_branch,
9009 struct got_reference *tmp_branch, struct got_repository *repo,
9010 int create_backup)
9012 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9013 return got_worktree_rebase_complete(worktree, fileindex,
9014 new_base_branch, tmp_branch, branch, repo, create_backup);
9017 static const struct got_error *
9018 rebase_commit(struct got_pathlist_head *merged_paths,
9019 struct got_worktree *worktree, struct got_fileindex *fileindex,
9020 struct got_reference *tmp_branch,
9021 struct got_object_id *commit_id, struct got_repository *repo)
9023 const struct got_error *error;
9024 struct got_commit_object *commit;
9025 struct got_object_id *new_commit_id;
9027 error = got_object_open_as_commit(&commit, repo, commit_id);
9028 if (error)
9029 return error;
9031 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9032 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9033 if (error) {
9034 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9035 goto done;
9036 error = show_rebase_progress(commit, commit_id, NULL);
9037 } else {
9038 error = show_rebase_progress(commit, commit_id, new_commit_id);
9039 free(new_commit_id);
9041 done:
9042 got_object_commit_close(commit);
9043 return error;
9046 struct check_path_prefix_arg {
9047 const char *path_prefix;
9048 size_t len;
9049 int errcode;
9052 static const struct got_error *
9053 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9054 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9055 struct got_object_id *id1, struct got_object_id *id2,
9056 const char *path1, const char *path2,
9057 mode_t mode1, mode_t mode2, struct got_repository *repo)
9059 struct check_path_prefix_arg *a = arg;
9061 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9062 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9063 return got_error(a->errcode);
9065 return NULL;
9068 static const struct got_error *
9069 check_path_prefix(struct got_object_id *parent_id,
9070 struct got_object_id *commit_id, const char *path_prefix,
9071 int errcode, struct got_repository *repo)
9073 const struct got_error *err;
9074 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9075 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9076 struct check_path_prefix_arg cpp_arg;
9078 if (got_path_is_root_dir(path_prefix))
9079 return NULL;
9081 err = got_object_open_as_commit(&commit, repo, commit_id);
9082 if (err)
9083 goto done;
9085 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9086 if (err)
9087 goto done;
9089 err = got_object_open_as_tree(&tree1, repo,
9090 got_object_commit_get_tree_id(parent_commit));
9091 if (err)
9092 goto done;
9094 err = got_object_open_as_tree(&tree2, repo,
9095 got_object_commit_get_tree_id(commit));
9096 if (err)
9097 goto done;
9099 cpp_arg.path_prefix = path_prefix;
9100 while (cpp_arg.path_prefix[0] == '/')
9101 cpp_arg.path_prefix++;
9102 cpp_arg.len = strlen(cpp_arg.path_prefix);
9103 cpp_arg.errcode = errcode;
9104 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9105 check_path_prefix_in_diff, &cpp_arg, 0);
9106 done:
9107 if (tree1)
9108 got_object_tree_close(tree1);
9109 if (tree2)
9110 got_object_tree_close(tree2);
9111 if (commit)
9112 got_object_commit_close(commit);
9113 if (parent_commit)
9114 got_object_commit_close(parent_commit);
9115 return err;
9118 static const struct got_error *
9119 collect_commits(struct got_object_id_queue *commits,
9120 struct got_object_id *initial_commit_id,
9121 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9122 const char *path_prefix, int path_prefix_errcode,
9123 struct got_repository *repo)
9125 const struct got_error *err = NULL;
9126 struct got_commit_graph *graph = NULL;
9127 struct got_object_id *parent_id = NULL;
9128 struct got_object_qid *qid;
9129 struct got_object_id *commit_id = initial_commit_id;
9131 err = got_commit_graph_open(&graph, "/", 1);
9132 if (err)
9133 return err;
9135 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9136 check_cancelled, NULL);
9137 if (err)
9138 goto done;
9139 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9140 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9141 check_cancelled, NULL);
9142 if (err) {
9143 if (err->code == GOT_ERR_ITER_COMPLETED) {
9144 err = got_error_msg(GOT_ERR_ANCESTRY,
9145 "ran out of commits to rebase before "
9146 "youngest common ancestor commit has "
9147 "been reached?!?");
9149 goto done;
9150 } else {
9151 err = check_path_prefix(parent_id, commit_id,
9152 path_prefix, path_prefix_errcode, repo);
9153 if (err)
9154 goto done;
9156 err = got_object_qid_alloc(&qid, commit_id);
9157 if (err)
9158 goto done;
9159 STAILQ_INSERT_HEAD(commits, qid, entry);
9160 commit_id = parent_id;
9163 done:
9164 got_commit_graph_close(graph);
9165 return err;
9168 static const struct got_error *
9169 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9171 const struct got_error *err = NULL;
9172 time_t committer_time;
9173 struct tm tm;
9174 char datebuf[11]; /* YYYY-MM-DD + NUL */
9175 char *author0 = NULL, *author, *smallerthan;
9176 char *logmsg0 = NULL, *logmsg, *newline;
9178 committer_time = got_object_commit_get_committer_time(commit);
9179 if (gmtime_r(&committer_time, &tm) == NULL)
9180 return got_error_from_errno("gmtime_r");
9181 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9182 return got_error(GOT_ERR_NO_SPACE);
9184 author0 = strdup(got_object_commit_get_author(commit));
9185 if (author0 == NULL)
9186 return got_error_from_errno("strdup");
9187 author = author0;
9188 smallerthan = strchr(author, '<');
9189 if (smallerthan && smallerthan[1] != '\0')
9190 author = smallerthan + 1;
9191 author[strcspn(author, "@>")] = '\0';
9193 err = got_object_commit_get_logmsg(&logmsg0, commit);
9194 if (err)
9195 goto done;
9196 logmsg = logmsg0;
9197 while (*logmsg == '\n')
9198 logmsg++;
9199 newline = strchr(logmsg, '\n');
9200 if (newline)
9201 *newline = '\0';
9203 if (asprintf(brief_str, "%s %s %s",
9204 datebuf, author, logmsg) == -1)
9205 err = got_error_from_errno("asprintf");
9206 done:
9207 free(author0);
9208 free(logmsg0);
9209 return err;
9212 static const struct got_error *
9213 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9214 struct got_repository *repo)
9216 const struct got_error *err;
9217 char *id_str;
9219 err = got_object_id_str(&id_str, id);
9220 if (err)
9221 return err;
9223 err = got_ref_delete(ref, repo);
9224 if (err)
9225 goto done;
9227 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9228 done:
9229 free(id_str);
9230 return err;
9233 static const struct got_error *
9234 print_backup_ref(const char *branch_name, const char *new_id_str,
9235 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9236 struct got_reflist_object_id_map *refs_idmap,
9237 struct got_repository *repo)
9239 const struct got_error *err = NULL;
9240 struct got_reflist_head *refs;
9241 char *refs_str = NULL;
9242 struct got_object_id *new_commit_id = NULL;
9243 struct got_commit_object *new_commit = NULL;
9244 char *new_commit_brief_str = NULL;
9245 struct got_object_id *yca_id = NULL;
9246 struct got_commit_object *yca_commit = NULL;
9247 char *yca_id_str = NULL, *yca_brief_str = NULL;
9248 char *custom_refs_str;
9250 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9251 return got_error_from_errno("asprintf");
9253 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9254 0, 0, refs_idmap, custom_refs_str);
9255 if (err)
9256 goto done;
9258 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9259 if (err)
9260 goto done;
9262 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9263 if (refs) {
9264 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9265 if (err)
9266 goto done;
9269 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9270 if (err)
9271 goto done;
9273 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9274 if (err)
9275 goto done;
9277 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9278 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9279 if (err)
9280 goto done;
9282 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9283 refs_str ? " (" : "", refs_str ? refs_str : "",
9284 refs_str ? ")" : "", new_commit_brief_str);
9285 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9286 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9287 free(refs_str);
9288 refs_str = NULL;
9290 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9291 if (err)
9292 goto done;
9294 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9295 if (err)
9296 goto done;
9298 err = got_object_id_str(&yca_id_str, yca_id);
9299 if (err)
9300 goto done;
9302 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9303 if (refs) {
9304 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9305 if (err)
9306 goto done;
9308 printf("history forked at %s%s%s%s\n %s\n",
9309 yca_id_str,
9310 refs_str ? " (" : "", refs_str ? refs_str : "",
9311 refs_str ? ")" : "", yca_brief_str);
9313 done:
9314 free(custom_refs_str);
9315 free(new_commit_id);
9316 free(refs_str);
9317 free(yca_id);
9318 free(yca_id_str);
9319 free(yca_brief_str);
9320 if (new_commit)
9321 got_object_commit_close(new_commit);
9322 if (yca_commit)
9323 got_object_commit_close(yca_commit);
9325 return NULL;
9328 static const struct got_error *
9329 process_backup_refs(const char *backup_ref_prefix,
9330 const char *wanted_branch_name,
9331 int delete, struct got_repository *repo)
9333 const struct got_error *err;
9334 struct got_reflist_head refs, backup_refs;
9335 struct got_reflist_entry *re;
9336 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9337 struct got_object_id *old_commit_id = NULL;
9338 char *branch_name = NULL;
9339 struct got_commit_object *old_commit = NULL;
9340 struct got_reflist_object_id_map *refs_idmap = NULL;
9341 int wanted_branch_found = 0;
9343 TAILQ_INIT(&refs);
9344 TAILQ_INIT(&backup_refs);
9346 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9347 if (err)
9348 return err;
9350 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9351 if (err)
9352 goto done;
9354 if (wanted_branch_name) {
9355 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9356 wanted_branch_name += 11;
9359 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9360 got_ref_cmp_by_commit_timestamp_descending, repo);
9361 if (err)
9362 goto done;
9364 TAILQ_FOREACH(re, &backup_refs, entry) {
9365 const char *refname = got_ref_get_name(re->ref);
9366 char *slash;
9368 err = check_cancelled(NULL);
9369 if (err)
9370 break;
9372 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9373 if (err)
9374 break;
9376 err = got_object_open_as_commit(&old_commit, repo,
9377 old_commit_id);
9378 if (err)
9379 break;
9381 if (strncmp(backup_ref_prefix, refname,
9382 backup_ref_prefix_len) == 0)
9383 refname += backup_ref_prefix_len;
9385 while (refname[0] == '/')
9386 refname++;
9388 branch_name = strdup(refname);
9389 if (branch_name == NULL) {
9390 err = got_error_from_errno("strdup");
9391 break;
9393 slash = strrchr(branch_name, '/');
9394 if (slash) {
9395 *slash = '\0';
9396 refname += strlen(branch_name) + 1;
9399 if (wanted_branch_name == NULL ||
9400 strcmp(wanted_branch_name, branch_name) == 0) {
9401 wanted_branch_found = 1;
9402 if (delete) {
9403 err = delete_backup_ref(re->ref,
9404 old_commit_id, repo);
9405 } else {
9406 err = print_backup_ref(branch_name, refname,
9407 old_commit_id, old_commit, refs_idmap,
9408 repo);
9410 if (err)
9411 break;
9414 free(old_commit_id);
9415 old_commit_id = NULL;
9416 free(branch_name);
9417 branch_name = NULL;
9418 got_object_commit_close(old_commit);
9419 old_commit = NULL;
9422 if (wanted_branch_name && !wanted_branch_found) {
9423 err = got_error_fmt(GOT_ERR_NOT_REF,
9424 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9426 done:
9427 if (refs_idmap)
9428 got_reflist_object_id_map_free(refs_idmap);
9429 got_ref_list_free(&refs);
9430 got_ref_list_free(&backup_refs);
9431 free(old_commit_id);
9432 free(branch_name);
9433 if (old_commit)
9434 got_object_commit_close(old_commit);
9435 return err;
9438 static const struct got_error *
9439 abort_progress(void *arg, unsigned char status, const char *path)
9442 * Unversioned files should not clutter progress output when
9443 * an operation is aborted.
9445 if (status == GOT_STATUS_UNVERSIONED)
9446 return NULL;
9448 return update_progress(arg, status, path);
9451 static const struct got_error *
9452 cmd_rebase(int argc, char *argv[])
9454 const struct got_error *error = NULL;
9455 struct got_worktree *worktree = NULL;
9456 struct got_repository *repo = NULL;
9457 struct got_fileindex *fileindex = NULL;
9458 char *cwd = NULL;
9459 struct got_reference *branch = NULL;
9460 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9461 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9462 struct got_object_id *resume_commit_id = NULL;
9463 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9464 struct got_commit_object *commit = NULL;
9465 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9466 int histedit_in_progress = 0, merge_in_progress = 0;
9467 int create_backup = 1, list_backups = 0, delete_backups = 0;
9468 struct got_object_id_queue commits;
9469 struct got_pathlist_head merged_paths;
9470 const struct got_object_id_queue *parent_ids;
9471 struct got_object_qid *qid, *pid;
9472 struct got_update_progress_arg upa;
9474 STAILQ_INIT(&commits);
9475 TAILQ_INIT(&merged_paths);
9476 memset(&upa, 0, sizeof(upa));
9478 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9479 switch (ch) {
9480 case 'a':
9481 abort_rebase = 1;
9482 break;
9483 case 'c':
9484 continue_rebase = 1;
9485 break;
9486 case 'l':
9487 list_backups = 1;
9488 break;
9489 case 'X':
9490 delete_backups = 1;
9491 break;
9492 default:
9493 usage_rebase();
9494 /* NOTREACHED */
9498 argc -= optind;
9499 argv += optind;
9501 #ifndef PROFILE
9502 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9503 "unveil", NULL) == -1)
9504 err(1, "pledge");
9505 #endif
9506 if (list_backups) {
9507 if (abort_rebase)
9508 option_conflict('l', 'a');
9509 if (continue_rebase)
9510 option_conflict('l', 'c');
9511 if (delete_backups)
9512 option_conflict('l', 'X');
9513 if (argc != 0 && argc != 1)
9514 usage_rebase();
9515 } else if (delete_backups) {
9516 if (abort_rebase)
9517 option_conflict('X', 'a');
9518 if (continue_rebase)
9519 option_conflict('X', 'c');
9520 if (list_backups)
9521 option_conflict('l', 'X');
9522 if (argc != 0 && argc != 1)
9523 usage_rebase();
9524 } else {
9525 if (abort_rebase && continue_rebase)
9526 usage_rebase();
9527 else if (abort_rebase || continue_rebase) {
9528 if (argc != 0)
9529 usage_rebase();
9530 } else if (argc != 1)
9531 usage_rebase();
9534 cwd = getcwd(NULL, 0);
9535 if (cwd == NULL) {
9536 error = got_error_from_errno("getcwd");
9537 goto done;
9539 error = got_worktree_open(&worktree, cwd);
9540 if (error) {
9541 if (list_backups || delete_backups) {
9542 if (error->code != GOT_ERR_NOT_WORKTREE)
9543 goto done;
9544 } else {
9545 if (error->code == GOT_ERR_NOT_WORKTREE)
9546 error = wrap_not_worktree_error(error,
9547 "rebase", cwd);
9548 goto done;
9552 error = got_repo_open(&repo,
9553 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9554 if (error != NULL)
9555 goto done;
9557 error = apply_unveil(got_repo_get_path(repo), 0,
9558 worktree ? got_worktree_get_root_path(worktree) : NULL);
9559 if (error)
9560 goto done;
9562 if (list_backups || delete_backups) {
9563 error = process_backup_refs(
9564 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9565 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9566 goto done; /* nothing else to do */
9569 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9570 worktree);
9571 if (error)
9572 goto done;
9573 if (histedit_in_progress) {
9574 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9575 goto done;
9578 error = got_worktree_merge_in_progress(&merge_in_progress,
9579 worktree, repo);
9580 if (error)
9581 goto done;
9582 if (merge_in_progress) {
9583 error = got_error(GOT_ERR_MERGE_BUSY);
9584 goto done;
9587 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9588 if (error)
9589 goto done;
9591 if (abort_rebase) {
9592 if (!rebase_in_progress) {
9593 error = got_error(GOT_ERR_NOT_REBASING);
9594 goto done;
9596 error = got_worktree_rebase_continue(&resume_commit_id,
9597 &new_base_branch, &tmp_branch, &branch, &fileindex,
9598 worktree, repo);
9599 if (error)
9600 goto done;
9601 printf("Switching work tree to %s\n",
9602 got_ref_get_symref_target(new_base_branch));
9603 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9604 new_base_branch, abort_progress, &upa);
9605 if (error)
9606 goto done;
9607 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9608 print_merge_progress_stats(&upa);
9609 goto done; /* nothing else to do */
9612 if (continue_rebase) {
9613 if (!rebase_in_progress) {
9614 error = got_error(GOT_ERR_NOT_REBASING);
9615 goto done;
9617 error = got_worktree_rebase_continue(&resume_commit_id,
9618 &new_base_branch, &tmp_branch, &branch, &fileindex,
9619 worktree, repo);
9620 if (error)
9621 goto done;
9623 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9624 resume_commit_id, repo);
9625 if (error)
9626 goto done;
9628 yca_id = got_object_id_dup(resume_commit_id);
9629 if (yca_id == NULL) {
9630 error = got_error_from_errno("got_object_id_dup");
9631 goto done;
9633 } else {
9634 error = got_ref_open(&branch, repo, argv[0], 0);
9635 if (error != NULL)
9636 goto done;
9639 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9640 if (error)
9641 goto done;
9643 if (!continue_rebase) {
9644 struct got_object_id *base_commit_id;
9646 base_commit_id = got_worktree_get_base_commit_id(worktree);
9647 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9648 base_commit_id, branch_head_commit_id, 1, repo,
9649 check_cancelled, NULL);
9650 if (error)
9651 goto done;
9652 if (yca_id == NULL) {
9653 error = got_error_msg(GOT_ERR_ANCESTRY,
9654 "specified branch shares no common ancestry "
9655 "with work tree's branch");
9656 goto done;
9659 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9660 if (error) {
9661 if (error->code != GOT_ERR_ANCESTRY)
9662 goto done;
9663 error = NULL;
9664 } else {
9665 struct got_pathlist_head paths;
9666 printf("%s is already based on %s\n",
9667 got_ref_get_name(branch),
9668 got_worktree_get_head_ref_name(worktree));
9669 error = switch_head_ref(branch, branch_head_commit_id,
9670 worktree, repo);
9671 if (error)
9672 goto done;
9673 error = got_worktree_set_base_commit_id(worktree, repo,
9674 branch_head_commit_id);
9675 if (error)
9676 goto done;
9677 TAILQ_INIT(&paths);
9678 error = got_pathlist_append(&paths, "", NULL);
9679 if (error)
9680 goto done;
9681 error = got_worktree_checkout_files(worktree,
9682 &paths, repo, update_progress, &upa,
9683 check_cancelled, NULL);
9684 got_pathlist_free(&paths);
9685 if (error)
9686 goto done;
9687 if (upa.did_something) {
9688 char *id_str;
9689 error = got_object_id_str(&id_str,
9690 branch_head_commit_id);
9691 if (error)
9692 goto done;
9693 printf("Updated to %s: %s\n",
9694 got_worktree_get_head_ref_name(worktree),
9695 id_str);
9696 free(id_str);
9697 } else
9698 printf("Already up-to-date\n");
9699 print_update_progress_stats(&upa);
9700 goto done;
9704 commit_id = branch_head_commit_id;
9705 error = got_object_open_as_commit(&commit, repo, commit_id);
9706 if (error)
9707 goto done;
9709 parent_ids = got_object_commit_get_parent_ids(commit);
9710 pid = STAILQ_FIRST(parent_ids);
9711 if (pid == NULL) {
9712 error = got_error(GOT_ERR_EMPTY_REBASE);
9713 goto done;
9715 error = collect_commits(&commits, commit_id, &pid->id,
9716 yca_id, got_worktree_get_path_prefix(worktree),
9717 GOT_ERR_REBASE_PATH, repo);
9718 got_object_commit_close(commit);
9719 commit = NULL;
9720 if (error)
9721 goto done;
9723 if (!continue_rebase) {
9724 error = got_worktree_rebase_prepare(&new_base_branch,
9725 &tmp_branch, &fileindex, worktree, branch, repo);
9726 if (error)
9727 goto done;
9730 if (STAILQ_EMPTY(&commits)) {
9731 if (continue_rebase) {
9732 error = rebase_complete(worktree, fileindex,
9733 branch, new_base_branch, tmp_branch, repo,
9734 create_backup);
9735 goto done;
9736 } else {
9737 /* Fast-forward the reference of the branch. */
9738 struct got_object_id *new_head_commit_id;
9739 char *id_str;
9740 error = got_ref_resolve(&new_head_commit_id, repo,
9741 new_base_branch);
9742 if (error)
9743 goto done;
9744 error = got_object_id_str(&id_str, new_head_commit_id);
9745 printf("Forwarding %s to commit %s\n",
9746 got_ref_get_name(branch), id_str);
9747 free(id_str);
9748 error = got_ref_change_ref(branch,
9749 new_head_commit_id);
9750 if (error)
9751 goto done;
9752 /* No backup needed since objects did not change. */
9753 create_backup = 0;
9757 pid = NULL;
9758 STAILQ_FOREACH(qid, &commits, entry) {
9760 commit_id = &qid->id;
9761 parent_id = pid ? &pid->id : yca_id;
9762 pid = qid;
9764 memset(&upa, 0, sizeof(upa));
9765 error = got_worktree_rebase_merge_files(&merged_paths,
9766 worktree, fileindex, parent_id, commit_id, repo,
9767 update_progress, &upa, check_cancelled, NULL);
9768 if (error)
9769 goto done;
9771 print_merge_progress_stats(&upa);
9772 if (upa.conflicts > 0 || upa.missing > 0 ||
9773 upa.not_deleted > 0 || upa.unversioned > 0) {
9774 if (upa.conflicts > 0) {
9775 error = show_rebase_merge_conflict(&qid->id,
9776 repo);
9777 if (error)
9778 goto done;
9780 got_worktree_rebase_pathlist_free(&merged_paths);
9781 break;
9784 error = rebase_commit(&merged_paths, worktree, fileindex,
9785 tmp_branch, commit_id, repo);
9786 got_worktree_rebase_pathlist_free(&merged_paths);
9787 if (error)
9788 goto done;
9791 if (upa.conflicts > 0 || upa.missing > 0 ||
9792 upa.not_deleted > 0 || upa.unversioned > 0) {
9793 error = got_worktree_rebase_postpone(worktree, fileindex);
9794 if (error)
9795 goto done;
9796 if (upa.conflicts > 0 && upa.missing == 0 &&
9797 upa.not_deleted == 0 && upa.unversioned == 0) {
9798 error = got_error_msg(GOT_ERR_CONFLICTS,
9799 "conflicts must be resolved before rebasing "
9800 "can continue");
9801 } else if (upa.conflicts > 0) {
9802 error = got_error_msg(GOT_ERR_CONFLICTS,
9803 "conflicts must be resolved before rebasing "
9804 "can continue; changes destined for some "
9805 "files were not yet merged and should be "
9806 "merged manually if required before the "
9807 "rebase operation is continued");
9808 } else {
9809 error = got_error_msg(GOT_ERR_CONFLICTS,
9810 "changes destined for some files were not "
9811 "yet merged and should be merged manually "
9812 "if required before the rebase operation "
9813 "is continued");
9815 } else
9816 error = rebase_complete(worktree, fileindex, branch,
9817 new_base_branch, tmp_branch, repo, create_backup);
9818 done:
9819 got_object_id_queue_free(&commits);
9820 free(branch_head_commit_id);
9821 free(resume_commit_id);
9822 free(yca_id);
9823 if (commit)
9824 got_object_commit_close(commit);
9825 if (branch)
9826 got_ref_close(branch);
9827 if (new_base_branch)
9828 got_ref_close(new_base_branch);
9829 if (tmp_branch)
9830 got_ref_close(tmp_branch);
9831 if (worktree)
9832 got_worktree_close(worktree);
9833 if (repo) {
9834 const struct got_error *close_err = got_repo_close(repo);
9835 if (error == NULL)
9836 error = close_err;
9838 return error;
9841 __dead static void
9842 usage_histedit(void)
9844 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9845 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9846 getprogname());
9847 exit(1);
9850 #define GOT_HISTEDIT_PICK 'p'
9851 #define GOT_HISTEDIT_EDIT 'e'
9852 #define GOT_HISTEDIT_FOLD 'f'
9853 #define GOT_HISTEDIT_DROP 'd'
9854 #define GOT_HISTEDIT_MESG 'm'
9856 static const struct got_histedit_cmd {
9857 unsigned char code;
9858 const char *name;
9859 const char *desc;
9860 } got_histedit_cmds[] = {
9861 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9862 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9863 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9864 "be used" },
9865 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9866 { GOT_HISTEDIT_MESG, "mesg",
9867 "single-line log message for commit above (open editor if empty)" },
9870 struct got_histedit_list_entry {
9871 TAILQ_ENTRY(got_histedit_list_entry) entry;
9872 struct got_object_id *commit_id;
9873 const struct got_histedit_cmd *cmd;
9874 char *logmsg;
9876 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9878 static const struct got_error *
9879 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9880 FILE *f, struct got_repository *repo)
9882 const struct got_error *err = NULL;
9883 char *logmsg = NULL, *id_str = NULL;
9884 struct got_commit_object *commit = NULL;
9885 int n;
9887 err = got_object_open_as_commit(&commit, repo, commit_id);
9888 if (err)
9889 goto done;
9891 err = get_short_logmsg(&logmsg, 34, commit);
9892 if (err)
9893 goto done;
9895 err = got_object_id_str(&id_str, commit_id);
9896 if (err)
9897 goto done;
9899 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9900 if (n < 0)
9901 err = got_ferror(f, GOT_ERR_IO);
9902 done:
9903 if (commit)
9904 got_object_commit_close(commit);
9905 free(id_str);
9906 free(logmsg);
9907 return err;
9910 static const struct got_error *
9911 histedit_write_commit_list(struct got_object_id_queue *commits,
9912 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9913 struct got_repository *repo)
9915 const struct got_error *err = NULL;
9916 struct got_object_qid *qid;
9917 const char *histedit_cmd = NULL;
9919 if (STAILQ_EMPTY(commits))
9920 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9922 STAILQ_FOREACH(qid, commits, entry) {
9923 histedit_cmd = got_histedit_cmds[0].name;
9924 if (edit_only)
9925 histedit_cmd = "edit";
9926 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9927 histedit_cmd = "fold";
9928 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9929 if (err)
9930 break;
9931 if (edit_logmsg_only) {
9932 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9933 if (n < 0) {
9934 err = got_ferror(f, GOT_ERR_IO);
9935 break;
9940 return err;
9943 static const struct got_error *
9944 write_cmd_list(FILE *f, const char *branch_name,
9945 struct got_object_id_queue *commits)
9947 const struct got_error *err = NULL;
9948 size_t i;
9949 int n;
9950 char *id_str;
9951 struct got_object_qid *qid;
9953 qid = STAILQ_FIRST(commits);
9954 err = got_object_id_str(&id_str, &qid->id);
9955 if (err)
9956 return err;
9958 n = fprintf(f,
9959 "# Editing the history of branch '%s' starting at\n"
9960 "# commit %s\n"
9961 "# Commits will be processed in order from top to "
9962 "bottom of this file.\n", branch_name, id_str);
9963 if (n < 0) {
9964 err = got_ferror(f, GOT_ERR_IO);
9965 goto done;
9968 n = fprintf(f, "# Available histedit commands:\n");
9969 if (n < 0) {
9970 err = got_ferror(f, GOT_ERR_IO);
9971 goto done;
9974 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9975 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9976 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9977 cmd->desc);
9978 if (n < 0) {
9979 err = got_ferror(f, GOT_ERR_IO);
9980 break;
9983 done:
9984 free(id_str);
9985 return err;
9988 static const struct got_error *
9989 histedit_syntax_error(int lineno)
9991 static char msg[42];
9992 int ret;
9994 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9995 lineno);
9996 if (ret == -1 || ret >= sizeof(msg))
9997 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9999 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10002 static const struct got_error *
10003 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10004 char *logmsg, struct got_repository *repo)
10006 const struct got_error *err;
10007 struct got_commit_object *folded_commit = NULL;
10008 char *id_str, *folded_logmsg = NULL;
10010 err = got_object_id_str(&id_str, hle->commit_id);
10011 if (err)
10012 return err;
10014 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10015 if (err)
10016 goto done;
10018 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10019 if (err)
10020 goto done;
10021 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10022 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10023 folded_logmsg) == -1) {
10024 err = got_error_from_errno("asprintf");
10026 done:
10027 if (folded_commit)
10028 got_object_commit_close(folded_commit);
10029 free(id_str);
10030 free(folded_logmsg);
10031 return err;
10034 static struct got_histedit_list_entry *
10035 get_folded_commits(struct got_histedit_list_entry *hle)
10037 struct got_histedit_list_entry *prev, *folded = NULL;
10039 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10040 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10041 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10042 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10043 folded = prev;
10044 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10047 return folded;
10050 static const struct got_error *
10051 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10052 struct got_repository *repo)
10054 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10055 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10056 const struct got_error *err = NULL;
10057 struct got_commit_object *commit = NULL;
10058 int logmsg_len;
10059 int fd;
10060 struct got_histedit_list_entry *folded = NULL;
10062 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10063 if (err)
10064 return err;
10066 folded = get_folded_commits(hle);
10067 if (folded) {
10068 while (folded != hle) {
10069 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10070 folded = TAILQ_NEXT(folded, entry);
10071 continue;
10073 err = append_folded_commit_msg(&new_msg, folded,
10074 logmsg, repo);
10075 if (err)
10076 goto done;
10077 free(logmsg);
10078 logmsg = new_msg;
10079 folded = TAILQ_NEXT(folded, entry);
10083 err = got_object_id_str(&id_str, hle->commit_id);
10084 if (err)
10085 goto done;
10086 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10087 if (err)
10088 goto done;
10089 logmsg_len = asprintf(&new_msg,
10090 "%s\n# original log message of commit %s: %s",
10091 logmsg ? logmsg : "", id_str, orig_logmsg);
10092 if (logmsg_len == -1) {
10093 err = got_error_from_errno("asprintf");
10094 goto done;
10096 free(logmsg);
10097 logmsg = new_msg;
10099 err = got_object_id_str(&id_str, hle->commit_id);
10100 if (err)
10101 goto done;
10103 err = got_opentemp_named_fd(&logmsg_path, &fd,
10104 GOT_TMPDIR_STR "/got-logmsg");
10105 if (err)
10106 goto done;
10108 write(fd, logmsg, logmsg_len);
10109 close(fd);
10111 err = get_editor(&editor);
10112 if (err)
10113 goto done;
10115 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10116 logmsg_len, 0);
10117 if (err) {
10118 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10119 goto done;
10120 err = NULL;
10121 hle->logmsg = strdup(new_msg);
10122 if (hle->logmsg == NULL)
10123 err = got_error_from_errno("strdup");
10125 done:
10126 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10127 err = got_error_from_errno2("unlink", logmsg_path);
10128 free(logmsg_path);
10129 free(logmsg);
10130 free(orig_logmsg);
10131 free(editor);
10132 if (commit)
10133 got_object_commit_close(commit);
10134 return err;
10137 static const struct got_error *
10138 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10139 FILE *f, struct got_repository *repo)
10141 const struct got_error *err = NULL;
10142 char *line = NULL, *p, *end;
10143 size_t i, size;
10144 ssize_t len;
10145 int lineno = 0;
10146 const struct got_histedit_cmd *cmd;
10147 struct got_object_id *commit_id = NULL;
10148 struct got_histedit_list_entry *hle = NULL;
10150 for (;;) {
10151 len = getline(&line, &size, f);
10152 if (len == -1) {
10153 const struct got_error *getline_err;
10154 if (feof(f))
10155 break;
10156 getline_err = got_error_from_errno("getline");
10157 err = got_ferror(f, getline_err->code);
10158 break;
10160 lineno++;
10161 p = line;
10162 while (isspace((unsigned char)p[0]))
10163 p++;
10164 if (p[0] == '#' || p[0] == '\0') {
10165 free(line);
10166 line = NULL;
10167 continue;
10169 cmd = NULL;
10170 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10171 cmd = &got_histedit_cmds[i];
10172 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10173 isspace((unsigned char)p[strlen(cmd->name)])) {
10174 p += strlen(cmd->name);
10175 break;
10177 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10178 p++;
10179 break;
10182 if (i == nitems(got_histedit_cmds)) {
10183 err = histedit_syntax_error(lineno);
10184 break;
10186 while (isspace((unsigned char)p[0]))
10187 p++;
10188 if (cmd->code == GOT_HISTEDIT_MESG) {
10189 if (hle == NULL || hle->logmsg != NULL) {
10190 err = got_error(GOT_ERR_HISTEDIT_CMD);
10191 break;
10193 if (p[0] == '\0') {
10194 err = histedit_edit_logmsg(hle, repo);
10195 if (err)
10196 break;
10197 } else {
10198 hle->logmsg = strdup(p);
10199 if (hle->logmsg == NULL) {
10200 err = got_error_from_errno("strdup");
10201 break;
10204 free(line);
10205 line = NULL;
10206 continue;
10207 } else {
10208 end = p;
10209 while (end[0] && !isspace((unsigned char)end[0]))
10210 end++;
10211 *end = '\0';
10213 err = got_object_resolve_id_str(&commit_id, repo, p);
10214 if (err) {
10215 /* override error code */
10216 err = histedit_syntax_error(lineno);
10217 break;
10220 hle = malloc(sizeof(*hle));
10221 if (hle == NULL) {
10222 err = got_error_from_errno("malloc");
10223 break;
10225 hle->cmd = cmd;
10226 hle->commit_id = commit_id;
10227 hle->logmsg = NULL;
10228 commit_id = NULL;
10229 free(line);
10230 line = NULL;
10231 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10234 free(line);
10235 free(commit_id);
10236 return err;
10239 static const struct got_error *
10240 histedit_check_script(struct got_histedit_list *histedit_cmds,
10241 struct got_object_id_queue *commits, struct got_repository *repo)
10243 const struct got_error *err = NULL;
10244 struct got_object_qid *qid;
10245 struct got_histedit_list_entry *hle;
10246 static char msg[92];
10247 char *id_str;
10249 if (TAILQ_EMPTY(histedit_cmds))
10250 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10251 "histedit script contains no commands");
10252 if (STAILQ_EMPTY(commits))
10253 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10255 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10256 struct got_histedit_list_entry *hle2;
10257 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10258 if (hle == hle2)
10259 continue;
10260 if (got_object_id_cmp(hle->commit_id,
10261 hle2->commit_id) != 0)
10262 continue;
10263 err = got_object_id_str(&id_str, hle->commit_id);
10264 if (err)
10265 return err;
10266 snprintf(msg, sizeof(msg), "commit %s is listed "
10267 "more than once in histedit script", id_str);
10268 free(id_str);
10269 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10273 STAILQ_FOREACH(qid, commits, entry) {
10274 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10275 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10276 break;
10278 if (hle == NULL) {
10279 err = got_object_id_str(&id_str, &qid->id);
10280 if (err)
10281 return err;
10282 snprintf(msg, sizeof(msg),
10283 "commit %s missing from histedit script", id_str);
10284 free(id_str);
10285 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10289 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10290 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10291 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10292 "last commit in histedit script cannot be folded");
10294 return NULL;
10297 static const struct got_error *
10298 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10299 const char *path, struct got_object_id_queue *commits,
10300 struct got_repository *repo)
10302 const struct got_error *err = NULL;
10303 char *editor;
10304 FILE *f = NULL;
10306 err = get_editor(&editor);
10307 if (err)
10308 return err;
10310 if (spawn_editor(editor, path) == -1) {
10311 err = got_error_from_errno("failed spawning editor");
10312 goto done;
10315 f = fopen(path, "re");
10316 if (f == NULL) {
10317 err = got_error_from_errno("fopen");
10318 goto done;
10320 err = histedit_parse_list(histedit_cmds, f, repo);
10321 if (err)
10322 goto done;
10324 err = histedit_check_script(histedit_cmds, commits, repo);
10325 done:
10326 if (f && fclose(f) == EOF && err == NULL)
10327 err = got_error_from_errno("fclose");
10328 free(editor);
10329 return err;
10332 static const struct got_error *
10333 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10334 struct got_object_id_queue *, const char *, const char *,
10335 struct got_repository *);
10337 static const struct got_error *
10338 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10339 struct got_object_id_queue *commits, const char *branch_name,
10340 int edit_logmsg_only, int fold_only, int edit_only,
10341 struct got_repository *repo)
10343 const struct got_error *err;
10344 FILE *f = NULL;
10345 char *path = NULL;
10347 err = got_opentemp_named(&path, &f, "got-histedit");
10348 if (err)
10349 return err;
10351 err = write_cmd_list(f, branch_name, commits);
10352 if (err)
10353 goto done;
10355 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10356 fold_only, edit_only, repo);
10357 if (err)
10358 goto done;
10360 if (edit_logmsg_only || fold_only || edit_only) {
10361 rewind(f);
10362 err = histedit_parse_list(histedit_cmds, f, repo);
10363 } else {
10364 if (fclose(f) == EOF) {
10365 err = got_error_from_errno("fclose");
10366 goto done;
10368 f = NULL;
10369 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10370 if (err) {
10371 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10372 err->code != GOT_ERR_HISTEDIT_CMD)
10373 goto done;
10374 err = histedit_edit_list_retry(histedit_cmds, err,
10375 commits, path, branch_name, repo);
10378 done:
10379 if (f && fclose(f) == EOF && err == NULL)
10380 err = got_error_from_errno("fclose");
10381 if (path && unlink(path) != 0 && err == NULL)
10382 err = got_error_from_errno2("unlink", path);
10383 free(path);
10384 return err;
10387 static const struct got_error *
10388 histedit_save_list(struct got_histedit_list *histedit_cmds,
10389 struct got_worktree *worktree, struct got_repository *repo)
10391 const struct got_error *err = NULL;
10392 char *path = NULL;
10393 FILE *f = NULL;
10394 struct got_histedit_list_entry *hle;
10395 struct got_commit_object *commit = NULL;
10397 err = got_worktree_get_histedit_script_path(&path, worktree);
10398 if (err)
10399 return err;
10401 f = fopen(path, "we");
10402 if (f == NULL) {
10403 err = got_error_from_errno2("fopen", path);
10404 goto done;
10406 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10407 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10408 repo);
10409 if (err)
10410 break;
10412 if (hle->logmsg) {
10413 int n = fprintf(f, "%c %s\n",
10414 GOT_HISTEDIT_MESG, hle->logmsg);
10415 if (n < 0) {
10416 err = got_ferror(f, GOT_ERR_IO);
10417 break;
10421 done:
10422 if (f && fclose(f) == EOF && err == NULL)
10423 err = got_error_from_errno("fclose");
10424 free(path);
10425 if (commit)
10426 got_object_commit_close(commit);
10427 return err;
10430 void
10431 histedit_free_list(struct got_histedit_list *histedit_cmds)
10433 struct got_histedit_list_entry *hle;
10435 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10436 TAILQ_REMOVE(histedit_cmds, hle, entry);
10437 free(hle);
10441 static const struct got_error *
10442 histedit_load_list(struct got_histedit_list *histedit_cmds,
10443 const char *path, struct got_repository *repo)
10445 const struct got_error *err = NULL;
10446 FILE *f = NULL;
10448 f = fopen(path, "re");
10449 if (f == NULL) {
10450 err = got_error_from_errno2("fopen", path);
10451 goto done;
10454 err = histedit_parse_list(histedit_cmds, f, repo);
10455 done:
10456 if (f && fclose(f) == EOF && err == NULL)
10457 err = got_error_from_errno("fclose");
10458 return err;
10461 static const struct got_error *
10462 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10463 const struct got_error *edit_err, struct got_object_id_queue *commits,
10464 const char *path, const char *branch_name, struct got_repository *repo)
10466 const struct got_error *err = NULL, *prev_err = edit_err;
10467 int resp = ' ';
10469 while (resp != 'c' && resp != 'r' && resp != 'a') {
10470 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10471 "or (a)bort: ", getprogname(), prev_err->msg);
10472 resp = getchar();
10473 if (resp == '\n')
10474 resp = getchar();
10475 if (resp == 'c') {
10476 histedit_free_list(histedit_cmds);
10477 err = histedit_run_editor(histedit_cmds, path, commits,
10478 repo);
10479 if (err) {
10480 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10481 err->code != GOT_ERR_HISTEDIT_CMD)
10482 break;
10483 prev_err = err;
10484 resp = ' ';
10485 continue;
10487 break;
10488 } else if (resp == 'r') {
10489 histedit_free_list(histedit_cmds);
10490 err = histedit_edit_script(histedit_cmds,
10491 commits, branch_name, 0, 0, 0, repo);
10492 if (err) {
10493 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10494 err->code != GOT_ERR_HISTEDIT_CMD)
10495 break;
10496 prev_err = err;
10497 resp = ' ';
10498 continue;
10500 break;
10501 } else if (resp == 'a') {
10502 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10503 break;
10504 } else
10505 printf("invalid response '%c'\n", resp);
10508 return err;
10511 static const struct got_error *
10512 histedit_complete(struct got_worktree *worktree,
10513 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10514 struct got_reference *branch, struct got_repository *repo)
10516 printf("Switching work tree to %s\n",
10517 got_ref_get_symref_target(branch));
10518 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10519 branch, repo);
10522 static const struct got_error *
10523 show_histedit_progress(struct got_commit_object *commit,
10524 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10526 const struct got_error *err;
10527 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10529 err = got_object_id_str(&old_id_str, hle->commit_id);
10530 if (err)
10531 goto done;
10533 if (new_id) {
10534 err = got_object_id_str(&new_id_str, new_id);
10535 if (err)
10536 goto done;
10539 old_id_str[12] = '\0';
10540 if (new_id_str)
10541 new_id_str[12] = '\0';
10543 if (hle->logmsg) {
10544 logmsg = strdup(hle->logmsg);
10545 if (logmsg == NULL) {
10546 err = got_error_from_errno("strdup");
10547 goto done;
10549 trim_logmsg(logmsg, 42);
10550 } else {
10551 err = get_short_logmsg(&logmsg, 42, commit);
10552 if (err)
10553 goto done;
10556 switch (hle->cmd->code) {
10557 case GOT_HISTEDIT_PICK:
10558 case GOT_HISTEDIT_EDIT:
10559 printf("%s -> %s: %s\n", old_id_str,
10560 new_id_str ? new_id_str : "no-op change", logmsg);
10561 break;
10562 case GOT_HISTEDIT_DROP:
10563 case GOT_HISTEDIT_FOLD:
10564 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10565 logmsg);
10566 break;
10567 default:
10568 break;
10570 done:
10571 free(old_id_str);
10572 free(new_id_str);
10573 return err;
10576 static const struct got_error *
10577 histedit_commit(struct got_pathlist_head *merged_paths,
10578 struct got_worktree *worktree, struct got_fileindex *fileindex,
10579 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10580 struct got_repository *repo)
10582 const struct got_error *err;
10583 struct got_commit_object *commit;
10584 struct got_object_id *new_commit_id;
10586 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10587 && hle->logmsg == NULL) {
10588 err = histedit_edit_logmsg(hle, repo);
10589 if (err)
10590 return err;
10593 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10594 if (err)
10595 return err;
10597 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10598 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10599 hle->logmsg, repo);
10600 if (err) {
10601 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10602 goto done;
10603 err = show_histedit_progress(commit, hle, NULL);
10604 } else {
10605 err = show_histedit_progress(commit, hle, new_commit_id);
10606 free(new_commit_id);
10608 done:
10609 got_object_commit_close(commit);
10610 return err;
10613 static const struct got_error *
10614 histedit_skip_commit(struct got_histedit_list_entry *hle,
10615 struct got_worktree *worktree, struct got_repository *repo)
10617 const struct got_error *error;
10618 struct got_commit_object *commit;
10620 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10621 repo);
10622 if (error)
10623 return error;
10625 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10626 if (error)
10627 return error;
10629 error = show_histedit_progress(commit, hle, NULL);
10630 got_object_commit_close(commit);
10631 return error;
10634 static const struct got_error *
10635 check_local_changes(void *arg, unsigned char status,
10636 unsigned char staged_status, const char *path,
10637 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10638 struct got_object_id *commit_id, int dirfd, const char *de_name)
10640 int *have_local_changes = arg;
10642 switch (status) {
10643 case GOT_STATUS_ADD:
10644 case GOT_STATUS_DELETE:
10645 case GOT_STATUS_MODIFY:
10646 case GOT_STATUS_CONFLICT:
10647 *have_local_changes = 1;
10648 return got_error(GOT_ERR_CANCELLED);
10649 default:
10650 break;
10653 switch (staged_status) {
10654 case GOT_STATUS_ADD:
10655 case GOT_STATUS_DELETE:
10656 case GOT_STATUS_MODIFY:
10657 *have_local_changes = 1;
10658 return got_error(GOT_ERR_CANCELLED);
10659 default:
10660 break;
10663 return NULL;
10666 static const struct got_error *
10667 cmd_histedit(int argc, char *argv[])
10669 const struct got_error *error = NULL;
10670 struct got_worktree *worktree = NULL;
10671 struct got_fileindex *fileindex = NULL;
10672 struct got_repository *repo = NULL;
10673 char *cwd = NULL;
10674 struct got_reference *branch = NULL;
10675 struct got_reference *tmp_branch = NULL;
10676 struct got_object_id *resume_commit_id = NULL;
10677 struct got_object_id *base_commit_id = NULL;
10678 struct got_object_id *head_commit_id = NULL;
10679 struct got_commit_object *commit = NULL;
10680 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10681 struct got_update_progress_arg upa;
10682 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10683 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10684 int list_backups = 0, delete_backups = 0;
10685 const char *edit_script_path = NULL;
10686 struct got_object_id_queue commits;
10687 struct got_pathlist_head merged_paths;
10688 const struct got_object_id_queue *parent_ids;
10689 struct got_object_qid *pid;
10690 struct got_histedit_list histedit_cmds;
10691 struct got_histedit_list_entry *hle;
10693 STAILQ_INIT(&commits);
10694 TAILQ_INIT(&histedit_cmds);
10695 TAILQ_INIT(&merged_paths);
10696 memset(&upa, 0, sizeof(upa));
10698 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10699 switch (ch) {
10700 case 'a':
10701 abort_edit = 1;
10702 break;
10703 case 'c':
10704 continue_edit = 1;
10705 break;
10706 case 'e':
10707 edit_only = 1;
10708 break;
10709 case 'f':
10710 fold_only = 1;
10711 break;
10712 case 'F':
10713 edit_script_path = optarg;
10714 break;
10715 case 'm':
10716 edit_logmsg_only = 1;
10717 break;
10718 case 'l':
10719 list_backups = 1;
10720 break;
10721 case 'X':
10722 delete_backups = 1;
10723 break;
10724 default:
10725 usage_histedit();
10726 /* NOTREACHED */
10730 argc -= optind;
10731 argv += optind;
10733 #ifndef PROFILE
10734 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10735 "unveil", NULL) == -1)
10736 err(1, "pledge");
10737 #endif
10738 if (abort_edit && continue_edit)
10739 option_conflict('a', 'c');
10740 if (edit_script_path && edit_logmsg_only)
10741 option_conflict('F', 'm');
10742 if (abort_edit && edit_logmsg_only)
10743 option_conflict('a', 'm');
10744 if (continue_edit && edit_logmsg_only)
10745 option_conflict('c', 'm');
10746 if (abort_edit && fold_only)
10747 option_conflict('a', 'f');
10748 if (continue_edit && fold_only)
10749 option_conflict('c', 'f');
10750 if (fold_only && edit_logmsg_only)
10751 option_conflict('f', 'm');
10752 if (edit_script_path && fold_only)
10753 option_conflict('F', 'f');
10754 if (abort_edit && edit_only)
10755 option_conflict('a', 'e');
10756 if (continue_edit && edit_only)
10757 option_conflict('c', 'e');
10758 if (edit_only && edit_logmsg_only)
10759 option_conflict('e', 'm');
10760 if (edit_script_path && edit_only)
10761 option_conflict('F', 'e');
10762 if (list_backups) {
10763 if (abort_edit)
10764 option_conflict('l', 'a');
10765 if (continue_edit)
10766 option_conflict('l', 'c');
10767 if (edit_script_path)
10768 option_conflict('l', 'F');
10769 if (edit_logmsg_only)
10770 option_conflict('l', 'm');
10771 if (fold_only)
10772 option_conflict('l', 'f');
10773 if (edit_only)
10774 option_conflict('l', 'e');
10775 if (delete_backups)
10776 option_conflict('l', 'X');
10777 if (argc != 0 && argc != 1)
10778 usage_histedit();
10779 } else if (delete_backups) {
10780 if (abort_edit)
10781 option_conflict('X', 'a');
10782 if (continue_edit)
10783 option_conflict('X', 'c');
10784 if (edit_script_path)
10785 option_conflict('X', 'F');
10786 if (edit_logmsg_only)
10787 option_conflict('X', 'm');
10788 if (fold_only)
10789 option_conflict('X', 'f');
10790 if (edit_only)
10791 option_conflict('X', 'e');
10792 if (list_backups)
10793 option_conflict('X', 'l');
10794 if (argc != 0 && argc != 1)
10795 usage_histedit();
10796 } else if (argc != 0)
10797 usage_histedit();
10800 * This command cannot apply unveil(2) in all cases because the
10801 * user may choose to run an editor to edit the histedit script
10802 * and to edit individual commit log messages.
10803 * unveil(2) traverses exec(2); if an editor is used we have to
10804 * apply unveil after edit script and log messages have been written.
10805 * XXX TODO: Make use of unveil(2) where possible.
10808 cwd = getcwd(NULL, 0);
10809 if (cwd == NULL) {
10810 error = got_error_from_errno("getcwd");
10811 goto done;
10813 error = got_worktree_open(&worktree, cwd);
10814 if (error) {
10815 if (list_backups || delete_backups) {
10816 if (error->code != GOT_ERR_NOT_WORKTREE)
10817 goto done;
10818 } else {
10819 if (error->code == GOT_ERR_NOT_WORKTREE)
10820 error = wrap_not_worktree_error(error,
10821 "histedit", cwd);
10822 goto done;
10826 if (list_backups || delete_backups) {
10827 error = got_repo_open(&repo,
10828 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10829 NULL);
10830 if (error != NULL)
10831 goto done;
10832 error = apply_unveil(got_repo_get_path(repo), 0,
10833 worktree ? got_worktree_get_root_path(worktree) : NULL);
10834 if (error)
10835 goto done;
10836 error = process_backup_refs(
10837 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10838 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10839 goto done; /* nothing else to do */
10842 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10843 NULL);
10844 if (error != NULL)
10845 goto done;
10847 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10848 if (error)
10849 goto done;
10850 if (rebase_in_progress) {
10851 error = got_error(GOT_ERR_REBASING);
10852 goto done;
10855 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10856 repo);
10857 if (error)
10858 goto done;
10859 if (merge_in_progress) {
10860 error = got_error(GOT_ERR_MERGE_BUSY);
10861 goto done;
10864 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10865 if (error)
10866 goto done;
10868 if (edit_in_progress && edit_logmsg_only) {
10869 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10870 "histedit operation is in progress in this "
10871 "work tree and must be continued or aborted "
10872 "before the -m option can be used");
10873 goto done;
10875 if (edit_in_progress && fold_only) {
10876 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10877 "histedit operation is in progress in this "
10878 "work tree and must be continued or aborted "
10879 "before the -f option can be used");
10880 goto done;
10882 if (edit_in_progress && edit_only) {
10883 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10884 "histedit operation is in progress in this "
10885 "work tree and must be continued or aborted "
10886 "before the -e option can be used");
10887 goto done;
10890 if (edit_in_progress && abort_edit) {
10891 error = got_worktree_histedit_continue(&resume_commit_id,
10892 &tmp_branch, &branch, &base_commit_id, &fileindex,
10893 worktree, repo);
10894 if (error)
10895 goto done;
10896 printf("Switching work tree to %s\n",
10897 got_ref_get_symref_target(branch));
10898 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10899 branch, base_commit_id, abort_progress, &upa);
10900 if (error)
10901 goto done;
10902 printf("Histedit of %s aborted\n",
10903 got_ref_get_symref_target(branch));
10904 print_merge_progress_stats(&upa);
10905 goto done; /* nothing else to do */
10906 } else if (abort_edit) {
10907 error = got_error(GOT_ERR_NOT_HISTEDIT);
10908 goto done;
10911 if (continue_edit) {
10912 char *path;
10914 if (!edit_in_progress) {
10915 error = got_error(GOT_ERR_NOT_HISTEDIT);
10916 goto done;
10919 error = got_worktree_get_histedit_script_path(&path, worktree);
10920 if (error)
10921 goto done;
10923 error = histedit_load_list(&histedit_cmds, path, repo);
10924 free(path);
10925 if (error)
10926 goto done;
10928 error = got_worktree_histedit_continue(&resume_commit_id,
10929 &tmp_branch, &branch, &base_commit_id, &fileindex,
10930 worktree, repo);
10931 if (error)
10932 goto done;
10934 error = got_ref_resolve(&head_commit_id, repo, branch);
10935 if (error)
10936 goto done;
10938 error = got_object_open_as_commit(&commit, repo,
10939 head_commit_id);
10940 if (error)
10941 goto done;
10942 parent_ids = got_object_commit_get_parent_ids(commit);
10943 pid = STAILQ_FIRST(parent_ids);
10944 if (pid == NULL) {
10945 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10946 goto done;
10948 error = collect_commits(&commits, head_commit_id, &pid->id,
10949 base_commit_id, got_worktree_get_path_prefix(worktree),
10950 GOT_ERR_HISTEDIT_PATH, repo);
10951 got_object_commit_close(commit);
10952 commit = NULL;
10953 if (error)
10954 goto done;
10955 } else {
10956 if (edit_in_progress) {
10957 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10958 goto done;
10961 error = got_ref_open(&branch, repo,
10962 got_worktree_get_head_ref_name(worktree), 0);
10963 if (error != NULL)
10964 goto done;
10966 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10967 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10968 "will not edit commit history of a branch outside "
10969 "the \"refs/heads/\" reference namespace");
10970 goto done;
10973 error = got_ref_resolve(&head_commit_id, repo, branch);
10974 got_ref_close(branch);
10975 branch = NULL;
10976 if (error)
10977 goto done;
10979 error = got_object_open_as_commit(&commit, repo,
10980 head_commit_id);
10981 if (error)
10982 goto done;
10983 parent_ids = got_object_commit_get_parent_ids(commit);
10984 pid = STAILQ_FIRST(parent_ids);
10985 if (pid == NULL) {
10986 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10987 goto done;
10989 error = collect_commits(&commits, head_commit_id, &pid->id,
10990 got_worktree_get_base_commit_id(worktree),
10991 got_worktree_get_path_prefix(worktree),
10992 GOT_ERR_HISTEDIT_PATH, repo);
10993 got_object_commit_close(commit);
10994 commit = NULL;
10995 if (error)
10996 goto done;
10998 if (STAILQ_EMPTY(&commits)) {
10999 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11000 goto done;
11003 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11004 &base_commit_id, &fileindex, worktree, repo);
11005 if (error)
11006 goto done;
11008 if (edit_script_path) {
11009 error = histedit_load_list(&histedit_cmds,
11010 edit_script_path, repo);
11011 if (error) {
11012 got_worktree_histedit_abort(worktree, fileindex,
11013 repo, branch, base_commit_id,
11014 abort_progress, &upa);
11015 print_merge_progress_stats(&upa);
11016 goto done;
11018 } else {
11019 const char *branch_name;
11020 branch_name = got_ref_get_symref_target(branch);
11021 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11022 branch_name += 11;
11023 error = histedit_edit_script(&histedit_cmds, &commits,
11024 branch_name, edit_logmsg_only, fold_only,
11025 edit_only, repo);
11026 if (error) {
11027 got_worktree_histedit_abort(worktree, fileindex,
11028 repo, branch, base_commit_id,
11029 abort_progress, &upa);
11030 print_merge_progress_stats(&upa);
11031 goto done;
11036 error = histedit_save_list(&histedit_cmds, worktree,
11037 repo);
11038 if (error) {
11039 got_worktree_histedit_abort(worktree, fileindex,
11040 repo, branch, base_commit_id,
11041 abort_progress, &upa);
11042 print_merge_progress_stats(&upa);
11043 goto done;
11048 error = histedit_check_script(&histedit_cmds, &commits, repo);
11049 if (error)
11050 goto done;
11052 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11053 if (resume_commit_id) {
11054 if (got_object_id_cmp(hle->commit_id,
11055 resume_commit_id) != 0)
11056 continue;
11058 resume_commit_id = NULL;
11059 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11060 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11061 error = histedit_skip_commit(hle, worktree,
11062 repo);
11063 if (error)
11064 goto done;
11065 } else {
11066 struct got_pathlist_head paths;
11067 int have_changes = 0;
11069 TAILQ_INIT(&paths);
11070 error = got_pathlist_append(&paths, "", NULL);
11071 if (error)
11072 goto done;
11073 error = got_worktree_status(worktree, &paths,
11074 repo, 0, check_local_changes, &have_changes,
11075 check_cancelled, NULL);
11076 got_pathlist_free(&paths);
11077 if (error) {
11078 if (error->code != GOT_ERR_CANCELLED)
11079 goto done;
11080 if (sigint_received || sigpipe_received)
11081 goto done;
11083 if (have_changes) {
11084 error = histedit_commit(NULL, worktree,
11085 fileindex, tmp_branch, hle, repo);
11086 if (error)
11087 goto done;
11088 } else {
11089 error = got_object_open_as_commit(
11090 &commit, repo, hle->commit_id);
11091 if (error)
11092 goto done;
11093 error = show_histedit_progress(commit,
11094 hle, NULL);
11095 got_object_commit_close(commit);
11096 commit = NULL;
11097 if (error)
11098 goto done;
11101 continue;
11104 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11105 error = histedit_skip_commit(hle, worktree, repo);
11106 if (error)
11107 goto done;
11108 continue;
11111 error = got_object_open_as_commit(&commit, repo,
11112 hle->commit_id);
11113 if (error)
11114 goto done;
11115 parent_ids = got_object_commit_get_parent_ids(commit);
11116 pid = STAILQ_FIRST(parent_ids);
11118 error = got_worktree_histedit_merge_files(&merged_paths,
11119 worktree, fileindex, &pid->id, hle->commit_id, repo,
11120 update_progress, &upa, check_cancelled, NULL);
11121 if (error)
11122 goto done;
11123 got_object_commit_close(commit);
11124 commit = NULL;
11126 print_merge_progress_stats(&upa);
11127 if (upa.conflicts > 0 || upa.missing > 0 ||
11128 upa.not_deleted > 0 || upa.unversioned > 0) {
11129 if (upa.conflicts > 0) {
11130 error = show_rebase_merge_conflict(
11131 hle->commit_id, repo);
11132 if (error)
11133 goto done;
11135 got_worktree_rebase_pathlist_free(&merged_paths);
11136 break;
11139 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11140 char *id_str;
11141 error = got_object_id_str(&id_str, hle->commit_id);
11142 if (error)
11143 goto done;
11144 printf("Stopping histedit for amending commit %s\n",
11145 id_str);
11146 free(id_str);
11147 got_worktree_rebase_pathlist_free(&merged_paths);
11148 error = got_worktree_histedit_postpone(worktree,
11149 fileindex);
11150 goto done;
11153 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11154 error = histedit_skip_commit(hle, worktree, repo);
11155 if (error)
11156 goto done;
11157 continue;
11160 error = histedit_commit(&merged_paths, worktree, fileindex,
11161 tmp_branch, hle, repo);
11162 got_worktree_rebase_pathlist_free(&merged_paths);
11163 if (error)
11164 goto done;
11167 if (upa.conflicts > 0 || upa.missing > 0 ||
11168 upa.not_deleted > 0 || upa.unversioned > 0) {
11169 error = got_worktree_histedit_postpone(worktree, fileindex);
11170 if (error)
11171 goto done;
11172 if (upa.conflicts > 0 && upa.missing == 0 &&
11173 upa.not_deleted == 0 && upa.unversioned == 0) {
11174 error = got_error_msg(GOT_ERR_CONFLICTS,
11175 "conflicts must be resolved before histedit "
11176 "can continue");
11177 } else if (upa.conflicts > 0) {
11178 error = got_error_msg(GOT_ERR_CONFLICTS,
11179 "conflicts must be resolved before histedit "
11180 "can continue; changes destined for some "
11181 "files were not yet merged and should be "
11182 "merged manually if required before the "
11183 "histedit operation is continued");
11184 } else {
11185 error = got_error_msg(GOT_ERR_CONFLICTS,
11186 "changes destined for some files were not "
11187 "yet merged and should be merged manually "
11188 "if required before the histedit operation "
11189 "is continued");
11191 } else
11192 error = histedit_complete(worktree, fileindex, tmp_branch,
11193 branch, repo);
11194 done:
11195 got_object_id_queue_free(&commits);
11196 histedit_free_list(&histedit_cmds);
11197 free(head_commit_id);
11198 free(base_commit_id);
11199 free(resume_commit_id);
11200 if (commit)
11201 got_object_commit_close(commit);
11202 if (branch)
11203 got_ref_close(branch);
11204 if (tmp_branch)
11205 got_ref_close(tmp_branch);
11206 if (worktree)
11207 got_worktree_close(worktree);
11208 if (repo) {
11209 const struct got_error *close_err = got_repo_close(repo);
11210 if (error == NULL)
11211 error = close_err;
11213 return error;
11216 __dead static void
11217 usage_integrate(void)
11219 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11220 exit(1);
11223 static const struct got_error *
11224 cmd_integrate(int argc, char *argv[])
11226 const struct got_error *error = NULL;
11227 struct got_repository *repo = NULL;
11228 struct got_worktree *worktree = NULL;
11229 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11230 const char *branch_arg = NULL;
11231 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11232 struct got_fileindex *fileindex = NULL;
11233 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11234 int ch;
11235 struct got_update_progress_arg upa;
11237 while ((ch = getopt(argc, argv, "")) != -1) {
11238 switch (ch) {
11239 default:
11240 usage_integrate();
11241 /* NOTREACHED */
11245 argc -= optind;
11246 argv += optind;
11248 if (argc != 1)
11249 usage_integrate();
11250 branch_arg = argv[0];
11251 #ifndef PROFILE
11252 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11253 "unveil", NULL) == -1)
11254 err(1, "pledge");
11255 #endif
11256 cwd = getcwd(NULL, 0);
11257 if (cwd == NULL) {
11258 error = got_error_from_errno("getcwd");
11259 goto done;
11262 error = got_worktree_open(&worktree, cwd);
11263 if (error) {
11264 if (error->code == GOT_ERR_NOT_WORKTREE)
11265 error = wrap_not_worktree_error(error, "integrate",
11266 cwd);
11267 goto done;
11270 error = check_rebase_or_histedit_in_progress(worktree);
11271 if (error)
11272 goto done;
11274 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11275 NULL);
11276 if (error != NULL)
11277 goto done;
11279 error = apply_unveil(got_repo_get_path(repo), 0,
11280 got_worktree_get_root_path(worktree));
11281 if (error)
11282 goto done;
11284 error = check_merge_in_progress(worktree, repo);
11285 if (error)
11286 goto done;
11288 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11289 error = got_error_from_errno("asprintf");
11290 goto done;
11293 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11294 &base_branch_ref, worktree, refname, repo);
11295 if (error)
11296 goto done;
11298 refname = strdup(got_ref_get_name(branch_ref));
11299 if (refname == NULL) {
11300 error = got_error_from_errno("strdup");
11301 got_worktree_integrate_abort(worktree, fileindex, repo,
11302 branch_ref, base_branch_ref);
11303 goto done;
11305 base_refname = strdup(got_ref_get_name(base_branch_ref));
11306 if (base_refname == NULL) {
11307 error = got_error_from_errno("strdup");
11308 got_worktree_integrate_abort(worktree, fileindex, repo,
11309 branch_ref, base_branch_ref);
11310 goto done;
11313 error = got_ref_resolve(&commit_id, repo, branch_ref);
11314 if (error)
11315 goto done;
11317 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11318 if (error)
11319 goto done;
11321 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11322 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11323 "specified branch has already been integrated");
11324 got_worktree_integrate_abort(worktree, fileindex, repo,
11325 branch_ref, base_branch_ref);
11326 goto done;
11329 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11330 if (error) {
11331 if (error->code == GOT_ERR_ANCESTRY)
11332 error = got_error(GOT_ERR_REBASE_REQUIRED);
11333 got_worktree_integrate_abort(worktree, fileindex, repo,
11334 branch_ref, base_branch_ref);
11335 goto done;
11338 memset(&upa, 0, sizeof(upa));
11339 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11340 branch_ref, base_branch_ref, update_progress, &upa,
11341 check_cancelled, NULL);
11342 if (error)
11343 goto done;
11345 printf("Integrated %s into %s\n", refname, base_refname);
11346 print_update_progress_stats(&upa);
11347 done:
11348 if (repo) {
11349 const struct got_error *close_err = got_repo_close(repo);
11350 if (error == NULL)
11351 error = close_err;
11353 if (worktree)
11354 got_worktree_close(worktree);
11355 free(cwd);
11356 free(base_commit_id);
11357 free(commit_id);
11358 free(refname);
11359 free(base_refname);
11360 return error;
11363 __dead static void
11364 usage_merge(void)
11366 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11367 getprogname());
11368 exit(1);
11371 static const struct got_error *
11372 cmd_merge(int argc, char *argv[])
11374 const struct got_error *error = NULL;
11375 struct got_worktree *worktree = NULL;
11376 struct got_repository *repo = NULL;
11377 struct got_fileindex *fileindex = NULL;
11378 char *cwd = NULL, *id_str = NULL, *author = NULL;
11379 struct got_reference *branch = NULL, *wt_branch = NULL;
11380 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11381 struct got_object_id *wt_branch_tip = NULL;
11382 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11383 int interrupt_merge = 0;
11384 struct got_update_progress_arg upa;
11385 struct got_object_id *merge_commit_id = NULL;
11386 char *branch_name = NULL;
11388 memset(&upa, 0, sizeof(upa));
11390 while ((ch = getopt(argc, argv, "acn")) != -1) {
11391 switch (ch) {
11392 case 'a':
11393 abort_merge = 1;
11394 break;
11395 case 'c':
11396 continue_merge = 1;
11397 break;
11398 case 'n':
11399 interrupt_merge = 1;
11400 break;
11401 default:
11402 usage_rebase();
11403 /* NOTREACHED */
11407 argc -= optind;
11408 argv += optind;
11410 #ifndef PROFILE
11411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11412 "unveil", NULL) == -1)
11413 err(1, "pledge");
11414 #endif
11416 if (abort_merge && continue_merge)
11417 option_conflict('a', 'c');
11418 if (abort_merge || continue_merge) {
11419 if (argc != 0)
11420 usage_merge();
11421 } else if (argc != 1)
11422 usage_merge();
11424 cwd = getcwd(NULL, 0);
11425 if (cwd == NULL) {
11426 error = got_error_from_errno("getcwd");
11427 goto done;
11430 error = got_worktree_open(&worktree, cwd);
11431 if (error) {
11432 if (error->code == GOT_ERR_NOT_WORKTREE)
11433 error = wrap_not_worktree_error(error,
11434 "merge", cwd);
11435 goto done;
11438 error = got_repo_open(&repo,
11439 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11440 if (error != NULL)
11441 goto done;
11443 error = apply_unveil(got_repo_get_path(repo), 0,
11444 worktree ? got_worktree_get_root_path(worktree) : NULL);
11445 if (error)
11446 goto done;
11448 error = check_rebase_or_histedit_in_progress(worktree);
11449 if (error)
11450 goto done;
11452 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11453 repo);
11454 if (error)
11455 goto done;
11457 if (abort_merge) {
11458 if (!merge_in_progress) {
11459 error = got_error(GOT_ERR_NOT_MERGING);
11460 goto done;
11462 error = got_worktree_merge_continue(&branch_name,
11463 &branch_tip, &fileindex, worktree, repo);
11464 if (error)
11465 goto done;
11466 error = got_worktree_merge_abort(worktree, fileindex, repo,
11467 abort_progress, &upa);
11468 if (error)
11469 goto done;
11470 printf("Merge of %s aborted\n", branch_name);
11471 goto done; /* nothing else to do */
11474 error = get_author(&author, repo, worktree);
11475 if (error)
11476 goto done;
11478 if (continue_merge) {
11479 if (!merge_in_progress) {
11480 error = got_error(GOT_ERR_NOT_MERGING);
11481 goto done;
11483 error = got_worktree_merge_continue(&branch_name,
11484 &branch_tip, &fileindex, worktree, repo);
11485 if (error)
11486 goto done;
11487 } else {
11488 error = got_ref_open(&branch, repo, argv[0], 0);
11489 if (error != NULL)
11490 goto done;
11491 branch_name = strdup(got_ref_get_name(branch));
11492 if (branch_name == NULL) {
11493 error = got_error_from_errno("strdup");
11494 goto done;
11496 error = got_ref_resolve(&branch_tip, repo, branch);
11497 if (error)
11498 goto done;
11501 error = got_ref_open(&wt_branch, repo,
11502 got_worktree_get_head_ref_name(worktree), 0);
11503 if (error)
11504 goto done;
11505 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11506 if (error)
11507 goto done;
11508 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11509 wt_branch_tip, branch_tip, 0, repo,
11510 check_cancelled, NULL);
11511 if (error && error->code != GOT_ERR_ANCESTRY)
11512 goto done;
11514 if (!continue_merge) {
11515 error = check_path_prefix(wt_branch_tip, branch_tip,
11516 got_worktree_get_path_prefix(worktree),
11517 GOT_ERR_MERGE_PATH, repo);
11518 if (error)
11519 goto done;
11520 if (yca_id) {
11521 error = check_same_branch(wt_branch_tip, branch,
11522 yca_id, repo);
11523 if (error) {
11524 if (error->code != GOT_ERR_ANCESTRY)
11525 goto done;
11526 error = NULL;
11527 } else {
11528 static char msg[512];
11529 snprintf(msg, sizeof(msg),
11530 "cannot create a merge commit because "
11531 "%s is based on %s; %s can be integrated "
11532 "with 'got integrate' instead", branch_name,
11533 got_worktree_get_head_ref_name(worktree),
11534 branch_name);
11535 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11536 goto done;
11539 error = got_worktree_merge_prepare(&fileindex, worktree,
11540 branch, repo);
11541 if (error)
11542 goto done;
11544 error = got_worktree_merge_branch(worktree, fileindex,
11545 yca_id, branch_tip, repo, update_progress, &upa,
11546 check_cancelled, NULL);
11547 if (error)
11548 goto done;
11549 print_merge_progress_stats(&upa);
11550 if (!upa.did_something) {
11551 error = got_worktree_merge_abort(worktree, fileindex,
11552 repo, abort_progress, &upa);
11553 if (error)
11554 goto done;
11555 printf("Already up-to-date\n");
11556 goto done;
11560 if (interrupt_merge) {
11561 error = got_worktree_merge_postpone(worktree, fileindex);
11562 if (error)
11563 goto done;
11564 printf("Merge of %s interrupted on request\n", branch_name);
11565 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11566 upa.not_deleted > 0 || upa.unversioned > 0) {
11567 error = got_worktree_merge_postpone(worktree, fileindex);
11568 if (error)
11569 goto done;
11570 if (upa.conflicts > 0 && upa.missing == 0 &&
11571 upa.not_deleted == 0 && upa.unversioned == 0) {
11572 error = got_error_msg(GOT_ERR_CONFLICTS,
11573 "conflicts must be resolved before merging "
11574 "can continue");
11575 } else if (upa.conflicts > 0) {
11576 error = got_error_msg(GOT_ERR_CONFLICTS,
11577 "conflicts must be resolved before merging "
11578 "can continue; changes destined for some "
11579 "files were not yet merged and "
11580 "should be merged manually if required before the "
11581 "merge operation is continued");
11582 } else {
11583 error = got_error_msg(GOT_ERR_CONFLICTS,
11584 "changes destined for some "
11585 "files were not yet merged and should be "
11586 "merged manually if required before the "
11587 "merge operation is continued");
11589 goto done;
11590 } else {
11591 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11592 fileindex, author, NULL, 1, branch_tip, branch_name,
11593 repo, continue_merge ? print_status : NULL, NULL);
11594 if (error)
11595 goto done;
11596 error = got_worktree_merge_complete(worktree, fileindex, repo);
11597 if (error)
11598 goto done;
11599 error = got_object_id_str(&id_str, merge_commit_id);
11600 if (error)
11601 goto done;
11602 printf("Merged %s into %s: %s\n", branch_name,
11603 got_worktree_get_head_ref_name(worktree),
11604 id_str);
11607 done:
11608 free(id_str);
11609 free(merge_commit_id);
11610 free(author);
11611 free(branch_tip);
11612 free(branch_name);
11613 free(yca_id);
11614 if (branch)
11615 got_ref_close(branch);
11616 if (wt_branch)
11617 got_ref_close(wt_branch);
11618 if (worktree)
11619 got_worktree_close(worktree);
11620 if (repo) {
11621 const struct got_error *close_err = got_repo_close(repo);
11622 if (error == NULL)
11623 error = close_err;
11625 return error;
11628 __dead static void
11629 usage_stage(void)
11631 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11632 "[-S] [file-path ...]\n",
11633 getprogname());
11634 exit(1);
11637 static const struct got_error *
11638 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11639 const char *path, struct got_object_id *blob_id,
11640 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11641 int dirfd, const char *de_name)
11643 const struct got_error *err = NULL;
11644 char *id_str = NULL;
11646 if (staged_status != GOT_STATUS_ADD &&
11647 staged_status != GOT_STATUS_MODIFY &&
11648 staged_status != GOT_STATUS_DELETE)
11649 return NULL;
11651 if (staged_status == GOT_STATUS_ADD ||
11652 staged_status == GOT_STATUS_MODIFY)
11653 err = got_object_id_str(&id_str, staged_blob_id);
11654 else
11655 err = got_object_id_str(&id_str, blob_id);
11656 if (err)
11657 return err;
11659 printf("%s %c %s\n", id_str, staged_status, path);
11660 free(id_str);
11661 return NULL;
11664 static const struct got_error *
11665 cmd_stage(int argc, char *argv[])
11667 const struct got_error *error = NULL;
11668 struct got_repository *repo = NULL;
11669 struct got_worktree *worktree = NULL;
11670 char *cwd = NULL;
11671 struct got_pathlist_head paths;
11672 struct got_pathlist_entry *pe;
11673 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11674 FILE *patch_script_file = NULL;
11675 const char *patch_script_path = NULL;
11676 struct choose_patch_arg cpa;
11678 TAILQ_INIT(&paths);
11680 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11681 switch (ch) {
11682 case 'l':
11683 list_stage = 1;
11684 break;
11685 case 'p':
11686 pflag = 1;
11687 break;
11688 case 'F':
11689 patch_script_path = optarg;
11690 break;
11691 case 'S':
11692 allow_bad_symlinks = 1;
11693 break;
11694 default:
11695 usage_stage();
11696 /* NOTREACHED */
11700 argc -= optind;
11701 argv += optind;
11703 #ifndef PROFILE
11704 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11705 "unveil", NULL) == -1)
11706 err(1, "pledge");
11707 #endif
11708 if (list_stage && (pflag || patch_script_path))
11709 errx(1, "-l option cannot be used with other options");
11710 if (patch_script_path && !pflag)
11711 errx(1, "-F option can only be used together with -p option");
11713 cwd = getcwd(NULL, 0);
11714 if (cwd == NULL) {
11715 error = got_error_from_errno("getcwd");
11716 goto done;
11719 error = got_worktree_open(&worktree, cwd);
11720 if (error) {
11721 if (error->code == GOT_ERR_NOT_WORKTREE)
11722 error = wrap_not_worktree_error(error, "stage", cwd);
11723 goto done;
11726 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11727 NULL);
11728 if (error != NULL)
11729 goto done;
11731 if (patch_script_path) {
11732 patch_script_file = fopen(patch_script_path, "re");
11733 if (patch_script_file == NULL) {
11734 error = got_error_from_errno2("fopen",
11735 patch_script_path);
11736 goto done;
11739 error = apply_unveil(got_repo_get_path(repo), 0,
11740 got_worktree_get_root_path(worktree));
11741 if (error)
11742 goto done;
11744 error = check_merge_in_progress(worktree, repo);
11745 if (error)
11746 goto done;
11748 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11749 if (error)
11750 goto done;
11752 if (list_stage)
11753 error = got_worktree_status(worktree, &paths, repo, 0,
11754 print_stage, NULL, check_cancelled, NULL);
11755 else {
11756 cpa.patch_script_file = patch_script_file;
11757 cpa.action = "stage";
11758 error = got_worktree_stage(worktree, &paths,
11759 pflag ? NULL : print_status, NULL,
11760 pflag ? choose_patch : NULL, &cpa,
11761 allow_bad_symlinks, repo);
11763 done:
11764 if (patch_script_file && fclose(patch_script_file) == EOF &&
11765 error == NULL)
11766 error = got_error_from_errno2("fclose", patch_script_path);
11767 if (repo) {
11768 const struct got_error *close_err = got_repo_close(repo);
11769 if (error == NULL)
11770 error = close_err;
11772 if (worktree)
11773 got_worktree_close(worktree);
11774 TAILQ_FOREACH(pe, &paths, entry)
11775 free((char *)pe->path);
11776 got_pathlist_free(&paths);
11777 free(cwd);
11778 return error;
11781 __dead static void
11782 usage_unstage(void)
11784 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11785 "[file-path ...]\n",
11786 getprogname());
11787 exit(1);
11791 static const struct got_error *
11792 cmd_unstage(int argc, char *argv[])
11794 const struct got_error *error = NULL;
11795 struct got_repository *repo = NULL;
11796 struct got_worktree *worktree = NULL;
11797 char *cwd = NULL;
11798 struct got_pathlist_head paths;
11799 struct got_pathlist_entry *pe;
11800 int ch, pflag = 0;
11801 struct got_update_progress_arg upa;
11802 FILE *patch_script_file = NULL;
11803 const char *patch_script_path = NULL;
11804 struct choose_patch_arg cpa;
11806 TAILQ_INIT(&paths);
11808 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11809 switch (ch) {
11810 case 'p':
11811 pflag = 1;
11812 break;
11813 case 'F':
11814 patch_script_path = optarg;
11815 break;
11816 default:
11817 usage_unstage();
11818 /* NOTREACHED */
11822 argc -= optind;
11823 argv += optind;
11825 #ifndef PROFILE
11826 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11827 "unveil", NULL) == -1)
11828 err(1, "pledge");
11829 #endif
11830 if (patch_script_path && !pflag)
11831 errx(1, "-F option can only be used together with -p option");
11833 cwd = getcwd(NULL, 0);
11834 if (cwd == NULL) {
11835 error = got_error_from_errno("getcwd");
11836 goto done;
11839 error = got_worktree_open(&worktree, cwd);
11840 if (error) {
11841 if (error->code == GOT_ERR_NOT_WORKTREE)
11842 error = wrap_not_worktree_error(error, "unstage", cwd);
11843 goto done;
11846 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11847 NULL);
11848 if (error != NULL)
11849 goto done;
11851 if (patch_script_path) {
11852 patch_script_file = fopen(patch_script_path, "re");
11853 if (patch_script_file == NULL) {
11854 error = got_error_from_errno2("fopen",
11855 patch_script_path);
11856 goto done;
11860 error = apply_unveil(got_repo_get_path(repo), 0,
11861 got_worktree_get_root_path(worktree));
11862 if (error)
11863 goto done;
11865 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11866 if (error)
11867 goto done;
11869 cpa.patch_script_file = patch_script_file;
11870 cpa.action = "unstage";
11871 memset(&upa, 0, sizeof(upa));
11872 error = got_worktree_unstage(worktree, &paths, update_progress,
11873 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11874 if (!error)
11875 print_merge_progress_stats(&upa);
11876 done:
11877 if (patch_script_file && fclose(patch_script_file) == EOF &&
11878 error == NULL)
11879 error = got_error_from_errno2("fclose", patch_script_path);
11880 if (repo) {
11881 const struct got_error *close_err = got_repo_close(repo);
11882 if (error == NULL)
11883 error = close_err;
11885 if (worktree)
11886 got_worktree_close(worktree);
11887 TAILQ_FOREACH(pe, &paths, entry)
11888 free((char *)pe->path);
11889 got_pathlist_free(&paths);
11890 free(cwd);
11891 return error;
11894 __dead static void
11895 usage_cat(void)
11897 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11898 "arg1 [arg2 ...]\n", getprogname());
11899 exit(1);
11902 static const struct got_error *
11903 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11905 const struct got_error *err;
11906 struct got_blob_object *blob;
11908 err = got_object_open_as_blob(&blob, repo, id, 8192);
11909 if (err)
11910 return err;
11912 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11913 got_object_blob_close(blob);
11914 return err;
11917 static const struct got_error *
11918 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11920 const struct got_error *err;
11921 struct got_tree_object *tree;
11922 int nentries, i;
11924 err = got_object_open_as_tree(&tree, repo, id);
11925 if (err)
11926 return err;
11928 nentries = got_object_tree_get_nentries(tree);
11929 for (i = 0; i < nentries; i++) {
11930 struct got_tree_entry *te;
11931 char *id_str;
11932 if (sigint_received || sigpipe_received)
11933 break;
11934 te = got_object_tree_get_entry(tree, i);
11935 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11936 if (err)
11937 break;
11938 fprintf(outfile, "%s %.7o %s\n", id_str,
11939 got_tree_entry_get_mode(te),
11940 got_tree_entry_get_name(te));
11941 free(id_str);
11944 got_object_tree_close(tree);
11945 return err;
11948 static void
11949 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11951 long long h, m;
11952 char sign = '+';
11954 if (gmtoff < 0) {
11955 sign = '-';
11956 gmtoff = -gmtoff;
11959 h = (long long)gmtoff / 3600;
11960 m = ((long long)gmtoff - h*3600) / 60;
11961 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11964 static const struct got_error *
11965 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11967 const struct got_error *err;
11968 struct got_commit_object *commit;
11969 const struct got_object_id_queue *parent_ids;
11970 struct got_object_qid *pid;
11971 char *id_str = NULL;
11972 const char *logmsg = NULL;
11973 char gmtoff[6];
11975 err = got_object_open_as_commit(&commit, repo, id);
11976 if (err)
11977 return err;
11979 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11980 if (err)
11981 goto done;
11983 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11984 parent_ids = got_object_commit_get_parent_ids(commit);
11985 fprintf(outfile, "numparents %d\n",
11986 got_object_commit_get_nparents(commit));
11987 STAILQ_FOREACH(pid, parent_ids, entry) {
11988 char *pid_str;
11989 err = got_object_id_str(&pid_str, &pid->id);
11990 if (err)
11991 goto done;
11992 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11993 free(pid_str);
11995 format_gmtoff(gmtoff, sizeof(gmtoff),
11996 got_object_commit_get_author_gmtoff(commit));
11997 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11998 got_object_commit_get_author(commit),
11999 (long long)got_object_commit_get_author_time(commit),
12000 gmtoff);
12002 format_gmtoff(gmtoff, sizeof(gmtoff),
12003 got_object_commit_get_committer_gmtoff(commit));
12004 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12005 got_object_commit_get_author(commit),
12006 (long long)got_object_commit_get_committer_time(commit),
12007 gmtoff);
12009 logmsg = got_object_commit_get_logmsg_raw(commit);
12010 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12011 fprintf(outfile, "%s", logmsg);
12012 done:
12013 free(id_str);
12014 got_object_commit_close(commit);
12015 return err;
12018 static const struct got_error *
12019 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12021 const struct got_error *err;
12022 struct got_tag_object *tag;
12023 char *id_str = NULL;
12024 const char *tagmsg = NULL;
12025 char gmtoff[6];
12027 err = got_object_open_as_tag(&tag, repo, id);
12028 if (err)
12029 return err;
12031 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12032 if (err)
12033 goto done;
12035 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12037 switch (got_object_tag_get_object_type(tag)) {
12038 case GOT_OBJ_TYPE_BLOB:
12039 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12040 GOT_OBJ_LABEL_BLOB);
12041 break;
12042 case GOT_OBJ_TYPE_TREE:
12043 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12044 GOT_OBJ_LABEL_TREE);
12045 break;
12046 case GOT_OBJ_TYPE_COMMIT:
12047 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12048 GOT_OBJ_LABEL_COMMIT);
12049 break;
12050 case GOT_OBJ_TYPE_TAG:
12051 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12052 GOT_OBJ_LABEL_TAG);
12053 break;
12054 default:
12055 break;
12058 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12059 got_object_tag_get_name(tag));
12061 format_gmtoff(gmtoff, sizeof(gmtoff),
12062 got_object_tag_get_tagger_gmtoff(tag));
12063 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12064 got_object_tag_get_tagger(tag),
12065 (long long)got_object_tag_get_tagger_time(tag),
12066 gmtoff);
12068 tagmsg = got_object_tag_get_message(tag);
12069 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12070 fprintf(outfile, "%s", tagmsg);
12071 done:
12072 free(id_str);
12073 got_object_tag_close(tag);
12074 return err;
12077 static const struct got_error *
12078 cmd_cat(int argc, char *argv[])
12080 const struct got_error *error;
12081 struct got_repository *repo = NULL;
12082 struct got_worktree *worktree = NULL;
12083 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12084 const char *commit_id_str = NULL;
12085 struct got_object_id *id = NULL, *commit_id = NULL;
12086 struct got_commit_object *commit = NULL;
12087 int ch, obj_type, i, force_path = 0;
12088 struct got_reflist_head refs;
12090 TAILQ_INIT(&refs);
12092 #ifndef PROFILE
12093 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12094 NULL) == -1)
12095 err(1, "pledge");
12096 #endif
12098 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12099 switch (ch) {
12100 case 'c':
12101 commit_id_str = optarg;
12102 break;
12103 case 'r':
12104 repo_path = realpath(optarg, NULL);
12105 if (repo_path == NULL)
12106 return got_error_from_errno2("realpath",
12107 optarg);
12108 got_path_strip_trailing_slashes(repo_path);
12109 break;
12110 case 'P':
12111 force_path = 1;
12112 break;
12113 default:
12114 usage_cat();
12115 /* NOTREACHED */
12119 argc -= optind;
12120 argv += optind;
12122 cwd = getcwd(NULL, 0);
12123 if (cwd == NULL) {
12124 error = got_error_from_errno("getcwd");
12125 goto done;
12128 if (repo_path == NULL) {
12129 error = got_worktree_open(&worktree, cwd);
12130 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12131 goto done;
12132 if (worktree) {
12133 repo_path = strdup(
12134 got_worktree_get_repo_path(worktree));
12135 if (repo_path == NULL) {
12136 error = got_error_from_errno("strdup");
12137 goto done;
12140 /* Release work tree lock. */
12141 got_worktree_close(worktree);
12142 worktree = NULL;
12146 if (repo_path == NULL) {
12147 repo_path = strdup(cwd);
12148 if (repo_path == NULL)
12149 return got_error_from_errno("strdup");
12152 error = got_repo_open(&repo, repo_path, NULL);
12153 free(repo_path);
12154 if (error != NULL)
12155 goto done;
12157 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12158 if (error)
12159 goto done;
12161 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12162 if (error)
12163 goto done;
12165 if (commit_id_str == NULL)
12166 commit_id_str = GOT_REF_HEAD;
12167 error = got_repo_match_object_id(&commit_id, NULL,
12168 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12169 if (error)
12170 goto done;
12172 error = got_object_open_as_commit(&commit, repo, commit_id);
12173 if (error)
12174 goto done;
12176 for (i = 0; i < argc; i++) {
12177 if (force_path) {
12178 error = got_object_id_by_path(&id, repo, commit,
12179 argv[i]);
12180 if (error)
12181 break;
12182 } else {
12183 error = got_repo_match_object_id(&id, &label, argv[i],
12184 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12185 repo);
12186 if (error) {
12187 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12188 error->code != GOT_ERR_NOT_REF)
12189 break;
12190 error = got_object_id_by_path(&id, repo,
12191 commit, argv[i]);
12192 if (error)
12193 break;
12197 error = got_object_get_type(&obj_type, repo, id);
12198 if (error)
12199 break;
12201 switch (obj_type) {
12202 case GOT_OBJ_TYPE_BLOB:
12203 error = cat_blob(id, repo, stdout);
12204 break;
12205 case GOT_OBJ_TYPE_TREE:
12206 error = cat_tree(id, repo, stdout);
12207 break;
12208 case GOT_OBJ_TYPE_COMMIT:
12209 error = cat_commit(id, repo, stdout);
12210 break;
12211 case GOT_OBJ_TYPE_TAG:
12212 error = cat_tag(id, repo, stdout);
12213 break;
12214 default:
12215 error = got_error(GOT_ERR_OBJ_TYPE);
12216 break;
12218 if (error)
12219 break;
12220 free(label);
12221 label = NULL;
12222 free(id);
12223 id = NULL;
12225 done:
12226 free(label);
12227 free(id);
12228 free(commit_id);
12229 if (commit)
12230 got_object_commit_close(commit);
12231 if (worktree)
12232 got_worktree_close(worktree);
12233 if (repo) {
12234 const struct got_error *close_err = got_repo_close(repo);
12235 if (error == NULL)
12236 error = close_err;
12238 got_ref_list_free(&refs);
12239 return error;
12242 __dead static void
12243 usage_info(void)
12245 fprintf(stderr, "usage: %s info [path ...]\n",
12246 getprogname());
12247 exit(1);
12250 static const struct got_error *
12251 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12252 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12253 struct got_object_id *commit_id)
12255 const struct got_error *err = NULL;
12256 char *id_str = NULL;
12257 char datebuf[128];
12258 struct tm mytm, *tm;
12259 struct got_pathlist_head *paths = arg;
12260 struct got_pathlist_entry *pe;
12263 * Clear error indication from any of the path arguments which
12264 * would cause this file index entry to be displayed.
12266 TAILQ_FOREACH(pe, paths, entry) {
12267 if (got_path_cmp(path, pe->path, strlen(path),
12268 pe->path_len) == 0 ||
12269 got_path_is_child(path, pe->path, pe->path_len))
12270 pe->data = NULL; /* no error */
12273 printf(GOT_COMMIT_SEP_STR);
12274 if (S_ISLNK(mode))
12275 printf("symlink: %s\n", path);
12276 else if (S_ISREG(mode)) {
12277 printf("file: %s\n", path);
12278 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12279 } else if (S_ISDIR(mode))
12280 printf("directory: %s\n", path);
12281 else
12282 printf("something: %s\n", path);
12284 tm = localtime_r(&mtime, &mytm);
12285 if (tm == NULL)
12286 return NULL;
12287 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12288 return got_error(GOT_ERR_NO_SPACE);
12289 printf("timestamp: %s\n", datebuf);
12291 if (blob_id) {
12292 err = got_object_id_str(&id_str, blob_id);
12293 if (err)
12294 return err;
12295 printf("based on blob: %s\n", id_str);
12296 free(id_str);
12299 if (staged_blob_id) {
12300 err = got_object_id_str(&id_str, staged_blob_id);
12301 if (err)
12302 return err;
12303 printf("based on staged blob: %s\n", id_str);
12304 free(id_str);
12307 if (commit_id) {
12308 err = got_object_id_str(&id_str, commit_id);
12309 if (err)
12310 return err;
12311 printf("based on commit: %s\n", id_str);
12312 free(id_str);
12315 return NULL;
12318 static const struct got_error *
12319 cmd_info(int argc, char *argv[])
12321 const struct got_error *error = NULL;
12322 struct got_worktree *worktree = NULL;
12323 char *cwd = NULL, *id_str = NULL;
12324 struct got_pathlist_head paths;
12325 struct got_pathlist_entry *pe;
12326 char *uuidstr = NULL;
12327 int ch, show_files = 0;
12329 TAILQ_INIT(&paths);
12331 while ((ch = getopt(argc, argv, "")) != -1) {
12332 switch (ch) {
12333 default:
12334 usage_info();
12335 /* NOTREACHED */
12339 argc -= optind;
12340 argv += optind;
12342 #ifndef PROFILE
12343 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12344 NULL) == -1)
12345 err(1, "pledge");
12346 #endif
12347 cwd = getcwd(NULL, 0);
12348 if (cwd == NULL) {
12349 error = got_error_from_errno("getcwd");
12350 goto done;
12353 error = got_worktree_open(&worktree, cwd);
12354 if (error) {
12355 if (error->code == GOT_ERR_NOT_WORKTREE)
12356 error = wrap_not_worktree_error(error, "info", cwd);
12357 goto done;
12360 #ifndef PROFILE
12361 /* Remove "cpath" promise. */
12362 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12363 NULL) == -1)
12364 err(1, "pledge");
12365 #endif
12366 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12367 if (error)
12368 goto done;
12370 if (argc >= 1) {
12371 error = get_worktree_paths_from_argv(&paths, argc, argv,
12372 worktree);
12373 if (error)
12374 goto done;
12375 show_files = 1;
12378 error = got_object_id_str(&id_str,
12379 got_worktree_get_base_commit_id(worktree));
12380 if (error)
12381 goto done;
12383 error = got_worktree_get_uuid(&uuidstr, worktree);
12384 if (error)
12385 goto done;
12387 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12388 printf("work tree base commit: %s\n", id_str);
12389 printf("work tree path prefix: %s\n",
12390 got_worktree_get_path_prefix(worktree));
12391 printf("work tree branch reference: %s\n",
12392 got_worktree_get_head_ref_name(worktree));
12393 printf("work tree UUID: %s\n", uuidstr);
12394 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12396 if (show_files) {
12397 struct got_pathlist_entry *pe;
12398 TAILQ_FOREACH(pe, &paths, entry) {
12399 if (pe->path_len == 0)
12400 continue;
12402 * Assume this path will fail. This will be corrected
12403 * in print_path_info() in case the path does suceeed.
12405 pe->data = (void *)got_error_path(pe->path,
12406 GOT_ERR_BAD_PATH);
12408 error = got_worktree_path_info(worktree, &paths,
12409 print_path_info, &paths, check_cancelled, NULL);
12410 if (error)
12411 goto done;
12412 TAILQ_FOREACH(pe, &paths, entry) {
12413 if (pe->data != NULL) {
12414 error = pe->data; /* bad path */
12415 break;
12419 done:
12420 TAILQ_FOREACH(pe, &paths, entry)
12421 free((char *)pe->path);
12422 got_pathlist_free(&paths);
12423 free(cwd);
12424 free(id_str);
12425 free(uuidstr);
12426 return error;