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 return err;
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 err = got_error_from_errno("gmtime_r");
3922 goto done;
3924 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3925 err = got_error(GOT_ERR_NO_SPACE);
3926 goto done;
3929 err = got_object_commit_get_logmsg(&logmsg0, commit);
3930 if (err)
3931 goto done;
3933 s = logmsg0;
3934 while (isspace((unsigned char)s[0]))
3935 s++;
3937 nl = strchr(s, '\n');
3938 if (nl) {
3939 *nl = '\0';
3942 if (ref_str)
3943 printf("%s%-7s %s\n", datebuf, ref_str, s);
3944 else
3945 printf("%s%.7s %s\n", datebuf, id_str, s);
3947 if (fflush(stdout) != 0 && err == NULL)
3948 err = got_error_from_errno("fflush");
3949 done:
3950 free(id_str);
3951 free(ref_str);
3952 free(logmsg0);
3953 return err;
3956 static const struct got_error *
3957 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3958 struct got_repository *repo, const char *path,
3959 struct got_pathlist_head *changed_paths, int show_patch,
3960 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3961 const char *custom_refs_str)
3963 const struct got_error *err = NULL;
3964 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3965 char datebuf[26];
3966 time_t committer_time;
3967 const char *author, *committer;
3968 char *refs_str = NULL;
3970 err = got_object_id_str(&id_str, id);
3971 if (err)
3972 return err;
3974 if (custom_refs_str == NULL) {
3975 struct got_reflist_head *refs;
3976 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3977 if (refs) {
3978 err = build_refs_str(&refs_str, refs, id, repo, 0);
3979 if (err)
3980 goto done;
3984 printf(GOT_COMMIT_SEP_STR);
3985 if (custom_refs_str)
3986 printf("commit %s (%s)\n", id_str, custom_refs_str);
3987 else
3988 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3989 refs_str ? refs_str : "", refs_str ? ")" : "");
3990 free(id_str);
3991 id_str = NULL;
3992 free(refs_str);
3993 refs_str = NULL;
3994 printf("from: %s\n", got_object_commit_get_author(commit));
3995 committer_time = got_object_commit_get_committer_time(commit);
3996 datestr = get_datestr(&committer_time, datebuf);
3997 if (datestr)
3998 printf("date: %s UTC\n", datestr);
3999 author = got_object_commit_get_author(commit);
4000 committer = got_object_commit_get_committer(commit);
4001 if (strcmp(author, committer) != 0)
4002 printf("via: %s\n", committer);
4003 if (got_object_commit_get_nparents(commit) > 1) {
4004 const struct got_object_id_queue *parent_ids;
4005 struct got_object_qid *qid;
4006 int n = 1;
4007 parent_ids = got_object_commit_get_parent_ids(commit);
4008 STAILQ_FOREACH(qid, parent_ids, entry) {
4009 err = got_object_id_str(&id_str, &qid->id);
4010 if (err)
4011 goto done;
4012 printf("parent %d: %s\n", n++, id_str);
4013 free(id_str);
4014 id_str = NULL;
4018 err = got_object_commit_get_logmsg(&logmsg0, commit);
4019 if (err)
4020 goto done;
4022 logmsg = logmsg0;
4023 do {
4024 line = strsep(&logmsg, "\n");
4025 if (line)
4026 printf(" %s\n", line);
4027 } while (line);
4028 free(logmsg0);
4030 if (changed_paths) {
4031 struct got_pathlist_entry *pe;
4032 TAILQ_FOREACH(pe, changed_paths, entry) {
4033 struct got_diff_changed_path *cp = pe->data;
4034 printf(" %c %s\n", cp->status, pe->path);
4036 printf("\n");
4038 if (show_patch) {
4039 err = print_patch(commit, id, path, diff_context, repo, stdout);
4040 if (err == 0)
4041 printf("\n");
4044 if (fflush(stdout) != 0 && err == NULL)
4045 err = got_error_from_errno("fflush");
4046 done:
4047 free(id_str);
4048 free(refs_str);
4049 return err;
4052 static const struct got_error *
4053 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4054 struct got_repository *repo, const char *path, int show_changed_paths,
4055 int show_patch, const char *search_pattern, int diff_context, int limit,
4056 int log_branches, int reverse_display_order,
4057 struct got_reflist_object_id_map *refs_idmap, int one_line,
4058 FILE *tmpfile)
4060 const struct got_error *err;
4061 struct got_commit_graph *graph;
4062 regex_t regex;
4063 int have_match;
4064 struct got_object_id_queue reversed_commits;
4065 struct got_object_qid *qid;
4066 struct got_commit_object *commit;
4067 struct got_pathlist_head changed_paths;
4068 struct got_pathlist_entry *pe;
4070 STAILQ_INIT(&reversed_commits);
4071 TAILQ_INIT(&changed_paths);
4073 if (search_pattern && regcomp(&regex, search_pattern,
4074 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4075 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4077 err = got_commit_graph_open(&graph, path, !log_branches);
4078 if (err)
4079 return err;
4080 err = got_commit_graph_iter_start(graph, root_id, repo,
4081 check_cancelled, NULL);
4082 if (err)
4083 goto done;
4084 for (;;) {
4085 struct got_object_id *id;
4087 if (sigint_received || sigpipe_received)
4088 break;
4090 err = got_commit_graph_iter_next(&id, graph, repo,
4091 check_cancelled, NULL);
4092 if (err) {
4093 if (err->code == GOT_ERR_ITER_COMPLETED)
4094 err = NULL;
4095 break;
4097 if (id == NULL)
4098 break;
4100 err = got_object_open_as_commit(&commit, repo, id);
4101 if (err)
4102 break;
4104 if (show_changed_paths && !reverse_display_order) {
4105 err = get_changed_paths(&changed_paths, commit, repo);
4106 if (err)
4107 break;
4110 if (search_pattern) {
4111 err = match_commit(&have_match, id, commit, &regex);
4112 if (err) {
4113 got_object_commit_close(commit);
4114 break;
4116 if (have_match == 0 && show_changed_paths)
4117 match_changed_paths(&have_match,
4118 &changed_paths, &regex);
4119 if (have_match == 0 && show_patch) {
4120 err = match_patch(&have_match, commit, id,
4121 path, diff_context, repo, &regex,
4122 tmpfile);
4123 if (err)
4124 break;
4126 if (have_match == 0) {
4127 got_object_commit_close(commit);
4128 TAILQ_FOREACH(pe, &changed_paths, entry) {
4129 free((char *)pe->path);
4130 free(pe->data);
4132 got_pathlist_free(&changed_paths);
4133 continue;
4137 if (reverse_display_order) {
4138 err = got_object_qid_alloc(&qid, id);
4139 if (err)
4140 break;
4141 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4142 got_object_commit_close(commit);
4143 } else {
4144 if (one_line)
4145 err = print_commit_oneline(commit, id,
4146 repo, refs_idmap);
4147 else
4148 err = print_commit(commit, id, repo, path,
4149 show_changed_paths ? &changed_paths : NULL,
4150 show_patch, diff_context, refs_idmap, NULL);
4151 got_object_commit_close(commit);
4152 if (err)
4153 break;
4155 if ((limit && --limit == 0) ||
4156 (end_id && got_object_id_cmp(id, end_id) == 0))
4157 break;
4159 TAILQ_FOREACH(pe, &changed_paths, entry) {
4160 free((char *)pe->path);
4161 free(pe->data);
4163 got_pathlist_free(&changed_paths);
4165 if (reverse_display_order) {
4166 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4167 err = got_object_open_as_commit(&commit, repo,
4168 &qid->id);
4169 if (err)
4170 break;
4171 if (show_changed_paths) {
4172 err = get_changed_paths(&changed_paths,
4173 commit, repo);
4174 if (err)
4175 break;
4177 if (one_line)
4178 err = print_commit_oneline(commit, &qid->id,
4179 repo, refs_idmap);
4180 else
4181 err = print_commit(commit, &qid->id, repo, path,
4182 show_changed_paths ? &changed_paths : NULL,
4183 show_patch, diff_context, refs_idmap, NULL);
4184 got_object_commit_close(commit);
4185 if (err)
4186 break;
4187 TAILQ_FOREACH(pe, &changed_paths, entry) {
4188 free((char *)pe->path);
4189 free(pe->data);
4191 got_pathlist_free(&changed_paths);
4194 done:
4195 while (!STAILQ_EMPTY(&reversed_commits)) {
4196 qid = STAILQ_FIRST(&reversed_commits);
4197 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4198 got_object_qid_free(qid);
4200 TAILQ_FOREACH(pe, &changed_paths, entry) {
4201 free((char *)pe->path);
4202 free(pe->data);
4204 got_pathlist_free(&changed_paths);
4205 if (search_pattern)
4206 regfree(&regex);
4207 got_commit_graph_close(graph);
4208 return err;
4211 __dead static void
4212 usage_log(void)
4214 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4215 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4216 "[-r repository-path] [-R] [path]\n", getprogname());
4217 exit(1);
4220 static int
4221 get_default_log_limit(void)
4223 const char *got_default_log_limit;
4224 long long n;
4225 const char *errstr;
4227 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4228 if (got_default_log_limit == NULL)
4229 return 0;
4230 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4231 if (errstr != NULL)
4232 return 0;
4233 return n;
4236 static const struct got_error *
4237 cmd_log(int argc, char *argv[])
4239 const struct got_error *error;
4240 struct got_repository *repo = NULL;
4241 struct got_worktree *worktree = NULL;
4242 struct got_object_id *start_id = NULL, *end_id = NULL;
4243 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4244 const char *start_commit = NULL, *end_commit = NULL;
4245 const char *search_pattern = NULL;
4246 int diff_context = -1, ch;
4247 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4248 int reverse_display_order = 0, one_line = 0;
4249 const char *errstr;
4250 struct got_reflist_head refs;
4251 struct got_reflist_object_id_map *refs_idmap = NULL;
4252 FILE *tmpfile = NULL;
4254 TAILQ_INIT(&refs);
4256 #ifndef PROFILE
4257 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4258 NULL)
4259 == -1)
4260 err(1, "pledge");
4261 #endif
4263 limit = get_default_log_limit();
4265 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4266 switch (ch) {
4267 case 'p':
4268 show_patch = 1;
4269 break;
4270 case 'P':
4271 show_changed_paths = 1;
4272 break;
4273 case 'c':
4274 start_commit = optarg;
4275 break;
4276 case 'C':
4277 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4278 &errstr);
4279 if (errstr != NULL)
4280 errx(1, "number of context lines is %s: %s",
4281 errstr, optarg);
4282 break;
4283 case 'l':
4284 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4285 if (errstr != NULL)
4286 errx(1, "number of commits is %s: %s",
4287 errstr, optarg);
4288 break;
4289 case 'b':
4290 log_branches = 1;
4291 break;
4292 case 'r':
4293 repo_path = realpath(optarg, NULL);
4294 if (repo_path == NULL)
4295 return got_error_from_errno2("realpath",
4296 optarg);
4297 got_path_strip_trailing_slashes(repo_path);
4298 break;
4299 case 'R':
4300 reverse_display_order = 1;
4301 break;
4302 case 's':
4303 one_line = 1;
4304 break;
4305 case 'S':
4306 search_pattern = optarg;
4307 break;
4308 case 'x':
4309 end_commit = optarg;
4310 break;
4311 default:
4312 usage_log();
4313 /* NOTREACHED */
4317 argc -= optind;
4318 argv += optind;
4320 if (diff_context == -1)
4321 diff_context = 3;
4322 else if (!show_patch)
4323 errx(1, "-C requires -p");
4325 if (one_line && (show_patch || show_changed_paths))
4326 errx(1, "cannot use -s with -p or -P");
4328 cwd = getcwd(NULL, 0);
4329 if (cwd == NULL) {
4330 error = got_error_from_errno("getcwd");
4331 goto done;
4334 if (repo_path == NULL) {
4335 error = got_worktree_open(&worktree, cwd);
4336 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4337 goto done;
4338 error = NULL;
4341 if (argc == 1) {
4342 if (worktree) {
4343 error = got_worktree_resolve_path(&path, worktree,
4344 argv[0]);
4345 if (error)
4346 goto done;
4347 } else {
4348 path = strdup(argv[0]);
4349 if (path == NULL) {
4350 error = got_error_from_errno("strdup");
4351 goto done;
4354 } else if (argc != 0)
4355 usage_log();
4357 if (repo_path == NULL) {
4358 repo_path = worktree ?
4359 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4361 if (repo_path == NULL) {
4362 error = got_error_from_errno("strdup");
4363 goto done;
4366 error = got_repo_open(&repo, repo_path, NULL);
4367 if (error != NULL)
4368 goto done;
4370 error = apply_unveil(got_repo_get_path(repo), 1,
4371 worktree ? got_worktree_get_root_path(worktree) : NULL);
4372 if (error)
4373 goto done;
4375 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4376 if (error)
4377 goto done;
4379 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4380 if (error)
4381 goto done;
4383 if (start_commit == NULL) {
4384 struct got_reference *head_ref;
4385 struct got_commit_object *commit = NULL;
4386 error = got_ref_open(&head_ref, repo,
4387 worktree ? got_worktree_get_head_ref_name(worktree)
4388 : GOT_REF_HEAD, 0);
4389 if (error != NULL)
4390 goto done;
4391 error = got_ref_resolve(&start_id, repo, head_ref);
4392 got_ref_close(head_ref);
4393 if (error != NULL)
4394 goto done;
4395 error = got_object_open_as_commit(&commit, repo,
4396 start_id);
4397 if (error != NULL)
4398 goto done;
4399 got_object_commit_close(commit);
4400 } else {
4401 error = got_repo_match_object_id(&start_id, NULL,
4402 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4403 if (error != NULL)
4404 goto done;
4406 if (end_commit != NULL) {
4407 error = got_repo_match_object_id(&end_id, NULL,
4408 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4409 if (error != NULL)
4410 goto done;
4413 if (worktree) {
4415 * If a path was specified on the command line it was resolved
4416 * to a path in the work tree above. Prepend the work tree's
4417 * path prefix to obtain the corresponding in-repository path.
4419 if (path) {
4420 const char *prefix;
4421 prefix = got_worktree_get_path_prefix(worktree);
4422 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4423 (path[0] != '\0') ? "/" : "", path) == -1) {
4424 error = got_error_from_errno("asprintf");
4425 goto done;
4428 } else
4429 error = got_repo_map_path(&in_repo_path, repo,
4430 path ? path : "");
4431 if (error != NULL)
4432 goto done;
4433 if (in_repo_path) {
4434 free(path);
4435 path = in_repo_path;
4438 if (worktree) {
4439 /* Release work tree lock. */
4440 got_worktree_close(worktree);
4441 worktree = NULL;
4444 if (search_pattern && show_patch) {
4445 tmpfile = got_opentemp();
4446 if (tmpfile == NULL) {
4447 error = got_error_from_errno("got_opentemp");
4448 goto done;
4452 error = print_commits(start_id, end_id, repo, path ? path : "",
4453 show_changed_paths, show_patch, search_pattern, diff_context,
4454 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4455 tmpfile);
4456 done:
4457 free(path);
4458 free(repo_path);
4459 free(cwd);
4460 if (worktree)
4461 got_worktree_close(worktree);
4462 if (repo) {
4463 const struct got_error *close_err = got_repo_close(repo);
4464 if (error == NULL)
4465 error = close_err;
4467 if (refs_idmap)
4468 got_reflist_object_id_map_free(refs_idmap);
4469 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4470 error = got_error_from_errno("fclose");
4471 got_ref_list_free(&refs);
4472 return error;
4475 __dead static void
4476 usage_diff(void)
4478 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4479 "[-r repository-path] [-s] [-w] [-P] "
4480 "[object1 object2 | path ...]\n", getprogname());
4481 exit(1);
4484 struct print_diff_arg {
4485 struct got_repository *repo;
4486 struct got_worktree *worktree;
4487 int diff_context;
4488 const char *id_str;
4489 int header_shown;
4490 int diff_staged;
4491 int ignore_whitespace;
4492 int force_text_diff;
4496 * Create a file which contains the target path of a symlink so we can feed
4497 * it as content to the diff engine.
4499 static const struct got_error *
4500 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4501 const char *abspath)
4503 const struct got_error *err = NULL;
4504 char target_path[PATH_MAX];
4505 ssize_t target_len, outlen;
4507 *fd = -1;
4509 if (dirfd != -1) {
4510 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4511 if (target_len == -1)
4512 return got_error_from_errno2("readlinkat", abspath);
4513 } else {
4514 target_len = readlink(abspath, target_path, PATH_MAX);
4515 if (target_len == -1)
4516 return got_error_from_errno2("readlink", abspath);
4519 *fd = got_opentempfd();
4520 if (*fd == -1)
4521 return got_error_from_errno("got_opentempfd");
4523 outlen = write(*fd, target_path, target_len);
4524 if (outlen == -1) {
4525 err = got_error_from_errno("got_opentempfd");
4526 goto done;
4529 if (lseek(*fd, 0, SEEK_SET) == -1) {
4530 err = got_error_from_errno2("lseek", abspath);
4531 goto done;
4533 done:
4534 if (err) {
4535 close(*fd);
4536 *fd = -1;
4538 return err;
4541 static const struct got_error *
4542 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4543 const char *path, struct got_object_id *blob_id,
4544 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4545 int dirfd, const char *de_name)
4547 struct print_diff_arg *a = arg;
4548 const struct got_error *err = NULL;
4549 struct got_blob_object *blob1 = NULL;
4550 int fd = -1;
4551 FILE *f1 = NULL, *f2 = NULL;
4552 char *abspath = NULL, *label1 = NULL;
4553 struct stat sb;
4554 off_t size1 = 0;
4556 if (a->diff_staged) {
4557 if (staged_status != GOT_STATUS_MODIFY &&
4558 staged_status != GOT_STATUS_ADD &&
4559 staged_status != GOT_STATUS_DELETE)
4560 return NULL;
4561 } else {
4562 if (staged_status == GOT_STATUS_DELETE)
4563 return NULL;
4564 if (status == GOT_STATUS_NONEXISTENT)
4565 return got_error_set_errno(ENOENT, path);
4566 if (status != GOT_STATUS_MODIFY &&
4567 status != GOT_STATUS_ADD &&
4568 status != GOT_STATUS_DELETE &&
4569 status != GOT_STATUS_CONFLICT)
4570 return NULL;
4573 if (!a->header_shown) {
4574 printf("diff %s %s%s\n", a->id_str,
4575 got_worktree_get_root_path(a->worktree),
4576 a->diff_staged ? " (staged changes)" : "");
4577 a->header_shown = 1;
4580 if (a->diff_staged) {
4581 const char *label1 = NULL, *label2 = NULL;
4582 switch (staged_status) {
4583 case GOT_STATUS_MODIFY:
4584 label1 = path;
4585 label2 = path;
4586 break;
4587 case GOT_STATUS_ADD:
4588 label2 = path;
4589 break;
4590 case GOT_STATUS_DELETE:
4591 label1 = path;
4592 break;
4593 default:
4594 return got_error(GOT_ERR_FILE_STATUS);
4596 f1 = got_opentemp();
4597 if (f1 == NULL) {
4598 err = got_error_from_errno("got_opentemp");
4599 goto done;
4601 f2 = got_opentemp();
4602 if (f2 == NULL) {
4603 err = got_error_from_errno("got_opentemp");
4604 goto done;
4606 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4607 blob_id, staged_blob_id, label1, label2, a->diff_context,
4608 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4609 goto done;
4612 if (staged_status == GOT_STATUS_ADD ||
4613 staged_status == GOT_STATUS_MODIFY) {
4614 char *id_str;
4615 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4616 8192);
4617 if (err)
4618 goto done;
4619 err = got_object_id_str(&id_str, staged_blob_id);
4620 if (err)
4621 goto done;
4622 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4623 err = got_error_from_errno("asprintf");
4624 free(id_str);
4625 goto done;
4627 free(id_str);
4628 } else if (status != GOT_STATUS_ADD) {
4629 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4630 if (err)
4631 goto done;
4634 if (status != GOT_STATUS_DELETE) {
4635 if (asprintf(&abspath, "%s/%s",
4636 got_worktree_get_root_path(a->worktree), path) == -1) {
4637 err = got_error_from_errno("asprintf");
4638 goto done;
4641 if (dirfd != -1) {
4642 fd = openat(dirfd, de_name,
4643 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4644 if (fd == -1) {
4645 if (!got_err_open_nofollow_on_symlink()) {
4646 err = got_error_from_errno2("openat",
4647 abspath);
4648 goto done;
4650 err = get_symlink_target_file(&fd, dirfd,
4651 de_name, abspath);
4652 if (err)
4653 goto done;
4655 } else {
4656 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4657 if (fd == -1) {
4658 if (!got_err_open_nofollow_on_symlink()) {
4659 err = got_error_from_errno2("open",
4660 abspath);
4661 goto done;
4663 err = get_symlink_target_file(&fd, dirfd,
4664 de_name, abspath);
4665 if (err)
4666 goto done;
4669 if (fstat(fd, &sb) == -1) {
4670 err = got_error_from_errno2("fstat", abspath);
4671 goto done;
4673 f2 = fdopen(fd, "r");
4674 if (f2 == NULL) {
4675 err = got_error_from_errno2("fdopen", abspath);
4676 goto done;
4678 fd = -1;
4679 } else
4680 sb.st_size = 0;
4682 if (blob1) {
4683 f1 = got_opentemp();
4684 if (f1 == NULL) {
4685 err = got_error_from_errno("got_opentemp");
4686 goto done;
4688 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4689 blob1);
4690 if (err)
4691 goto done;
4694 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4695 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4696 stdout);
4697 done:
4698 if (blob1)
4699 got_object_blob_close(blob1);
4700 if (f1 && fclose(f1) == EOF && err == NULL)
4701 err = got_error_from_errno("fclose");
4702 if (f2 && fclose(f2) == EOF && err == NULL)
4703 err = got_error_from_errno("fclose");
4704 if (fd != -1 && close(fd) == -1 && err == NULL)
4705 err = got_error_from_errno("close");
4706 free(abspath);
4707 return err;
4710 static const struct got_error *
4711 cmd_diff(int argc, char *argv[])
4713 const struct got_error *error;
4714 struct got_repository *repo = NULL;
4715 struct got_worktree *worktree = NULL;
4716 char *cwd = NULL, *repo_path = NULL;
4717 const char *commit_args[2] = { NULL, NULL };
4718 int ncommit_args = 0;
4719 struct got_object_id *ids[2] = { NULL, NULL };
4720 char *labels[2] = { NULL, NULL };
4721 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4722 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4723 int force_text_diff = 0, force_path = 0, rflag = 0;
4724 const char *errstr;
4725 struct got_reflist_head refs;
4726 struct got_pathlist_head paths;
4727 struct got_pathlist_entry *pe;
4728 FILE *f1 = NULL, *f2 = NULL;
4730 TAILQ_INIT(&refs);
4731 TAILQ_INIT(&paths);
4733 #ifndef PROFILE
4734 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4735 NULL) == -1)
4736 err(1, "pledge");
4737 #endif
4739 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4740 switch (ch) {
4741 case 'a':
4742 force_text_diff = 1;
4743 break;
4744 case 'c':
4745 if (ncommit_args >= 2)
4746 errx(1, "too many -c options used");
4747 commit_args[ncommit_args++] = optarg;
4748 break;
4749 case 'C':
4750 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4751 &errstr);
4752 if (errstr != NULL)
4753 errx(1, "number of context lines is %s: %s",
4754 errstr, optarg);
4755 break;
4756 case 'r':
4757 repo_path = realpath(optarg, NULL);
4758 if (repo_path == NULL)
4759 return got_error_from_errno2("realpath",
4760 optarg);
4761 got_path_strip_trailing_slashes(repo_path);
4762 rflag = 1;
4763 break;
4764 case 's':
4765 diff_staged = 1;
4766 break;
4767 case 'w':
4768 ignore_whitespace = 1;
4769 break;
4770 case 'P':
4771 force_path = 1;
4772 break;
4773 default:
4774 usage_diff();
4775 /* NOTREACHED */
4779 argc -= optind;
4780 argv += optind;
4782 cwd = getcwd(NULL, 0);
4783 if (cwd == NULL) {
4784 error = got_error_from_errno("getcwd");
4785 goto done;
4788 if (repo_path == NULL) {
4789 error = got_worktree_open(&worktree, cwd);
4790 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4791 goto done;
4792 else
4793 error = NULL;
4794 if (worktree) {
4795 repo_path =
4796 strdup(got_worktree_get_repo_path(worktree));
4797 if (repo_path == NULL) {
4798 error = got_error_from_errno("strdup");
4799 goto done;
4801 } else {
4802 repo_path = strdup(cwd);
4803 if (repo_path == NULL) {
4804 error = got_error_from_errno("strdup");
4805 goto done;
4810 error = got_repo_open(&repo, repo_path, NULL);
4811 free(repo_path);
4812 if (error != NULL)
4813 goto done;
4815 if (rflag || worktree == NULL || ncommit_args > 0) {
4816 if (force_path) {
4817 error = got_error_msg(GOT_ERR_NOT_IMPL,
4818 "-P option can only be used when diffing "
4819 "a work tree");
4820 goto done;
4822 if (diff_staged) {
4823 error = got_error_msg(GOT_ERR_NOT_IMPL,
4824 "-s option can only be used when diffing "
4825 "a work tree");
4826 goto done;
4830 error = apply_unveil(got_repo_get_path(repo), 1,
4831 worktree ? got_worktree_get_root_path(worktree) : NULL);
4832 if (error)
4833 goto done;
4835 if ((!force_path && argc == 2) || ncommit_args > 0) {
4836 int obj_type = (ncommit_args > 0 ?
4837 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4838 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4839 NULL);
4840 if (error)
4841 goto done;
4842 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4843 const char *arg;
4844 if (ncommit_args > 0)
4845 arg = commit_args[i];
4846 else
4847 arg = argv[i];
4848 error = got_repo_match_object_id(&ids[i], &labels[i],
4849 arg, obj_type, &refs, repo);
4850 if (error) {
4851 if (error->code != GOT_ERR_NOT_REF &&
4852 error->code != GOT_ERR_NO_OBJ)
4853 goto done;
4854 if (ncommit_args > 0)
4855 goto done;
4856 error = NULL;
4857 break;
4862 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4863 struct print_diff_arg arg;
4864 char *id_str;
4866 if (worktree == NULL) {
4867 if (argc == 2 && ids[0] == NULL) {
4868 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4869 goto done;
4870 } else if (argc == 2 && ids[1] == NULL) {
4871 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4872 goto done;
4873 } else if (argc > 0) {
4874 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4875 "%s", "specified paths cannot be resolved");
4876 goto done;
4877 } else {
4878 error = got_error(GOT_ERR_NOT_WORKTREE);
4879 goto done;
4883 error = get_worktree_paths_from_argv(&paths, argc, argv,
4884 worktree);
4885 if (error)
4886 goto done;
4888 error = got_object_id_str(&id_str,
4889 got_worktree_get_base_commit_id(worktree));
4890 if (error)
4891 goto done;
4892 arg.repo = repo;
4893 arg.worktree = worktree;
4894 arg.diff_context = diff_context;
4895 arg.id_str = id_str;
4896 arg.header_shown = 0;
4897 arg.diff_staged = diff_staged;
4898 arg.ignore_whitespace = ignore_whitespace;
4899 arg.force_text_diff = force_text_diff;
4901 error = got_worktree_status(worktree, &paths, repo, 0,
4902 print_diff, &arg, check_cancelled, NULL);
4903 free(id_str);
4904 goto done;
4907 if (ncommit_args == 1) {
4908 struct got_commit_object *commit;
4909 error = got_object_open_as_commit(&commit, repo, ids[0]);
4910 if (error)
4911 goto done;
4913 labels[1] = labels[0];
4914 ids[1] = ids[0];
4915 if (got_object_commit_get_nparents(commit) > 0) {
4916 const struct got_object_id_queue *pids;
4917 struct got_object_qid *pid;
4918 pids = got_object_commit_get_parent_ids(commit);
4919 pid = STAILQ_FIRST(pids);
4920 ids[0] = got_object_id_dup(&pid->id);
4921 if (ids[0] == NULL) {
4922 error = got_error_from_errno(
4923 "got_object_id_dup");
4924 got_object_commit_close(commit);
4925 goto done;
4927 error = got_object_id_str(&labels[0], ids[0]);
4928 if (error) {
4929 got_object_commit_close(commit);
4930 goto done;
4932 } else {
4933 ids[0] = NULL;
4934 labels[0] = strdup("/dev/null");
4935 if (labels[0] == NULL) {
4936 error = got_error_from_errno("strdup");
4937 got_object_commit_close(commit);
4938 goto done;
4942 got_object_commit_close(commit);
4945 if (ncommit_args == 0 && argc > 2) {
4946 error = got_error_msg(GOT_ERR_BAD_PATH,
4947 "path arguments cannot be used when diffing two objects");
4948 goto done;
4951 if (ids[0]) {
4952 error = got_object_get_type(&type1, repo, ids[0]);
4953 if (error)
4954 goto done;
4957 error = got_object_get_type(&type2, repo, ids[1]);
4958 if (error)
4959 goto done;
4960 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4961 error = got_error(GOT_ERR_OBJ_TYPE);
4962 goto done;
4964 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4965 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4966 "path arguments cannot be used when diffing blobs");
4967 goto done;
4970 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4971 char *in_repo_path;
4972 struct got_pathlist_entry *new;
4973 if (worktree) {
4974 const char *prefix;
4975 char *p;
4976 error = got_worktree_resolve_path(&p, worktree,
4977 argv[i]);
4978 if (error)
4979 goto done;
4980 prefix = got_worktree_get_path_prefix(worktree);
4981 while (prefix[0] == '/')
4982 prefix++;
4983 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4984 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4985 p) == -1) {
4986 error = got_error_from_errno("asprintf");
4987 free(p);
4988 goto done;
4990 free(p);
4991 } else {
4992 char *mapped_path, *s;
4993 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4994 if (error)
4995 goto done;
4996 s = mapped_path;
4997 while (s[0] == '/')
4998 s++;
4999 in_repo_path = strdup(s);
5000 if (in_repo_path == NULL) {
5001 error = got_error_from_errno("asprintf");
5002 free(mapped_path);
5003 goto done;
5005 free(mapped_path);
5008 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5009 if (error || new == NULL /* duplicate */)
5010 free(in_repo_path);
5011 if (error)
5012 goto done;
5015 if (worktree) {
5016 /* Release work tree lock. */
5017 got_worktree_close(worktree);
5018 worktree = NULL;
5021 f1 = got_opentemp();
5022 if (f1 == NULL) {
5023 error = got_error_from_errno("got_opentemp");
5024 goto done;
5027 f2 = got_opentemp();
5028 if (f2 == NULL) {
5029 error = got_error_from_errno("got_opentemp");
5030 goto done;
5033 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5034 case GOT_OBJ_TYPE_BLOB:
5035 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5036 ids[0], ids[1], NULL, NULL, diff_context,
5037 ignore_whitespace, force_text_diff, repo, stdout);
5038 break;
5039 case GOT_OBJ_TYPE_TREE:
5040 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
5041 ids[0], ids[1], &paths, "", "", diff_context,
5042 ignore_whitespace, force_text_diff, repo, stdout);
5043 break;
5044 case GOT_OBJ_TYPE_COMMIT:
5045 printf("diff %s %s\n", labels[0], labels[1]);
5046 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5047 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
5048 force_text_diff, repo, stdout);
5049 break;
5050 default:
5051 error = got_error(GOT_ERR_OBJ_TYPE);
5053 done:
5054 free(labels[0]);
5055 free(labels[1]);
5056 free(ids[0]);
5057 free(ids[1]);
5058 if (worktree)
5059 got_worktree_close(worktree);
5060 if (repo) {
5061 const struct got_error *close_err = got_repo_close(repo);
5062 if (error == NULL)
5063 error = close_err;
5065 TAILQ_FOREACH(pe, &paths, entry)
5066 free((char *)pe->path);
5067 got_pathlist_free(&paths);
5068 got_ref_list_free(&refs);
5069 if (f1 && fclose(f1) == EOF && error == NULL)
5070 error = got_error_from_errno("fclose");
5071 if (f2 && fclose(f2) == EOF && error == NULL)
5072 error = got_error_from_errno("fclose");
5073 return error;
5076 __dead static void
5077 usage_blame(void)
5079 fprintf(stderr,
5080 "usage: %s blame [-c commit] [-r repository-path] path\n",
5081 getprogname());
5082 exit(1);
5085 struct blame_line {
5086 int annotated;
5087 char *id_str;
5088 char *committer;
5089 char datebuf[11]; /* YYYY-MM-DD + NUL */
5092 struct blame_cb_args {
5093 struct blame_line *lines;
5094 int nlines;
5095 int nlines_prec;
5096 int lineno_cur;
5097 off_t *line_offsets;
5098 FILE *f;
5099 struct got_repository *repo;
5102 static const struct got_error *
5103 blame_cb(void *arg, int nlines, int lineno,
5104 struct got_commit_object *commit, struct got_object_id *id)
5106 const struct got_error *err = NULL;
5107 struct blame_cb_args *a = arg;
5108 struct blame_line *bline;
5109 char *line = NULL;
5110 size_t linesize = 0;
5111 off_t offset;
5112 struct tm tm;
5113 time_t committer_time;
5115 if (nlines != a->nlines ||
5116 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5117 return got_error(GOT_ERR_RANGE);
5119 if (sigint_received)
5120 return got_error(GOT_ERR_ITER_COMPLETED);
5122 if (lineno == -1)
5123 return NULL; /* no change in this commit */
5125 /* Annotate this line. */
5126 bline = &a->lines[lineno - 1];
5127 if (bline->annotated)
5128 return NULL;
5129 err = got_object_id_str(&bline->id_str, id);
5130 if (err)
5131 return err;
5133 bline->committer = strdup(got_object_commit_get_committer(commit));
5134 if (bline->committer == NULL) {
5135 err = got_error_from_errno("strdup");
5136 goto done;
5139 committer_time = got_object_commit_get_committer_time(commit);
5140 if (gmtime_r(&committer_time, &tm) == NULL)
5141 return got_error_from_errno("gmtime_r");
5142 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5143 &tm) == 0) {
5144 err = got_error(GOT_ERR_NO_SPACE);
5145 goto done;
5147 bline->annotated = 1;
5149 /* Print lines annotated so far. */
5150 bline = &a->lines[a->lineno_cur - 1];
5151 if (!bline->annotated)
5152 goto done;
5154 offset = a->line_offsets[a->lineno_cur - 1];
5155 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5156 err = got_error_from_errno("fseeko");
5157 goto done;
5160 while (bline->annotated) {
5161 char *smallerthan, *at, *nl, *committer;
5162 size_t len;
5164 if (getline(&line, &linesize, a->f) == -1) {
5165 if (ferror(a->f))
5166 err = got_error_from_errno("getline");
5167 break;
5170 committer = bline->committer;
5171 smallerthan = strchr(committer, '<');
5172 if (smallerthan && smallerthan[1] != '\0')
5173 committer = smallerthan + 1;
5174 at = strchr(committer, '@');
5175 if (at)
5176 *at = '\0';
5177 len = strlen(committer);
5178 if (len >= 9)
5179 committer[8] = '\0';
5181 nl = strchr(line, '\n');
5182 if (nl)
5183 *nl = '\0';
5184 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5185 bline->id_str, bline->datebuf, committer, line);
5187 a->lineno_cur++;
5188 bline = &a->lines[a->lineno_cur - 1];
5190 done:
5191 free(line);
5192 return err;
5195 static const struct got_error *
5196 cmd_blame(int argc, char *argv[])
5198 const struct got_error *error;
5199 struct got_repository *repo = NULL;
5200 struct got_worktree *worktree = NULL;
5201 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5202 char *link_target = NULL;
5203 struct got_object_id *obj_id = NULL;
5204 struct got_object_id *commit_id = NULL;
5205 struct got_commit_object *commit = NULL;
5206 struct got_blob_object *blob = NULL;
5207 char *commit_id_str = NULL;
5208 struct blame_cb_args bca;
5209 int ch, obj_type, i;
5210 off_t filesize;
5212 memset(&bca, 0, sizeof(bca));
5214 #ifndef PROFILE
5215 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5216 NULL) == -1)
5217 err(1, "pledge");
5218 #endif
5220 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5221 switch (ch) {
5222 case 'c':
5223 commit_id_str = optarg;
5224 break;
5225 case 'r':
5226 repo_path = realpath(optarg, NULL);
5227 if (repo_path == NULL)
5228 return got_error_from_errno2("realpath",
5229 optarg);
5230 got_path_strip_trailing_slashes(repo_path);
5231 break;
5232 default:
5233 usage_blame();
5234 /* NOTREACHED */
5238 argc -= optind;
5239 argv += optind;
5241 if (argc == 1)
5242 path = argv[0];
5243 else
5244 usage_blame();
5246 cwd = getcwd(NULL, 0);
5247 if (cwd == NULL) {
5248 error = got_error_from_errno("getcwd");
5249 goto done;
5251 if (repo_path == NULL) {
5252 error = got_worktree_open(&worktree, cwd);
5253 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5254 goto done;
5255 else
5256 error = NULL;
5257 if (worktree) {
5258 repo_path =
5259 strdup(got_worktree_get_repo_path(worktree));
5260 if (repo_path == NULL) {
5261 error = got_error_from_errno("strdup");
5262 if (error)
5263 goto done;
5265 } else {
5266 repo_path = strdup(cwd);
5267 if (repo_path == NULL) {
5268 error = got_error_from_errno("strdup");
5269 goto done;
5274 error = got_repo_open(&repo, repo_path, NULL);
5275 if (error != NULL)
5276 goto done;
5278 if (worktree) {
5279 const char *prefix = got_worktree_get_path_prefix(worktree);
5280 char *p;
5282 error = got_worktree_resolve_path(&p, worktree, path);
5283 if (error)
5284 goto done;
5285 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5286 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5287 p) == -1) {
5288 error = got_error_from_errno("asprintf");
5289 free(p);
5290 goto done;
5292 free(p);
5293 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5294 } else {
5295 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5296 if (error)
5297 goto done;
5298 error = got_repo_map_path(&in_repo_path, repo, path);
5300 if (error)
5301 goto done;
5303 if (commit_id_str == NULL) {
5304 struct got_reference *head_ref;
5305 error = got_ref_open(&head_ref, repo, worktree ?
5306 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5307 if (error != NULL)
5308 goto done;
5309 error = got_ref_resolve(&commit_id, repo, head_ref);
5310 got_ref_close(head_ref);
5311 if (error != NULL)
5312 goto done;
5313 } else {
5314 struct got_reflist_head refs;
5315 TAILQ_INIT(&refs);
5316 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5317 NULL);
5318 if (error)
5319 goto done;
5320 error = got_repo_match_object_id(&commit_id, NULL,
5321 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5322 got_ref_list_free(&refs);
5323 if (error)
5324 goto done;
5327 if (worktree) {
5328 /* Release work tree lock. */
5329 got_worktree_close(worktree);
5330 worktree = NULL;
5333 error = got_object_open_as_commit(&commit, repo, commit_id);
5334 if (error)
5335 goto done;
5337 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5338 commit, repo);
5339 if (error)
5340 goto done;
5342 error = got_object_id_by_path(&obj_id, repo, commit,
5343 link_target ? link_target : in_repo_path);
5344 if (error)
5345 goto done;
5347 error = got_object_get_type(&obj_type, repo, obj_id);
5348 if (error)
5349 goto done;
5351 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5352 error = got_error_path(link_target ? link_target : in_repo_path,
5353 GOT_ERR_OBJ_TYPE);
5354 goto done;
5357 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5358 if (error)
5359 goto done;
5360 bca.f = got_opentemp();
5361 if (bca.f == NULL) {
5362 error = got_error_from_errno("got_opentemp");
5363 goto done;
5365 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5366 &bca.line_offsets, bca.f, blob);
5367 if (error || bca.nlines == 0)
5368 goto done;
5370 /* Don't include \n at EOF in the blame line count. */
5371 if (bca.line_offsets[bca.nlines - 1] == filesize)
5372 bca.nlines--;
5374 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5375 if (bca.lines == NULL) {
5376 error = got_error_from_errno("calloc");
5377 goto done;
5379 bca.lineno_cur = 1;
5380 bca.nlines_prec = 0;
5381 i = bca.nlines;
5382 while (i > 0) {
5383 i /= 10;
5384 bca.nlines_prec++;
5386 bca.repo = repo;
5388 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5389 repo, blame_cb, &bca, check_cancelled, NULL);
5390 done:
5391 free(in_repo_path);
5392 free(link_target);
5393 free(repo_path);
5394 free(cwd);
5395 free(commit_id);
5396 free(obj_id);
5397 if (commit)
5398 got_object_commit_close(commit);
5399 if (blob)
5400 got_object_blob_close(blob);
5401 if (worktree)
5402 got_worktree_close(worktree);
5403 if (repo) {
5404 const struct got_error *close_err = got_repo_close(repo);
5405 if (error == NULL)
5406 error = close_err;
5408 if (bca.lines) {
5409 for (i = 0; i < bca.nlines; i++) {
5410 struct blame_line *bline = &bca.lines[i];
5411 free(bline->id_str);
5412 free(bline->committer);
5414 free(bca.lines);
5416 free(bca.line_offsets);
5417 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5418 error = got_error_from_errno("fclose");
5419 return error;
5422 __dead static void
5423 usage_tree(void)
5425 fprintf(stderr,
5426 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5427 getprogname());
5428 exit(1);
5431 static const struct got_error *
5432 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5433 const char *root_path, struct got_repository *repo)
5435 const struct got_error *err = NULL;
5436 int is_root_path = (strcmp(path, root_path) == 0);
5437 const char *modestr = "";
5438 mode_t mode = got_tree_entry_get_mode(te);
5439 char *link_target = NULL;
5441 path += strlen(root_path);
5442 while (path[0] == '/')
5443 path++;
5445 if (got_object_tree_entry_is_submodule(te))
5446 modestr = "$";
5447 else if (S_ISLNK(mode)) {
5448 int i;
5450 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5451 if (err)
5452 return err;
5453 for (i = 0; i < strlen(link_target); i++) {
5454 if (!isprint((unsigned char)link_target[i]))
5455 link_target[i] = '?';
5458 modestr = "@";
5460 else if (S_ISDIR(mode))
5461 modestr = "/";
5462 else if (mode & S_IXUSR)
5463 modestr = "*";
5465 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5466 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5467 link_target ? " -> ": "", link_target ? link_target : "");
5469 free(link_target);
5470 return NULL;
5473 static const struct got_error *
5474 print_tree(const char *path, struct got_commit_object *commit,
5475 int show_ids, int recurse, const char *root_path,
5476 struct got_repository *repo)
5478 const struct got_error *err = NULL;
5479 struct got_object_id *tree_id = NULL;
5480 struct got_tree_object *tree = NULL;
5481 int nentries, i;
5483 err = got_object_id_by_path(&tree_id, repo, commit, path);
5484 if (err)
5485 goto done;
5487 err = got_object_open_as_tree(&tree, repo, tree_id);
5488 if (err)
5489 goto done;
5490 nentries = got_object_tree_get_nentries(tree);
5491 for (i = 0; i < nentries; i++) {
5492 struct got_tree_entry *te;
5493 char *id = NULL;
5495 if (sigint_received || sigpipe_received)
5496 break;
5498 te = got_object_tree_get_entry(tree, i);
5499 if (show_ids) {
5500 char *id_str;
5501 err = got_object_id_str(&id_str,
5502 got_tree_entry_get_id(te));
5503 if (err)
5504 goto done;
5505 if (asprintf(&id, "%s ", id_str) == -1) {
5506 err = got_error_from_errno("asprintf");
5507 free(id_str);
5508 goto done;
5510 free(id_str);
5512 err = print_entry(te, id, path, root_path, repo);
5513 free(id);
5514 if (err)
5515 goto done;
5517 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5518 char *child_path;
5519 if (asprintf(&child_path, "%s%s%s", path,
5520 path[0] == '/' && path[1] == '\0' ? "" : "/",
5521 got_tree_entry_get_name(te)) == -1) {
5522 err = got_error_from_errno("asprintf");
5523 goto done;
5525 err = print_tree(child_path, commit, show_ids, 1,
5526 root_path, repo);
5527 free(child_path);
5528 if (err)
5529 goto done;
5532 done:
5533 if (tree)
5534 got_object_tree_close(tree);
5535 free(tree_id);
5536 return err;
5539 static const struct got_error *
5540 cmd_tree(int argc, char *argv[])
5542 const struct got_error *error;
5543 struct got_repository *repo = NULL;
5544 struct got_worktree *worktree = NULL;
5545 const char *path, *refname = NULL;
5546 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5547 struct got_object_id *commit_id = NULL;
5548 struct got_commit_object *commit = NULL;
5549 char *commit_id_str = NULL;
5550 int show_ids = 0, recurse = 0;
5551 int ch;
5553 #ifndef PROFILE
5554 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5555 NULL) == -1)
5556 err(1, "pledge");
5557 #endif
5559 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5560 switch (ch) {
5561 case 'c':
5562 commit_id_str = optarg;
5563 break;
5564 case 'r':
5565 repo_path = realpath(optarg, NULL);
5566 if (repo_path == NULL)
5567 return got_error_from_errno2("realpath",
5568 optarg);
5569 got_path_strip_trailing_slashes(repo_path);
5570 break;
5571 case 'i':
5572 show_ids = 1;
5573 break;
5574 case 'R':
5575 recurse = 1;
5576 break;
5577 default:
5578 usage_tree();
5579 /* NOTREACHED */
5583 argc -= optind;
5584 argv += optind;
5586 if (argc == 1)
5587 path = argv[0];
5588 else if (argc > 1)
5589 usage_tree();
5590 else
5591 path = NULL;
5593 cwd = getcwd(NULL, 0);
5594 if (cwd == NULL) {
5595 error = got_error_from_errno("getcwd");
5596 goto done;
5598 if (repo_path == NULL) {
5599 error = got_worktree_open(&worktree, cwd);
5600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5601 goto done;
5602 else
5603 error = NULL;
5604 if (worktree) {
5605 repo_path =
5606 strdup(got_worktree_get_repo_path(worktree));
5607 if (repo_path == NULL)
5608 error = got_error_from_errno("strdup");
5609 if (error)
5610 goto done;
5611 } else {
5612 repo_path = strdup(cwd);
5613 if (repo_path == NULL) {
5614 error = got_error_from_errno("strdup");
5615 goto done;
5620 error = got_repo_open(&repo, repo_path, NULL);
5621 if (error != NULL)
5622 goto done;
5624 if (worktree) {
5625 const char *prefix = got_worktree_get_path_prefix(worktree);
5626 char *p;
5628 if (path == NULL)
5629 path = "";
5630 error = got_worktree_resolve_path(&p, worktree, path);
5631 if (error)
5632 goto done;
5633 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5634 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5635 p) == -1) {
5636 error = got_error_from_errno("asprintf");
5637 free(p);
5638 goto done;
5640 free(p);
5641 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5642 if (error)
5643 goto done;
5644 } else {
5645 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5646 if (error)
5647 goto done;
5648 if (path == NULL)
5649 path = "/";
5650 error = got_repo_map_path(&in_repo_path, repo, path);
5651 if (error != NULL)
5652 goto done;
5655 if (commit_id_str == NULL) {
5656 struct got_reference *head_ref;
5657 if (worktree)
5658 refname = got_worktree_get_head_ref_name(worktree);
5659 else
5660 refname = GOT_REF_HEAD;
5661 error = got_ref_open(&head_ref, repo, refname, 0);
5662 if (error != NULL)
5663 goto done;
5664 error = got_ref_resolve(&commit_id, repo, head_ref);
5665 got_ref_close(head_ref);
5666 if (error != NULL)
5667 goto done;
5668 } else {
5669 struct got_reflist_head refs;
5670 TAILQ_INIT(&refs);
5671 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5672 NULL);
5673 if (error)
5674 goto done;
5675 error = got_repo_match_object_id(&commit_id, NULL,
5676 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5677 got_ref_list_free(&refs);
5678 if (error)
5679 goto done;
5682 if (worktree) {
5683 /* Release work tree lock. */
5684 got_worktree_close(worktree);
5685 worktree = NULL;
5688 error = got_object_open_as_commit(&commit, repo, commit_id);
5689 if (error)
5690 goto done;
5692 error = print_tree(in_repo_path, commit, show_ids, recurse,
5693 in_repo_path, repo);
5694 done:
5695 free(in_repo_path);
5696 free(repo_path);
5697 free(cwd);
5698 free(commit_id);
5699 if (commit)
5700 got_object_commit_close(commit);
5701 if (worktree)
5702 got_worktree_close(worktree);
5703 if (repo) {
5704 const struct got_error *close_err = got_repo_close(repo);
5705 if (error == NULL)
5706 error = close_err;
5708 return error;
5711 __dead static void
5712 usage_status(void)
5714 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5715 "[-S status-codes] [path ...]\n", getprogname());
5716 exit(1);
5719 struct got_status_arg {
5720 char *status_codes;
5721 int suppress;
5724 static const struct got_error *
5725 print_status(void *arg, unsigned char status, unsigned char staged_status,
5726 const char *path, struct got_object_id *blob_id,
5727 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5728 int dirfd, const char *de_name)
5730 struct got_status_arg *st = arg;
5732 if (status == staged_status && (status == GOT_STATUS_DELETE))
5733 status = GOT_STATUS_NO_CHANGE;
5734 if (st != NULL && st->status_codes) {
5735 size_t ncodes = strlen(st->status_codes);
5736 int i, j = 0;
5738 for (i = 0; i < ncodes ; i++) {
5739 if (st->suppress) {
5740 if (status == st->status_codes[i] ||
5741 staged_status == st->status_codes[i]) {
5742 j++;
5743 continue;
5745 } else {
5746 if (status == st->status_codes[i] ||
5747 staged_status == st->status_codes[i])
5748 break;
5752 if (st->suppress && j == 0)
5753 goto print;
5755 if (i == ncodes)
5756 return NULL;
5758 print:
5759 printf("%c%c %s\n", status, staged_status, path);
5760 return NULL;
5763 static const struct got_error *
5764 cmd_status(int argc, char *argv[])
5766 const struct got_error *error = NULL;
5767 struct got_repository *repo = NULL;
5768 struct got_worktree *worktree = NULL;
5769 struct got_status_arg st;
5770 char *cwd = NULL;
5771 struct got_pathlist_head paths;
5772 struct got_pathlist_entry *pe;
5773 int ch, i, no_ignores = 0;
5775 TAILQ_INIT(&paths);
5777 memset(&st, 0, sizeof(st));
5778 st.status_codes = NULL;
5779 st.suppress = 0;
5781 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5782 switch (ch) {
5783 case 'I':
5784 no_ignores = 1;
5785 break;
5786 case 'S':
5787 if (st.status_codes != NULL && st.suppress == 0)
5788 option_conflict('S', 's');
5789 st.suppress = 1;
5790 /* fallthrough */
5791 case 's':
5792 for (i = 0; i < strlen(optarg); i++) {
5793 switch (optarg[i]) {
5794 case GOT_STATUS_MODIFY:
5795 case GOT_STATUS_ADD:
5796 case GOT_STATUS_DELETE:
5797 case GOT_STATUS_CONFLICT:
5798 case GOT_STATUS_MISSING:
5799 case GOT_STATUS_OBSTRUCTED:
5800 case GOT_STATUS_UNVERSIONED:
5801 case GOT_STATUS_MODE_CHANGE:
5802 case GOT_STATUS_NONEXISTENT:
5803 break;
5804 default:
5805 errx(1, "invalid status code '%c'",
5806 optarg[i]);
5809 if (ch == 's' && st.suppress)
5810 option_conflict('s', 'S');
5811 st.status_codes = optarg;
5812 break;
5813 default:
5814 usage_status();
5815 /* NOTREACHED */
5819 argc -= optind;
5820 argv += optind;
5822 #ifndef PROFILE
5823 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5824 NULL) == -1)
5825 err(1, "pledge");
5826 #endif
5827 cwd = getcwd(NULL, 0);
5828 if (cwd == NULL) {
5829 error = got_error_from_errno("getcwd");
5830 goto done;
5833 error = got_worktree_open(&worktree, cwd);
5834 if (error) {
5835 if (error->code == GOT_ERR_NOT_WORKTREE)
5836 error = wrap_not_worktree_error(error, "status", cwd);
5837 goto done;
5840 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5841 NULL);
5842 if (error != NULL)
5843 goto done;
5845 error = apply_unveil(got_repo_get_path(repo), 1,
5846 got_worktree_get_root_path(worktree));
5847 if (error)
5848 goto done;
5850 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5851 if (error)
5852 goto done;
5854 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5855 print_status, &st, check_cancelled, NULL);
5856 done:
5857 TAILQ_FOREACH(pe, &paths, entry)
5858 free((char *)pe->path);
5859 got_pathlist_free(&paths);
5860 free(cwd);
5861 return error;
5864 __dead static void
5865 usage_ref(void)
5867 fprintf(stderr,
5868 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5869 "[-s reference] [-d] [name]\n",
5870 getprogname());
5871 exit(1);
5874 static const struct got_error *
5875 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5877 static const struct got_error *err = NULL;
5878 struct got_reflist_head refs;
5879 struct got_reflist_entry *re;
5881 TAILQ_INIT(&refs);
5882 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5883 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5884 repo);
5885 if (err)
5886 return err;
5888 TAILQ_FOREACH(re, &refs, entry) {
5889 char *refstr;
5890 refstr = got_ref_to_str(re->ref);
5891 if (refstr == NULL) {
5892 err = got_error_from_errno("got_ref_to_str");
5893 break;
5895 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5896 free(refstr);
5899 got_ref_list_free(&refs);
5900 return err;
5903 static const struct got_error *
5904 delete_ref_by_name(struct got_repository *repo, const char *refname)
5906 const struct got_error *err;
5907 struct got_reference *ref;
5909 err = got_ref_open(&ref, repo, refname, 0);
5910 if (err)
5911 return err;
5913 err = delete_ref(repo, ref);
5914 got_ref_close(ref);
5915 return err;
5918 static const struct got_error *
5919 add_ref(struct got_repository *repo, const char *refname, const char *target)
5921 const struct got_error *err = NULL;
5922 struct got_object_id *id = NULL;
5923 struct got_reference *ref = NULL;
5924 struct got_reflist_head refs;
5927 * Don't let the user create a reference name with a leading '-'.
5928 * While technically a valid reference name, this case is usually
5929 * an unintended typo.
5931 if (refname[0] == '-')
5932 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5934 TAILQ_INIT(&refs);
5935 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5936 if (err)
5937 goto done;
5938 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5939 &refs, repo);
5940 got_ref_list_free(&refs);
5941 if (err)
5942 goto done;
5944 err = got_ref_alloc(&ref, refname, id);
5945 if (err)
5946 goto done;
5948 err = got_ref_write(ref, repo);
5949 done:
5950 if (ref)
5951 got_ref_close(ref);
5952 free(id);
5953 return err;
5956 static const struct got_error *
5957 add_symref(struct got_repository *repo, const char *refname, const char *target)
5959 const struct got_error *err = NULL;
5960 struct got_reference *ref = NULL;
5961 struct got_reference *target_ref = NULL;
5964 * Don't let the user create a reference name with a leading '-'.
5965 * While technically a valid reference name, this case is usually
5966 * an unintended typo.
5968 if (refname[0] == '-')
5969 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5971 err = got_ref_open(&target_ref, repo, target, 0);
5972 if (err)
5973 return err;
5975 err = got_ref_alloc_symref(&ref, refname, target_ref);
5976 if (err)
5977 goto done;
5979 err = got_ref_write(ref, repo);
5980 done:
5981 if (target_ref)
5982 got_ref_close(target_ref);
5983 if (ref)
5984 got_ref_close(ref);
5985 return err;
5988 static const struct got_error *
5989 cmd_ref(int argc, char *argv[])
5991 const struct got_error *error = NULL;
5992 struct got_repository *repo = NULL;
5993 struct got_worktree *worktree = NULL;
5994 char *cwd = NULL, *repo_path = NULL;
5995 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5996 const char *obj_arg = NULL, *symref_target= NULL;
5997 char *refname = NULL;
5999 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6000 switch (ch) {
6001 case 'c':
6002 obj_arg = optarg;
6003 break;
6004 case 'd':
6005 do_delete = 1;
6006 break;
6007 case 'r':
6008 repo_path = realpath(optarg, NULL);
6009 if (repo_path == NULL)
6010 return got_error_from_errno2("realpath",
6011 optarg);
6012 got_path_strip_trailing_slashes(repo_path);
6013 break;
6014 case 'l':
6015 do_list = 1;
6016 break;
6017 case 's':
6018 symref_target = optarg;
6019 break;
6020 case 't':
6021 sort_by_time = 1;
6022 break;
6023 default:
6024 usage_ref();
6025 /* NOTREACHED */
6029 if (obj_arg && do_list)
6030 option_conflict('c', 'l');
6031 if (obj_arg && do_delete)
6032 option_conflict('c', 'd');
6033 if (obj_arg && symref_target)
6034 option_conflict('c', 's');
6035 if (symref_target && do_delete)
6036 option_conflict('s', 'd');
6037 if (symref_target && do_list)
6038 option_conflict('s', 'l');
6039 if (do_delete && do_list)
6040 option_conflict('d', 'l');
6041 if (sort_by_time && !do_list)
6042 errx(1, "-t option requires -l option");
6044 argc -= optind;
6045 argv += optind;
6047 if (do_list) {
6048 if (argc != 0 && argc != 1)
6049 usage_ref();
6050 if (argc == 1) {
6051 refname = strdup(argv[0]);
6052 if (refname == NULL) {
6053 error = got_error_from_errno("strdup");
6054 goto done;
6057 } else {
6058 if (argc != 1)
6059 usage_ref();
6060 refname = strdup(argv[0]);
6061 if (refname == NULL) {
6062 error = got_error_from_errno("strdup");
6063 goto done;
6067 if (refname)
6068 got_path_strip_trailing_slashes(refname);
6070 #ifndef PROFILE
6071 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6072 "sendfd unveil", NULL) == -1)
6073 err(1, "pledge");
6074 #endif
6075 cwd = getcwd(NULL, 0);
6076 if (cwd == NULL) {
6077 error = got_error_from_errno("getcwd");
6078 goto done;
6081 if (repo_path == NULL) {
6082 error = got_worktree_open(&worktree, cwd);
6083 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6084 goto done;
6085 else
6086 error = NULL;
6087 if (worktree) {
6088 repo_path =
6089 strdup(got_worktree_get_repo_path(worktree));
6090 if (repo_path == NULL)
6091 error = got_error_from_errno("strdup");
6092 if (error)
6093 goto done;
6094 } else {
6095 repo_path = strdup(cwd);
6096 if (repo_path == NULL) {
6097 error = got_error_from_errno("strdup");
6098 goto done;
6103 error = got_repo_open(&repo, repo_path, NULL);
6104 if (error != NULL)
6105 goto done;
6107 #ifndef PROFILE
6108 if (do_list) {
6109 /* Remove "cpath" promise. */
6110 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6111 NULL) == -1)
6112 err(1, "pledge");
6114 #endif
6116 error = apply_unveil(got_repo_get_path(repo), do_list,
6117 worktree ? got_worktree_get_root_path(worktree) : NULL);
6118 if (error)
6119 goto done;
6121 if (do_list)
6122 error = list_refs(repo, refname, sort_by_time);
6123 else if (do_delete)
6124 error = delete_ref_by_name(repo, refname);
6125 else if (symref_target)
6126 error = add_symref(repo, refname, symref_target);
6127 else {
6128 if (obj_arg == NULL)
6129 usage_ref();
6130 error = add_ref(repo, refname, obj_arg);
6132 done:
6133 free(refname);
6134 if (repo) {
6135 const struct got_error *close_err = got_repo_close(repo);
6136 if (error == NULL)
6137 error = close_err;
6139 if (worktree)
6140 got_worktree_close(worktree);
6141 free(cwd);
6142 free(repo_path);
6143 return error;
6146 __dead static void
6147 usage_branch(void)
6149 fprintf(stderr,
6150 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6151 "[-n] [name]\n", getprogname());
6152 exit(1);
6155 static const struct got_error *
6156 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6157 struct got_reference *ref)
6159 const struct got_error *err = NULL;
6160 const char *refname, *marker = " ";
6161 char *refstr;
6163 refname = got_ref_get_name(ref);
6164 if (worktree && strcmp(refname,
6165 got_worktree_get_head_ref_name(worktree)) == 0) {
6166 struct got_object_id *id = NULL;
6168 err = got_ref_resolve(&id, repo, ref);
6169 if (err)
6170 return err;
6171 if (got_object_id_cmp(id,
6172 got_worktree_get_base_commit_id(worktree)) == 0)
6173 marker = "* ";
6174 else
6175 marker = "~ ";
6176 free(id);
6179 if (strncmp(refname, "refs/heads/", 11) == 0)
6180 refname += 11;
6181 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6182 refname += 18;
6183 if (strncmp(refname, "refs/remotes/", 13) == 0)
6184 refname += 13;
6186 refstr = got_ref_to_str(ref);
6187 if (refstr == NULL)
6188 return got_error_from_errno("got_ref_to_str");
6190 printf("%s%s: %s\n", marker, refname, refstr);
6191 free(refstr);
6192 return NULL;
6195 static const struct got_error *
6196 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6198 const char *refname;
6200 if (worktree == NULL)
6201 return got_error(GOT_ERR_NOT_WORKTREE);
6203 refname = got_worktree_get_head_ref_name(worktree);
6205 if (strncmp(refname, "refs/heads/", 11) == 0)
6206 refname += 11;
6207 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6208 refname += 18;
6210 printf("%s\n", refname);
6212 return NULL;
6215 static const struct got_error *
6216 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6217 int sort_by_time)
6219 static const struct got_error *err = NULL;
6220 struct got_reflist_head refs;
6221 struct got_reflist_entry *re;
6222 struct got_reference *temp_ref = NULL;
6223 int rebase_in_progress, histedit_in_progress;
6225 TAILQ_INIT(&refs);
6227 if (worktree) {
6228 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6229 worktree);
6230 if (err)
6231 return err;
6233 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6234 worktree);
6235 if (err)
6236 return err;
6238 if (rebase_in_progress || histedit_in_progress) {
6239 err = got_ref_open(&temp_ref, repo,
6240 got_worktree_get_head_ref_name(worktree), 0);
6241 if (err)
6242 return err;
6243 list_branch(repo, worktree, temp_ref);
6244 got_ref_close(temp_ref);
6248 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6249 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6250 repo);
6251 if (err)
6252 return err;
6254 TAILQ_FOREACH(re, &refs, entry)
6255 list_branch(repo, worktree, re->ref);
6257 got_ref_list_free(&refs);
6259 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6260 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6261 repo);
6262 if (err)
6263 return err;
6265 TAILQ_FOREACH(re, &refs, entry)
6266 list_branch(repo, worktree, re->ref);
6268 got_ref_list_free(&refs);
6270 return NULL;
6273 static const struct got_error *
6274 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6275 const char *branch_name)
6277 const struct got_error *err = NULL;
6278 struct got_reference *ref = NULL;
6279 char *refname, *remote_refname = NULL;
6281 if (strncmp(branch_name, "refs/", 5) == 0)
6282 branch_name += 5;
6283 if (strncmp(branch_name, "heads/", 6) == 0)
6284 branch_name += 6;
6285 else if (strncmp(branch_name, "remotes/", 8) == 0)
6286 branch_name += 8;
6288 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6289 return got_error_from_errno("asprintf");
6291 if (asprintf(&remote_refname, "refs/remotes/%s",
6292 branch_name) == -1) {
6293 err = got_error_from_errno("asprintf");
6294 goto done;
6297 err = got_ref_open(&ref, repo, refname, 0);
6298 if (err) {
6299 const struct got_error *err2;
6300 if (err->code != GOT_ERR_NOT_REF)
6301 goto done;
6303 * Keep 'err' intact such that if neither branch exists
6304 * we report "refs/heads" rather than "refs/remotes" in
6305 * our error message.
6307 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6308 if (err2)
6309 goto done;
6310 err = NULL;
6313 if (worktree &&
6314 strcmp(got_worktree_get_head_ref_name(worktree),
6315 got_ref_get_name(ref)) == 0) {
6316 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6317 "will not delete this work tree's current branch");
6318 goto done;
6321 err = delete_ref(repo, ref);
6322 done:
6323 if (ref)
6324 got_ref_close(ref);
6325 free(refname);
6326 free(remote_refname);
6327 return err;
6330 static const struct got_error *
6331 add_branch(struct got_repository *repo, const char *branch_name,
6332 struct got_object_id *base_commit_id)
6334 const struct got_error *err = NULL;
6335 struct got_reference *ref = NULL;
6336 char *base_refname = NULL, *refname = NULL;
6339 * Don't let the user create a branch name with a leading '-'.
6340 * While technically a valid reference name, this case is usually
6341 * an unintended typo.
6343 if (branch_name[0] == '-')
6344 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6346 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6347 branch_name += 11;
6349 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6350 err = got_error_from_errno("asprintf");
6351 goto done;
6354 err = got_ref_open(&ref, repo, refname, 0);
6355 if (err == NULL) {
6356 err = got_error(GOT_ERR_BRANCH_EXISTS);
6357 goto done;
6358 } else if (err->code != GOT_ERR_NOT_REF)
6359 goto done;
6361 err = got_ref_alloc(&ref, refname, base_commit_id);
6362 if (err)
6363 goto done;
6365 err = got_ref_write(ref, repo);
6366 done:
6367 if (ref)
6368 got_ref_close(ref);
6369 free(base_refname);
6370 free(refname);
6371 return err;
6374 static const struct got_error *
6375 cmd_branch(int argc, char *argv[])
6377 const struct got_error *error = NULL;
6378 struct got_repository *repo = NULL;
6379 struct got_worktree *worktree = NULL;
6380 char *cwd = NULL, *repo_path = NULL;
6381 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6382 const char *delref = NULL, *commit_id_arg = NULL;
6383 struct got_reference *ref = NULL;
6384 struct got_pathlist_head paths;
6385 struct got_pathlist_entry *pe;
6386 struct got_object_id *commit_id = NULL;
6387 char *commit_id_str = NULL;
6389 TAILQ_INIT(&paths);
6391 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6392 switch (ch) {
6393 case 'c':
6394 commit_id_arg = optarg;
6395 break;
6396 case 'd':
6397 delref = optarg;
6398 break;
6399 case 'r':
6400 repo_path = realpath(optarg, NULL);
6401 if (repo_path == NULL)
6402 return got_error_from_errno2("realpath",
6403 optarg);
6404 got_path_strip_trailing_slashes(repo_path);
6405 break;
6406 case 'l':
6407 do_list = 1;
6408 break;
6409 case 'n':
6410 do_update = 0;
6411 break;
6412 case 't':
6413 sort_by_time = 1;
6414 break;
6415 default:
6416 usage_branch();
6417 /* NOTREACHED */
6421 if (do_list && delref)
6422 option_conflict('l', 'd');
6423 if (sort_by_time && !do_list)
6424 errx(1, "-t option requires -l option");
6426 argc -= optind;
6427 argv += optind;
6429 if (!do_list && !delref && argc == 0)
6430 do_show = 1;
6432 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6433 errx(1, "-c option can only be used when creating a branch");
6435 if (do_list || delref) {
6436 if (argc > 0)
6437 usage_branch();
6438 } else if (!do_show && argc != 1)
6439 usage_branch();
6441 #ifndef PROFILE
6442 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6443 "sendfd unveil", NULL) == -1)
6444 err(1, "pledge");
6445 #endif
6446 cwd = getcwd(NULL, 0);
6447 if (cwd == NULL) {
6448 error = got_error_from_errno("getcwd");
6449 goto done;
6452 if (repo_path == NULL) {
6453 error = got_worktree_open(&worktree, cwd);
6454 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6455 goto done;
6456 else
6457 error = NULL;
6458 if (worktree) {
6459 repo_path =
6460 strdup(got_worktree_get_repo_path(worktree));
6461 if (repo_path == NULL)
6462 error = got_error_from_errno("strdup");
6463 if (error)
6464 goto done;
6465 } else {
6466 repo_path = strdup(cwd);
6467 if (repo_path == NULL) {
6468 error = got_error_from_errno("strdup");
6469 goto done;
6474 error = got_repo_open(&repo, repo_path, NULL);
6475 if (error != NULL)
6476 goto done;
6478 #ifndef PROFILE
6479 if (do_list || do_show) {
6480 /* Remove "cpath" promise. */
6481 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6482 NULL) == -1)
6483 err(1, "pledge");
6485 #endif
6487 error = apply_unveil(got_repo_get_path(repo), do_list,
6488 worktree ? got_worktree_get_root_path(worktree) : NULL);
6489 if (error)
6490 goto done;
6492 if (do_show)
6493 error = show_current_branch(repo, worktree);
6494 else if (do_list)
6495 error = list_branches(repo, worktree, sort_by_time);
6496 else if (delref)
6497 error = delete_branch(repo, worktree, delref);
6498 else {
6499 struct got_reflist_head refs;
6500 TAILQ_INIT(&refs);
6501 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6502 NULL);
6503 if (error)
6504 goto done;
6505 if (commit_id_arg == NULL)
6506 commit_id_arg = worktree ?
6507 got_worktree_get_head_ref_name(worktree) :
6508 GOT_REF_HEAD;
6509 error = got_repo_match_object_id(&commit_id, NULL,
6510 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6511 got_ref_list_free(&refs);
6512 if (error)
6513 goto done;
6514 error = add_branch(repo, argv[0], commit_id);
6515 if (error)
6516 goto done;
6517 if (worktree && do_update) {
6518 struct got_update_progress_arg upa;
6519 char *branch_refname = NULL;
6521 error = got_object_id_str(&commit_id_str, commit_id);
6522 if (error)
6523 goto done;
6524 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6525 worktree);
6526 if (error)
6527 goto done;
6528 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6529 == -1) {
6530 error = got_error_from_errno("asprintf");
6531 goto done;
6533 error = got_ref_open(&ref, repo, branch_refname, 0);
6534 free(branch_refname);
6535 if (error)
6536 goto done;
6537 error = switch_head_ref(ref, commit_id, worktree,
6538 repo);
6539 if (error)
6540 goto done;
6541 error = got_worktree_set_base_commit_id(worktree, repo,
6542 commit_id);
6543 if (error)
6544 goto done;
6545 memset(&upa, 0, sizeof(upa));
6546 error = got_worktree_checkout_files(worktree, &paths,
6547 repo, update_progress, &upa, check_cancelled,
6548 NULL);
6549 if (error)
6550 goto done;
6551 if (upa.did_something) {
6552 printf("Updated to %s: %s\n",
6553 got_worktree_get_head_ref_name(worktree),
6554 commit_id_str);
6556 print_update_progress_stats(&upa);
6559 done:
6560 if (ref)
6561 got_ref_close(ref);
6562 if (repo) {
6563 const struct got_error *close_err = got_repo_close(repo);
6564 if (error == NULL)
6565 error = close_err;
6567 if (worktree)
6568 got_worktree_close(worktree);
6569 free(cwd);
6570 free(repo_path);
6571 free(commit_id);
6572 free(commit_id_str);
6573 TAILQ_FOREACH(pe, &paths, entry)
6574 free((char *)pe->path);
6575 got_pathlist_free(&paths);
6576 return error;
6580 __dead static void
6581 usage_tag(void)
6583 fprintf(stderr,
6584 "usage: %s tag [-c commit] [-r repository] [-l] "
6585 "[-m message] name\n", getprogname());
6586 exit(1);
6589 #if 0
6590 static const struct got_error *
6591 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6593 const struct got_error *err = NULL;
6594 struct got_reflist_entry *re, *se, *new;
6595 struct got_object_id *re_id, *se_id;
6596 struct got_tag_object *re_tag, *se_tag;
6597 time_t re_time, se_time;
6599 STAILQ_FOREACH(re, tags, entry) {
6600 se = STAILQ_FIRST(sorted);
6601 if (se == NULL) {
6602 err = got_reflist_entry_dup(&new, re);
6603 if (err)
6604 return err;
6605 STAILQ_INSERT_HEAD(sorted, new, entry);
6606 continue;
6607 } else {
6608 err = got_ref_resolve(&re_id, repo, re->ref);
6609 if (err)
6610 break;
6611 err = got_object_open_as_tag(&re_tag, repo, re_id);
6612 free(re_id);
6613 if (err)
6614 break;
6615 re_time = got_object_tag_get_tagger_time(re_tag);
6616 got_object_tag_close(re_tag);
6619 while (se) {
6620 err = got_ref_resolve(&se_id, repo, re->ref);
6621 if (err)
6622 break;
6623 err = got_object_open_as_tag(&se_tag, repo, se_id);
6624 free(se_id);
6625 if (err)
6626 break;
6627 se_time = got_object_tag_get_tagger_time(se_tag);
6628 got_object_tag_close(se_tag);
6630 if (se_time > re_time) {
6631 err = got_reflist_entry_dup(&new, re);
6632 if (err)
6633 return err;
6634 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6635 break;
6637 se = STAILQ_NEXT(se, entry);
6638 continue;
6641 done:
6642 return err;
6644 #endif
6646 static const struct got_error *
6647 list_tags(struct got_repository *repo)
6649 static const struct got_error *err = NULL;
6650 struct got_reflist_head refs;
6651 struct got_reflist_entry *re;
6653 TAILQ_INIT(&refs);
6655 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6656 if (err)
6657 return err;
6659 TAILQ_FOREACH(re, &refs, entry) {
6660 const char *refname;
6661 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6662 char datebuf[26];
6663 const char *tagger;
6664 time_t tagger_time;
6665 struct got_object_id *id;
6666 struct got_tag_object *tag;
6667 struct got_commit_object *commit = NULL;
6669 refname = got_ref_get_name(re->ref);
6670 if (strncmp(refname, "refs/tags/", 10) != 0)
6671 continue;
6672 refname += 10;
6673 refstr = got_ref_to_str(re->ref);
6674 if (refstr == NULL) {
6675 err = got_error_from_errno("got_ref_to_str");
6676 break;
6678 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6679 free(refstr);
6681 err = got_ref_resolve(&id, repo, re->ref);
6682 if (err)
6683 break;
6684 err = got_object_open_as_tag(&tag, repo, id);
6685 if (err) {
6686 if (err->code != GOT_ERR_OBJ_TYPE) {
6687 free(id);
6688 break;
6690 /* "lightweight" tag */
6691 err = got_object_open_as_commit(&commit, repo, id);
6692 if (err) {
6693 free(id);
6694 break;
6696 tagger = got_object_commit_get_committer(commit);
6697 tagger_time =
6698 got_object_commit_get_committer_time(commit);
6699 err = got_object_id_str(&id_str, id);
6700 free(id);
6701 if (err)
6702 break;
6703 } else {
6704 free(id);
6705 tagger = got_object_tag_get_tagger(tag);
6706 tagger_time = got_object_tag_get_tagger_time(tag);
6707 err = got_object_id_str(&id_str,
6708 got_object_tag_get_object_id(tag));
6709 if (err)
6710 break;
6712 printf("from: %s\n", tagger);
6713 datestr = get_datestr(&tagger_time, datebuf);
6714 if (datestr)
6715 printf("date: %s UTC\n", datestr);
6716 if (commit)
6717 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6718 else {
6719 switch (got_object_tag_get_object_type(tag)) {
6720 case GOT_OBJ_TYPE_BLOB:
6721 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6722 id_str);
6723 break;
6724 case GOT_OBJ_TYPE_TREE:
6725 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6726 id_str);
6727 break;
6728 case GOT_OBJ_TYPE_COMMIT:
6729 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6730 id_str);
6731 break;
6732 case GOT_OBJ_TYPE_TAG:
6733 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6734 id_str);
6735 break;
6736 default:
6737 break;
6740 free(id_str);
6741 if (commit) {
6742 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6743 if (err)
6744 break;
6745 got_object_commit_close(commit);
6746 } else {
6747 tagmsg0 = strdup(got_object_tag_get_message(tag));
6748 got_object_tag_close(tag);
6749 if (tagmsg0 == NULL) {
6750 err = got_error_from_errno("strdup");
6751 break;
6755 tagmsg = tagmsg0;
6756 do {
6757 line = strsep(&tagmsg, "\n");
6758 if (line)
6759 printf(" %s\n", line);
6760 } while (line);
6761 free(tagmsg0);
6764 got_ref_list_free(&refs);
6765 return NULL;
6768 static const struct got_error *
6769 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6770 const char *tag_name, const char *repo_path)
6772 const struct got_error *err = NULL;
6773 char *template = NULL, *initial_content = NULL;
6774 char *editor = NULL;
6775 int initial_content_len;
6776 int fd = -1;
6778 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6779 err = got_error_from_errno("asprintf");
6780 goto done;
6783 initial_content_len = asprintf(&initial_content,
6784 "\n# tagging commit %s as %s\n",
6785 commit_id_str, tag_name);
6786 if (initial_content_len == -1) {
6787 err = got_error_from_errno("asprintf");
6788 goto done;
6791 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6792 if (err)
6793 goto done;
6795 if (write(fd, initial_content, initial_content_len) == -1) {
6796 err = got_error_from_errno2("write", *tagmsg_path);
6797 goto done;
6800 err = get_editor(&editor);
6801 if (err)
6802 goto done;
6803 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6804 initial_content_len, 1);
6805 done:
6806 free(initial_content);
6807 free(template);
6808 free(editor);
6810 if (fd != -1 && close(fd) == -1 && err == NULL)
6811 err = got_error_from_errno2("close", *tagmsg_path);
6813 /* Editor is done; we can now apply unveil(2) */
6814 if (err == NULL)
6815 err = apply_unveil(repo_path, 0, NULL);
6816 if (err) {
6817 free(*tagmsg);
6818 *tagmsg = NULL;
6820 return err;
6823 static const struct got_error *
6824 add_tag(struct got_repository *repo, const char *tagger,
6825 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6827 const struct got_error *err = NULL;
6828 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6829 char *label = NULL, *commit_id_str = NULL;
6830 struct got_reference *ref = NULL;
6831 char *refname = NULL, *tagmsg = NULL;
6832 char *tagmsg_path = NULL, *tag_id_str = NULL;
6833 int preserve_tagmsg = 0;
6834 struct got_reflist_head refs;
6836 TAILQ_INIT(&refs);
6839 * Don't let the user create a tag name with a leading '-'.
6840 * While technically a valid reference name, this case is usually
6841 * an unintended typo.
6843 if (tag_name[0] == '-')
6844 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6846 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6847 if (err)
6848 goto done;
6850 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6851 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6852 if (err)
6853 goto done;
6855 err = got_object_id_str(&commit_id_str, commit_id);
6856 if (err)
6857 goto done;
6859 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6860 refname = strdup(tag_name);
6861 if (refname == NULL) {
6862 err = got_error_from_errno("strdup");
6863 goto done;
6865 tag_name += 10;
6866 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6867 err = got_error_from_errno("asprintf");
6868 goto done;
6871 err = got_ref_open(&ref, repo, refname, 0);
6872 if (err == NULL) {
6873 err = got_error(GOT_ERR_TAG_EXISTS);
6874 goto done;
6875 } else if (err->code != GOT_ERR_NOT_REF)
6876 goto done;
6878 if (tagmsg_arg == NULL) {
6879 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6880 tag_name, got_repo_get_path(repo));
6881 if (err) {
6882 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6883 tagmsg_path != NULL)
6884 preserve_tagmsg = 1;
6885 goto done;
6889 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6890 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6891 if (err) {
6892 if (tagmsg_path)
6893 preserve_tagmsg = 1;
6894 goto done;
6897 err = got_ref_alloc(&ref, refname, tag_id);
6898 if (err) {
6899 if (tagmsg_path)
6900 preserve_tagmsg = 1;
6901 goto done;
6904 err = got_ref_write(ref, repo);
6905 if (err) {
6906 if (tagmsg_path)
6907 preserve_tagmsg = 1;
6908 goto done;
6911 err = got_object_id_str(&tag_id_str, tag_id);
6912 if (err) {
6913 if (tagmsg_path)
6914 preserve_tagmsg = 1;
6915 goto done;
6917 printf("Created tag %s\n", tag_id_str);
6918 done:
6919 if (preserve_tagmsg) {
6920 fprintf(stderr, "%s: tag message preserved in %s\n",
6921 getprogname(), tagmsg_path);
6922 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6923 err = got_error_from_errno2("unlink", tagmsg_path);
6924 free(tag_id_str);
6925 if (ref)
6926 got_ref_close(ref);
6927 free(commit_id);
6928 free(commit_id_str);
6929 free(refname);
6930 free(tagmsg);
6931 free(tagmsg_path);
6932 got_ref_list_free(&refs);
6933 return err;
6936 static const struct got_error *
6937 cmd_tag(int argc, char *argv[])
6939 const struct got_error *error = NULL;
6940 struct got_repository *repo = NULL;
6941 struct got_worktree *worktree = NULL;
6942 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6943 char *gitconfig_path = NULL, *tagger = NULL;
6944 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6945 int ch, do_list = 0;
6947 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6948 switch (ch) {
6949 case 'c':
6950 commit_id_arg = optarg;
6951 break;
6952 case 'm':
6953 tagmsg = optarg;
6954 break;
6955 case 'r':
6956 repo_path = realpath(optarg, NULL);
6957 if (repo_path == NULL)
6958 return got_error_from_errno2("realpath",
6959 optarg);
6960 got_path_strip_trailing_slashes(repo_path);
6961 break;
6962 case 'l':
6963 do_list = 1;
6964 break;
6965 default:
6966 usage_tag();
6967 /* NOTREACHED */
6971 argc -= optind;
6972 argv += optind;
6974 if (do_list) {
6975 if (commit_id_arg != NULL)
6976 errx(1,
6977 "-c option can only be used when creating a tag");
6978 if (tagmsg)
6979 option_conflict('l', 'm');
6980 if (argc > 0)
6981 usage_tag();
6982 } else if (argc != 1)
6983 usage_tag();
6985 tag_name = argv[0];
6987 #ifndef PROFILE
6988 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6989 "sendfd unveil", NULL) == -1)
6990 err(1, "pledge");
6991 #endif
6992 cwd = getcwd(NULL, 0);
6993 if (cwd == NULL) {
6994 error = got_error_from_errno("getcwd");
6995 goto done;
6998 if (repo_path == NULL) {
6999 error = got_worktree_open(&worktree, cwd);
7000 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7001 goto done;
7002 else
7003 error = NULL;
7004 if (worktree) {
7005 repo_path =
7006 strdup(got_worktree_get_repo_path(worktree));
7007 if (repo_path == NULL)
7008 error = got_error_from_errno("strdup");
7009 if (error)
7010 goto done;
7011 } else {
7012 repo_path = strdup(cwd);
7013 if (repo_path == NULL) {
7014 error = got_error_from_errno("strdup");
7015 goto done;
7020 if (do_list) {
7021 if (worktree) {
7022 /* Release work tree lock. */
7023 got_worktree_close(worktree);
7024 worktree = NULL;
7026 error = got_repo_open(&repo, repo_path, NULL);
7027 if (error != NULL)
7028 goto done;
7029 #ifndef PROFILE
7030 /* Remove "cpath" promise. */
7031 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7032 NULL) == -1)
7033 err(1, "pledge");
7034 #endif
7035 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7036 if (error)
7037 goto done;
7038 error = list_tags(repo);
7039 } else {
7040 error = get_gitconfig_path(&gitconfig_path);
7041 if (error)
7042 goto done;
7043 error = got_repo_open(&repo, repo_path, gitconfig_path);
7044 if (error != NULL)
7045 goto done;
7047 error = get_author(&tagger, repo, worktree);
7048 if (error)
7049 goto done;
7050 if (worktree) {
7051 /* Release work tree lock. */
7052 got_worktree_close(worktree);
7053 worktree = NULL;
7056 if (tagmsg) {
7057 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7058 if (error)
7059 goto done;
7062 if (commit_id_arg == NULL) {
7063 struct got_reference *head_ref;
7064 struct got_object_id *commit_id;
7065 error = got_ref_open(&head_ref, repo,
7066 worktree ? got_worktree_get_head_ref_name(worktree)
7067 : GOT_REF_HEAD, 0);
7068 if (error)
7069 goto done;
7070 error = got_ref_resolve(&commit_id, repo, head_ref);
7071 got_ref_close(head_ref);
7072 if (error)
7073 goto done;
7074 error = got_object_id_str(&commit_id_str, commit_id);
7075 free(commit_id);
7076 if (error)
7077 goto done;
7080 error = add_tag(repo, tagger, tag_name,
7081 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7083 done:
7084 if (repo) {
7085 const struct got_error *close_err = got_repo_close(repo);
7086 if (error == NULL)
7087 error = close_err;
7089 if (worktree)
7090 got_worktree_close(worktree);
7091 free(cwd);
7092 free(repo_path);
7093 free(gitconfig_path);
7094 free(commit_id_str);
7095 free(tagger);
7096 return error;
7099 __dead static void
7100 usage_add(void)
7102 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7103 getprogname());
7104 exit(1);
7107 static const struct got_error *
7108 add_progress(void *arg, unsigned char status, const char *path)
7110 while (path[0] == '/')
7111 path++;
7112 printf("%c %s\n", status, path);
7113 return NULL;
7116 static const struct got_error *
7117 cmd_add(int argc, char *argv[])
7119 const struct got_error *error = NULL;
7120 struct got_repository *repo = NULL;
7121 struct got_worktree *worktree = NULL;
7122 char *cwd = NULL;
7123 struct got_pathlist_head paths;
7124 struct got_pathlist_entry *pe;
7125 int ch, can_recurse = 0, no_ignores = 0;
7127 TAILQ_INIT(&paths);
7129 while ((ch = getopt(argc, argv, "IR")) != -1) {
7130 switch (ch) {
7131 case 'I':
7132 no_ignores = 1;
7133 break;
7134 case 'R':
7135 can_recurse = 1;
7136 break;
7137 default:
7138 usage_add();
7139 /* NOTREACHED */
7143 argc -= optind;
7144 argv += optind;
7146 #ifndef PROFILE
7147 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7148 NULL) == -1)
7149 err(1, "pledge");
7150 #endif
7151 if (argc < 1)
7152 usage_add();
7154 cwd = getcwd(NULL, 0);
7155 if (cwd == NULL) {
7156 error = got_error_from_errno("getcwd");
7157 goto done;
7160 error = got_worktree_open(&worktree, cwd);
7161 if (error) {
7162 if (error->code == GOT_ERR_NOT_WORKTREE)
7163 error = wrap_not_worktree_error(error, "add", cwd);
7164 goto done;
7167 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7168 NULL);
7169 if (error != NULL)
7170 goto done;
7172 error = apply_unveil(got_repo_get_path(repo), 1,
7173 got_worktree_get_root_path(worktree));
7174 if (error)
7175 goto done;
7177 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7178 if (error)
7179 goto done;
7181 if (!can_recurse) {
7182 char *ondisk_path;
7183 struct stat sb;
7184 TAILQ_FOREACH(pe, &paths, entry) {
7185 if (asprintf(&ondisk_path, "%s/%s",
7186 got_worktree_get_root_path(worktree),
7187 pe->path) == -1) {
7188 error = got_error_from_errno("asprintf");
7189 goto done;
7191 if (lstat(ondisk_path, &sb) == -1) {
7192 if (errno == ENOENT) {
7193 free(ondisk_path);
7194 continue;
7196 error = got_error_from_errno2("lstat",
7197 ondisk_path);
7198 free(ondisk_path);
7199 goto done;
7201 free(ondisk_path);
7202 if (S_ISDIR(sb.st_mode)) {
7203 error = got_error_msg(GOT_ERR_BAD_PATH,
7204 "adding directories requires -R option");
7205 goto done;
7210 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7211 NULL, repo, no_ignores);
7212 done:
7213 if (repo) {
7214 const struct got_error *close_err = got_repo_close(repo);
7215 if (error == NULL)
7216 error = close_err;
7218 if (worktree)
7219 got_worktree_close(worktree);
7220 TAILQ_FOREACH(pe, &paths, entry)
7221 free((char *)pe->path);
7222 got_pathlist_free(&paths);
7223 free(cwd);
7224 return error;
7227 __dead static void
7228 usage_remove(void)
7230 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7231 "path ...\n", getprogname());
7232 exit(1);
7235 static const struct got_error *
7236 print_remove_status(void *arg, unsigned char status,
7237 unsigned char staged_status, const char *path)
7239 while (path[0] == '/')
7240 path++;
7241 if (status == GOT_STATUS_NONEXISTENT)
7242 return NULL;
7243 if (status == staged_status && (status == GOT_STATUS_DELETE))
7244 status = GOT_STATUS_NO_CHANGE;
7245 printf("%c%c %s\n", status, staged_status, path);
7246 return NULL;
7249 static const struct got_error *
7250 cmd_remove(int argc, char *argv[])
7252 const struct got_error *error = NULL;
7253 struct got_worktree *worktree = NULL;
7254 struct got_repository *repo = NULL;
7255 const char *status_codes = NULL;
7256 char *cwd = NULL;
7257 struct got_pathlist_head paths;
7258 struct got_pathlist_entry *pe;
7259 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7260 int ignore_missing_paths = 0;
7262 TAILQ_INIT(&paths);
7264 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7265 switch (ch) {
7266 case 'f':
7267 delete_local_mods = 1;
7268 ignore_missing_paths = 1;
7269 break;
7270 case 'k':
7271 keep_on_disk = 1;
7272 break;
7273 case 'R':
7274 can_recurse = 1;
7275 break;
7276 case 's':
7277 for (i = 0; i < strlen(optarg); i++) {
7278 switch (optarg[i]) {
7279 case GOT_STATUS_MODIFY:
7280 delete_local_mods = 1;
7281 break;
7282 case GOT_STATUS_MISSING:
7283 ignore_missing_paths = 1;
7284 break;
7285 default:
7286 errx(1, "invalid status code '%c'",
7287 optarg[i]);
7290 status_codes = optarg;
7291 break;
7292 default:
7293 usage_remove();
7294 /* NOTREACHED */
7298 argc -= optind;
7299 argv += optind;
7301 #ifndef PROFILE
7302 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7303 NULL) == -1)
7304 err(1, "pledge");
7305 #endif
7306 if (argc < 1)
7307 usage_remove();
7309 cwd = getcwd(NULL, 0);
7310 if (cwd == NULL) {
7311 error = got_error_from_errno("getcwd");
7312 goto done;
7314 error = got_worktree_open(&worktree, cwd);
7315 if (error) {
7316 if (error->code == GOT_ERR_NOT_WORKTREE)
7317 error = wrap_not_worktree_error(error, "remove", cwd);
7318 goto done;
7321 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7322 NULL);
7323 if (error)
7324 goto done;
7326 error = apply_unveil(got_repo_get_path(repo), 1,
7327 got_worktree_get_root_path(worktree));
7328 if (error)
7329 goto done;
7331 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7332 if (error)
7333 goto done;
7335 if (!can_recurse) {
7336 char *ondisk_path;
7337 struct stat sb;
7338 TAILQ_FOREACH(pe, &paths, entry) {
7339 if (asprintf(&ondisk_path, "%s/%s",
7340 got_worktree_get_root_path(worktree),
7341 pe->path) == -1) {
7342 error = got_error_from_errno("asprintf");
7343 goto done;
7345 if (lstat(ondisk_path, &sb) == -1) {
7346 if (errno == ENOENT) {
7347 free(ondisk_path);
7348 continue;
7350 error = got_error_from_errno2("lstat",
7351 ondisk_path);
7352 free(ondisk_path);
7353 goto done;
7355 free(ondisk_path);
7356 if (S_ISDIR(sb.st_mode)) {
7357 error = got_error_msg(GOT_ERR_BAD_PATH,
7358 "removing directories requires -R option");
7359 goto done;
7364 error = got_worktree_schedule_delete(worktree, &paths,
7365 delete_local_mods, status_codes, print_remove_status, NULL,
7366 repo, keep_on_disk, ignore_missing_paths);
7367 done:
7368 if (repo) {
7369 const struct got_error *close_err = got_repo_close(repo);
7370 if (error == NULL)
7371 error = close_err;
7373 if (worktree)
7374 got_worktree_close(worktree);
7375 TAILQ_FOREACH(pe, &paths, entry)
7376 free((char *)pe->path);
7377 got_pathlist_free(&paths);
7378 free(cwd);
7379 return error;
7382 __dead static void
7383 usage_patch(void)
7385 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7386 "[-R] [patchfile]\n", getprogname());
7387 exit(1);
7390 static const struct got_error *
7391 patch_from_stdin(int *patchfd)
7393 const struct got_error *err = NULL;
7394 ssize_t r;
7395 char *path, buf[BUFSIZ];
7396 sig_t sighup, sigint, sigquit;
7398 err = got_opentemp_named_fd(&path, patchfd,
7399 GOT_TMPDIR_STR "/got-patch");
7400 if (err)
7401 return err;
7402 unlink(path);
7403 free(path);
7405 sighup = signal(SIGHUP, SIG_DFL);
7406 sigint = signal(SIGINT, SIG_DFL);
7407 sigquit = signal(SIGQUIT, SIG_DFL);
7409 for (;;) {
7410 r = read(0, buf, sizeof(buf));
7411 if (r == -1) {
7412 err = got_error_from_errno("read");
7413 break;
7415 if (r == 0)
7416 break;
7417 if (write(*patchfd, buf, r) == -1) {
7418 err = got_error_from_errno("write");
7419 break;
7423 signal(SIGHUP, sighup);
7424 signal(SIGINT, sigint);
7425 signal(SIGQUIT, sigquit);
7427 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7428 err = got_error_from_errno("lseek");
7430 if (err != NULL) {
7431 close(*patchfd);
7432 *patchfd = -1;
7435 return err;
7438 static const struct got_error *
7439 patch_progress(void *arg, const char *old, const char *new,
7440 unsigned char status, const struct got_error *error, long old_from,
7441 long old_lines, long new_from, long new_lines, long offset,
7442 const struct got_error *hunk_err)
7444 const char *path = new == NULL ? old : new;
7446 while (*path == '/')
7447 path++;
7449 if (status != 0)
7450 printf("%c %s\n", status, path);
7452 if (error != NULL)
7453 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7455 if (offset != 0 || hunk_err != NULL) {
7456 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7457 old_lines, new_from, new_lines);
7458 if (hunk_err != NULL)
7459 printf("%s\n", hunk_err->msg);
7460 else
7461 printf("applied with offset %ld\n", offset);
7464 return NULL;
7467 static const struct got_error *
7468 cmd_patch(int argc, char *argv[])
7470 const struct got_error *error = NULL, *close_error = NULL;
7471 struct got_worktree *worktree = NULL;
7472 struct got_repository *repo = NULL;
7473 const char *errstr;
7474 char *cwd = NULL;
7475 int ch, nop = 0, strip = -1, reverse = 0;
7476 int patchfd;
7478 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7479 switch (ch) {
7480 case 'n':
7481 nop = 1;
7482 break;
7483 case 'p':
7484 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7485 if (errstr != NULL)
7486 errx(1, "pathname strip count is %s: %s",
7487 errstr, optarg);
7488 break;
7489 case 'R':
7490 reverse = 1;
7491 break;
7492 default:
7493 usage_patch();
7494 /* NOTREACHED */
7498 argc -= optind;
7499 argv += optind;
7501 if (argc == 0) {
7502 error = patch_from_stdin(&patchfd);
7503 if (error)
7504 return error;
7505 } else if (argc == 1) {
7506 patchfd = open(argv[0], O_RDONLY);
7507 if (patchfd == -1) {
7508 error = got_error_from_errno2("open", argv[0]);
7509 return error;
7511 } else
7512 usage_patch();
7514 if ((cwd = getcwd(NULL, 0)) == NULL) {
7515 error = got_error_from_errno("getcwd");
7516 goto done;
7519 error = got_worktree_open(&worktree, cwd);
7520 if (error != NULL)
7521 goto done;
7523 const char *repo_path = got_worktree_get_repo_path(worktree);
7524 error = got_repo_open(&repo, repo_path, NULL);
7525 if (error != NULL)
7526 goto done;
7528 error = apply_unveil(got_repo_get_path(repo), 0,
7529 got_worktree_get_root_path(worktree));
7530 if (error != NULL)
7531 goto done;
7533 #ifndef PROFILE
7534 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7535 NULL) == -1)
7536 err(1, "pledge");
7537 #endif
7539 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7540 &patch_progress, NULL, check_cancelled, NULL);
7542 done:
7543 if (repo) {
7544 close_error = got_repo_close(repo);
7545 if (error == NULL)
7546 error = close_error;
7548 if (worktree != NULL) {
7549 close_error = got_worktree_close(worktree);
7550 if (error == NULL)
7551 error = close_error;
7553 free(cwd);
7554 return error;
7557 __dead static void
7558 usage_revert(void)
7560 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7561 "path ...\n", getprogname());
7562 exit(1);
7565 static const struct got_error *
7566 revert_progress(void *arg, unsigned char status, const char *path)
7568 if (status == GOT_STATUS_UNVERSIONED)
7569 return NULL;
7571 while (path[0] == '/')
7572 path++;
7573 printf("%c %s\n", status, path);
7574 return NULL;
7577 struct choose_patch_arg {
7578 FILE *patch_script_file;
7579 const char *action;
7582 static const struct got_error *
7583 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7584 int nchanges, const char *action)
7586 const struct got_error *err;
7587 char *line = NULL;
7588 size_t linesize = 0;
7589 ssize_t linelen;
7591 switch (status) {
7592 case GOT_STATUS_ADD:
7593 printf("A %s\n%s this addition? [y/n] ", path, action);
7594 break;
7595 case GOT_STATUS_DELETE:
7596 printf("D %s\n%s this deletion? [y/n] ", path, action);
7597 break;
7598 case GOT_STATUS_MODIFY:
7599 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7600 return got_error_from_errno("fseek");
7601 printf(GOT_COMMIT_SEP_STR);
7602 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7603 printf("%s", line);
7604 if (linelen == -1 && ferror(patch_file)) {
7605 err = got_error_from_errno("getline");
7606 free(line);
7607 return err;
7609 free(line);
7610 printf(GOT_COMMIT_SEP_STR);
7611 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7612 path, n, nchanges, action);
7613 break;
7614 default:
7615 return got_error_path(path, GOT_ERR_FILE_STATUS);
7618 return NULL;
7621 static const struct got_error *
7622 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7623 FILE *patch_file, int n, int nchanges)
7625 const struct got_error *err = NULL;
7626 char *line = NULL;
7627 size_t linesize = 0;
7628 ssize_t linelen;
7629 int resp = ' ';
7630 struct choose_patch_arg *a = arg;
7632 *choice = GOT_PATCH_CHOICE_NONE;
7634 if (a->patch_script_file) {
7635 char *nl;
7636 err = show_change(status, path, patch_file, n, nchanges,
7637 a->action);
7638 if (err)
7639 return err;
7640 linelen = getline(&line, &linesize, a->patch_script_file);
7641 if (linelen == -1) {
7642 if (ferror(a->patch_script_file))
7643 return got_error_from_errno("getline");
7644 return NULL;
7646 nl = strchr(line, '\n');
7647 if (nl)
7648 *nl = '\0';
7649 if (strcmp(line, "y") == 0) {
7650 *choice = GOT_PATCH_CHOICE_YES;
7651 printf("y\n");
7652 } else if (strcmp(line, "n") == 0) {
7653 *choice = GOT_PATCH_CHOICE_NO;
7654 printf("n\n");
7655 } else if (strcmp(line, "q") == 0 &&
7656 status == GOT_STATUS_MODIFY) {
7657 *choice = GOT_PATCH_CHOICE_QUIT;
7658 printf("q\n");
7659 } else
7660 printf("invalid response '%s'\n", line);
7661 free(line);
7662 return NULL;
7665 while (resp != 'y' && resp != 'n' && resp != 'q') {
7666 err = show_change(status, path, patch_file, n, nchanges,
7667 a->action);
7668 if (err)
7669 return err;
7670 resp = getchar();
7671 if (resp == '\n')
7672 resp = getchar();
7673 if (status == GOT_STATUS_MODIFY) {
7674 if (resp != 'y' && resp != 'n' && resp != 'q') {
7675 printf("invalid response '%c'\n", resp);
7676 resp = ' ';
7678 } else if (resp != 'y' && resp != 'n') {
7679 printf("invalid response '%c'\n", resp);
7680 resp = ' ';
7684 if (resp == 'y')
7685 *choice = GOT_PATCH_CHOICE_YES;
7686 else if (resp == 'n')
7687 *choice = GOT_PATCH_CHOICE_NO;
7688 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7689 *choice = GOT_PATCH_CHOICE_QUIT;
7691 return NULL;
7694 static const struct got_error *
7695 cmd_revert(int argc, char *argv[])
7697 const struct got_error *error = NULL;
7698 struct got_worktree *worktree = NULL;
7699 struct got_repository *repo = NULL;
7700 char *cwd = NULL, *path = NULL;
7701 struct got_pathlist_head paths;
7702 struct got_pathlist_entry *pe;
7703 int ch, can_recurse = 0, pflag = 0;
7704 FILE *patch_script_file = NULL;
7705 const char *patch_script_path = NULL;
7706 struct choose_patch_arg cpa;
7708 TAILQ_INIT(&paths);
7710 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7711 switch (ch) {
7712 case 'p':
7713 pflag = 1;
7714 break;
7715 case 'F':
7716 patch_script_path = optarg;
7717 break;
7718 case 'R':
7719 can_recurse = 1;
7720 break;
7721 default:
7722 usage_revert();
7723 /* NOTREACHED */
7727 argc -= optind;
7728 argv += optind;
7730 #ifndef PROFILE
7731 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7732 "unveil", NULL) == -1)
7733 err(1, "pledge");
7734 #endif
7735 if (argc < 1)
7736 usage_revert();
7737 if (patch_script_path && !pflag)
7738 errx(1, "-F option can only be used together with -p option");
7740 cwd = getcwd(NULL, 0);
7741 if (cwd == NULL) {
7742 error = got_error_from_errno("getcwd");
7743 goto done;
7745 error = got_worktree_open(&worktree, cwd);
7746 if (error) {
7747 if (error->code == GOT_ERR_NOT_WORKTREE)
7748 error = wrap_not_worktree_error(error, "revert", cwd);
7749 goto done;
7752 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7753 NULL);
7754 if (error != NULL)
7755 goto done;
7757 if (patch_script_path) {
7758 patch_script_file = fopen(patch_script_path, "re");
7759 if (patch_script_file == NULL) {
7760 error = got_error_from_errno2("fopen",
7761 patch_script_path);
7762 goto done;
7765 error = apply_unveil(got_repo_get_path(repo), 1,
7766 got_worktree_get_root_path(worktree));
7767 if (error)
7768 goto done;
7770 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7771 if (error)
7772 goto done;
7774 if (!can_recurse) {
7775 char *ondisk_path;
7776 struct stat sb;
7777 TAILQ_FOREACH(pe, &paths, entry) {
7778 if (asprintf(&ondisk_path, "%s/%s",
7779 got_worktree_get_root_path(worktree),
7780 pe->path) == -1) {
7781 error = got_error_from_errno("asprintf");
7782 goto done;
7784 if (lstat(ondisk_path, &sb) == -1) {
7785 if (errno == ENOENT) {
7786 free(ondisk_path);
7787 continue;
7789 error = got_error_from_errno2("lstat",
7790 ondisk_path);
7791 free(ondisk_path);
7792 goto done;
7794 free(ondisk_path);
7795 if (S_ISDIR(sb.st_mode)) {
7796 error = got_error_msg(GOT_ERR_BAD_PATH,
7797 "reverting directories requires -R option");
7798 goto done;
7803 cpa.patch_script_file = patch_script_file;
7804 cpa.action = "revert";
7805 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7806 pflag ? choose_patch : NULL, &cpa, repo);
7807 done:
7808 if (patch_script_file && fclose(patch_script_file) == EOF &&
7809 error == NULL)
7810 error = got_error_from_errno2("fclose", patch_script_path);
7811 if (repo) {
7812 const struct got_error *close_err = got_repo_close(repo);
7813 if (error == NULL)
7814 error = close_err;
7816 if (worktree)
7817 got_worktree_close(worktree);
7818 free(path);
7819 free(cwd);
7820 return error;
7823 __dead static void
7824 usage_commit(void)
7826 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7827 "[path ...]\n", getprogname());
7828 exit(1);
7831 struct collect_commit_logmsg_arg {
7832 const char *cmdline_log;
7833 const char *prepared_log;
7834 int non_interactive;
7835 const char *editor;
7836 const char *worktree_path;
7837 const char *branch_name;
7838 const char *repo_path;
7839 char *logmsg_path;
7843 static const struct got_error *
7844 read_prepared_logmsg(char **logmsg, const char *path)
7846 const struct got_error *err = NULL;
7847 FILE *f = NULL;
7848 struct stat sb;
7849 size_t r;
7851 *logmsg = NULL;
7852 memset(&sb, 0, sizeof(sb));
7854 f = fopen(path, "re");
7855 if (f == NULL)
7856 return got_error_from_errno2("fopen", path);
7858 if (fstat(fileno(f), &sb) == -1) {
7859 err = got_error_from_errno2("fstat", path);
7860 goto done;
7862 if (sb.st_size == 0) {
7863 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7864 goto done;
7867 *logmsg = malloc(sb.st_size + 1);
7868 if (*logmsg == NULL) {
7869 err = got_error_from_errno("malloc");
7870 goto done;
7873 r = fread(*logmsg, 1, sb.st_size, f);
7874 if (r != sb.st_size) {
7875 if (ferror(f))
7876 err = got_error_from_errno2("fread", path);
7877 else
7878 err = got_error(GOT_ERR_IO);
7879 goto done;
7881 (*logmsg)[sb.st_size] = '\0';
7882 done:
7883 if (fclose(f) == EOF && err == NULL)
7884 err = got_error_from_errno2("fclose", path);
7885 if (err) {
7886 free(*logmsg);
7887 *logmsg = NULL;
7889 return err;
7893 static const struct got_error *
7894 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7895 void *arg)
7897 char *initial_content = NULL;
7898 struct got_pathlist_entry *pe;
7899 const struct got_error *err = NULL;
7900 char *template = NULL;
7901 struct collect_commit_logmsg_arg *a = arg;
7902 int initial_content_len;
7903 int fd = -1;
7904 size_t len;
7906 /* if a message was specified on the command line, just use it */
7907 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7908 len = strlen(a->cmdline_log) + 1;
7909 *logmsg = malloc(len + 1);
7910 if (*logmsg == NULL)
7911 return got_error_from_errno("malloc");
7912 strlcpy(*logmsg, a->cmdline_log, len);
7913 return NULL;
7914 } else if (a->prepared_log != NULL && a->non_interactive)
7915 return read_prepared_logmsg(logmsg, a->prepared_log);
7917 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7918 return got_error_from_errno("asprintf");
7920 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7921 if (err)
7922 goto done;
7924 if (a->prepared_log) {
7925 char *msg;
7926 err = read_prepared_logmsg(&msg, a->prepared_log);
7927 if (err)
7928 goto done;
7929 if (write(fd, msg, strlen(msg)) == -1) {
7930 err = got_error_from_errno2("write", a->logmsg_path);
7931 free(msg);
7932 goto done;
7934 free(msg);
7937 initial_content_len = asprintf(&initial_content,
7938 "\n# changes to be committed on branch %s:\n",
7939 a->branch_name);
7940 if (initial_content_len == -1) {
7941 err = got_error_from_errno("asprintf");
7942 goto done;
7945 if (write(fd, initial_content, initial_content_len) == -1) {
7946 err = got_error_from_errno2("write", a->logmsg_path);
7947 goto done;
7950 TAILQ_FOREACH(pe, commitable_paths, entry) {
7951 struct got_commitable *ct = pe->data;
7952 dprintf(fd, "# %c %s\n",
7953 got_commitable_get_status(ct),
7954 got_commitable_get_path(ct));
7957 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7958 initial_content_len, a->prepared_log ? 0 : 1);
7959 done:
7960 free(initial_content);
7961 free(template);
7963 if (fd != -1 && close(fd) == -1 && err == NULL)
7964 err = got_error_from_errno2("close", a->logmsg_path);
7966 /* Editor is done; we can now apply unveil(2) */
7967 if (err == NULL)
7968 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7969 if (err) {
7970 free(*logmsg);
7971 *logmsg = NULL;
7973 return err;
7976 static const struct got_error *
7977 cmd_commit(int argc, char *argv[])
7979 const struct got_error *error = NULL;
7980 struct got_worktree *worktree = NULL;
7981 struct got_repository *repo = NULL;
7982 char *cwd = NULL, *id_str = NULL;
7983 struct got_object_id *id = NULL;
7984 const char *logmsg = NULL;
7985 char *prepared_logmsg = NULL;
7986 struct collect_commit_logmsg_arg cl_arg;
7987 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7988 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7989 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7990 struct got_pathlist_head paths;
7992 TAILQ_INIT(&paths);
7993 cl_arg.logmsg_path = NULL;
7995 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7996 switch (ch) {
7997 case 'F':
7998 if (logmsg != NULL)
7999 option_conflict('F', 'm');
8000 prepared_logmsg = realpath(optarg, NULL);
8001 if (prepared_logmsg == NULL)
8002 return got_error_from_errno2("realpath",
8003 optarg);
8004 break;
8005 case 'm':
8006 if (prepared_logmsg)
8007 option_conflict('m', 'F');
8008 logmsg = optarg;
8009 break;
8010 case 'N':
8011 non_interactive = 1;
8012 break;
8013 case 'S':
8014 allow_bad_symlinks = 1;
8015 break;
8016 default:
8017 usage_commit();
8018 /* NOTREACHED */
8022 argc -= optind;
8023 argv += optind;
8025 #ifndef PROFILE
8026 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8027 "unveil", NULL) == -1)
8028 err(1, "pledge");
8029 #endif
8030 cwd = getcwd(NULL, 0);
8031 if (cwd == NULL) {
8032 error = got_error_from_errno("getcwd");
8033 goto done;
8035 error = got_worktree_open(&worktree, cwd);
8036 if (error) {
8037 if (error->code == GOT_ERR_NOT_WORKTREE)
8038 error = wrap_not_worktree_error(error, "commit", cwd);
8039 goto done;
8042 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8043 if (error)
8044 goto done;
8045 if (rebase_in_progress) {
8046 error = got_error(GOT_ERR_REBASING);
8047 goto done;
8050 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8051 worktree);
8052 if (error)
8053 goto done;
8055 error = get_gitconfig_path(&gitconfig_path);
8056 if (error)
8057 goto done;
8058 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8059 gitconfig_path);
8060 if (error != NULL)
8061 goto done;
8063 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8064 if (error)
8065 goto done;
8066 if (merge_in_progress) {
8067 error = got_error(GOT_ERR_MERGE_BUSY);
8068 goto done;
8071 error = get_author(&author, repo, worktree);
8072 if (error)
8073 return error;
8076 * unveil(2) traverses exec(2); if an editor is used we have
8077 * to apply unveil after the log message has been written.
8079 if (logmsg == NULL || strlen(logmsg) == 0)
8080 error = get_editor(&editor);
8081 else
8082 error = apply_unveil(got_repo_get_path(repo), 0,
8083 got_worktree_get_root_path(worktree));
8084 if (error)
8085 goto done;
8087 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8088 if (error)
8089 goto done;
8091 cl_arg.editor = editor;
8092 cl_arg.cmdline_log = logmsg;
8093 cl_arg.prepared_log = prepared_logmsg;
8094 cl_arg.non_interactive = non_interactive;
8095 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8096 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8097 if (!histedit_in_progress) {
8098 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8099 error = got_error(GOT_ERR_COMMIT_BRANCH);
8100 goto done;
8102 cl_arg.branch_name += 11;
8104 cl_arg.repo_path = got_repo_get_path(repo);
8105 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8106 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8107 print_status, NULL, repo);
8108 if (error) {
8109 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8110 cl_arg.logmsg_path != NULL)
8111 preserve_logmsg = 1;
8112 goto done;
8115 error = got_object_id_str(&id_str, id);
8116 if (error)
8117 goto done;
8118 printf("Created commit %s\n", id_str);
8119 done:
8120 if (preserve_logmsg) {
8121 fprintf(stderr, "%s: log message preserved in %s\n",
8122 getprogname(), cl_arg.logmsg_path);
8123 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8124 error == NULL)
8125 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8126 free(cl_arg.logmsg_path);
8127 if (repo) {
8128 const struct got_error *close_err = got_repo_close(repo);
8129 if (error == NULL)
8130 error = close_err;
8132 if (worktree)
8133 got_worktree_close(worktree);
8134 free(cwd);
8135 free(id_str);
8136 free(gitconfig_path);
8137 free(editor);
8138 free(author);
8139 free(prepared_logmsg);
8140 return error;
8143 __dead static void
8144 usage_send(void)
8146 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8147 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8148 "[remote-repository]\n", getprogname());
8149 exit(1);
8152 static void
8153 print_load_info(int print_colored, int print_found, int print_trees,
8154 int ncolored, int nfound, int ntrees)
8156 if (print_colored) {
8157 printf("%d commit%s colored", ncolored,
8158 ncolored == 1 ? "" : "s");
8160 if (print_found) {
8161 printf("%s%d object%s found",
8162 ncolored > 0 ? "; " : "",
8163 nfound, nfound == 1 ? "" : "s");
8165 if (print_trees) {
8166 printf("; %d tree%s scanned", ntrees,
8167 ntrees == 1 ? "" : "s");
8171 struct got_send_progress_arg {
8172 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8173 int verbosity;
8174 int last_ncolored;
8175 int last_nfound;
8176 int last_ntrees;
8177 int loading_done;
8178 int last_ncommits;
8179 int last_nobj_total;
8180 int last_p_deltify;
8181 int last_p_written;
8182 int last_p_sent;
8183 int printed_something;
8184 int sent_something;
8185 struct got_pathlist_head *delete_branches;
8188 static const struct got_error *
8189 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8190 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8191 int nobj_written, off_t bytes_sent, const char *refname, int success)
8193 struct got_send_progress_arg *a = arg;
8194 char scaled_packsize[FMT_SCALED_STRSIZE];
8195 char scaled_sent[FMT_SCALED_STRSIZE];
8196 int p_deltify = 0, p_written = 0, p_sent = 0;
8197 int print_colored = 0, print_found = 0, print_trees = 0;
8198 int print_searching = 0, print_total = 0;
8199 int print_deltify = 0, print_written = 0, print_sent = 0;
8201 if (a->verbosity < 0)
8202 return NULL;
8204 if (refname) {
8205 const char *status = success ? "accepted" : "rejected";
8207 if (success) {
8208 struct got_pathlist_entry *pe;
8209 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8210 const char *branchname = pe->path;
8211 if (got_path_cmp(branchname, refname,
8212 strlen(branchname), strlen(refname)) == 0) {
8213 status = "deleted";
8214 a->sent_something = 1;
8215 break;
8220 if (a->printed_something)
8221 putchar('\n');
8222 printf("Server has %s %s", status, refname);
8223 a->printed_something = 1;
8224 return NULL;
8227 if (a->last_ncolored != ncolored) {
8228 print_colored = 1;
8229 a->last_ncolored = ncolored;
8232 if (a->last_nfound != nfound) {
8233 print_colored = 1;
8234 print_found = 1;
8235 a->last_nfound = nfound;
8238 if (a->last_ntrees != ntrees) {
8239 print_colored = 1;
8240 print_found = 1;
8241 print_trees = 1;
8242 a->last_ntrees = ntrees;
8245 if ((print_colored || print_found || print_trees) &&
8246 !a->loading_done) {
8247 printf("\r");
8248 print_load_info(print_colored, print_found, print_trees,
8249 ncolored, nfound, ntrees);
8250 a->printed_something = 1;
8251 fflush(stdout);
8252 return NULL;
8253 } else if (!a->loading_done) {
8254 printf("\r");
8255 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8256 printf("\n");
8257 a->loading_done = 1;
8260 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8261 return got_error_from_errno("fmt_scaled");
8262 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8263 return got_error_from_errno("fmt_scaled");
8265 if (a->last_ncommits != ncommits) {
8266 print_searching = 1;
8267 a->last_ncommits = ncommits;
8270 if (a->last_nobj_total != nobj_total) {
8271 print_searching = 1;
8272 print_total = 1;
8273 a->last_nobj_total = nobj_total;
8276 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8277 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8278 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8279 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8280 return got_error(GOT_ERR_NO_SPACE);
8283 if (nobj_deltify > 0 || nobj_written > 0) {
8284 if (nobj_deltify > 0) {
8285 p_deltify = (nobj_deltify * 100) / nobj_total;
8286 if (p_deltify != a->last_p_deltify) {
8287 a->last_p_deltify = p_deltify;
8288 print_searching = 1;
8289 print_total = 1;
8290 print_deltify = 1;
8293 if (nobj_written > 0) {
8294 p_written = (nobj_written * 100) / nobj_total;
8295 if (p_written != a->last_p_written) {
8296 a->last_p_written = p_written;
8297 print_searching = 1;
8298 print_total = 1;
8299 print_deltify = 1;
8300 print_written = 1;
8305 if (bytes_sent > 0) {
8306 p_sent = (bytes_sent * 100) / packfile_size;
8307 if (p_sent != a->last_p_sent) {
8308 a->last_p_sent = p_sent;
8309 print_searching = 1;
8310 print_total = 1;
8311 print_deltify = 1;
8312 print_written = 1;
8313 print_sent = 1;
8315 a->sent_something = 1;
8318 if (print_searching || print_total || print_deltify || print_written ||
8319 print_sent)
8320 printf("\r");
8321 if (print_searching)
8322 printf("packing %d reference%s", ncommits,
8323 ncommits == 1 ? "" : "s");
8324 if (print_total)
8325 printf("; %d object%s", nobj_total,
8326 nobj_total == 1 ? "" : "s");
8327 if (print_deltify)
8328 printf("; deltify: %d%%", p_deltify);
8329 if (print_sent)
8330 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8331 scaled_packsize, p_sent);
8332 else if (print_written)
8333 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8334 scaled_packsize, p_written);
8335 if (print_searching || print_total || print_deltify ||
8336 print_written || print_sent) {
8337 a->printed_something = 1;
8338 fflush(stdout);
8340 return NULL;
8343 static const struct got_error *
8344 cmd_send(int argc, char *argv[])
8346 const struct got_error *error = NULL;
8347 char *cwd = NULL, *repo_path = NULL;
8348 const char *remote_name;
8349 char *proto = NULL, *host = NULL, *port = NULL;
8350 char *repo_name = NULL, *server_path = NULL;
8351 const struct got_remote_repo *remotes, *remote = NULL;
8352 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8353 struct got_repository *repo = NULL;
8354 struct got_worktree *worktree = NULL;
8355 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8356 struct got_pathlist_head branches;
8357 struct got_pathlist_head tags;
8358 struct got_reflist_head all_branches;
8359 struct got_reflist_head all_tags;
8360 struct got_pathlist_head delete_args;
8361 struct got_pathlist_head delete_branches;
8362 struct got_reflist_entry *re;
8363 struct got_pathlist_entry *pe;
8364 int i, ch, sendfd = -1, sendstatus;
8365 pid_t sendpid = -1;
8366 struct got_send_progress_arg spa;
8367 int verbosity = 0, overwrite_refs = 0;
8368 int send_all_branches = 0, send_all_tags = 0;
8369 struct got_reference *ref = NULL;
8371 TAILQ_INIT(&branches);
8372 TAILQ_INIT(&tags);
8373 TAILQ_INIT(&all_branches);
8374 TAILQ_INIT(&all_tags);
8375 TAILQ_INIT(&delete_args);
8376 TAILQ_INIT(&delete_branches);
8378 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8379 switch (ch) {
8380 case 'a':
8381 send_all_branches = 1;
8382 break;
8383 case 'b':
8384 error = got_pathlist_append(&branches, optarg, NULL);
8385 if (error)
8386 return error;
8387 nbranches++;
8388 break;
8389 case 'd':
8390 error = got_pathlist_append(&delete_args, optarg, NULL);
8391 if (error)
8392 return error;
8393 break;
8394 case 'f':
8395 overwrite_refs = 1;
8396 break;
8397 case 'r':
8398 repo_path = realpath(optarg, NULL);
8399 if (repo_path == NULL)
8400 return got_error_from_errno2("realpath",
8401 optarg);
8402 got_path_strip_trailing_slashes(repo_path);
8403 break;
8404 case 't':
8405 error = got_pathlist_append(&tags, optarg, NULL);
8406 if (error)
8407 return error;
8408 ntags++;
8409 break;
8410 case 'T':
8411 send_all_tags = 1;
8412 break;
8413 case 'v':
8414 if (verbosity < 0)
8415 verbosity = 0;
8416 else if (verbosity < 3)
8417 verbosity++;
8418 break;
8419 case 'q':
8420 verbosity = -1;
8421 break;
8422 default:
8423 usage_send();
8424 /* NOTREACHED */
8427 argc -= optind;
8428 argv += optind;
8430 if (send_all_branches && !TAILQ_EMPTY(&branches))
8431 option_conflict('a', 'b');
8432 if (send_all_tags && !TAILQ_EMPTY(&tags))
8433 option_conflict('T', 't');
8436 if (argc == 0)
8437 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8438 else if (argc == 1)
8439 remote_name = argv[0];
8440 else
8441 usage_send();
8443 cwd = getcwd(NULL, 0);
8444 if (cwd == NULL) {
8445 error = got_error_from_errno("getcwd");
8446 goto done;
8449 if (repo_path == NULL) {
8450 error = got_worktree_open(&worktree, cwd);
8451 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8452 goto done;
8453 else
8454 error = NULL;
8455 if (worktree) {
8456 repo_path =
8457 strdup(got_worktree_get_repo_path(worktree));
8458 if (repo_path == NULL)
8459 error = got_error_from_errno("strdup");
8460 if (error)
8461 goto done;
8462 } else {
8463 repo_path = strdup(cwd);
8464 if (repo_path == NULL) {
8465 error = got_error_from_errno("strdup");
8466 goto done;
8471 error = got_repo_open(&repo, repo_path, NULL);
8472 if (error)
8473 goto done;
8475 if (worktree) {
8476 worktree_conf = got_worktree_get_gotconfig(worktree);
8477 if (worktree_conf) {
8478 got_gotconfig_get_remotes(&nremotes, &remotes,
8479 worktree_conf);
8480 for (i = 0; i < nremotes; i++) {
8481 if (strcmp(remotes[i].name, remote_name) == 0) {
8482 remote = &remotes[i];
8483 break;
8488 if (remote == NULL) {
8489 repo_conf = got_repo_get_gotconfig(repo);
8490 if (repo_conf) {
8491 got_gotconfig_get_remotes(&nremotes, &remotes,
8492 repo_conf);
8493 for (i = 0; i < nremotes; i++) {
8494 if (strcmp(remotes[i].name, remote_name) == 0) {
8495 remote = &remotes[i];
8496 break;
8501 if (remote == NULL) {
8502 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8503 for (i = 0; i < nremotes; i++) {
8504 if (strcmp(remotes[i].name, remote_name) == 0) {
8505 remote = &remotes[i];
8506 break;
8510 if (remote == NULL) {
8511 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8512 goto done;
8515 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8516 &repo_name, remote->send_url);
8517 if (error)
8518 goto done;
8520 if (strcmp(proto, "git") == 0) {
8521 #ifndef PROFILE
8522 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8523 "sendfd dns inet unveil", NULL) == -1)
8524 err(1, "pledge");
8525 #endif
8526 } else if (strcmp(proto, "git+ssh") == 0 ||
8527 strcmp(proto, "ssh") == 0) {
8528 #ifndef PROFILE
8529 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8530 "sendfd unveil", NULL) == -1)
8531 err(1, "pledge");
8532 #endif
8533 } else if (strcmp(proto, "http") == 0 ||
8534 strcmp(proto, "git+http") == 0) {
8535 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8536 goto done;
8537 } else {
8538 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8539 goto done;
8542 error = got_dial_apply_unveil(proto);
8543 if (error)
8544 goto done;
8546 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8547 if (error)
8548 goto done;
8550 if (send_all_branches) {
8551 error = got_ref_list(&all_branches, repo, "refs/heads",
8552 got_ref_cmp_by_name, NULL);
8553 if (error)
8554 goto done;
8555 TAILQ_FOREACH(re, &all_branches, entry) {
8556 const char *branchname = got_ref_get_name(re->ref);
8557 error = got_pathlist_append(&branches,
8558 branchname, NULL);
8559 if (error)
8560 goto done;
8561 nbranches++;
8563 } else if (nbranches == 0) {
8564 for (i = 0; i < remote->nsend_branches; i++) {
8565 got_pathlist_append(&branches,
8566 remote->send_branches[i], NULL);
8570 if (send_all_tags) {
8571 error = got_ref_list(&all_tags, repo, "refs/tags",
8572 got_ref_cmp_by_name, NULL);
8573 if (error)
8574 goto done;
8575 TAILQ_FOREACH(re, &all_tags, entry) {
8576 const char *tagname = got_ref_get_name(re->ref);
8577 error = got_pathlist_append(&tags,
8578 tagname, NULL);
8579 if (error)
8580 goto done;
8581 ntags++;
8586 * To prevent accidents only branches in refs/heads/ can be deleted
8587 * with 'got send -d'.
8588 * Deleting anything else requires local repository access or Git.
8590 TAILQ_FOREACH(pe, &delete_args, entry) {
8591 const char *branchname = pe->path;
8592 char *s;
8593 struct got_pathlist_entry *new;
8594 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8595 s = strdup(branchname);
8596 if (s == NULL) {
8597 error = got_error_from_errno("strdup");
8598 goto done;
8600 } else {
8601 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8602 error = got_error_from_errno("asprintf");
8603 goto done;
8606 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8607 if (error || new == NULL /* duplicate */)
8608 free(s);
8609 if (error)
8610 goto done;
8611 ndelete_branches++;
8614 if (nbranches == 0 && ndelete_branches == 0) {
8615 struct got_reference *head_ref;
8616 if (worktree)
8617 error = got_ref_open(&head_ref, repo,
8618 got_worktree_get_head_ref_name(worktree), 0);
8619 else
8620 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8621 if (error)
8622 goto done;
8623 if (got_ref_is_symbolic(head_ref)) {
8624 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8625 got_ref_close(head_ref);
8626 if (error)
8627 goto done;
8628 } else
8629 ref = head_ref;
8630 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8631 NULL);
8632 if (error)
8633 goto done;
8634 nbranches++;
8637 if (verbosity >= 0)
8638 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8639 port ? ":" : "", port ? port : "");
8641 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8642 server_path, verbosity);
8643 if (error)
8644 goto done;
8646 memset(&spa, 0, sizeof(spa));
8647 spa.last_scaled_packsize[0] = '\0';
8648 spa.last_p_deltify = -1;
8649 spa.last_p_written = -1;
8650 spa.verbosity = verbosity;
8651 spa.delete_branches = &delete_branches;
8652 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8653 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8654 check_cancelled, NULL);
8655 if (spa.printed_something)
8656 putchar('\n');
8657 if (error)
8658 goto done;
8659 if (!spa.sent_something && verbosity >= 0)
8660 printf("Already up-to-date\n");
8661 done:
8662 if (sendpid > 0) {
8663 if (kill(sendpid, SIGTERM) == -1)
8664 error = got_error_from_errno("kill");
8665 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8666 error = got_error_from_errno("waitpid");
8668 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8669 error = got_error_from_errno("close");
8670 if (repo) {
8671 const struct got_error *close_err = got_repo_close(repo);
8672 if (error == NULL)
8673 error = close_err;
8675 if (worktree)
8676 got_worktree_close(worktree);
8677 if (ref)
8678 got_ref_close(ref);
8679 got_pathlist_free(&branches);
8680 got_pathlist_free(&tags);
8681 got_ref_list_free(&all_branches);
8682 got_ref_list_free(&all_tags);
8683 got_pathlist_free(&delete_args);
8684 TAILQ_FOREACH(pe, &delete_branches, entry)
8685 free((char *)pe->path);
8686 got_pathlist_free(&delete_branches);
8687 free(cwd);
8688 free(repo_path);
8689 free(proto);
8690 free(host);
8691 free(port);
8692 free(server_path);
8693 free(repo_name);
8694 return error;
8697 __dead static void
8698 usage_cherrypick(void)
8700 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8701 exit(1);
8704 static const struct got_error *
8705 cmd_cherrypick(int argc, char *argv[])
8707 const struct got_error *error = NULL;
8708 struct got_worktree *worktree = NULL;
8709 struct got_repository *repo = NULL;
8710 char *cwd = NULL, *commit_id_str = NULL;
8711 struct got_object_id *commit_id = NULL;
8712 struct got_commit_object *commit = NULL;
8713 struct got_object_qid *pid;
8714 int ch;
8715 struct got_update_progress_arg upa;
8717 while ((ch = getopt(argc, argv, "")) != -1) {
8718 switch (ch) {
8719 default:
8720 usage_cherrypick();
8721 /* NOTREACHED */
8725 argc -= optind;
8726 argv += optind;
8728 #ifndef PROFILE
8729 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8730 "unveil", NULL) == -1)
8731 err(1, "pledge");
8732 #endif
8733 if (argc != 1)
8734 usage_cherrypick();
8736 cwd = getcwd(NULL, 0);
8737 if (cwd == NULL) {
8738 error = got_error_from_errno("getcwd");
8739 goto done;
8741 error = got_worktree_open(&worktree, cwd);
8742 if (error) {
8743 if (error->code == GOT_ERR_NOT_WORKTREE)
8744 error = wrap_not_worktree_error(error, "cherrypick",
8745 cwd);
8746 goto done;
8749 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8750 NULL);
8751 if (error != NULL)
8752 goto done;
8754 error = apply_unveil(got_repo_get_path(repo), 0,
8755 got_worktree_get_root_path(worktree));
8756 if (error)
8757 goto done;
8759 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8760 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8761 if (error)
8762 goto done;
8763 error = got_object_id_str(&commit_id_str, commit_id);
8764 if (error)
8765 goto done;
8767 error = got_object_open_as_commit(&commit, repo, commit_id);
8768 if (error)
8769 goto done;
8770 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8771 memset(&upa, 0, sizeof(upa));
8772 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8773 commit_id, repo, update_progress, &upa, check_cancelled,
8774 NULL);
8775 if (error != NULL)
8776 goto done;
8778 if (upa.did_something)
8779 printf("Merged commit %s\n", commit_id_str);
8780 print_merge_progress_stats(&upa);
8781 done:
8782 if (commit)
8783 got_object_commit_close(commit);
8784 free(commit_id_str);
8785 if (worktree)
8786 got_worktree_close(worktree);
8787 if (repo) {
8788 const struct got_error *close_err = got_repo_close(repo);
8789 if (error == NULL)
8790 error = close_err;
8792 return error;
8795 __dead static void
8796 usage_backout(void)
8798 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8799 exit(1);
8802 static const struct got_error *
8803 cmd_backout(int argc, char *argv[])
8805 const struct got_error *error = NULL;
8806 struct got_worktree *worktree = NULL;
8807 struct got_repository *repo = NULL;
8808 char *cwd = NULL, *commit_id_str = NULL;
8809 struct got_object_id *commit_id = NULL;
8810 struct got_commit_object *commit = NULL;
8811 struct got_object_qid *pid;
8812 int ch;
8813 struct got_update_progress_arg upa;
8815 while ((ch = getopt(argc, argv, "")) != -1) {
8816 switch (ch) {
8817 default:
8818 usage_backout();
8819 /* NOTREACHED */
8823 argc -= optind;
8824 argv += optind;
8826 #ifndef PROFILE
8827 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8828 "unveil", NULL) == -1)
8829 err(1, "pledge");
8830 #endif
8831 if (argc != 1)
8832 usage_backout();
8834 cwd = getcwd(NULL, 0);
8835 if (cwd == NULL) {
8836 error = got_error_from_errno("getcwd");
8837 goto done;
8839 error = got_worktree_open(&worktree, cwd);
8840 if (error) {
8841 if (error->code == GOT_ERR_NOT_WORKTREE)
8842 error = wrap_not_worktree_error(error, "backout", cwd);
8843 goto done;
8846 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8847 NULL);
8848 if (error != NULL)
8849 goto done;
8851 error = apply_unveil(got_repo_get_path(repo), 0,
8852 got_worktree_get_root_path(worktree));
8853 if (error)
8854 goto done;
8856 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8857 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8858 if (error)
8859 goto done;
8860 error = got_object_id_str(&commit_id_str, commit_id);
8861 if (error)
8862 goto done;
8864 error = got_object_open_as_commit(&commit, repo, commit_id);
8865 if (error)
8866 goto done;
8867 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8868 if (pid == NULL) {
8869 error = got_error(GOT_ERR_ROOT_COMMIT);
8870 goto done;
8873 memset(&upa, 0, sizeof(upa));
8874 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8875 repo, update_progress, &upa, check_cancelled, NULL);
8876 if (error != NULL)
8877 goto done;
8879 if (upa.did_something)
8880 printf("Backed out commit %s\n", commit_id_str);
8881 print_merge_progress_stats(&upa);
8882 done:
8883 if (commit)
8884 got_object_commit_close(commit);
8885 free(commit_id_str);
8886 if (worktree)
8887 got_worktree_close(worktree);
8888 if (repo) {
8889 const struct got_error *close_err = got_repo_close(repo);
8890 if (error == NULL)
8891 error = close_err;
8893 return error;
8896 __dead static void
8897 usage_rebase(void)
8899 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8900 getprogname());
8901 exit(1);
8904 void
8905 trim_logmsg(char *logmsg, int limit)
8907 char *nl;
8908 size_t len;
8910 len = strlen(logmsg);
8911 if (len > limit)
8912 len = limit;
8913 logmsg[len] = '\0';
8914 nl = strchr(logmsg, '\n');
8915 if (nl)
8916 *nl = '\0';
8919 static const struct got_error *
8920 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8922 const struct got_error *err;
8923 char *logmsg0 = NULL;
8924 const char *s;
8926 err = got_object_commit_get_logmsg(&logmsg0, commit);
8927 if (err)
8928 return err;
8930 s = logmsg0;
8931 while (isspace((unsigned char)s[0]))
8932 s++;
8934 *logmsg = strdup(s);
8935 if (*logmsg == NULL) {
8936 err = got_error_from_errno("strdup");
8937 goto done;
8940 trim_logmsg(*logmsg, limit);
8941 done:
8942 free(logmsg0);
8943 return err;
8946 static const struct got_error *
8947 show_rebase_merge_conflict(struct got_object_id *id,
8948 struct got_repository *repo)
8950 const struct got_error *err;
8951 struct got_commit_object *commit = NULL;
8952 char *id_str = NULL, *logmsg = NULL;
8954 err = got_object_open_as_commit(&commit, repo, id);
8955 if (err)
8956 return err;
8958 err = got_object_id_str(&id_str, id);
8959 if (err)
8960 goto done;
8962 id_str[12] = '\0';
8964 err = get_short_logmsg(&logmsg, 42, commit);
8965 if (err)
8966 goto done;
8968 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8969 done:
8970 free(id_str);
8971 got_object_commit_close(commit);
8972 free(logmsg);
8973 return err;
8976 static const struct got_error *
8977 show_rebase_progress(struct got_commit_object *commit,
8978 struct got_object_id *old_id, struct got_object_id *new_id)
8980 const struct got_error *err;
8981 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8983 err = got_object_id_str(&old_id_str, old_id);
8984 if (err)
8985 goto done;
8987 if (new_id) {
8988 err = got_object_id_str(&new_id_str, new_id);
8989 if (err)
8990 goto done;
8993 old_id_str[12] = '\0';
8994 if (new_id_str)
8995 new_id_str[12] = '\0';
8997 err = get_short_logmsg(&logmsg, 42, commit);
8998 if (err)
8999 goto done;
9001 printf("%s -> %s: %s\n", old_id_str,
9002 new_id_str ? new_id_str : "no-op change", logmsg);
9003 done:
9004 free(old_id_str);
9005 free(new_id_str);
9006 free(logmsg);
9007 return err;
9010 static const struct got_error *
9011 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9012 struct got_reference *branch, struct got_reference *new_base_branch,
9013 struct got_reference *tmp_branch, struct got_repository *repo,
9014 int create_backup)
9016 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9017 return got_worktree_rebase_complete(worktree, fileindex,
9018 new_base_branch, tmp_branch, branch, repo, create_backup);
9021 static const struct got_error *
9022 rebase_commit(struct got_pathlist_head *merged_paths,
9023 struct got_worktree *worktree, struct got_fileindex *fileindex,
9024 struct got_reference *tmp_branch,
9025 struct got_object_id *commit_id, struct got_repository *repo)
9027 const struct got_error *error;
9028 struct got_commit_object *commit;
9029 struct got_object_id *new_commit_id;
9031 error = got_object_open_as_commit(&commit, repo, commit_id);
9032 if (error)
9033 return error;
9035 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9036 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9037 if (error) {
9038 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9039 goto done;
9040 error = show_rebase_progress(commit, commit_id, NULL);
9041 } else {
9042 error = show_rebase_progress(commit, commit_id, new_commit_id);
9043 free(new_commit_id);
9045 done:
9046 got_object_commit_close(commit);
9047 return error;
9050 struct check_path_prefix_arg {
9051 const char *path_prefix;
9052 size_t len;
9053 int errcode;
9056 static const struct got_error *
9057 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9058 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9059 struct got_object_id *id1, struct got_object_id *id2,
9060 const char *path1, const char *path2,
9061 mode_t mode1, mode_t mode2, struct got_repository *repo)
9063 struct check_path_prefix_arg *a = arg;
9065 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9066 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9067 return got_error(a->errcode);
9069 return NULL;
9072 static const struct got_error *
9073 check_path_prefix(struct got_object_id *parent_id,
9074 struct got_object_id *commit_id, const char *path_prefix,
9075 int errcode, struct got_repository *repo)
9077 const struct got_error *err;
9078 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9079 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9080 struct check_path_prefix_arg cpp_arg;
9082 if (got_path_is_root_dir(path_prefix))
9083 return NULL;
9085 err = got_object_open_as_commit(&commit, repo, commit_id);
9086 if (err)
9087 goto done;
9089 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9090 if (err)
9091 goto done;
9093 err = got_object_open_as_tree(&tree1, repo,
9094 got_object_commit_get_tree_id(parent_commit));
9095 if (err)
9096 goto done;
9098 err = got_object_open_as_tree(&tree2, repo,
9099 got_object_commit_get_tree_id(commit));
9100 if (err)
9101 goto done;
9103 cpp_arg.path_prefix = path_prefix;
9104 while (cpp_arg.path_prefix[0] == '/')
9105 cpp_arg.path_prefix++;
9106 cpp_arg.len = strlen(cpp_arg.path_prefix);
9107 cpp_arg.errcode = errcode;
9108 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
9109 check_path_prefix_in_diff, &cpp_arg, 0);
9110 done:
9111 if (tree1)
9112 got_object_tree_close(tree1);
9113 if (tree2)
9114 got_object_tree_close(tree2);
9115 if (commit)
9116 got_object_commit_close(commit);
9117 if (parent_commit)
9118 got_object_commit_close(parent_commit);
9119 return err;
9122 static const struct got_error *
9123 collect_commits(struct got_object_id_queue *commits,
9124 struct got_object_id *initial_commit_id,
9125 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9126 const char *path_prefix, int path_prefix_errcode,
9127 struct got_repository *repo)
9129 const struct got_error *err = NULL;
9130 struct got_commit_graph *graph = NULL;
9131 struct got_object_id *parent_id = NULL;
9132 struct got_object_qid *qid;
9133 struct got_object_id *commit_id = initial_commit_id;
9135 err = got_commit_graph_open(&graph, "/", 1);
9136 if (err)
9137 return err;
9139 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9140 check_cancelled, NULL);
9141 if (err)
9142 goto done;
9143 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9144 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9145 check_cancelled, NULL);
9146 if (err) {
9147 if (err->code == GOT_ERR_ITER_COMPLETED) {
9148 err = got_error_msg(GOT_ERR_ANCESTRY,
9149 "ran out of commits to rebase before "
9150 "youngest common ancestor commit has "
9151 "been reached?!?");
9153 goto done;
9154 } else {
9155 err = check_path_prefix(parent_id, commit_id,
9156 path_prefix, path_prefix_errcode, repo);
9157 if (err)
9158 goto done;
9160 err = got_object_qid_alloc(&qid, commit_id);
9161 if (err)
9162 goto done;
9163 STAILQ_INSERT_HEAD(commits, qid, entry);
9164 commit_id = parent_id;
9167 done:
9168 got_commit_graph_close(graph);
9169 return err;
9172 static const struct got_error *
9173 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9175 const struct got_error *err = NULL;
9176 time_t committer_time;
9177 struct tm tm;
9178 char datebuf[11]; /* YYYY-MM-DD + NUL */
9179 char *author0 = NULL, *author, *smallerthan;
9180 char *logmsg0 = NULL, *logmsg, *newline;
9182 committer_time = got_object_commit_get_committer_time(commit);
9183 if (gmtime_r(&committer_time, &tm) == NULL)
9184 return got_error_from_errno("gmtime_r");
9185 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9186 return got_error(GOT_ERR_NO_SPACE);
9188 author0 = strdup(got_object_commit_get_author(commit));
9189 if (author0 == NULL)
9190 return got_error_from_errno("strdup");
9191 author = author0;
9192 smallerthan = strchr(author, '<');
9193 if (smallerthan && smallerthan[1] != '\0')
9194 author = smallerthan + 1;
9195 author[strcspn(author, "@>")] = '\0';
9197 err = got_object_commit_get_logmsg(&logmsg0, commit);
9198 if (err)
9199 goto done;
9200 logmsg = logmsg0;
9201 while (*logmsg == '\n')
9202 logmsg++;
9203 newline = strchr(logmsg, '\n');
9204 if (newline)
9205 *newline = '\0';
9207 if (asprintf(brief_str, "%s %s %s",
9208 datebuf, author, logmsg) == -1)
9209 err = got_error_from_errno("asprintf");
9210 done:
9211 free(author0);
9212 free(logmsg0);
9213 return err;
9216 static const struct got_error *
9217 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9218 struct got_repository *repo)
9220 const struct got_error *err;
9221 char *id_str;
9223 err = got_object_id_str(&id_str, id);
9224 if (err)
9225 return err;
9227 err = got_ref_delete(ref, repo);
9228 if (err)
9229 goto done;
9231 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9232 done:
9233 free(id_str);
9234 return err;
9237 static const struct got_error *
9238 print_backup_ref(const char *branch_name, const char *new_id_str,
9239 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9240 struct got_reflist_object_id_map *refs_idmap,
9241 struct got_repository *repo)
9243 const struct got_error *err = NULL;
9244 struct got_reflist_head *refs;
9245 char *refs_str = NULL;
9246 struct got_object_id *new_commit_id = NULL;
9247 struct got_commit_object *new_commit = NULL;
9248 char *new_commit_brief_str = NULL;
9249 struct got_object_id *yca_id = NULL;
9250 struct got_commit_object *yca_commit = NULL;
9251 char *yca_id_str = NULL, *yca_brief_str = NULL;
9252 char *custom_refs_str;
9254 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9255 return got_error_from_errno("asprintf");
9257 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9258 0, 0, refs_idmap, custom_refs_str);
9259 if (err)
9260 goto done;
9262 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9263 if (err)
9264 goto done;
9266 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9267 if (refs) {
9268 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9269 if (err)
9270 goto done;
9273 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9274 if (err)
9275 goto done;
9277 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9278 if (err)
9279 goto done;
9281 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9282 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9283 if (err)
9284 goto done;
9286 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9287 refs_str ? " (" : "", refs_str ? refs_str : "",
9288 refs_str ? ")" : "", new_commit_brief_str);
9289 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9290 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9291 free(refs_str);
9292 refs_str = NULL;
9294 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9295 if (err)
9296 goto done;
9298 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9299 if (err)
9300 goto done;
9302 err = got_object_id_str(&yca_id_str, yca_id);
9303 if (err)
9304 goto done;
9306 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9307 if (refs) {
9308 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9309 if (err)
9310 goto done;
9312 printf("history forked at %s%s%s%s\n %s\n",
9313 yca_id_str,
9314 refs_str ? " (" : "", refs_str ? refs_str : "",
9315 refs_str ? ")" : "", yca_brief_str);
9317 done:
9318 free(custom_refs_str);
9319 free(new_commit_id);
9320 free(refs_str);
9321 free(yca_id);
9322 free(yca_id_str);
9323 free(yca_brief_str);
9324 if (new_commit)
9325 got_object_commit_close(new_commit);
9326 if (yca_commit)
9327 got_object_commit_close(yca_commit);
9329 return NULL;
9332 static const struct got_error *
9333 process_backup_refs(const char *backup_ref_prefix,
9334 const char *wanted_branch_name,
9335 int delete, struct got_repository *repo)
9337 const struct got_error *err;
9338 struct got_reflist_head refs, backup_refs;
9339 struct got_reflist_entry *re;
9340 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9341 struct got_object_id *old_commit_id = NULL;
9342 char *branch_name = NULL;
9343 struct got_commit_object *old_commit = NULL;
9344 struct got_reflist_object_id_map *refs_idmap = NULL;
9345 int wanted_branch_found = 0;
9347 TAILQ_INIT(&refs);
9348 TAILQ_INIT(&backup_refs);
9350 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9351 if (err)
9352 return err;
9354 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9355 if (err)
9356 goto done;
9358 if (wanted_branch_name) {
9359 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9360 wanted_branch_name += 11;
9363 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9364 got_ref_cmp_by_commit_timestamp_descending, repo);
9365 if (err)
9366 goto done;
9368 TAILQ_FOREACH(re, &backup_refs, entry) {
9369 const char *refname = got_ref_get_name(re->ref);
9370 char *slash;
9372 err = check_cancelled(NULL);
9373 if (err)
9374 break;
9376 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9377 if (err)
9378 break;
9380 err = got_object_open_as_commit(&old_commit, repo,
9381 old_commit_id);
9382 if (err)
9383 break;
9385 if (strncmp(backup_ref_prefix, refname,
9386 backup_ref_prefix_len) == 0)
9387 refname += backup_ref_prefix_len;
9389 while (refname[0] == '/')
9390 refname++;
9392 branch_name = strdup(refname);
9393 if (branch_name == NULL) {
9394 err = got_error_from_errno("strdup");
9395 break;
9397 slash = strrchr(branch_name, '/');
9398 if (slash) {
9399 *slash = '\0';
9400 refname += strlen(branch_name) + 1;
9403 if (wanted_branch_name == NULL ||
9404 strcmp(wanted_branch_name, branch_name) == 0) {
9405 wanted_branch_found = 1;
9406 if (delete) {
9407 err = delete_backup_ref(re->ref,
9408 old_commit_id, repo);
9409 } else {
9410 err = print_backup_ref(branch_name, refname,
9411 old_commit_id, old_commit, refs_idmap,
9412 repo);
9414 if (err)
9415 break;
9418 free(old_commit_id);
9419 old_commit_id = NULL;
9420 free(branch_name);
9421 branch_name = NULL;
9422 got_object_commit_close(old_commit);
9423 old_commit = NULL;
9426 if (wanted_branch_name && !wanted_branch_found) {
9427 err = got_error_fmt(GOT_ERR_NOT_REF,
9428 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9430 done:
9431 if (refs_idmap)
9432 got_reflist_object_id_map_free(refs_idmap);
9433 got_ref_list_free(&refs);
9434 got_ref_list_free(&backup_refs);
9435 free(old_commit_id);
9436 free(branch_name);
9437 if (old_commit)
9438 got_object_commit_close(old_commit);
9439 return err;
9442 static const struct got_error *
9443 abort_progress(void *arg, unsigned char status, const char *path)
9446 * Unversioned files should not clutter progress output when
9447 * an operation is aborted.
9449 if (status == GOT_STATUS_UNVERSIONED)
9450 return NULL;
9452 return update_progress(arg, status, path);
9455 static const struct got_error *
9456 cmd_rebase(int argc, char *argv[])
9458 const struct got_error *error = NULL;
9459 struct got_worktree *worktree = NULL;
9460 struct got_repository *repo = NULL;
9461 struct got_fileindex *fileindex = NULL;
9462 char *cwd = NULL;
9463 struct got_reference *branch = NULL;
9464 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9465 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9466 struct got_object_id *resume_commit_id = NULL;
9467 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9468 struct got_commit_object *commit = NULL;
9469 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9470 int histedit_in_progress = 0, merge_in_progress = 0;
9471 int create_backup = 1, list_backups = 0, delete_backups = 0;
9472 struct got_object_id_queue commits;
9473 struct got_pathlist_head merged_paths;
9474 const struct got_object_id_queue *parent_ids;
9475 struct got_object_qid *qid, *pid;
9476 struct got_update_progress_arg upa;
9478 STAILQ_INIT(&commits);
9479 TAILQ_INIT(&merged_paths);
9480 memset(&upa, 0, sizeof(upa));
9482 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9483 switch (ch) {
9484 case 'a':
9485 abort_rebase = 1;
9486 break;
9487 case 'c':
9488 continue_rebase = 1;
9489 break;
9490 case 'l':
9491 list_backups = 1;
9492 break;
9493 case 'X':
9494 delete_backups = 1;
9495 break;
9496 default:
9497 usage_rebase();
9498 /* NOTREACHED */
9502 argc -= optind;
9503 argv += optind;
9505 #ifndef PROFILE
9506 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9507 "unveil", NULL) == -1)
9508 err(1, "pledge");
9509 #endif
9510 if (list_backups) {
9511 if (abort_rebase)
9512 option_conflict('l', 'a');
9513 if (continue_rebase)
9514 option_conflict('l', 'c');
9515 if (delete_backups)
9516 option_conflict('l', 'X');
9517 if (argc != 0 && argc != 1)
9518 usage_rebase();
9519 } else if (delete_backups) {
9520 if (abort_rebase)
9521 option_conflict('X', 'a');
9522 if (continue_rebase)
9523 option_conflict('X', 'c');
9524 if (list_backups)
9525 option_conflict('l', 'X');
9526 if (argc != 0 && argc != 1)
9527 usage_rebase();
9528 } else {
9529 if (abort_rebase && continue_rebase)
9530 usage_rebase();
9531 else if (abort_rebase || continue_rebase) {
9532 if (argc != 0)
9533 usage_rebase();
9534 } else if (argc != 1)
9535 usage_rebase();
9538 cwd = getcwd(NULL, 0);
9539 if (cwd == NULL) {
9540 error = got_error_from_errno("getcwd");
9541 goto done;
9543 error = got_worktree_open(&worktree, cwd);
9544 if (error) {
9545 if (list_backups || delete_backups) {
9546 if (error->code != GOT_ERR_NOT_WORKTREE)
9547 goto done;
9548 } else {
9549 if (error->code == GOT_ERR_NOT_WORKTREE)
9550 error = wrap_not_worktree_error(error,
9551 "rebase", cwd);
9552 goto done;
9556 error = got_repo_open(&repo,
9557 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9558 if (error != NULL)
9559 goto done;
9561 error = apply_unveil(got_repo_get_path(repo), 0,
9562 worktree ? got_worktree_get_root_path(worktree) : NULL);
9563 if (error)
9564 goto done;
9566 if (list_backups || delete_backups) {
9567 error = process_backup_refs(
9568 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9569 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9570 goto done; /* nothing else to do */
9573 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9574 worktree);
9575 if (error)
9576 goto done;
9577 if (histedit_in_progress) {
9578 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9579 goto done;
9582 error = got_worktree_merge_in_progress(&merge_in_progress,
9583 worktree, repo);
9584 if (error)
9585 goto done;
9586 if (merge_in_progress) {
9587 error = got_error(GOT_ERR_MERGE_BUSY);
9588 goto done;
9591 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9592 if (error)
9593 goto done;
9595 if (abort_rebase) {
9596 if (!rebase_in_progress) {
9597 error = got_error(GOT_ERR_NOT_REBASING);
9598 goto done;
9600 error = got_worktree_rebase_continue(&resume_commit_id,
9601 &new_base_branch, &tmp_branch, &branch, &fileindex,
9602 worktree, repo);
9603 if (error)
9604 goto done;
9605 printf("Switching work tree to %s\n",
9606 got_ref_get_symref_target(new_base_branch));
9607 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9608 new_base_branch, abort_progress, &upa);
9609 if (error)
9610 goto done;
9611 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9612 print_merge_progress_stats(&upa);
9613 goto done; /* nothing else to do */
9616 if (continue_rebase) {
9617 if (!rebase_in_progress) {
9618 error = got_error(GOT_ERR_NOT_REBASING);
9619 goto done;
9621 error = got_worktree_rebase_continue(&resume_commit_id,
9622 &new_base_branch, &tmp_branch, &branch, &fileindex,
9623 worktree, repo);
9624 if (error)
9625 goto done;
9627 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9628 resume_commit_id, repo);
9629 if (error)
9630 goto done;
9632 yca_id = got_object_id_dup(resume_commit_id);
9633 if (yca_id == NULL) {
9634 error = got_error_from_errno("got_object_id_dup");
9635 goto done;
9637 } else {
9638 error = got_ref_open(&branch, repo, argv[0], 0);
9639 if (error != NULL)
9640 goto done;
9643 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9644 if (error)
9645 goto done;
9647 if (!continue_rebase) {
9648 struct got_object_id *base_commit_id;
9650 base_commit_id = got_worktree_get_base_commit_id(worktree);
9651 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9652 base_commit_id, branch_head_commit_id, 1, repo,
9653 check_cancelled, NULL);
9654 if (error)
9655 goto done;
9656 if (yca_id == NULL) {
9657 error = got_error_msg(GOT_ERR_ANCESTRY,
9658 "specified branch shares no common ancestry "
9659 "with work tree's branch");
9660 goto done;
9663 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9664 if (error) {
9665 if (error->code != GOT_ERR_ANCESTRY)
9666 goto done;
9667 error = NULL;
9668 } else {
9669 struct got_pathlist_head paths;
9670 printf("%s is already based on %s\n",
9671 got_ref_get_name(branch),
9672 got_worktree_get_head_ref_name(worktree));
9673 error = switch_head_ref(branch, branch_head_commit_id,
9674 worktree, repo);
9675 if (error)
9676 goto done;
9677 error = got_worktree_set_base_commit_id(worktree, repo,
9678 branch_head_commit_id);
9679 if (error)
9680 goto done;
9681 TAILQ_INIT(&paths);
9682 error = got_pathlist_append(&paths, "", NULL);
9683 if (error)
9684 goto done;
9685 error = got_worktree_checkout_files(worktree,
9686 &paths, repo, update_progress, &upa,
9687 check_cancelled, NULL);
9688 got_pathlist_free(&paths);
9689 if (error)
9690 goto done;
9691 if (upa.did_something) {
9692 char *id_str;
9693 error = got_object_id_str(&id_str,
9694 branch_head_commit_id);
9695 if (error)
9696 goto done;
9697 printf("Updated to %s: %s\n",
9698 got_worktree_get_head_ref_name(worktree),
9699 id_str);
9700 free(id_str);
9701 } else
9702 printf("Already up-to-date\n");
9703 print_update_progress_stats(&upa);
9704 goto done;
9708 commit_id = branch_head_commit_id;
9709 error = got_object_open_as_commit(&commit, repo, commit_id);
9710 if (error)
9711 goto done;
9713 parent_ids = got_object_commit_get_parent_ids(commit);
9714 pid = STAILQ_FIRST(parent_ids);
9715 if (pid == NULL) {
9716 error = got_error(GOT_ERR_EMPTY_REBASE);
9717 goto done;
9719 error = collect_commits(&commits, commit_id, &pid->id,
9720 yca_id, got_worktree_get_path_prefix(worktree),
9721 GOT_ERR_REBASE_PATH, repo);
9722 got_object_commit_close(commit);
9723 commit = NULL;
9724 if (error)
9725 goto done;
9727 if (!continue_rebase) {
9728 error = got_worktree_rebase_prepare(&new_base_branch,
9729 &tmp_branch, &fileindex, worktree, branch, repo);
9730 if (error)
9731 goto done;
9734 if (STAILQ_EMPTY(&commits)) {
9735 if (continue_rebase) {
9736 error = rebase_complete(worktree, fileindex,
9737 branch, new_base_branch, tmp_branch, repo,
9738 create_backup);
9739 goto done;
9740 } else {
9741 /* Fast-forward the reference of the branch. */
9742 struct got_object_id *new_head_commit_id;
9743 char *id_str;
9744 error = got_ref_resolve(&new_head_commit_id, repo,
9745 new_base_branch);
9746 if (error)
9747 goto done;
9748 error = got_object_id_str(&id_str, new_head_commit_id);
9749 printf("Forwarding %s to commit %s\n",
9750 got_ref_get_name(branch), id_str);
9751 free(id_str);
9752 error = got_ref_change_ref(branch,
9753 new_head_commit_id);
9754 if (error)
9755 goto done;
9756 /* No backup needed since objects did not change. */
9757 create_backup = 0;
9761 pid = NULL;
9762 STAILQ_FOREACH(qid, &commits, entry) {
9764 commit_id = &qid->id;
9765 parent_id = pid ? &pid->id : yca_id;
9766 pid = qid;
9768 memset(&upa, 0, sizeof(upa));
9769 error = got_worktree_rebase_merge_files(&merged_paths,
9770 worktree, fileindex, parent_id, commit_id, repo,
9771 update_progress, &upa, check_cancelled, NULL);
9772 if (error)
9773 goto done;
9775 print_merge_progress_stats(&upa);
9776 if (upa.conflicts > 0 || upa.missing > 0 ||
9777 upa.not_deleted > 0 || upa.unversioned > 0) {
9778 if (upa.conflicts > 0) {
9779 error = show_rebase_merge_conflict(&qid->id,
9780 repo);
9781 if (error)
9782 goto done;
9784 got_worktree_rebase_pathlist_free(&merged_paths);
9785 break;
9788 error = rebase_commit(&merged_paths, worktree, fileindex,
9789 tmp_branch, commit_id, repo);
9790 got_worktree_rebase_pathlist_free(&merged_paths);
9791 if (error)
9792 goto done;
9795 if (upa.conflicts > 0 || upa.missing > 0 ||
9796 upa.not_deleted > 0 || upa.unversioned > 0) {
9797 error = got_worktree_rebase_postpone(worktree, fileindex);
9798 if (error)
9799 goto done;
9800 if (upa.conflicts > 0 && upa.missing == 0 &&
9801 upa.not_deleted == 0 && upa.unversioned == 0) {
9802 error = got_error_msg(GOT_ERR_CONFLICTS,
9803 "conflicts must be resolved before rebasing "
9804 "can continue");
9805 } else if (upa.conflicts > 0) {
9806 error = got_error_msg(GOT_ERR_CONFLICTS,
9807 "conflicts must be resolved before rebasing "
9808 "can continue; changes destined for some "
9809 "files were not yet merged and should be "
9810 "merged manually if required before the "
9811 "rebase operation is continued");
9812 } else {
9813 error = got_error_msg(GOT_ERR_CONFLICTS,
9814 "changes destined for some files were not "
9815 "yet merged and should be merged manually "
9816 "if required before the rebase operation "
9817 "is continued");
9819 } else
9820 error = rebase_complete(worktree, fileindex, branch,
9821 new_base_branch, tmp_branch, repo, create_backup);
9822 done:
9823 got_object_id_queue_free(&commits);
9824 free(branch_head_commit_id);
9825 free(resume_commit_id);
9826 free(yca_id);
9827 if (commit)
9828 got_object_commit_close(commit);
9829 if (branch)
9830 got_ref_close(branch);
9831 if (new_base_branch)
9832 got_ref_close(new_base_branch);
9833 if (tmp_branch)
9834 got_ref_close(tmp_branch);
9835 if (worktree)
9836 got_worktree_close(worktree);
9837 if (repo) {
9838 const struct got_error *close_err = got_repo_close(repo);
9839 if (error == NULL)
9840 error = close_err;
9842 return error;
9845 __dead static void
9846 usage_histedit(void)
9848 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9849 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9850 getprogname());
9851 exit(1);
9854 #define GOT_HISTEDIT_PICK 'p'
9855 #define GOT_HISTEDIT_EDIT 'e'
9856 #define GOT_HISTEDIT_FOLD 'f'
9857 #define GOT_HISTEDIT_DROP 'd'
9858 #define GOT_HISTEDIT_MESG 'm'
9860 static const struct got_histedit_cmd {
9861 unsigned char code;
9862 const char *name;
9863 const char *desc;
9864 } got_histedit_cmds[] = {
9865 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9866 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9867 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9868 "be used" },
9869 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9870 { GOT_HISTEDIT_MESG, "mesg",
9871 "single-line log message for commit above (open editor if empty)" },
9874 struct got_histedit_list_entry {
9875 TAILQ_ENTRY(got_histedit_list_entry) entry;
9876 struct got_object_id *commit_id;
9877 const struct got_histedit_cmd *cmd;
9878 char *logmsg;
9880 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9882 static const struct got_error *
9883 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9884 FILE *f, struct got_repository *repo)
9886 const struct got_error *err = NULL;
9887 char *logmsg = NULL, *id_str = NULL;
9888 struct got_commit_object *commit = NULL;
9889 int n;
9891 err = got_object_open_as_commit(&commit, repo, commit_id);
9892 if (err)
9893 goto done;
9895 err = get_short_logmsg(&logmsg, 34, commit);
9896 if (err)
9897 goto done;
9899 err = got_object_id_str(&id_str, commit_id);
9900 if (err)
9901 goto done;
9903 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9904 if (n < 0)
9905 err = got_ferror(f, GOT_ERR_IO);
9906 done:
9907 if (commit)
9908 got_object_commit_close(commit);
9909 free(id_str);
9910 free(logmsg);
9911 return err;
9914 static const struct got_error *
9915 histedit_write_commit_list(struct got_object_id_queue *commits,
9916 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9917 struct got_repository *repo)
9919 const struct got_error *err = NULL;
9920 struct got_object_qid *qid;
9921 const char *histedit_cmd = NULL;
9923 if (STAILQ_EMPTY(commits))
9924 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9926 STAILQ_FOREACH(qid, commits, entry) {
9927 histedit_cmd = got_histedit_cmds[0].name;
9928 if (edit_only)
9929 histedit_cmd = "edit";
9930 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9931 histedit_cmd = "fold";
9932 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9933 if (err)
9934 break;
9935 if (edit_logmsg_only) {
9936 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9937 if (n < 0) {
9938 err = got_ferror(f, GOT_ERR_IO);
9939 break;
9944 return err;
9947 static const struct got_error *
9948 write_cmd_list(FILE *f, const char *branch_name,
9949 struct got_object_id_queue *commits)
9951 const struct got_error *err = NULL;
9952 size_t i;
9953 int n;
9954 char *id_str;
9955 struct got_object_qid *qid;
9957 qid = STAILQ_FIRST(commits);
9958 err = got_object_id_str(&id_str, &qid->id);
9959 if (err)
9960 return err;
9962 n = fprintf(f,
9963 "# Editing the history of branch '%s' starting at\n"
9964 "# commit %s\n"
9965 "# Commits will be processed in order from top to "
9966 "bottom of this file.\n", branch_name, id_str);
9967 if (n < 0) {
9968 err = got_ferror(f, GOT_ERR_IO);
9969 goto done;
9972 n = fprintf(f, "# Available histedit commands:\n");
9973 if (n < 0) {
9974 err = got_ferror(f, GOT_ERR_IO);
9975 goto done;
9978 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9979 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9980 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9981 cmd->desc);
9982 if (n < 0) {
9983 err = got_ferror(f, GOT_ERR_IO);
9984 break;
9987 done:
9988 free(id_str);
9989 return err;
9992 static const struct got_error *
9993 histedit_syntax_error(int lineno)
9995 static char msg[42];
9996 int ret;
9998 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9999 lineno);
10000 if (ret == -1 || ret >= sizeof(msg))
10001 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10003 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10006 static const struct got_error *
10007 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10008 char *logmsg, struct got_repository *repo)
10010 const struct got_error *err;
10011 struct got_commit_object *folded_commit = NULL;
10012 char *id_str, *folded_logmsg = NULL;
10014 err = got_object_id_str(&id_str, hle->commit_id);
10015 if (err)
10016 return err;
10018 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10019 if (err)
10020 goto done;
10022 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10023 if (err)
10024 goto done;
10025 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10026 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10027 folded_logmsg) == -1) {
10028 err = got_error_from_errno("asprintf");
10030 done:
10031 if (folded_commit)
10032 got_object_commit_close(folded_commit);
10033 free(id_str);
10034 free(folded_logmsg);
10035 return err;
10038 static struct got_histedit_list_entry *
10039 get_folded_commits(struct got_histedit_list_entry *hle)
10041 struct got_histedit_list_entry *prev, *folded = NULL;
10043 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10044 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10045 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10046 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10047 folded = prev;
10048 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10051 return folded;
10054 static const struct got_error *
10055 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10056 struct got_repository *repo)
10058 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10059 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10060 const struct got_error *err = NULL;
10061 struct got_commit_object *commit = NULL;
10062 int logmsg_len;
10063 int fd;
10064 struct got_histedit_list_entry *folded = NULL;
10066 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10067 if (err)
10068 return err;
10070 folded = get_folded_commits(hle);
10071 if (folded) {
10072 while (folded != hle) {
10073 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10074 folded = TAILQ_NEXT(folded, entry);
10075 continue;
10077 err = append_folded_commit_msg(&new_msg, folded,
10078 logmsg, repo);
10079 if (err)
10080 goto done;
10081 free(logmsg);
10082 logmsg = new_msg;
10083 folded = TAILQ_NEXT(folded, entry);
10087 err = got_object_id_str(&id_str, hle->commit_id);
10088 if (err)
10089 goto done;
10090 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10091 if (err)
10092 goto done;
10093 logmsg_len = asprintf(&new_msg,
10094 "%s\n# original log message of commit %s: %s",
10095 logmsg ? logmsg : "", id_str, orig_logmsg);
10096 if (logmsg_len == -1) {
10097 err = got_error_from_errno("asprintf");
10098 goto done;
10100 free(logmsg);
10101 logmsg = new_msg;
10103 err = got_object_id_str(&id_str, hle->commit_id);
10104 if (err)
10105 goto done;
10107 err = got_opentemp_named_fd(&logmsg_path, &fd,
10108 GOT_TMPDIR_STR "/got-logmsg");
10109 if (err)
10110 goto done;
10112 write(fd, logmsg, logmsg_len);
10113 close(fd);
10115 err = get_editor(&editor);
10116 if (err)
10117 goto done;
10119 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10120 logmsg_len, 0);
10121 if (err) {
10122 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10123 goto done;
10124 err = NULL;
10125 hle->logmsg = strdup(new_msg);
10126 if (hle->logmsg == NULL)
10127 err = got_error_from_errno("strdup");
10129 done:
10130 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10131 err = got_error_from_errno2("unlink", logmsg_path);
10132 free(logmsg_path);
10133 free(logmsg);
10134 free(orig_logmsg);
10135 free(editor);
10136 if (commit)
10137 got_object_commit_close(commit);
10138 return err;
10141 static const struct got_error *
10142 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10143 FILE *f, struct got_repository *repo)
10145 const struct got_error *err = NULL;
10146 char *line = NULL, *p, *end;
10147 size_t i, size;
10148 ssize_t len;
10149 int lineno = 0;
10150 const struct got_histedit_cmd *cmd;
10151 struct got_object_id *commit_id = NULL;
10152 struct got_histedit_list_entry *hle = NULL;
10154 for (;;) {
10155 len = getline(&line, &size, f);
10156 if (len == -1) {
10157 const struct got_error *getline_err;
10158 if (feof(f))
10159 break;
10160 getline_err = got_error_from_errno("getline");
10161 err = got_ferror(f, getline_err->code);
10162 break;
10164 lineno++;
10165 p = line;
10166 while (isspace((unsigned char)p[0]))
10167 p++;
10168 if (p[0] == '#' || p[0] == '\0') {
10169 free(line);
10170 line = NULL;
10171 continue;
10173 cmd = NULL;
10174 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10175 cmd = &got_histedit_cmds[i];
10176 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10177 isspace((unsigned char)p[strlen(cmd->name)])) {
10178 p += strlen(cmd->name);
10179 break;
10181 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10182 p++;
10183 break;
10186 if (i == nitems(got_histedit_cmds)) {
10187 err = histedit_syntax_error(lineno);
10188 break;
10190 while (isspace((unsigned char)p[0]))
10191 p++;
10192 if (cmd->code == GOT_HISTEDIT_MESG) {
10193 if (hle == NULL || hle->logmsg != NULL) {
10194 err = got_error(GOT_ERR_HISTEDIT_CMD);
10195 break;
10197 if (p[0] == '\0') {
10198 err = histedit_edit_logmsg(hle, repo);
10199 if (err)
10200 break;
10201 } else {
10202 hle->logmsg = strdup(p);
10203 if (hle->logmsg == NULL) {
10204 err = got_error_from_errno("strdup");
10205 break;
10208 free(line);
10209 line = NULL;
10210 continue;
10211 } else {
10212 end = p;
10213 while (end[0] && !isspace((unsigned char)end[0]))
10214 end++;
10215 *end = '\0';
10217 err = got_object_resolve_id_str(&commit_id, repo, p);
10218 if (err) {
10219 /* override error code */
10220 err = histedit_syntax_error(lineno);
10221 break;
10224 hle = malloc(sizeof(*hle));
10225 if (hle == NULL) {
10226 err = got_error_from_errno("malloc");
10227 break;
10229 hle->cmd = cmd;
10230 hle->commit_id = commit_id;
10231 hle->logmsg = NULL;
10232 commit_id = NULL;
10233 free(line);
10234 line = NULL;
10235 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10238 free(line);
10239 free(commit_id);
10240 return err;
10243 static const struct got_error *
10244 histedit_check_script(struct got_histedit_list *histedit_cmds,
10245 struct got_object_id_queue *commits, struct got_repository *repo)
10247 const struct got_error *err = NULL;
10248 struct got_object_qid *qid;
10249 struct got_histedit_list_entry *hle;
10250 static char msg[92];
10251 char *id_str;
10253 if (TAILQ_EMPTY(histedit_cmds))
10254 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10255 "histedit script contains no commands");
10256 if (STAILQ_EMPTY(commits))
10257 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10259 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10260 struct got_histedit_list_entry *hle2;
10261 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10262 if (hle == hle2)
10263 continue;
10264 if (got_object_id_cmp(hle->commit_id,
10265 hle2->commit_id) != 0)
10266 continue;
10267 err = got_object_id_str(&id_str, hle->commit_id);
10268 if (err)
10269 return err;
10270 snprintf(msg, sizeof(msg), "commit %s is listed "
10271 "more than once in histedit script", id_str);
10272 free(id_str);
10273 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10277 STAILQ_FOREACH(qid, commits, entry) {
10278 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10279 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10280 break;
10282 if (hle == NULL) {
10283 err = got_object_id_str(&id_str, &qid->id);
10284 if (err)
10285 return err;
10286 snprintf(msg, sizeof(msg),
10287 "commit %s missing from histedit script", id_str);
10288 free(id_str);
10289 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10293 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10294 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10295 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10296 "last commit in histedit script cannot be folded");
10298 return NULL;
10301 static const struct got_error *
10302 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10303 const char *path, struct got_object_id_queue *commits,
10304 struct got_repository *repo)
10306 const struct got_error *err = NULL;
10307 char *editor;
10308 FILE *f = NULL;
10310 err = get_editor(&editor);
10311 if (err)
10312 return err;
10314 if (spawn_editor(editor, path) == -1) {
10315 err = got_error_from_errno("failed spawning editor");
10316 goto done;
10319 f = fopen(path, "re");
10320 if (f == NULL) {
10321 err = got_error_from_errno("fopen");
10322 goto done;
10324 err = histedit_parse_list(histedit_cmds, f, repo);
10325 if (err)
10326 goto done;
10328 err = histedit_check_script(histedit_cmds, commits, repo);
10329 done:
10330 if (f && fclose(f) == EOF && err == NULL)
10331 err = got_error_from_errno("fclose");
10332 free(editor);
10333 return err;
10336 static const struct got_error *
10337 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10338 struct got_object_id_queue *, const char *, const char *,
10339 struct got_repository *);
10341 static const struct got_error *
10342 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10343 struct got_object_id_queue *commits, const char *branch_name,
10344 int edit_logmsg_only, int fold_only, int edit_only,
10345 struct got_repository *repo)
10347 const struct got_error *err;
10348 FILE *f = NULL;
10349 char *path = NULL;
10351 err = got_opentemp_named(&path, &f, "got-histedit");
10352 if (err)
10353 return err;
10355 err = write_cmd_list(f, branch_name, commits);
10356 if (err)
10357 goto done;
10359 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10360 fold_only, edit_only, repo);
10361 if (err)
10362 goto done;
10364 if (edit_logmsg_only || fold_only || edit_only) {
10365 rewind(f);
10366 err = histedit_parse_list(histedit_cmds, f, repo);
10367 } else {
10368 if (fclose(f) == EOF) {
10369 err = got_error_from_errno("fclose");
10370 goto done;
10372 f = NULL;
10373 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10374 if (err) {
10375 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10376 err->code != GOT_ERR_HISTEDIT_CMD)
10377 goto done;
10378 err = histedit_edit_list_retry(histedit_cmds, err,
10379 commits, path, branch_name, repo);
10382 done:
10383 if (f && fclose(f) == EOF && err == NULL)
10384 err = got_error_from_errno("fclose");
10385 if (path && unlink(path) != 0 && err == NULL)
10386 err = got_error_from_errno2("unlink", path);
10387 free(path);
10388 return err;
10391 static const struct got_error *
10392 histedit_save_list(struct got_histedit_list *histedit_cmds,
10393 struct got_worktree *worktree, struct got_repository *repo)
10395 const struct got_error *err = NULL;
10396 char *path = NULL;
10397 FILE *f = NULL;
10398 struct got_histedit_list_entry *hle;
10399 struct got_commit_object *commit = NULL;
10401 err = got_worktree_get_histedit_script_path(&path, worktree);
10402 if (err)
10403 return err;
10405 f = fopen(path, "we");
10406 if (f == NULL) {
10407 err = got_error_from_errno2("fopen", path);
10408 goto done;
10410 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10411 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10412 repo);
10413 if (err)
10414 break;
10416 if (hle->logmsg) {
10417 int n = fprintf(f, "%c %s\n",
10418 GOT_HISTEDIT_MESG, hle->logmsg);
10419 if (n < 0) {
10420 err = got_ferror(f, GOT_ERR_IO);
10421 break;
10425 done:
10426 if (f && fclose(f) == EOF && err == NULL)
10427 err = got_error_from_errno("fclose");
10428 free(path);
10429 if (commit)
10430 got_object_commit_close(commit);
10431 return err;
10434 void
10435 histedit_free_list(struct got_histedit_list *histedit_cmds)
10437 struct got_histedit_list_entry *hle;
10439 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10440 TAILQ_REMOVE(histedit_cmds, hle, entry);
10441 free(hle);
10445 static const struct got_error *
10446 histedit_load_list(struct got_histedit_list *histedit_cmds,
10447 const char *path, struct got_repository *repo)
10449 const struct got_error *err = NULL;
10450 FILE *f = NULL;
10452 f = fopen(path, "re");
10453 if (f == NULL) {
10454 err = got_error_from_errno2("fopen", path);
10455 goto done;
10458 err = histedit_parse_list(histedit_cmds, f, repo);
10459 done:
10460 if (f && fclose(f) == EOF && err == NULL)
10461 err = got_error_from_errno("fclose");
10462 return err;
10465 static const struct got_error *
10466 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10467 const struct got_error *edit_err, struct got_object_id_queue *commits,
10468 const char *path, const char *branch_name, struct got_repository *repo)
10470 const struct got_error *err = NULL, *prev_err = edit_err;
10471 int resp = ' ';
10473 while (resp != 'c' && resp != 'r' && resp != 'a') {
10474 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10475 "or (a)bort: ", getprogname(), prev_err->msg);
10476 resp = getchar();
10477 if (resp == '\n')
10478 resp = getchar();
10479 if (resp == 'c') {
10480 histedit_free_list(histedit_cmds);
10481 err = histedit_run_editor(histedit_cmds, path, commits,
10482 repo);
10483 if (err) {
10484 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10485 err->code != GOT_ERR_HISTEDIT_CMD)
10486 break;
10487 prev_err = err;
10488 resp = ' ';
10489 continue;
10491 break;
10492 } else if (resp == 'r') {
10493 histedit_free_list(histedit_cmds);
10494 err = histedit_edit_script(histedit_cmds,
10495 commits, branch_name, 0, 0, 0, repo);
10496 if (err) {
10497 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10498 err->code != GOT_ERR_HISTEDIT_CMD)
10499 break;
10500 prev_err = err;
10501 resp = ' ';
10502 continue;
10504 break;
10505 } else if (resp == 'a') {
10506 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10507 break;
10508 } else
10509 printf("invalid response '%c'\n", resp);
10512 return err;
10515 static const struct got_error *
10516 histedit_complete(struct got_worktree *worktree,
10517 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10518 struct got_reference *branch, struct got_repository *repo)
10520 printf("Switching work tree to %s\n",
10521 got_ref_get_symref_target(branch));
10522 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10523 branch, repo);
10526 static const struct got_error *
10527 show_histedit_progress(struct got_commit_object *commit,
10528 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10530 const struct got_error *err;
10531 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10533 err = got_object_id_str(&old_id_str, hle->commit_id);
10534 if (err)
10535 goto done;
10537 if (new_id) {
10538 err = got_object_id_str(&new_id_str, new_id);
10539 if (err)
10540 goto done;
10543 old_id_str[12] = '\0';
10544 if (new_id_str)
10545 new_id_str[12] = '\0';
10547 if (hle->logmsg) {
10548 logmsg = strdup(hle->logmsg);
10549 if (logmsg == NULL) {
10550 err = got_error_from_errno("strdup");
10551 goto done;
10553 trim_logmsg(logmsg, 42);
10554 } else {
10555 err = get_short_logmsg(&logmsg, 42, commit);
10556 if (err)
10557 goto done;
10560 switch (hle->cmd->code) {
10561 case GOT_HISTEDIT_PICK:
10562 case GOT_HISTEDIT_EDIT:
10563 printf("%s -> %s: %s\n", old_id_str,
10564 new_id_str ? new_id_str : "no-op change", logmsg);
10565 break;
10566 case GOT_HISTEDIT_DROP:
10567 case GOT_HISTEDIT_FOLD:
10568 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10569 logmsg);
10570 break;
10571 default:
10572 break;
10574 done:
10575 free(old_id_str);
10576 free(new_id_str);
10577 return err;
10580 static const struct got_error *
10581 histedit_commit(struct got_pathlist_head *merged_paths,
10582 struct got_worktree *worktree, struct got_fileindex *fileindex,
10583 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10584 struct got_repository *repo)
10586 const struct got_error *err;
10587 struct got_commit_object *commit;
10588 struct got_object_id *new_commit_id;
10590 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10591 && hle->logmsg == NULL) {
10592 err = histedit_edit_logmsg(hle, repo);
10593 if (err)
10594 return err;
10597 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10598 if (err)
10599 return err;
10601 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10602 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10603 hle->logmsg, repo);
10604 if (err) {
10605 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10606 goto done;
10607 err = show_histedit_progress(commit, hle, NULL);
10608 } else {
10609 err = show_histedit_progress(commit, hle, new_commit_id);
10610 free(new_commit_id);
10612 done:
10613 got_object_commit_close(commit);
10614 return err;
10617 static const struct got_error *
10618 histedit_skip_commit(struct got_histedit_list_entry *hle,
10619 struct got_worktree *worktree, struct got_repository *repo)
10621 const struct got_error *error;
10622 struct got_commit_object *commit;
10624 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10625 repo);
10626 if (error)
10627 return error;
10629 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10630 if (error)
10631 return error;
10633 error = show_histedit_progress(commit, hle, NULL);
10634 got_object_commit_close(commit);
10635 return error;
10638 static const struct got_error *
10639 check_local_changes(void *arg, unsigned char status,
10640 unsigned char staged_status, const char *path,
10641 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10642 struct got_object_id *commit_id, int dirfd, const char *de_name)
10644 int *have_local_changes = arg;
10646 switch (status) {
10647 case GOT_STATUS_ADD:
10648 case GOT_STATUS_DELETE:
10649 case GOT_STATUS_MODIFY:
10650 case GOT_STATUS_CONFLICT:
10651 *have_local_changes = 1;
10652 return got_error(GOT_ERR_CANCELLED);
10653 default:
10654 break;
10657 switch (staged_status) {
10658 case GOT_STATUS_ADD:
10659 case GOT_STATUS_DELETE:
10660 case GOT_STATUS_MODIFY:
10661 *have_local_changes = 1;
10662 return got_error(GOT_ERR_CANCELLED);
10663 default:
10664 break;
10667 return NULL;
10670 static const struct got_error *
10671 cmd_histedit(int argc, char *argv[])
10673 const struct got_error *error = NULL;
10674 struct got_worktree *worktree = NULL;
10675 struct got_fileindex *fileindex = NULL;
10676 struct got_repository *repo = NULL;
10677 char *cwd = NULL;
10678 struct got_reference *branch = NULL;
10679 struct got_reference *tmp_branch = NULL;
10680 struct got_object_id *resume_commit_id = NULL;
10681 struct got_object_id *base_commit_id = NULL;
10682 struct got_object_id *head_commit_id = NULL;
10683 struct got_commit_object *commit = NULL;
10684 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10685 struct got_update_progress_arg upa;
10686 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10687 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10688 int list_backups = 0, delete_backups = 0;
10689 const char *edit_script_path = NULL;
10690 struct got_object_id_queue commits;
10691 struct got_pathlist_head merged_paths;
10692 const struct got_object_id_queue *parent_ids;
10693 struct got_object_qid *pid;
10694 struct got_histedit_list histedit_cmds;
10695 struct got_histedit_list_entry *hle;
10697 STAILQ_INIT(&commits);
10698 TAILQ_INIT(&histedit_cmds);
10699 TAILQ_INIT(&merged_paths);
10700 memset(&upa, 0, sizeof(upa));
10702 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10703 switch (ch) {
10704 case 'a':
10705 abort_edit = 1;
10706 break;
10707 case 'c':
10708 continue_edit = 1;
10709 break;
10710 case 'e':
10711 edit_only = 1;
10712 break;
10713 case 'f':
10714 fold_only = 1;
10715 break;
10716 case 'F':
10717 edit_script_path = optarg;
10718 break;
10719 case 'm':
10720 edit_logmsg_only = 1;
10721 break;
10722 case 'l':
10723 list_backups = 1;
10724 break;
10725 case 'X':
10726 delete_backups = 1;
10727 break;
10728 default:
10729 usage_histedit();
10730 /* NOTREACHED */
10734 argc -= optind;
10735 argv += optind;
10737 #ifndef PROFILE
10738 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10739 "unveil", NULL) == -1)
10740 err(1, "pledge");
10741 #endif
10742 if (abort_edit && continue_edit)
10743 option_conflict('a', 'c');
10744 if (edit_script_path && edit_logmsg_only)
10745 option_conflict('F', 'm');
10746 if (abort_edit && edit_logmsg_only)
10747 option_conflict('a', 'm');
10748 if (continue_edit && edit_logmsg_only)
10749 option_conflict('c', 'm');
10750 if (abort_edit && fold_only)
10751 option_conflict('a', 'f');
10752 if (continue_edit && fold_only)
10753 option_conflict('c', 'f');
10754 if (fold_only && edit_logmsg_only)
10755 option_conflict('f', 'm');
10756 if (edit_script_path && fold_only)
10757 option_conflict('F', 'f');
10758 if (abort_edit && edit_only)
10759 option_conflict('a', 'e');
10760 if (continue_edit && edit_only)
10761 option_conflict('c', 'e');
10762 if (edit_only && edit_logmsg_only)
10763 option_conflict('e', 'm');
10764 if (edit_script_path && edit_only)
10765 option_conflict('F', 'e');
10766 if (list_backups) {
10767 if (abort_edit)
10768 option_conflict('l', 'a');
10769 if (continue_edit)
10770 option_conflict('l', 'c');
10771 if (edit_script_path)
10772 option_conflict('l', 'F');
10773 if (edit_logmsg_only)
10774 option_conflict('l', 'm');
10775 if (fold_only)
10776 option_conflict('l', 'f');
10777 if (edit_only)
10778 option_conflict('l', 'e');
10779 if (delete_backups)
10780 option_conflict('l', 'X');
10781 if (argc != 0 && argc != 1)
10782 usage_histedit();
10783 } else if (delete_backups) {
10784 if (abort_edit)
10785 option_conflict('X', 'a');
10786 if (continue_edit)
10787 option_conflict('X', 'c');
10788 if (edit_script_path)
10789 option_conflict('X', 'F');
10790 if (edit_logmsg_only)
10791 option_conflict('X', 'm');
10792 if (fold_only)
10793 option_conflict('X', 'f');
10794 if (edit_only)
10795 option_conflict('X', 'e');
10796 if (list_backups)
10797 option_conflict('X', 'l');
10798 if (argc != 0 && argc != 1)
10799 usage_histedit();
10800 } else if (argc != 0)
10801 usage_histedit();
10804 * This command cannot apply unveil(2) in all cases because the
10805 * user may choose to run an editor to edit the histedit script
10806 * and to edit individual commit log messages.
10807 * unveil(2) traverses exec(2); if an editor is used we have to
10808 * apply unveil after edit script and log messages have been written.
10809 * XXX TODO: Make use of unveil(2) where possible.
10812 cwd = getcwd(NULL, 0);
10813 if (cwd == NULL) {
10814 error = got_error_from_errno("getcwd");
10815 goto done;
10817 error = got_worktree_open(&worktree, cwd);
10818 if (error) {
10819 if (list_backups || delete_backups) {
10820 if (error->code != GOT_ERR_NOT_WORKTREE)
10821 goto done;
10822 } else {
10823 if (error->code == GOT_ERR_NOT_WORKTREE)
10824 error = wrap_not_worktree_error(error,
10825 "histedit", cwd);
10826 goto done;
10830 if (list_backups || delete_backups) {
10831 error = got_repo_open(&repo,
10832 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10833 NULL);
10834 if (error != NULL)
10835 goto done;
10836 error = apply_unveil(got_repo_get_path(repo), 0,
10837 worktree ? got_worktree_get_root_path(worktree) : NULL);
10838 if (error)
10839 goto done;
10840 error = process_backup_refs(
10841 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10842 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10843 goto done; /* nothing else to do */
10846 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10847 NULL);
10848 if (error != NULL)
10849 goto done;
10851 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10852 if (error)
10853 goto done;
10854 if (rebase_in_progress) {
10855 error = got_error(GOT_ERR_REBASING);
10856 goto done;
10859 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10860 repo);
10861 if (error)
10862 goto done;
10863 if (merge_in_progress) {
10864 error = got_error(GOT_ERR_MERGE_BUSY);
10865 goto done;
10868 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10869 if (error)
10870 goto done;
10872 if (edit_in_progress && edit_logmsg_only) {
10873 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10874 "histedit operation is in progress in this "
10875 "work tree and must be continued or aborted "
10876 "before the -m option can be used");
10877 goto done;
10879 if (edit_in_progress && fold_only) {
10880 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10881 "histedit operation is in progress in this "
10882 "work tree and must be continued or aborted "
10883 "before the -f option can be used");
10884 goto done;
10886 if (edit_in_progress && edit_only) {
10887 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10888 "histedit operation is in progress in this "
10889 "work tree and must be continued or aborted "
10890 "before the -e option can be used");
10891 goto done;
10894 if (edit_in_progress && abort_edit) {
10895 error = got_worktree_histedit_continue(&resume_commit_id,
10896 &tmp_branch, &branch, &base_commit_id, &fileindex,
10897 worktree, repo);
10898 if (error)
10899 goto done;
10900 printf("Switching work tree to %s\n",
10901 got_ref_get_symref_target(branch));
10902 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10903 branch, base_commit_id, abort_progress, &upa);
10904 if (error)
10905 goto done;
10906 printf("Histedit of %s aborted\n",
10907 got_ref_get_symref_target(branch));
10908 print_merge_progress_stats(&upa);
10909 goto done; /* nothing else to do */
10910 } else if (abort_edit) {
10911 error = got_error(GOT_ERR_NOT_HISTEDIT);
10912 goto done;
10915 if (continue_edit) {
10916 char *path;
10918 if (!edit_in_progress) {
10919 error = got_error(GOT_ERR_NOT_HISTEDIT);
10920 goto done;
10923 error = got_worktree_get_histedit_script_path(&path, worktree);
10924 if (error)
10925 goto done;
10927 error = histedit_load_list(&histedit_cmds, path, repo);
10928 free(path);
10929 if (error)
10930 goto done;
10932 error = got_worktree_histedit_continue(&resume_commit_id,
10933 &tmp_branch, &branch, &base_commit_id, &fileindex,
10934 worktree, repo);
10935 if (error)
10936 goto done;
10938 error = got_ref_resolve(&head_commit_id, repo, branch);
10939 if (error)
10940 goto done;
10942 error = got_object_open_as_commit(&commit, repo,
10943 head_commit_id);
10944 if (error)
10945 goto done;
10946 parent_ids = got_object_commit_get_parent_ids(commit);
10947 pid = STAILQ_FIRST(parent_ids);
10948 if (pid == NULL) {
10949 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10950 goto done;
10952 error = collect_commits(&commits, head_commit_id, &pid->id,
10953 base_commit_id, got_worktree_get_path_prefix(worktree),
10954 GOT_ERR_HISTEDIT_PATH, repo);
10955 got_object_commit_close(commit);
10956 commit = NULL;
10957 if (error)
10958 goto done;
10959 } else {
10960 if (edit_in_progress) {
10961 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10962 goto done;
10965 error = got_ref_open(&branch, repo,
10966 got_worktree_get_head_ref_name(worktree), 0);
10967 if (error != NULL)
10968 goto done;
10970 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10971 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10972 "will not edit commit history of a branch outside "
10973 "the \"refs/heads/\" reference namespace");
10974 goto done;
10977 error = got_ref_resolve(&head_commit_id, repo, branch);
10978 got_ref_close(branch);
10979 branch = NULL;
10980 if (error)
10981 goto done;
10983 error = got_object_open_as_commit(&commit, repo,
10984 head_commit_id);
10985 if (error)
10986 goto done;
10987 parent_ids = got_object_commit_get_parent_ids(commit);
10988 pid = STAILQ_FIRST(parent_ids);
10989 if (pid == NULL) {
10990 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10991 goto done;
10993 error = collect_commits(&commits, head_commit_id, &pid->id,
10994 got_worktree_get_base_commit_id(worktree),
10995 got_worktree_get_path_prefix(worktree),
10996 GOT_ERR_HISTEDIT_PATH, repo);
10997 got_object_commit_close(commit);
10998 commit = NULL;
10999 if (error)
11000 goto done;
11002 if (STAILQ_EMPTY(&commits)) {
11003 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11004 goto done;
11007 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11008 &base_commit_id, &fileindex, worktree, repo);
11009 if (error)
11010 goto done;
11012 if (edit_script_path) {
11013 error = histedit_load_list(&histedit_cmds,
11014 edit_script_path, repo);
11015 if (error) {
11016 got_worktree_histedit_abort(worktree, fileindex,
11017 repo, branch, base_commit_id,
11018 abort_progress, &upa);
11019 print_merge_progress_stats(&upa);
11020 goto done;
11022 } else {
11023 const char *branch_name;
11024 branch_name = got_ref_get_symref_target(branch);
11025 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11026 branch_name += 11;
11027 error = histedit_edit_script(&histedit_cmds, &commits,
11028 branch_name, edit_logmsg_only, fold_only,
11029 edit_only, repo);
11030 if (error) {
11031 got_worktree_histedit_abort(worktree, fileindex,
11032 repo, branch, base_commit_id,
11033 abort_progress, &upa);
11034 print_merge_progress_stats(&upa);
11035 goto done;
11040 error = histedit_save_list(&histedit_cmds, worktree,
11041 repo);
11042 if (error) {
11043 got_worktree_histedit_abort(worktree, fileindex,
11044 repo, branch, base_commit_id,
11045 abort_progress, &upa);
11046 print_merge_progress_stats(&upa);
11047 goto done;
11052 error = histedit_check_script(&histedit_cmds, &commits, repo);
11053 if (error)
11054 goto done;
11056 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11057 if (resume_commit_id) {
11058 if (got_object_id_cmp(hle->commit_id,
11059 resume_commit_id) != 0)
11060 continue;
11062 resume_commit_id = NULL;
11063 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11064 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11065 error = histedit_skip_commit(hle, worktree,
11066 repo);
11067 if (error)
11068 goto done;
11069 } else {
11070 struct got_pathlist_head paths;
11071 int have_changes = 0;
11073 TAILQ_INIT(&paths);
11074 error = got_pathlist_append(&paths, "", NULL);
11075 if (error)
11076 goto done;
11077 error = got_worktree_status(worktree, &paths,
11078 repo, 0, check_local_changes, &have_changes,
11079 check_cancelled, NULL);
11080 got_pathlist_free(&paths);
11081 if (error) {
11082 if (error->code != GOT_ERR_CANCELLED)
11083 goto done;
11084 if (sigint_received || sigpipe_received)
11085 goto done;
11087 if (have_changes) {
11088 error = histedit_commit(NULL, worktree,
11089 fileindex, tmp_branch, hle, repo);
11090 if (error)
11091 goto done;
11092 } else {
11093 error = got_object_open_as_commit(
11094 &commit, repo, hle->commit_id);
11095 if (error)
11096 goto done;
11097 error = show_histedit_progress(commit,
11098 hle, NULL);
11099 got_object_commit_close(commit);
11100 commit = NULL;
11101 if (error)
11102 goto done;
11105 continue;
11108 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11109 error = histedit_skip_commit(hle, worktree, repo);
11110 if (error)
11111 goto done;
11112 continue;
11115 error = got_object_open_as_commit(&commit, repo,
11116 hle->commit_id);
11117 if (error)
11118 goto done;
11119 parent_ids = got_object_commit_get_parent_ids(commit);
11120 pid = STAILQ_FIRST(parent_ids);
11122 error = got_worktree_histedit_merge_files(&merged_paths,
11123 worktree, fileindex, &pid->id, hle->commit_id, repo,
11124 update_progress, &upa, check_cancelled, NULL);
11125 if (error)
11126 goto done;
11127 got_object_commit_close(commit);
11128 commit = NULL;
11130 print_merge_progress_stats(&upa);
11131 if (upa.conflicts > 0 || upa.missing > 0 ||
11132 upa.not_deleted > 0 || upa.unversioned > 0) {
11133 if (upa.conflicts > 0) {
11134 error = show_rebase_merge_conflict(
11135 hle->commit_id, repo);
11136 if (error)
11137 goto done;
11139 got_worktree_rebase_pathlist_free(&merged_paths);
11140 break;
11143 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11144 char *id_str;
11145 error = got_object_id_str(&id_str, hle->commit_id);
11146 if (error)
11147 goto done;
11148 printf("Stopping histedit for amending commit %s\n",
11149 id_str);
11150 free(id_str);
11151 got_worktree_rebase_pathlist_free(&merged_paths);
11152 error = got_worktree_histedit_postpone(worktree,
11153 fileindex);
11154 goto done;
11157 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11158 error = histedit_skip_commit(hle, worktree, repo);
11159 if (error)
11160 goto done;
11161 continue;
11164 error = histedit_commit(&merged_paths, worktree, fileindex,
11165 tmp_branch, hle, repo);
11166 got_worktree_rebase_pathlist_free(&merged_paths);
11167 if (error)
11168 goto done;
11171 if (upa.conflicts > 0 || upa.missing > 0 ||
11172 upa.not_deleted > 0 || upa.unversioned > 0) {
11173 error = got_worktree_histedit_postpone(worktree, fileindex);
11174 if (error)
11175 goto done;
11176 if (upa.conflicts > 0 && upa.missing == 0 &&
11177 upa.not_deleted == 0 && upa.unversioned == 0) {
11178 error = got_error_msg(GOT_ERR_CONFLICTS,
11179 "conflicts must be resolved before histedit "
11180 "can continue");
11181 } else if (upa.conflicts > 0) {
11182 error = got_error_msg(GOT_ERR_CONFLICTS,
11183 "conflicts must be resolved before histedit "
11184 "can continue; changes destined for some "
11185 "files were not yet merged and should be "
11186 "merged manually if required before the "
11187 "histedit operation is continued");
11188 } else {
11189 error = got_error_msg(GOT_ERR_CONFLICTS,
11190 "changes destined for some files were not "
11191 "yet merged and should be merged manually "
11192 "if required before the histedit operation "
11193 "is continued");
11195 } else
11196 error = histedit_complete(worktree, fileindex, tmp_branch,
11197 branch, repo);
11198 done:
11199 got_object_id_queue_free(&commits);
11200 histedit_free_list(&histedit_cmds);
11201 free(head_commit_id);
11202 free(base_commit_id);
11203 free(resume_commit_id);
11204 if (commit)
11205 got_object_commit_close(commit);
11206 if (branch)
11207 got_ref_close(branch);
11208 if (tmp_branch)
11209 got_ref_close(tmp_branch);
11210 if (worktree)
11211 got_worktree_close(worktree);
11212 if (repo) {
11213 const struct got_error *close_err = got_repo_close(repo);
11214 if (error == NULL)
11215 error = close_err;
11217 return error;
11220 __dead static void
11221 usage_integrate(void)
11223 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11224 exit(1);
11227 static const struct got_error *
11228 cmd_integrate(int argc, char *argv[])
11230 const struct got_error *error = NULL;
11231 struct got_repository *repo = NULL;
11232 struct got_worktree *worktree = NULL;
11233 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11234 const char *branch_arg = NULL;
11235 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11236 struct got_fileindex *fileindex = NULL;
11237 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11238 int ch;
11239 struct got_update_progress_arg upa;
11241 while ((ch = getopt(argc, argv, "")) != -1) {
11242 switch (ch) {
11243 default:
11244 usage_integrate();
11245 /* NOTREACHED */
11249 argc -= optind;
11250 argv += optind;
11252 if (argc != 1)
11253 usage_integrate();
11254 branch_arg = argv[0];
11255 #ifndef PROFILE
11256 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11257 "unveil", NULL) == -1)
11258 err(1, "pledge");
11259 #endif
11260 cwd = getcwd(NULL, 0);
11261 if (cwd == NULL) {
11262 error = got_error_from_errno("getcwd");
11263 goto done;
11266 error = got_worktree_open(&worktree, cwd);
11267 if (error) {
11268 if (error->code == GOT_ERR_NOT_WORKTREE)
11269 error = wrap_not_worktree_error(error, "integrate",
11270 cwd);
11271 goto done;
11274 error = check_rebase_or_histedit_in_progress(worktree);
11275 if (error)
11276 goto done;
11278 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11279 NULL);
11280 if (error != NULL)
11281 goto done;
11283 error = apply_unveil(got_repo_get_path(repo), 0,
11284 got_worktree_get_root_path(worktree));
11285 if (error)
11286 goto done;
11288 error = check_merge_in_progress(worktree, repo);
11289 if (error)
11290 goto done;
11292 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11293 error = got_error_from_errno("asprintf");
11294 goto done;
11297 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11298 &base_branch_ref, worktree, refname, repo);
11299 if (error)
11300 goto done;
11302 refname = strdup(got_ref_get_name(branch_ref));
11303 if (refname == NULL) {
11304 error = got_error_from_errno("strdup");
11305 got_worktree_integrate_abort(worktree, fileindex, repo,
11306 branch_ref, base_branch_ref);
11307 goto done;
11309 base_refname = strdup(got_ref_get_name(base_branch_ref));
11310 if (base_refname == NULL) {
11311 error = got_error_from_errno("strdup");
11312 got_worktree_integrate_abort(worktree, fileindex, repo,
11313 branch_ref, base_branch_ref);
11314 goto done;
11317 error = got_ref_resolve(&commit_id, repo, branch_ref);
11318 if (error)
11319 goto done;
11321 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11322 if (error)
11323 goto done;
11325 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11326 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11327 "specified branch has already been integrated");
11328 got_worktree_integrate_abort(worktree, fileindex, repo,
11329 branch_ref, base_branch_ref);
11330 goto done;
11333 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11334 if (error) {
11335 if (error->code == GOT_ERR_ANCESTRY)
11336 error = got_error(GOT_ERR_REBASE_REQUIRED);
11337 got_worktree_integrate_abort(worktree, fileindex, repo,
11338 branch_ref, base_branch_ref);
11339 goto done;
11342 memset(&upa, 0, sizeof(upa));
11343 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11344 branch_ref, base_branch_ref, update_progress, &upa,
11345 check_cancelled, NULL);
11346 if (error)
11347 goto done;
11349 printf("Integrated %s into %s\n", refname, base_refname);
11350 print_update_progress_stats(&upa);
11351 done:
11352 if (repo) {
11353 const struct got_error *close_err = got_repo_close(repo);
11354 if (error == NULL)
11355 error = close_err;
11357 if (worktree)
11358 got_worktree_close(worktree);
11359 free(cwd);
11360 free(base_commit_id);
11361 free(commit_id);
11362 free(refname);
11363 free(base_refname);
11364 return error;
11367 __dead static void
11368 usage_merge(void)
11370 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11371 getprogname());
11372 exit(1);
11375 static const struct got_error *
11376 cmd_merge(int argc, char *argv[])
11378 const struct got_error *error = NULL;
11379 struct got_worktree *worktree = NULL;
11380 struct got_repository *repo = NULL;
11381 struct got_fileindex *fileindex = NULL;
11382 char *cwd = NULL, *id_str = NULL, *author = NULL;
11383 struct got_reference *branch = NULL, *wt_branch = NULL;
11384 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11385 struct got_object_id *wt_branch_tip = NULL;
11386 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11387 int interrupt_merge = 0;
11388 struct got_update_progress_arg upa;
11389 struct got_object_id *merge_commit_id = NULL;
11390 char *branch_name = NULL;
11392 memset(&upa, 0, sizeof(upa));
11394 while ((ch = getopt(argc, argv, "acn")) != -1) {
11395 switch (ch) {
11396 case 'a':
11397 abort_merge = 1;
11398 break;
11399 case 'c':
11400 continue_merge = 1;
11401 break;
11402 case 'n':
11403 interrupt_merge = 1;
11404 break;
11405 default:
11406 usage_rebase();
11407 /* NOTREACHED */
11411 argc -= optind;
11412 argv += optind;
11414 #ifndef PROFILE
11415 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11416 "unveil", NULL) == -1)
11417 err(1, "pledge");
11418 #endif
11420 if (abort_merge && continue_merge)
11421 option_conflict('a', 'c');
11422 if (abort_merge || continue_merge) {
11423 if (argc != 0)
11424 usage_merge();
11425 } else if (argc != 1)
11426 usage_merge();
11428 cwd = getcwd(NULL, 0);
11429 if (cwd == NULL) {
11430 error = got_error_from_errno("getcwd");
11431 goto done;
11434 error = got_worktree_open(&worktree, cwd);
11435 if (error) {
11436 if (error->code == GOT_ERR_NOT_WORKTREE)
11437 error = wrap_not_worktree_error(error,
11438 "merge", cwd);
11439 goto done;
11442 error = got_repo_open(&repo,
11443 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11444 if (error != NULL)
11445 goto done;
11447 error = apply_unveil(got_repo_get_path(repo), 0,
11448 worktree ? got_worktree_get_root_path(worktree) : NULL);
11449 if (error)
11450 goto done;
11452 error = check_rebase_or_histedit_in_progress(worktree);
11453 if (error)
11454 goto done;
11456 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11457 repo);
11458 if (error)
11459 goto done;
11461 if (abort_merge) {
11462 if (!merge_in_progress) {
11463 error = got_error(GOT_ERR_NOT_MERGING);
11464 goto done;
11466 error = got_worktree_merge_continue(&branch_name,
11467 &branch_tip, &fileindex, worktree, repo);
11468 if (error)
11469 goto done;
11470 error = got_worktree_merge_abort(worktree, fileindex, repo,
11471 abort_progress, &upa);
11472 if (error)
11473 goto done;
11474 printf("Merge of %s aborted\n", branch_name);
11475 goto done; /* nothing else to do */
11478 error = get_author(&author, repo, worktree);
11479 if (error)
11480 goto done;
11482 if (continue_merge) {
11483 if (!merge_in_progress) {
11484 error = got_error(GOT_ERR_NOT_MERGING);
11485 goto done;
11487 error = got_worktree_merge_continue(&branch_name,
11488 &branch_tip, &fileindex, worktree, repo);
11489 if (error)
11490 goto done;
11491 } else {
11492 error = got_ref_open(&branch, repo, argv[0], 0);
11493 if (error != NULL)
11494 goto done;
11495 branch_name = strdup(got_ref_get_name(branch));
11496 if (branch_name == NULL) {
11497 error = got_error_from_errno("strdup");
11498 goto done;
11500 error = got_ref_resolve(&branch_tip, repo, branch);
11501 if (error)
11502 goto done;
11505 error = got_ref_open(&wt_branch, repo,
11506 got_worktree_get_head_ref_name(worktree), 0);
11507 if (error)
11508 goto done;
11509 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11510 if (error)
11511 goto done;
11512 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11513 wt_branch_tip, branch_tip, 0, repo,
11514 check_cancelled, NULL);
11515 if (error && error->code != GOT_ERR_ANCESTRY)
11516 goto done;
11518 if (!continue_merge) {
11519 error = check_path_prefix(wt_branch_tip, branch_tip,
11520 got_worktree_get_path_prefix(worktree),
11521 GOT_ERR_MERGE_PATH, repo);
11522 if (error)
11523 goto done;
11524 if (yca_id) {
11525 error = check_same_branch(wt_branch_tip, branch,
11526 yca_id, repo);
11527 if (error) {
11528 if (error->code != GOT_ERR_ANCESTRY)
11529 goto done;
11530 error = NULL;
11531 } else {
11532 static char msg[512];
11533 snprintf(msg, sizeof(msg),
11534 "cannot create a merge commit because "
11535 "%s is based on %s; %s can be integrated "
11536 "with 'got integrate' instead", branch_name,
11537 got_worktree_get_head_ref_name(worktree),
11538 branch_name);
11539 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11540 goto done;
11543 error = got_worktree_merge_prepare(&fileindex, worktree,
11544 branch, repo);
11545 if (error)
11546 goto done;
11548 error = got_worktree_merge_branch(worktree, fileindex,
11549 yca_id, branch_tip, repo, update_progress, &upa,
11550 check_cancelled, NULL);
11551 if (error)
11552 goto done;
11553 print_merge_progress_stats(&upa);
11554 if (!upa.did_something) {
11555 error = got_worktree_merge_abort(worktree, fileindex,
11556 repo, abort_progress, &upa);
11557 if (error)
11558 goto done;
11559 printf("Already up-to-date\n");
11560 goto done;
11564 if (interrupt_merge) {
11565 error = got_worktree_merge_postpone(worktree, fileindex);
11566 if (error)
11567 goto done;
11568 printf("Merge of %s interrupted on request\n", branch_name);
11569 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11570 upa.not_deleted > 0 || upa.unversioned > 0) {
11571 error = got_worktree_merge_postpone(worktree, fileindex);
11572 if (error)
11573 goto done;
11574 if (upa.conflicts > 0 && upa.missing == 0 &&
11575 upa.not_deleted == 0 && upa.unversioned == 0) {
11576 error = got_error_msg(GOT_ERR_CONFLICTS,
11577 "conflicts must be resolved before merging "
11578 "can continue");
11579 } else if (upa.conflicts > 0) {
11580 error = got_error_msg(GOT_ERR_CONFLICTS,
11581 "conflicts must be resolved before merging "
11582 "can continue; changes destined for some "
11583 "files were not yet merged and "
11584 "should be merged manually if required before the "
11585 "merge operation is continued");
11586 } else {
11587 error = got_error_msg(GOT_ERR_CONFLICTS,
11588 "changes destined for some "
11589 "files were not yet merged and should be "
11590 "merged manually if required before the "
11591 "merge operation is continued");
11593 goto done;
11594 } else {
11595 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11596 fileindex, author, NULL, 1, branch_tip, branch_name,
11597 repo, continue_merge ? print_status : NULL, NULL);
11598 if (error)
11599 goto done;
11600 error = got_worktree_merge_complete(worktree, fileindex, repo);
11601 if (error)
11602 goto done;
11603 error = got_object_id_str(&id_str, merge_commit_id);
11604 if (error)
11605 goto done;
11606 printf("Merged %s into %s: %s\n", branch_name,
11607 got_worktree_get_head_ref_name(worktree),
11608 id_str);
11611 done:
11612 free(id_str);
11613 free(merge_commit_id);
11614 free(author);
11615 free(branch_tip);
11616 free(branch_name);
11617 free(yca_id);
11618 if (branch)
11619 got_ref_close(branch);
11620 if (wt_branch)
11621 got_ref_close(wt_branch);
11622 if (worktree)
11623 got_worktree_close(worktree);
11624 if (repo) {
11625 const struct got_error *close_err = got_repo_close(repo);
11626 if (error == NULL)
11627 error = close_err;
11629 return error;
11632 __dead static void
11633 usage_stage(void)
11635 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11636 "[-S] [file-path ...]\n",
11637 getprogname());
11638 exit(1);
11641 static const struct got_error *
11642 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11643 const char *path, struct got_object_id *blob_id,
11644 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11645 int dirfd, const char *de_name)
11647 const struct got_error *err = NULL;
11648 char *id_str = NULL;
11650 if (staged_status != GOT_STATUS_ADD &&
11651 staged_status != GOT_STATUS_MODIFY &&
11652 staged_status != GOT_STATUS_DELETE)
11653 return NULL;
11655 if (staged_status == GOT_STATUS_ADD ||
11656 staged_status == GOT_STATUS_MODIFY)
11657 err = got_object_id_str(&id_str, staged_blob_id);
11658 else
11659 err = got_object_id_str(&id_str, blob_id);
11660 if (err)
11661 return err;
11663 printf("%s %c %s\n", id_str, staged_status, path);
11664 free(id_str);
11665 return NULL;
11668 static const struct got_error *
11669 cmd_stage(int argc, char *argv[])
11671 const struct got_error *error = NULL;
11672 struct got_repository *repo = NULL;
11673 struct got_worktree *worktree = NULL;
11674 char *cwd = NULL;
11675 struct got_pathlist_head paths;
11676 struct got_pathlist_entry *pe;
11677 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11678 FILE *patch_script_file = NULL;
11679 const char *patch_script_path = NULL;
11680 struct choose_patch_arg cpa;
11682 TAILQ_INIT(&paths);
11684 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11685 switch (ch) {
11686 case 'l':
11687 list_stage = 1;
11688 break;
11689 case 'p':
11690 pflag = 1;
11691 break;
11692 case 'F':
11693 patch_script_path = optarg;
11694 break;
11695 case 'S':
11696 allow_bad_symlinks = 1;
11697 break;
11698 default:
11699 usage_stage();
11700 /* NOTREACHED */
11704 argc -= optind;
11705 argv += optind;
11707 #ifndef PROFILE
11708 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11709 "unveil", NULL) == -1)
11710 err(1, "pledge");
11711 #endif
11712 if (list_stage && (pflag || patch_script_path))
11713 errx(1, "-l option cannot be used with other options");
11714 if (patch_script_path && !pflag)
11715 errx(1, "-F option can only be used together with -p option");
11717 cwd = getcwd(NULL, 0);
11718 if (cwd == NULL) {
11719 error = got_error_from_errno("getcwd");
11720 goto done;
11723 error = got_worktree_open(&worktree, cwd);
11724 if (error) {
11725 if (error->code == GOT_ERR_NOT_WORKTREE)
11726 error = wrap_not_worktree_error(error, "stage", cwd);
11727 goto done;
11730 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11731 NULL);
11732 if (error != NULL)
11733 goto done;
11735 if (patch_script_path) {
11736 patch_script_file = fopen(patch_script_path, "re");
11737 if (patch_script_file == NULL) {
11738 error = got_error_from_errno2("fopen",
11739 patch_script_path);
11740 goto done;
11743 error = apply_unveil(got_repo_get_path(repo), 0,
11744 got_worktree_get_root_path(worktree));
11745 if (error)
11746 goto done;
11748 error = check_merge_in_progress(worktree, repo);
11749 if (error)
11750 goto done;
11752 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11753 if (error)
11754 goto done;
11756 if (list_stage)
11757 error = got_worktree_status(worktree, &paths, repo, 0,
11758 print_stage, NULL, check_cancelled, NULL);
11759 else {
11760 cpa.patch_script_file = patch_script_file;
11761 cpa.action = "stage";
11762 error = got_worktree_stage(worktree, &paths,
11763 pflag ? NULL : print_status, NULL,
11764 pflag ? choose_patch : NULL, &cpa,
11765 allow_bad_symlinks, repo);
11767 done:
11768 if (patch_script_file && fclose(patch_script_file) == EOF &&
11769 error == NULL)
11770 error = got_error_from_errno2("fclose", patch_script_path);
11771 if (repo) {
11772 const struct got_error *close_err = got_repo_close(repo);
11773 if (error == NULL)
11774 error = close_err;
11776 if (worktree)
11777 got_worktree_close(worktree);
11778 TAILQ_FOREACH(pe, &paths, entry)
11779 free((char *)pe->path);
11780 got_pathlist_free(&paths);
11781 free(cwd);
11782 return error;
11785 __dead static void
11786 usage_unstage(void)
11788 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11789 "[file-path ...]\n",
11790 getprogname());
11791 exit(1);
11795 static const struct got_error *
11796 cmd_unstage(int argc, char *argv[])
11798 const struct got_error *error = NULL;
11799 struct got_repository *repo = NULL;
11800 struct got_worktree *worktree = NULL;
11801 char *cwd = NULL;
11802 struct got_pathlist_head paths;
11803 struct got_pathlist_entry *pe;
11804 int ch, pflag = 0;
11805 struct got_update_progress_arg upa;
11806 FILE *patch_script_file = NULL;
11807 const char *patch_script_path = NULL;
11808 struct choose_patch_arg cpa;
11810 TAILQ_INIT(&paths);
11812 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11813 switch (ch) {
11814 case 'p':
11815 pflag = 1;
11816 break;
11817 case 'F':
11818 patch_script_path = optarg;
11819 break;
11820 default:
11821 usage_unstage();
11822 /* NOTREACHED */
11826 argc -= optind;
11827 argv += optind;
11829 #ifndef PROFILE
11830 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11831 "unveil", NULL) == -1)
11832 err(1, "pledge");
11833 #endif
11834 if (patch_script_path && !pflag)
11835 errx(1, "-F option can only be used together with -p option");
11837 cwd = getcwd(NULL, 0);
11838 if (cwd == NULL) {
11839 error = got_error_from_errno("getcwd");
11840 goto done;
11843 error = got_worktree_open(&worktree, cwd);
11844 if (error) {
11845 if (error->code == GOT_ERR_NOT_WORKTREE)
11846 error = wrap_not_worktree_error(error, "unstage", cwd);
11847 goto done;
11850 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11851 NULL);
11852 if (error != NULL)
11853 goto done;
11855 if (patch_script_path) {
11856 patch_script_file = fopen(patch_script_path, "re");
11857 if (patch_script_file == NULL) {
11858 error = got_error_from_errno2("fopen",
11859 patch_script_path);
11860 goto done;
11864 error = apply_unveil(got_repo_get_path(repo), 0,
11865 got_worktree_get_root_path(worktree));
11866 if (error)
11867 goto done;
11869 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11870 if (error)
11871 goto done;
11873 cpa.patch_script_file = patch_script_file;
11874 cpa.action = "unstage";
11875 memset(&upa, 0, sizeof(upa));
11876 error = got_worktree_unstage(worktree, &paths, update_progress,
11877 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11878 if (!error)
11879 print_merge_progress_stats(&upa);
11880 done:
11881 if (patch_script_file && fclose(patch_script_file) == EOF &&
11882 error == NULL)
11883 error = got_error_from_errno2("fclose", patch_script_path);
11884 if (repo) {
11885 const struct got_error *close_err = got_repo_close(repo);
11886 if (error == NULL)
11887 error = close_err;
11889 if (worktree)
11890 got_worktree_close(worktree);
11891 TAILQ_FOREACH(pe, &paths, entry)
11892 free((char *)pe->path);
11893 got_pathlist_free(&paths);
11894 free(cwd);
11895 return error;
11898 __dead static void
11899 usage_cat(void)
11901 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11902 "arg1 [arg2 ...]\n", getprogname());
11903 exit(1);
11906 static const struct got_error *
11907 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11909 const struct got_error *err;
11910 struct got_blob_object *blob;
11912 err = got_object_open_as_blob(&blob, repo, id, 8192);
11913 if (err)
11914 return err;
11916 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11917 got_object_blob_close(blob);
11918 return err;
11921 static const struct got_error *
11922 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11924 const struct got_error *err;
11925 struct got_tree_object *tree;
11926 int nentries, i;
11928 err = got_object_open_as_tree(&tree, repo, id);
11929 if (err)
11930 return err;
11932 nentries = got_object_tree_get_nentries(tree);
11933 for (i = 0; i < nentries; i++) {
11934 struct got_tree_entry *te;
11935 char *id_str;
11936 if (sigint_received || sigpipe_received)
11937 break;
11938 te = got_object_tree_get_entry(tree, i);
11939 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11940 if (err)
11941 break;
11942 fprintf(outfile, "%s %.7o %s\n", id_str,
11943 got_tree_entry_get_mode(te),
11944 got_tree_entry_get_name(te));
11945 free(id_str);
11948 got_object_tree_close(tree);
11949 return err;
11952 static void
11953 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11955 long long h, m;
11956 char sign = '+';
11958 if (gmtoff < 0) {
11959 sign = '-';
11960 gmtoff = -gmtoff;
11963 h = (long long)gmtoff / 3600;
11964 m = ((long long)gmtoff - h*3600) / 60;
11965 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11968 static const struct got_error *
11969 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11971 const struct got_error *err;
11972 struct got_commit_object *commit;
11973 const struct got_object_id_queue *parent_ids;
11974 struct got_object_qid *pid;
11975 char *id_str = NULL;
11976 const char *logmsg = NULL;
11977 char gmtoff[6];
11979 err = got_object_open_as_commit(&commit, repo, id);
11980 if (err)
11981 return err;
11983 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11984 if (err)
11985 goto done;
11987 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11988 parent_ids = got_object_commit_get_parent_ids(commit);
11989 fprintf(outfile, "numparents %d\n",
11990 got_object_commit_get_nparents(commit));
11991 STAILQ_FOREACH(pid, parent_ids, entry) {
11992 char *pid_str;
11993 err = got_object_id_str(&pid_str, &pid->id);
11994 if (err)
11995 goto done;
11996 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11997 free(pid_str);
11999 format_gmtoff(gmtoff, sizeof(gmtoff),
12000 got_object_commit_get_author_gmtoff(commit));
12001 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12002 got_object_commit_get_author(commit),
12003 (long long)got_object_commit_get_author_time(commit),
12004 gmtoff);
12006 format_gmtoff(gmtoff, sizeof(gmtoff),
12007 got_object_commit_get_committer_gmtoff(commit));
12008 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12009 got_object_commit_get_author(commit),
12010 (long long)got_object_commit_get_committer_time(commit),
12011 gmtoff);
12013 logmsg = got_object_commit_get_logmsg_raw(commit);
12014 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12015 fprintf(outfile, "%s", logmsg);
12016 done:
12017 free(id_str);
12018 got_object_commit_close(commit);
12019 return err;
12022 static const struct got_error *
12023 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12025 const struct got_error *err;
12026 struct got_tag_object *tag;
12027 char *id_str = NULL;
12028 const char *tagmsg = NULL;
12029 char gmtoff[6];
12031 err = got_object_open_as_tag(&tag, repo, id);
12032 if (err)
12033 return err;
12035 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12036 if (err)
12037 goto done;
12039 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12041 switch (got_object_tag_get_object_type(tag)) {
12042 case GOT_OBJ_TYPE_BLOB:
12043 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12044 GOT_OBJ_LABEL_BLOB);
12045 break;
12046 case GOT_OBJ_TYPE_TREE:
12047 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12048 GOT_OBJ_LABEL_TREE);
12049 break;
12050 case GOT_OBJ_TYPE_COMMIT:
12051 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12052 GOT_OBJ_LABEL_COMMIT);
12053 break;
12054 case GOT_OBJ_TYPE_TAG:
12055 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12056 GOT_OBJ_LABEL_TAG);
12057 break;
12058 default:
12059 break;
12062 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12063 got_object_tag_get_name(tag));
12065 format_gmtoff(gmtoff, sizeof(gmtoff),
12066 got_object_tag_get_tagger_gmtoff(tag));
12067 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12068 got_object_tag_get_tagger(tag),
12069 (long long)got_object_tag_get_tagger_time(tag),
12070 gmtoff);
12072 tagmsg = got_object_tag_get_message(tag);
12073 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12074 fprintf(outfile, "%s", tagmsg);
12075 done:
12076 free(id_str);
12077 got_object_tag_close(tag);
12078 return err;
12081 static const struct got_error *
12082 cmd_cat(int argc, char *argv[])
12084 const struct got_error *error;
12085 struct got_repository *repo = NULL;
12086 struct got_worktree *worktree = NULL;
12087 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12088 const char *commit_id_str = NULL;
12089 struct got_object_id *id = NULL, *commit_id = NULL;
12090 struct got_commit_object *commit = NULL;
12091 int ch, obj_type, i, force_path = 0;
12092 struct got_reflist_head refs;
12094 TAILQ_INIT(&refs);
12096 #ifndef PROFILE
12097 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12098 NULL) == -1)
12099 err(1, "pledge");
12100 #endif
12102 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12103 switch (ch) {
12104 case 'c':
12105 commit_id_str = optarg;
12106 break;
12107 case 'r':
12108 repo_path = realpath(optarg, NULL);
12109 if (repo_path == NULL)
12110 return got_error_from_errno2("realpath",
12111 optarg);
12112 got_path_strip_trailing_slashes(repo_path);
12113 break;
12114 case 'P':
12115 force_path = 1;
12116 break;
12117 default:
12118 usage_cat();
12119 /* NOTREACHED */
12123 argc -= optind;
12124 argv += optind;
12126 cwd = getcwd(NULL, 0);
12127 if (cwd == NULL) {
12128 error = got_error_from_errno("getcwd");
12129 goto done;
12132 if (repo_path == NULL) {
12133 error = got_worktree_open(&worktree, cwd);
12134 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12135 goto done;
12136 if (worktree) {
12137 repo_path = strdup(
12138 got_worktree_get_repo_path(worktree));
12139 if (repo_path == NULL) {
12140 error = got_error_from_errno("strdup");
12141 goto done;
12144 /* Release work tree lock. */
12145 got_worktree_close(worktree);
12146 worktree = NULL;
12150 if (repo_path == NULL) {
12151 repo_path = strdup(cwd);
12152 if (repo_path == NULL)
12153 return got_error_from_errno("strdup");
12156 error = got_repo_open(&repo, repo_path, NULL);
12157 free(repo_path);
12158 if (error != NULL)
12159 goto done;
12161 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12162 if (error)
12163 goto done;
12165 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12166 if (error)
12167 goto done;
12169 if (commit_id_str == NULL)
12170 commit_id_str = GOT_REF_HEAD;
12171 error = got_repo_match_object_id(&commit_id, NULL,
12172 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12173 if (error)
12174 goto done;
12176 error = got_object_open_as_commit(&commit, repo, commit_id);
12177 if (error)
12178 goto done;
12180 for (i = 0; i < argc; i++) {
12181 if (force_path) {
12182 error = got_object_id_by_path(&id, repo, commit,
12183 argv[i]);
12184 if (error)
12185 break;
12186 } else {
12187 error = got_repo_match_object_id(&id, &label, argv[i],
12188 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12189 repo);
12190 if (error) {
12191 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12192 error->code != GOT_ERR_NOT_REF)
12193 break;
12194 error = got_object_id_by_path(&id, repo,
12195 commit, argv[i]);
12196 if (error)
12197 break;
12201 error = got_object_get_type(&obj_type, repo, id);
12202 if (error)
12203 break;
12205 switch (obj_type) {
12206 case GOT_OBJ_TYPE_BLOB:
12207 error = cat_blob(id, repo, stdout);
12208 break;
12209 case GOT_OBJ_TYPE_TREE:
12210 error = cat_tree(id, repo, stdout);
12211 break;
12212 case GOT_OBJ_TYPE_COMMIT:
12213 error = cat_commit(id, repo, stdout);
12214 break;
12215 case GOT_OBJ_TYPE_TAG:
12216 error = cat_tag(id, repo, stdout);
12217 break;
12218 default:
12219 error = got_error(GOT_ERR_OBJ_TYPE);
12220 break;
12222 if (error)
12223 break;
12224 free(label);
12225 label = NULL;
12226 free(id);
12227 id = NULL;
12229 done:
12230 free(label);
12231 free(id);
12232 free(commit_id);
12233 if (commit)
12234 got_object_commit_close(commit);
12235 if (worktree)
12236 got_worktree_close(worktree);
12237 if (repo) {
12238 const struct got_error *close_err = got_repo_close(repo);
12239 if (error == NULL)
12240 error = close_err;
12242 got_ref_list_free(&refs);
12243 return error;
12246 __dead static void
12247 usage_info(void)
12249 fprintf(stderr, "usage: %s info [path ...]\n",
12250 getprogname());
12251 exit(1);
12254 static const struct got_error *
12255 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12256 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12257 struct got_object_id *commit_id)
12259 const struct got_error *err = NULL;
12260 char *id_str = NULL;
12261 char datebuf[128];
12262 struct tm mytm, *tm;
12263 struct got_pathlist_head *paths = arg;
12264 struct got_pathlist_entry *pe;
12267 * Clear error indication from any of the path arguments which
12268 * would cause this file index entry to be displayed.
12270 TAILQ_FOREACH(pe, paths, entry) {
12271 if (got_path_cmp(path, pe->path, strlen(path),
12272 pe->path_len) == 0 ||
12273 got_path_is_child(path, pe->path, pe->path_len))
12274 pe->data = NULL; /* no error */
12277 printf(GOT_COMMIT_SEP_STR);
12278 if (S_ISLNK(mode))
12279 printf("symlink: %s\n", path);
12280 else if (S_ISREG(mode)) {
12281 printf("file: %s\n", path);
12282 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12283 } else if (S_ISDIR(mode))
12284 printf("directory: %s\n", path);
12285 else
12286 printf("something: %s\n", path);
12288 tm = localtime_r(&mtime, &mytm);
12289 if (tm == NULL)
12290 return NULL;
12291 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12292 return got_error(GOT_ERR_NO_SPACE);
12293 printf("timestamp: %s\n", datebuf);
12295 if (blob_id) {
12296 err = got_object_id_str(&id_str, blob_id);
12297 if (err)
12298 return err;
12299 printf("based on blob: %s\n", id_str);
12300 free(id_str);
12303 if (staged_blob_id) {
12304 err = got_object_id_str(&id_str, staged_blob_id);
12305 if (err)
12306 return err;
12307 printf("based on staged blob: %s\n", id_str);
12308 free(id_str);
12311 if (commit_id) {
12312 err = got_object_id_str(&id_str, commit_id);
12313 if (err)
12314 return err;
12315 printf("based on commit: %s\n", id_str);
12316 free(id_str);
12319 return NULL;
12322 static const struct got_error *
12323 cmd_info(int argc, char *argv[])
12325 const struct got_error *error = NULL;
12326 struct got_worktree *worktree = NULL;
12327 char *cwd = NULL, *id_str = NULL;
12328 struct got_pathlist_head paths;
12329 struct got_pathlist_entry *pe;
12330 char *uuidstr = NULL;
12331 int ch, show_files = 0;
12333 TAILQ_INIT(&paths);
12335 while ((ch = getopt(argc, argv, "")) != -1) {
12336 switch (ch) {
12337 default:
12338 usage_info();
12339 /* NOTREACHED */
12343 argc -= optind;
12344 argv += optind;
12346 #ifndef PROFILE
12347 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12348 NULL) == -1)
12349 err(1, "pledge");
12350 #endif
12351 cwd = getcwd(NULL, 0);
12352 if (cwd == NULL) {
12353 error = got_error_from_errno("getcwd");
12354 goto done;
12357 error = got_worktree_open(&worktree, cwd);
12358 if (error) {
12359 if (error->code == GOT_ERR_NOT_WORKTREE)
12360 error = wrap_not_worktree_error(error, "info", cwd);
12361 goto done;
12364 #ifndef PROFILE
12365 /* Remove "cpath" promise. */
12366 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12367 NULL) == -1)
12368 err(1, "pledge");
12369 #endif
12370 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12371 if (error)
12372 goto done;
12374 if (argc >= 1) {
12375 error = get_worktree_paths_from_argv(&paths, argc, argv,
12376 worktree);
12377 if (error)
12378 goto done;
12379 show_files = 1;
12382 error = got_object_id_str(&id_str,
12383 got_worktree_get_base_commit_id(worktree));
12384 if (error)
12385 goto done;
12387 error = got_worktree_get_uuid(&uuidstr, worktree);
12388 if (error)
12389 goto done;
12391 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12392 printf("work tree base commit: %s\n", id_str);
12393 printf("work tree path prefix: %s\n",
12394 got_worktree_get_path_prefix(worktree));
12395 printf("work tree branch reference: %s\n",
12396 got_worktree_get_head_ref_name(worktree));
12397 printf("work tree UUID: %s\n", uuidstr);
12398 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12400 if (show_files) {
12401 struct got_pathlist_entry *pe;
12402 TAILQ_FOREACH(pe, &paths, entry) {
12403 if (pe->path_len == 0)
12404 continue;
12406 * Assume this path will fail. This will be corrected
12407 * in print_path_info() in case the path does suceeed.
12409 pe->data = (void *)got_error_path(pe->path,
12410 GOT_ERR_BAD_PATH);
12412 error = got_worktree_path_info(worktree, &paths,
12413 print_path_info, &paths, check_cancelled, NULL);
12414 if (error)
12415 goto done;
12416 TAILQ_FOREACH(pe, &paths, entry) {
12417 if (pe->data != NULL) {
12418 error = pe->data; /* bad path */
12419 break;
12423 done:
12424 TAILQ_FOREACH(pe, &paths, entry)
12425 free((char *)pe->path);
12426 got_pathlist_free(&paths);
12427 free(cwd);
12428 free(id_str);
12429 free(uuidstr);
12430 return error;