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)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3485 if (blob_id1) {
3486 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3487 if (err)
3488 goto done;
3491 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3492 if (err)
3493 goto done;
3495 while (path[0] == '/')
3496 path++;
3497 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3498 diff_context, ignore_whitespace, force_text_diff, stdout);
3499 done:
3500 if (blob1)
3501 got_object_blob_close(blob1);
3502 got_object_blob_close(blob2);
3503 return err;
3506 static const struct got_error *
3507 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3508 const char *path, int diff_context, int ignore_whitespace,
3509 int force_text_diff, struct got_repository *repo)
3511 const struct got_error *err = NULL;
3512 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3513 struct got_diff_blob_output_unidiff_arg arg;
3515 if (tree_id1) {
3516 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3517 if (err)
3518 goto done;
3521 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3522 if (err)
3523 goto done;
3525 arg.diff_context = diff_context;
3526 arg.ignore_whitespace = ignore_whitespace;
3527 arg.force_text_diff = force_text_diff;
3528 arg.outfile = stdout;
3529 arg.line_offsets = NULL;
3530 arg.nlines = 0;
3531 while (path[0] == '/')
3532 path++;
3533 err = got_diff_tree(tree1, tree2, path, path, repo,
3534 got_diff_blob_output_unidiff, &arg, 1);
3535 done:
3536 if (tree1)
3537 got_object_tree_close(tree1);
3538 if (tree2)
3539 got_object_tree_close(tree2);
3540 return err;
3543 static const struct got_error *
3544 get_changed_paths(struct got_pathlist_head *paths,
3545 struct got_commit_object *commit, struct got_repository *repo)
3547 const struct got_error *err = NULL;
3548 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3549 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3550 struct got_object_qid *qid;
3552 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3553 if (qid != NULL) {
3554 struct got_commit_object *pcommit;
3555 err = got_object_open_as_commit(&pcommit, repo,
3556 &qid->id);
3557 if (err)
3558 return err;
3560 tree_id1 = got_object_id_dup(
3561 got_object_commit_get_tree_id(pcommit));
3562 if (tree_id1 == NULL) {
3563 got_object_commit_close(pcommit);
3564 return got_error_from_errno("got_object_id_dup");
3566 got_object_commit_close(pcommit);
3570 if (tree_id1) {
3571 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3572 if (err)
3573 goto done;
3576 tree_id2 = got_object_commit_get_tree_id(commit);
3577 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3578 if (err)
3579 goto done;
3581 err = got_diff_tree(tree1, tree2, "", "", repo,
3582 got_diff_tree_collect_changed_paths, paths, 0);
3583 done:
3584 if (tree1)
3585 got_object_tree_close(tree1);
3586 if (tree2)
3587 got_object_tree_close(tree2);
3588 free(tree_id1);
3589 return err;
3592 static const struct got_error *
3593 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3594 const char *path, int diff_context, struct got_repository *repo)
3596 const struct got_error *err = NULL;
3597 struct got_commit_object *pcommit = NULL;
3598 char *id_str1 = NULL, *id_str2 = NULL;
3599 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3600 struct got_object_qid *qid;
3602 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3603 if (qid != NULL) {
3604 err = got_object_open_as_commit(&pcommit, repo,
3605 &qid->id);
3606 if (err)
3607 return err;
3610 if (path && path[0] != '\0') {
3611 int obj_type;
3612 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3613 if (err)
3614 goto done;
3615 err = got_object_id_str(&id_str2, obj_id2);
3616 if (err) {
3617 free(obj_id2);
3618 goto done;
3620 if (pcommit) {
3621 err = got_object_id_by_path(&obj_id1, repo,
3622 pcommit, path);
3623 if (err) {
3624 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3625 free(obj_id2);
3626 goto done;
3628 } else {
3629 err = got_object_id_str(&id_str1, obj_id1);
3630 if (err) {
3631 free(obj_id2);
3632 goto done;
3636 err = got_object_get_type(&obj_type, repo, obj_id2);
3637 if (err) {
3638 free(obj_id2);
3639 goto done;
3641 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3642 switch (obj_type) {
3643 case GOT_OBJ_TYPE_BLOB:
3644 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3645 0, 0, repo);
3646 break;
3647 case GOT_OBJ_TYPE_TREE:
3648 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3649 0, 0, repo);
3650 break;
3651 default:
3652 err = got_error(GOT_ERR_OBJ_TYPE);
3653 break;
3655 free(obj_id1);
3656 free(obj_id2);
3657 } else {
3658 obj_id2 = got_object_commit_get_tree_id(commit);
3659 err = got_object_id_str(&id_str2, obj_id2);
3660 if (err)
3661 goto done;
3662 if (pcommit) {
3663 obj_id1 = got_object_commit_get_tree_id(pcommit);
3664 err = got_object_id_str(&id_str1, obj_id1);
3665 if (err)
3666 goto done;
3668 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3669 id_str2);
3670 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3671 repo);
3673 done:
3674 free(id_str1);
3675 free(id_str2);
3676 if (pcommit)
3677 got_object_commit_close(pcommit);
3678 return err;
3681 static char *
3682 get_datestr(time_t *time, char *datebuf)
3684 struct tm mytm, *tm;
3685 char *p, *s;
3687 tm = gmtime_r(time, &mytm);
3688 if (tm == NULL)
3689 return NULL;
3690 s = asctime_r(tm, datebuf);
3691 if (s == NULL)
3692 return NULL;
3693 p = strchr(s, '\n');
3694 if (p)
3695 *p = '\0';
3696 return s;
3699 static const struct got_error *
3700 match_logmsg(int *have_match, struct got_object_id *id,
3701 struct got_commit_object *commit, regex_t *regex)
3703 const struct got_error *err = NULL;
3704 regmatch_t regmatch;
3705 char *id_str = NULL, *logmsg = NULL;
3707 *have_match = 0;
3709 err = got_object_id_str(&id_str, id);
3710 if (err)
3711 return err;
3713 err = got_object_commit_get_logmsg(&logmsg, commit);
3714 if (err)
3715 goto done;
3717 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3718 *have_match = 1;
3719 done:
3720 free(id_str);
3721 free(logmsg);
3722 return err;
3725 static void
3726 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3727 regex_t *regex)
3729 regmatch_t regmatch;
3730 struct got_pathlist_entry *pe;
3732 *have_match = 0;
3734 TAILQ_FOREACH(pe, changed_paths, entry) {
3735 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3736 *have_match = 1;
3737 break;
3742 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3744 static const struct got_error*
3745 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3746 struct got_object_id *id, struct got_repository *repo)
3748 static const struct got_error *err = NULL;
3749 struct got_reflist_entry *re;
3750 char *s;
3751 const char *name;
3753 *refs_str = NULL;
3755 TAILQ_FOREACH(re, refs, entry) {
3756 struct got_tag_object *tag = NULL;
3757 struct got_object_id *ref_id;
3758 int cmp;
3760 name = got_ref_get_name(re->ref);
3761 if (strcmp(name, GOT_REF_HEAD) == 0)
3762 continue;
3763 if (strncmp(name, "refs/", 5) == 0)
3764 name += 5;
3765 if (strncmp(name, "got/", 4) == 0)
3766 continue;
3767 if (strncmp(name, "heads/", 6) == 0)
3768 name += 6;
3769 if (strncmp(name, "remotes/", 8) == 0) {
3770 name += 8;
3771 s = strstr(name, "/" GOT_REF_HEAD);
3772 if (s != NULL && s[strlen(s)] == '\0')
3773 continue;
3775 err = got_ref_resolve(&ref_id, repo, re->ref);
3776 if (err)
3777 break;
3778 if (strncmp(name, "tags/", 5) == 0) {
3779 err = got_object_open_as_tag(&tag, repo, ref_id);
3780 if (err) {
3781 if (err->code != GOT_ERR_OBJ_TYPE) {
3782 free(ref_id);
3783 break;
3785 /* Ref points at something other than a tag. */
3786 err = NULL;
3787 tag = NULL;
3790 cmp = got_object_id_cmp(tag ?
3791 got_object_tag_get_object_id(tag) : ref_id, id);
3792 free(ref_id);
3793 if (tag)
3794 got_object_tag_close(tag);
3795 if (cmp != 0)
3796 continue;
3797 s = *refs_str;
3798 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3799 s ? ", " : "", name) == -1) {
3800 err = got_error_from_errno("asprintf");
3801 free(s);
3802 *refs_str = NULL;
3803 break;
3805 free(s);
3808 return err;
3811 static const struct got_error *
3812 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3813 struct got_repository *repo, const char *path,
3814 struct got_pathlist_head *changed_paths, int show_patch,
3815 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3816 const char *custom_refs_str)
3818 const struct got_error *err = NULL;
3819 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3820 char datebuf[26];
3821 time_t committer_time;
3822 const char *author, *committer;
3823 char *refs_str = NULL;
3825 err = got_object_id_str(&id_str, id);
3826 if (err)
3827 return err;
3829 if (custom_refs_str == NULL) {
3830 struct got_reflist_head *refs;
3831 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3832 if (refs) {
3833 err = build_refs_str(&refs_str, refs, id, repo);
3834 if (err)
3835 goto done;
3839 printf(GOT_COMMIT_SEP_STR);
3840 if (custom_refs_str)
3841 printf("commit %s (%s)\n", id_str, custom_refs_str);
3842 else
3843 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3844 refs_str ? refs_str : "", refs_str ? ")" : "");
3845 free(id_str);
3846 id_str = NULL;
3847 free(refs_str);
3848 refs_str = NULL;
3849 printf("from: %s\n", got_object_commit_get_author(commit));
3850 committer_time = got_object_commit_get_committer_time(commit);
3851 datestr = get_datestr(&committer_time, datebuf);
3852 if (datestr)
3853 printf("date: %s UTC\n", datestr);
3854 author = got_object_commit_get_author(commit);
3855 committer = got_object_commit_get_committer(commit);
3856 if (strcmp(author, committer) != 0)
3857 printf("via: %s\n", committer);
3858 if (got_object_commit_get_nparents(commit) > 1) {
3859 const struct got_object_id_queue *parent_ids;
3860 struct got_object_qid *qid;
3861 int n = 1;
3862 parent_ids = got_object_commit_get_parent_ids(commit);
3863 STAILQ_FOREACH(qid, parent_ids, entry) {
3864 err = got_object_id_str(&id_str, &qid->id);
3865 if (err)
3866 goto done;
3867 printf("parent %d: %s\n", n++, id_str);
3868 free(id_str);
3869 id_str = NULL;
3873 err = got_object_commit_get_logmsg(&logmsg0, commit);
3874 if (err)
3875 goto done;
3877 logmsg = logmsg0;
3878 do {
3879 line = strsep(&logmsg, "\n");
3880 if (line)
3881 printf(" %s\n", line);
3882 } while (line);
3883 free(logmsg0);
3885 if (changed_paths) {
3886 struct got_pathlist_entry *pe;
3887 TAILQ_FOREACH(pe, changed_paths, entry) {
3888 struct got_diff_changed_path *cp = pe->data;
3889 printf(" %c %s\n", cp->status, pe->path);
3891 printf("\n");
3893 if (show_patch) {
3894 err = print_patch(commit, id, path, diff_context, repo);
3895 if (err == 0)
3896 printf("\n");
3899 if (fflush(stdout) != 0 && err == NULL)
3900 err = got_error_from_errno("fflush");
3901 done:
3902 free(id_str);
3903 free(refs_str);
3904 return err;
3907 static const struct got_error *
3908 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3909 struct got_repository *repo, const char *path, int show_changed_paths,
3910 int show_patch, const char *search_pattern, int diff_context, int limit,
3911 int log_branches, int reverse_display_order,
3912 struct got_reflist_object_id_map *refs_idmap)
3914 const struct got_error *err;
3915 struct got_commit_graph *graph;
3916 regex_t regex;
3917 int have_match;
3918 struct got_object_id_queue reversed_commits;
3919 struct got_object_qid *qid;
3920 struct got_commit_object *commit;
3921 struct got_pathlist_head changed_paths;
3922 struct got_pathlist_entry *pe;
3924 STAILQ_INIT(&reversed_commits);
3925 TAILQ_INIT(&changed_paths);
3927 if (search_pattern && regcomp(&regex, search_pattern,
3928 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3929 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3931 err = got_commit_graph_open(&graph, path, !log_branches);
3932 if (err)
3933 return err;
3934 err = got_commit_graph_iter_start(graph, root_id, repo,
3935 check_cancelled, NULL);
3936 if (err)
3937 goto done;
3938 for (;;) {
3939 struct got_object_id *id;
3941 if (sigint_received || sigpipe_received)
3942 break;
3944 err = got_commit_graph_iter_next(&id, graph, repo,
3945 check_cancelled, NULL);
3946 if (err) {
3947 if (err->code == GOT_ERR_ITER_COMPLETED)
3948 err = NULL;
3949 break;
3951 if (id == NULL)
3952 break;
3954 err = got_object_open_as_commit(&commit, repo, id);
3955 if (err)
3956 break;
3958 if (show_changed_paths && !reverse_display_order) {
3959 err = get_changed_paths(&changed_paths, commit, repo);
3960 if (err)
3961 break;
3964 if (search_pattern) {
3965 err = match_logmsg(&have_match, id, commit, &regex);
3966 if (err) {
3967 got_object_commit_close(commit);
3968 break;
3970 if (have_match == 0 && show_changed_paths)
3971 match_changed_paths(&have_match,
3972 &changed_paths, &regex);
3973 if (have_match == 0) {
3974 got_object_commit_close(commit);
3975 TAILQ_FOREACH(pe, &changed_paths, entry) {
3976 free((char *)pe->path);
3977 free(pe->data);
3979 got_pathlist_free(&changed_paths);
3980 continue;
3984 if (reverse_display_order) {
3985 err = got_object_qid_alloc(&qid, id);
3986 if (err)
3987 break;
3988 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3989 got_object_commit_close(commit);
3990 } else {
3991 err = print_commit(commit, id, repo, path,
3992 show_changed_paths ? &changed_paths : NULL,
3993 show_patch, diff_context, refs_idmap, NULL);
3994 got_object_commit_close(commit);
3995 if (err)
3996 break;
3998 if ((limit && --limit == 0) ||
3999 (end_id && got_object_id_cmp(id, end_id) == 0))
4000 break;
4002 TAILQ_FOREACH(pe, &changed_paths, entry) {
4003 free((char *)pe->path);
4004 free(pe->data);
4006 got_pathlist_free(&changed_paths);
4008 if (reverse_display_order) {
4009 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4010 err = got_object_open_as_commit(&commit, repo,
4011 &qid->id);
4012 if (err)
4013 break;
4014 if (show_changed_paths) {
4015 err = get_changed_paths(&changed_paths,
4016 commit, repo);
4017 if (err)
4018 break;
4020 err = print_commit(commit, &qid->id, repo, path,
4021 show_changed_paths ? &changed_paths : NULL,
4022 show_patch, diff_context, refs_idmap, NULL);
4023 got_object_commit_close(commit);
4024 if (err)
4025 break;
4026 TAILQ_FOREACH(pe, &changed_paths, entry) {
4027 free((char *)pe->path);
4028 free(pe->data);
4030 got_pathlist_free(&changed_paths);
4033 done:
4034 while (!STAILQ_EMPTY(&reversed_commits)) {
4035 qid = STAILQ_FIRST(&reversed_commits);
4036 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4037 got_object_qid_free(qid);
4039 TAILQ_FOREACH(pe, &changed_paths, entry) {
4040 free((char *)pe->path);
4041 free(pe->data);
4043 got_pathlist_free(&changed_paths);
4044 if (search_pattern)
4045 regfree(&regex);
4046 got_commit_graph_close(graph);
4047 return err;
4050 __dead static void
4051 usage_log(void)
4053 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4054 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4055 "[-R] [path]\n", getprogname());
4056 exit(1);
4059 static int
4060 get_default_log_limit(void)
4062 const char *got_default_log_limit;
4063 long long n;
4064 const char *errstr;
4066 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4067 if (got_default_log_limit == NULL)
4068 return 0;
4069 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4070 if (errstr != NULL)
4071 return 0;
4072 return n;
4075 static const struct got_error *
4076 cmd_log(int argc, char *argv[])
4078 const struct got_error *error;
4079 struct got_repository *repo = NULL;
4080 struct got_worktree *worktree = NULL;
4081 struct got_object_id *start_id = NULL, *end_id = NULL;
4082 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4083 const char *start_commit = NULL, *end_commit = NULL;
4084 const char *search_pattern = NULL;
4085 int diff_context = -1, ch;
4086 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4087 int reverse_display_order = 0;
4088 const char *errstr;
4089 struct got_reflist_head refs;
4090 struct got_reflist_object_id_map *refs_idmap = NULL;
4092 TAILQ_INIT(&refs);
4094 #ifndef PROFILE
4095 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4096 NULL)
4097 == -1)
4098 err(1, "pledge");
4099 #endif
4101 limit = get_default_log_limit();
4103 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4104 switch (ch) {
4105 case 'p':
4106 show_patch = 1;
4107 break;
4108 case 'P':
4109 show_changed_paths = 1;
4110 break;
4111 case 'c':
4112 start_commit = optarg;
4113 break;
4114 case 'C':
4115 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4116 &errstr);
4117 if (errstr != NULL)
4118 errx(1, "number of context lines is %s: %s",
4119 errstr, optarg);
4120 break;
4121 case 'l':
4122 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4123 if (errstr != NULL)
4124 errx(1, "number of commits is %s: %s",
4125 errstr, optarg);
4126 break;
4127 case 'b':
4128 log_branches = 1;
4129 break;
4130 case 'r':
4131 repo_path = realpath(optarg, NULL);
4132 if (repo_path == NULL)
4133 return got_error_from_errno2("realpath",
4134 optarg);
4135 got_path_strip_trailing_slashes(repo_path);
4136 break;
4137 case 'R':
4138 reverse_display_order = 1;
4139 break;
4140 case 's':
4141 search_pattern = optarg;
4142 break;
4143 case 'x':
4144 end_commit = optarg;
4145 break;
4146 default:
4147 usage_log();
4148 /* NOTREACHED */
4152 argc -= optind;
4153 argv += optind;
4155 if (diff_context == -1)
4156 diff_context = 3;
4157 else if (!show_patch)
4158 errx(1, "-C requires -p");
4160 cwd = getcwd(NULL, 0);
4161 if (cwd == NULL) {
4162 error = got_error_from_errno("getcwd");
4163 goto done;
4166 if (repo_path == NULL) {
4167 error = got_worktree_open(&worktree, cwd);
4168 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4169 goto done;
4170 error = NULL;
4173 if (argc == 1) {
4174 if (worktree) {
4175 error = got_worktree_resolve_path(&path, worktree,
4176 argv[0]);
4177 if (error)
4178 goto done;
4179 } else {
4180 path = strdup(argv[0]);
4181 if (path == NULL) {
4182 error = got_error_from_errno("strdup");
4183 goto done;
4186 } else if (argc != 0)
4187 usage_log();
4189 if (repo_path == NULL) {
4190 repo_path = worktree ?
4191 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4193 if (repo_path == NULL) {
4194 error = got_error_from_errno("strdup");
4195 goto done;
4198 error = got_repo_open(&repo, repo_path, NULL);
4199 if (error != NULL)
4200 goto done;
4202 error = apply_unveil(got_repo_get_path(repo), 1,
4203 worktree ? got_worktree_get_root_path(worktree) : NULL);
4204 if (error)
4205 goto done;
4207 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4208 if (error)
4209 goto done;
4211 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4212 if (error)
4213 goto done;
4215 if (start_commit == NULL) {
4216 struct got_reference *head_ref;
4217 struct got_commit_object *commit = NULL;
4218 error = got_ref_open(&head_ref, repo,
4219 worktree ? got_worktree_get_head_ref_name(worktree)
4220 : GOT_REF_HEAD, 0);
4221 if (error != NULL)
4222 goto done;
4223 error = got_ref_resolve(&start_id, repo, head_ref);
4224 got_ref_close(head_ref);
4225 if (error != NULL)
4226 goto done;
4227 error = got_object_open_as_commit(&commit, repo,
4228 start_id);
4229 if (error != NULL)
4230 goto done;
4231 got_object_commit_close(commit);
4232 } else {
4233 error = got_repo_match_object_id(&start_id, NULL,
4234 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4235 if (error != NULL)
4236 goto done;
4238 if (end_commit != NULL) {
4239 error = got_repo_match_object_id(&end_id, NULL,
4240 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4241 if (error != NULL)
4242 goto done;
4245 if (worktree) {
4247 * If a path was specified on the command line it was resolved
4248 * to a path in the work tree above. Prepend the work tree's
4249 * path prefix to obtain the corresponding in-repository path.
4251 if (path) {
4252 const char *prefix;
4253 prefix = got_worktree_get_path_prefix(worktree);
4254 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4255 (path[0] != '\0') ? "/" : "", path) == -1) {
4256 error = got_error_from_errno("asprintf");
4257 goto done;
4260 } else
4261 error = got_repo_map_path(&in_repo_path, repo,
4262 path ? path : "");
4263 if (error != NULL)
4264 goto done;
4265 if (in_repo_path) {
4266 free(path);
4267 path = in_repo_path;
4270 if (worktree) {
4271 /* Release work tree lock. */
4272 got_worktree_close(worktree);
4273 worktree = NULL;
4276 error = print_commits(start_id, end_id, repo, path ? path : "",
4277 show_changed_paths, show_patch, search_pattern, diff_context,
4278 limit, log_branches, reverse_display_order, refs_idmap);
4279 done:
4280 free(path);
4281 free(repo_path);
4282 free(cwd);
4283 if (worktree)
4284 got_worktree_close(worktree);
4285 if (repo) {
4286 const struct got_error *close_err = got_repo_close(repo);
4287 if (error == NULL)
4288 error = close_err;
4290 if (refs_idmap)
4291 got_reflist_object_id_map_free(refs_idmap);
4292 got_ref_list_free(&refs);
4293 return error;
4296 __dead static void
4297 usage_diff(void)
4299 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4300 "[-r repository-path] [-s] [-w] [-P] "
4301 "[object1 object2 | path ...]\n", getprogname());
4302 exit(1);
4305 struct print_diff_arg {
4306 struct got_repository *repo;
4307 struct got_worktree *worktree;
4308 int diff_context;
4309 const char *id_str;
4310 int header_shown;
4311 int diff_staged;
4312 int ignore_whitespace;
4313 int force_text_diff;
4317 * Create a file which contains the target path of a symlink so we can feed
4318 * it as content to the diff engine.
4320 static const struct got_error *
4321 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4322 const char *abspath)
4324 const struct got_error *err = NULL;
4325 char target_path[PATH_MAX];
4326 ssize_t target_len, outlen;
4328 *fd = -1;
4330 if (dirfd != -1) {
4331 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4332 if (target_len == -1)
4333 return got_error_from_errno2("readlinkat", abspath);
4334 } else {
4335 target_len = readlink(abspath, target_path, PATH_MAX);
4336 if (target_len == -1)
4337 return got_error_from_errno2("readlink", abspath);
4340 *fd = got_opentempfd();
4341 if (*fd == -1)
4342 return got_error_from_errno("got_opentempfd");
4344 outlen = write(*fd, target_path, target_len);
4345 if (outlen == -1) {
4346 err = got_error_from_errno("got_opentempfd");
4347 goto done;
4350 if (lseek(*fd, 0, SEEK_SET) == -1) {
4351 err = got_error_from_errno2("lseek", abspath);
4352 goto done;
4354 done:
4355 if (err) {
4356 close(*fd);
4357 *fd = -1;
4359 return err;
4362 static const struct got_error *
4363 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4364 const char *path, struct got_object_id *blob_id,
4365 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4366 int dirfd, const char *de_name)
4368 struct print_diff_arg *a = arg;
4369 const struct got_error *err = NULL;
4370 struct got_blob_object *blob1 = NULL;
4371 int fd = -1;
4372 FILE *f2 = NULL;
4373 char *abspath = NULL, *label1 = NULL;
4374 struct stat sb;
4376 if (a->diff_staged) {
4377 if (staged_status != GOT_STATUS_MODIFY &&
4378 staged_status != GOT_STATUS_ADD &&
4379 staged_status != GOT_STATUS_DELETE)
4380 return NULL;
4381 } else {
4382 if (staged_status == GOT_STATUS_DELETE)
4383 return NULL;
4384 if (status == GOT_STATUS_NONEXISTENT)
4385 return got_error_set_errno(ENOENT, path);
4386 if (status != GOT_STATUS_MODIFY &&
4387 status != GOT_STATUS_ADD &&
4388 status != GOT_STATUS_DELETE &&
4389 status != GOT_STATUS_CONFLICT)
4390 return NULL;
4393 if (!a->header_shown) {
4394 printf("diff %s %s%s\n", a->id_str,
4395 got_worktree_get_root_path(a->worktree),
4396 a->diff_staged ? " (staged changes)" : "");
4397 a->header_shown = 1;
4400 if (a->diff_staged) {
4401 const char *label1 = NULL, *label2 = NULL;
4402 switch (staged_status) {
4403 case GOT_STATUS_MODIFY:
4404 label1 = path;
4405 label2 = path;
4406 break;
4407 case GOT_STATUS_ADD:
4408 label2 = path;
4409 break;
4410 case GOT_STATUS_DELETE:
4411 label1 = path;
4412 break;
4413 default:
4414 return got_error(GOT_ERR_FILE_STATUS);
4416 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4417 staged_blob_id, label1, label2, a->diff_context,
4418 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4421 if (staged_status == GOT_STATUS_ADD ||
4422 staged_status == GOT_STATUS_MODIFY) {
4423 char *id_str;
4424 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4425 8192);
4426 if (err)
4427 goto done;
4428 err = got_object_id_str(&id_str, staged_blob_id);
4429 if (err)
4430 goto done;
4431 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4432 err = got_error_from_errno("asprintf");
4433 free(id_str);
4434 goto done;
4436 free(id_str);
4437 } else if (status != GOT_STATUS_ADD) {
4438 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4439 if (err)
4440 goto done;
4443 if (status != GOT_STATUS_DELETE) {
4444 if (asprintf(&abspath, "%s/%s",
4445 got_worktree_get_root_path(a->worktree), path) == -1) {
4446 err = got_error_from_errno("asprintf");
4447 goto done;
4450 if (dirfd != -1) {
4451 fd = openat(dirfd, de_name,
4452 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4453 if (fd == -1) {
4454 if (!got_err_open_nofollow_on_symlink()) {
4455 err = got_error_from_errno2("openat",
4456 abspath);
4457 goto done;
4459 err = get_symlink_target_file(&fd, dirfd,
4460 de_name, abspath);
4461 if (err)
4462 goto done;
4464 } else {
4465 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4466 if (fd == -1) {
4467 if (!got_err_open_nofollow_on_symlink()) {
4468 err = got_error_from_errno2("open",
4469 abspath);
4470 goto done;
4472 err = get_symlink_target_file(&fd, dirfd,
4473 de_name, abspath);
4474 if (err)
4475 goto done;
4478 if (fstat(fd, &sb) == -1) {
4479 err = got_error_from_errno2("fstat", abspath);
4480 goto done;
4482 f2 = fdopen(fd, "r");
4483 if (f2 == NULL) {
4484 err = got_error_from_errno2("fdopen", abspath);
4485 goto done;
4487 fd = -1;
4488 } else
4489 sb.st_size = 0;
4491 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4492 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4493 done:
4494 if (blob1)
4495 got_object_blob_close(blob1);
4496 if (f2 && fclose(f2) == EOF && err == NULL)
4497 err = got_error_from_errno("fclose");
4498 if (fd != -1 && close(fd) == -1 && err == NULL)
4499 err = got_error_from_errno("close");
4500 free(abspath);
4501 return err;
4504 static const struct got_error *
4505 cmd_diff(int argc, char *argv[])
4507 const struct got_error *error;
4508 struct got_repository *repo = NULL;
4509 struct got_worktree *worktree = NULL;
4510 char *cwd = NULL, *repo_path = NULL;
4511 const char *commit_args[2] = { NULL, NULL };
4512 int ncommit_args = 0;
4513 struct got_object_id *ids[2] = { NULL, NULL };
4514 char *labels[2] = { NULL, NULL };
4515 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4516 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4517 int force_text_diff = 0, force_path = 0, rflag = 0;
4518 const char *errstr;
4519 struct got_reflist_head refs;
4520 struct got_pathlist_head paths;
4521 struct got_pathlist_entry *pe;
4523 TAILQ_INIT(&refs);
4524 TAILQ_INIT(&paths);
4526 #ifndef PROFILE
4527 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4528 NULL) == -1)
4529 err(1, "pledge");
4530 #endif
4532 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4533 switch (ch) {
4534 case 'a':
4535 force_text_diff = 1;
4536 break;
4537 case 'c':
4538 if (ncommit_args >= 2)
4539 errx(1, "too many -c options used");
4540 commit_args[ncommit_args++] = optarg;
4541 break;
4542 case 'C':
4543 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4544 &errstr);
4545 if (errstr != NULL)
4546 errx(1, "number of context lines is %s: %s",
4547 errstr, optarg);
4548 break;
4549 case 'r':
4550 repo_path = realpath(optarg, NULL);
4551 if (repo_path == NULL)
4552 return got_error_from_errno2("realpath",
4553 optarg);
4554 got_path_strip_trailing_slashes(repo_path);
4555 rflag = 1;
4556 break;
4557 case 's':
4558 diff_staged = 1;
4559 break;
4560 case 'w':
4561 ignore_whitespace = 1;
4562 break;
4563 case 'P':
4564 force_path = 1;
4565 break;
4566 default:
4567 usage_diff();
4568 /* NOTREACHED */
4572 argc -= optind;
4573 argv += optind;
4575 cwd = getcwd(NULL, 0);
4576 if (cwd == NULL) {
4577 error = got_error_from_errno("getcwd");
4578 goto done;
4581 if (repo_path == NULL) {
4582 error = got_worktree_open(&worktree, cwd);
4583 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4584 goto done;
4585 else
4586 error = NULL;
4587 if (worktree) {
4588 repo_path =
4589 strdup(got_worktree_get_repo_path(worktree));
4590 if (repo_path == NULL) {
4591 error = got_error_from_errno("strdup");
4592 goto done;
4594 } else {
4595 repo_path = strdup(cwd);
4596 if (repo_path == NULL) {
4597 error = got_error_from_errno("strdup");
4598 goto done;
4603 error = got_repo_open(&repo, repo_path, NULL);
4604 free(repo_path);
4605 if (error != NULL)
4606 goto done;
4608 if (rflag || worktree == NULL || ncommit_args > 0) {
4609 if (force_path) {
4610 error = got_error_msg(GOT_ERR_NOT_IMPL,
4611 "-P option can only be used when diffing "
4612 "a work tree");
4613 goto done;
4615 if (diff_staged) {
4616 error = got_error_msg(GOT_ERR_NOT_IMPL,
4617 "-s option can only be used when diffing "
4618 "a work tree");
4619 goto done;
4623 error = apply_unveil(got_repo_get_path(repo), 1,
4624 worktree ? got_worktree_get_root_path(worktree) : NULL);
4625 if (error)
4626 goto done;
4628 if ((!force_path && argc == 2) || ncommit_args > 0) {
4629 int obj_type = (ncommit_args > 0 ?
4630 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4631 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4632 NULL);
4633 if (error)
4634 goto done;
4635 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4636 const char *arg;
4637 if (ncommit_args > 0)
4638 arg = commit_args[i];
4639 else
4640 arg = argv[i];
4641 error = got_repo_match_object_id(&ids[i], &labels[i],
4642 arg, obj_type, &refs, repo);
4643 if (error) {
4644 if (error->code != GOT_ERR_NOT_REF &&
4645 error->code != GOT_ERR_NO_OBJ)
4646 goto done;
4647 if (ncommit_args > 0)
4648 goto done;
4649 error = NULL;
4650 break;
4655 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4656 struct print_diff_arg arg;
4657 char *id_str;
4659 if (worktree == NULL) {
4660 if (argc == 2 && ids[0] == NULL) {
4661 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4662 goto done;
4663 } else if (argc == 2 && ids[1] == NULL) {
4664 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4665 goto done;
4666 } else if (argc > 0) {
4667 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4668 "%s", "specified paths cannot be resolved");
4669 goto done;
4670 } else {
4671 error = got_error(GOT_ERR_NOT_WORKTREE);
4672 goto done;
4676 error = get_worktree_paths_from_argv(&paths, argc, argv,
4677 worktree);
4678 if (error)
4679 goto done;
4681 error = got_object_id_str(&id_str,
4682 got_worktree_get_base_commit_id(worktree));
4683 if (error)
4684 goto done;
4685 arg.repo = repo;
4686 arg.worktree = worktree;
4687 arg.diff_context = diff_context;
4688 arg.id_str = id_str;
4689 arg.header_shown = 0;
4690 arg.diff_staged = diff_staged;
4691 arg.ignore_whitespace = ignore_whitespace;
4692 arg.force_text_diff = force_text_diff;
4694 error = got_worktree_status(worktree, &paths, repo, 0,
4695 print_diff, &arg, check_cancelled, NULL);
4696 free(id_str);
4697 goto done;
4700 if (ncommit_args == 1) {
4701 struct got_commit_object *commit;
4702 error = got_object_open_as_commit(&commit, repo, ids[0]);
4703 if (error)
4704 goto done;
4706 labels[1] = labels[0];
4707 ids[1] = ids[0];
4708 if (got_object_commit_get_nparents(commit) > 0) {
4709 const struct got_object_id_queue *pids;
4710 struct got_object_qid *pid;
4711 pids = got_object_commit_get_parent_ids(commit);
4712 pid = STAILQ_FIRST(pids);
4713 ids[0] = got_object_id_dup(&pid->id);
4714 if (ids[0] == NULL) {
4715 error = got_error_from_errno(
4716 "got_object_id_dup");
4717 got_object_commit_close(commit);
4718 goto done;
4720 error = got_object_id_str(&labels[0], ids[0]);
4721 if (error) {
4722 got_object_commit_close(commit);
4723 goto done;
4725 } else {
4726 ids[0] = NULL;
4727 labels[0] = strdup("/dev/null");
4728 if (labels[0] == NULL) {
4729 error = got_error_from_errno("strdup");
4730 got_object_commit_close(commit);
4731 goto done;
4735 got_object_commit_close(commit);
4738 if (ncommit_args == 0 && argc > 2) {
4739 error = got_error_msg(GOT_ERR_BAD_PATH,
4740 "path arguments cannot be used when diffing two objects");
4741 goto done;
4744 if (ids[0]) {
4745 error = got_object_get_type(&type1, repo, ids[0]);
4746 if (error)
4747 goto done;
4750 error = got_object_get_type(&type2, repo, ids[1]);
4751 if (error)
4752 goto done;
4753 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4754 error = got_error(GOT_ERR_OBJ_TYPE);
4755 goto done;
4757 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4758 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4759 "path arguments cannot be used when diffing blobs");
4760 goto done;
4763 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4764 char *in_repo_path;
4765 struct got_pathlist_entry *new;
4766 if (worktree) {
4767 const char *prefix;
4768 char *p;
4769 error = got_worktree_resolve_path(&p, worktree,
4770 argv[i]);
4771 if (error)
4772 goto done;
4773 prefix = got_worktree_get_path_prefix(worktree);
4774 while (prefix[0] == '/')
4775 prefix++;
4776 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4777 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4778 p) == -1) {
4779 error = got_error_from_errno("asprintf");
4780 free(p);
4781 goto done;
4783 free(p);
4784 } else {
4785 char *mapped_path, *s;
4786 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4787 if (error)
4788 goto done;
4789 s = mapped_path;
4790 while (s[0] == '/')
4791 s++;
4792 in_repo_path = strdup(s);
4793 if (in_repo_path == NULL) {
4794 error = got_error_from_errno("asprintf");
4795 free(mapped_path);
4796 goto done;
4798 free(mapped_path);
4801 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4802 if (error || new == NULL /* duplicate */)
4803 free(in_repo_path);
4804 if (error)
4805 goto done;
4808 if (worktree) {
4809 /* Release work tree lock. */
4810 got_worktree_close(worktree);
4811 worktree = NULL;
4814 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4815 case GOT_OBJ_TYPE_BLOB:
4816 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4817 NULL, NULL, diff_context, ignore_whitespace,
4818 force_text_diff, repo, stdout);
4819 break;
4820 case GOT_OBJ_TYPE_TREE:
4821 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4822 &paths, "", "", diff_context, ignore_whitespace,
4823 force_text_diff, repo, stdout);
4824 break;
4825 case GOT_OBJ_TYPE_COMMIT:
4826 printf("diff %s %s\n", labels[0], labels[1]);
4827 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4828 &paths, diff_context, ignore_whitespace, force_text_diff,
4829 repo, stdout);
4830 break;
4831 default:
4832 error = got_error(GOT_ERR_OBJ_TYPE);
4834 done:
4835 free(labels[0]);
4836 free(labels[1]);
4837 free(ids[0]);
4838 free(ids[1]);
4839 if (worktree)
4840 got_worktree_close(worktree);
4841 if (repo) {
4842 const struct got_error *close_err = got_repo_close(repo);
4843 if (error == NULL)
4844 error = close_err;
4846 TAILQ_FOREACH(pe, &paths, entry)
4847 free((char *)pe->path);
4848 got_pathlist_free(&paths);
4849 got_ref_list_free(&refs);
4850 return error;
4853 __dead static void
4854 usage_blame(void)
4856 fprintf(stderr,
4857 "usage: %s blame [-c commit] [-r repository-path] path\n",
4858 getprogname());
4859 exit(1);
4862 struct blame_line {
4863 int annotated;
4864 char *id_str;
4865 char *committer;
4866 char datebuf[11]; /* YYYY-MM-DD + NUL */
4869 struct blame_cb_args {
4870 struct blame_line *lines;
4871 int nlines;
4872 int nlines_prec;
4873 int lineno_cur;
4874 off_t *line_offsets;
4875 FILE *f;
4876 struct got_repository *repo;
4879 static const struct got_error *
4880 blame_cb(void *arg, int nlines, int lineno,
4881 struct got_commit_object *commit, struct got_object_id *id)
4883 const struct got_error *err = NULL;
4884 struct blame_cb_args *a = arg;
4885 struct blame_line *bline;
4886 char *line = NULL;
4887 size_t linesize = 0;
4888 off_t offset;
4889 struct tm tm;
4890 time_t committer_time;
4892 if (nlines != a->nlines ||
4893 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4894 return got_error(GOT_ERR_RANGE);
4896 if (sigint_received)
4897 return got_error(GOT_ERR_ITER_COMPLETED);
4899 if (lineno == -1)
4900 return NULL; /* no change in this commit */
4902 /* Annotate this line. */
4903 bline = &a->lines[lineno - 1];
4904 if (bline->annotated)
4905 return NULL;
4906 err = got_object_id_str(&bline->id_str, id);
4907 if (err)
4908 return err;
4910 bline->committer = strdup(got_object_commit_get_committer(commit));
4911 if (bline->committer == NULL) {
4912 err = got_error_from_errno("strdup");
4913 goto done;
4916 committer_time = got_object_commit_get_committer_time(commit);
4917 if (gmtime_r(&committer_time, &tm) == NULL)
4918 return got_error_from_errno("gmtime_r");
4919 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4920 &tm) == 0) {
4921 err = got_error(GOT_ERR_NO_SPACE);
4922 goto done;
4924 bline->annotated = 1;
4926 /* Print lines annotated so far. */
4927 bline = &a->lines[a->lineno_cur - 1];
4928 if (!bline->annotated)
4929 goto done;
4931 offset = a->line_offsets[a->lineno_cur - 1];
4932 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4933 err = got_error_from_errno("fseeko");
4934 goto done;
4937 while (bline->annotated) {
4938 char *smallerthan, *at, *nl, *committer;
4939 size_t len;
4941 if (getline(&line, &linesize, a->f) == -1) {
4942 if (ferror(a->f))
4943 err = got_error_from_errno("getline");
4944 break;
4947 committer = bline->committer;
4948 smallerthan = strchr(committer, '<');
4949 if (smallerthan && smallerthan[1] != '\0')
4950 committer = smallerthan + 1;
4951 at = strchr(committer, '@');
4952 if (at)
4953 *at = '\0';
4954 len = strlen(committer);
4955 if (len >= 9)
4956 committer[8] = '\0';
4958 nl = strchr(line, '\n');
4959 if (nl)
4960 *nl = '\0';
4961 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4962 bline->id_str, bline->datebuf, committer, line);
4964 a->lineno_cur++;
4965 bline = &a->lines[a->lineno_cur - 1];
4967 done:
4968 free(line);
4969 return err;
4972 static const struct got_error *
4973 cmd_blame(int argc, char *argv[])
4975 const struct got_error *error;
4976 struct got_repository *repo = NULL;
4977 struct got_worktree *worktree = NULL;
4978 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4979 char *link_target = NULL;
4980 struct got_object_id *obj_id = NULL;
4981 struct got_object_id *commit_id = NULL;
4982 struct got_commit_object *commit = NULL;
4983 struct got_blob_object *blob = NULL;
4984 char *commit_id_str = NULL;
4985 struct blame_cb_args bca;
4986 int ch, obj_type, i;
4987 off_t filesize;
4989 memset(&bca, 0, sizeof(bca));
4991 #ifndef PROFILE
4992 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4993 NULL) == -1)
4994 err(1, "pledge");
4995 #endif
4997 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4998 switch (ch) {
4999 case 'c':
5000 commit_id_str = optarg;
5001 break;
5002 case 'r':
5003 repo_path = realpath(optarg, NULL);
5004 if (repo_path == NULL)
5005 return got_error_from_errno2("realpath",
5006 optarg);
5007 got_path_strip_trailing_slashes(repo_path);
5008 break;
5009 default:
5010 usage_blame();
5011 /* NOTREACHED */
5015 argc -= optind;
5016 argv += optind;
5018 if (argc == 1)
5019 path = argv[0];
5020 else
5021 usage_blame();
5023 cwd = getcwd(NULL, 0);
5024 if (cwd == NULL) {
5025 error = got_error_from_errno("getcwd");
5026 goto done;
5028 if (repo_path == NULL) {
5029 error = got_worktree_open(&worktree, cwd);
5030 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5031 goto done;
5032 else
5033 error = NULL;
5034 if (worktree) {
5035 repo_path =
5036 strdup(got_worktree_get_repo_path(worktree));
5037 if (repo_path == NULL) {
5038 error = got_error_from_errno("strdup");
5039 if (error)
5040 goto done;
5042 } else {
5043 repo_path = strdup(cwd);
5044 if (repo_path == NULL) {
5045 error = got_error_from_errno("strdup");
5046 goto done;
5051 error = got_repo_open(&repo, repo_path, NULL);
5052 if (error != NULL)
5053 goto done;
5055 if (worktree) {
5056 const char *prefix = got_worktree_get_path_prefix(worktree);
5057 char *p;
5059 error = got_worktree_resolve_path(&p, worktree, path);
5060 if (error)
5061 goto done;
5062 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5063 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5064 p) == -1) {
5065 error = got_error_from_errno("asprintf");
5066 free(p);
5067 goto done;
5069 free(p);
5070 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5071 } else {
5072 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5073 if (error)
5074 goto done;
5075 error = got_repo_map_path(&in_repo_path, repo, path);
5077 if (error)
5078 goto done;
5080 if (commit_id_str == NULL) {
5081 struct got_reference *head_ref;
5082 error = got_ref_open(&head_ref, repo, worktree ?
5083 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5084 if (error != NULL)
5085 goto done;
5086 error = got_ref_resolve(&commit_id, repo, head_ref);
5087 got_ref_close(head_ref);
5088 if (error != NULL)
5089 goto done;
5090 } else {
5091 struct got_reflist_head refs;
5092 TAILQ_INIT(&refs);
5093 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5094 NULL);
5095 if (error)
5096 goto done;
5097 error = got_repo_match_object_id(&commit_id, NULL,
5098 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5099 got_ref_list_free(&refs);
5100 if (error)
5101 goto done;
5104 if (worktree) {
5105 /* Release work tree lock. */
5106 got_worktree_close(worktree);
5107 worktree = NULL;
5110 error = got_object_open_as_commit(&commit, repo, commit_id);
5111 if (error)
5112 goto done;
5114 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5115 commit, repo);
5116 if (error)
5117 goto done;
5119 error = got_object_id_by_path(&obj_id, repo, commit,
5120 link_target ? link_target : in_repo_path);
5121 if (error)
5122 goto done;
5124 error = got_object_get_type(&obj_type, repo, obj_id);
5125 if (error)
5126 goto done;
5128 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5129 error = got_error_path(link_target ? link_target : in_repo_path,
5130 GOT_ERR_OBJ_TYPE);
5131 goto done;
5134 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5135 if (error)
5136 goto done;
5137 bca.f = got_opentemp();
5138 if (bca.f == NULL) {
5139 error = got_error_from_errno("got_opentemp");
5140 goto done;
5142 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5143 &bca.line_offsets, bca.f, blob);
5144 if (error || bca.nlines == 0)
5145 goto done;
5147 /* Don't include \n at EOF in the blame line count. */
5148 if (bca.line_offsets[bca.nlines - 1] == filesize)
5149 bca.nlines--;
5151 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5152 if (bca.lines == NULL) {
5153 error = got_error_from_errno("calloc");
5154 goto done;
5156 bca.lineno_cur = 1;
5157 bca.nlines_prec = 0;
5158 i = bca.nlines;
5159 while (i > 0) {
5160 i /= 10;
5161 bca.nlines_prec++;
5163 bca.repo = repo;
5165 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5166 repo, blame_cb, &bca, check_cancelled, NULL);
5167 done:
5168 free(in_repo_path);
5169 free(link_target);
5170 free(repo_path);
5171 free(cwd);
5172 free(commit_id);
5173 free(obj_id);
5174 if (commit)
5175 got_object_commit_close(commit);
5176 if (blob)
5177 got_object_blob_close(blob);
5178 if (worktree)
5179 got_worktree_close(worktree);
5180 if (repo) {
5181 const struct got_error *close_err = got_repo_close(repo);
5182 if (error == NULL)
5183 error = close_err;
5185 if (bca.lines) {
5186 for (i = 0; i < bca.nlines; i++) {
5187 struct blame_line *bline = &bca.lines[i];
5188 free(bline->id_str);
5189 free(bline->committer);
5191 free(bca.lines);
5193 free(bca.line_offsets);
5194 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5195 error = got_error_from_errno("fclose");
5196 return error;
5199 __dead static void
5200 usage_tree(void)
5202 fprintf(stderr,
5203 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5204 getprogname());
5205 exit(1);
5208 static const struct got_error *
5209 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5210 const char *root_path, struct got_repository *repo)
5212 const struct got_error *err = NULL;
5213 int is_root_path = (strcmp(path, root_path) == 0);
5214 const char *modestr = "";
5215 mode_t mode = got_tree_entry_get_mode(te);
5216 char *link_target = NULL;
5218 path += strlen(root_path);
5219 while (path[0] == '/')
5220 path++;
5222 if (got_object_tree_entry_is_submodule(te))
5223 modestr = "$";
5224 else if (S_ISLNK(mode)) {
5225 int i;
5227 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5228 if (err)
5229 return err;
5230 for (i = 0; i < strlen(link_target); i++) {
5231 if (!isprint((unsigned char)link_target[i]))
5232 link_target[i] = '?';
5235 modestr = "@";
5237 else if (S_ISDIR(mode))
5238 modestr = "/";
5239 else if (mode & S_IXUSR)
5240 modestr = "*";
5242 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5243 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5244 link_target ? " -> ": "", link_target ? link_target : "");
5246 free(link_target);
5247 return NULL;
5250 static const struct got_error *
5251 print_tree(const char *path, struct got_commit_object *commit,
5252 int show_ids, int recurse, const char *root_path,
5253 struct got_repository *repo)
5255 const struct got_error *err = NULL;
5256 struct got_object_id *tree_id = NULL;
5257 struct got_tree_object *tree = NULL;
5258 int nentries, i;
5260 err = got_object_id_by_path(&tree_id, repo, commit, path);
5261 if (err)
5262 goto done;
5264 err = got_object_open_as_tree(&tree, repo, tree_id);
5265 if (err)
5266 goto done;
5267 nentries = got_object_tree_get_nentries(tree);
5268 for (i = 0; i < nentries; i++) {
5269 struct got_tree_entry *te;
5270 char *id = NULL;
5272 if (sigint_received || sigpipe_received)
5273 break;
5275 te = got_object_tree_get_entry(tree, i);
5276 if (show_ids) {
5277 char *id_str;
5278 err = got_object_id_str(&id_str,
5279 got_tree_entry_get_id(te));
5280 if (err)
5281 goto done;
5282 if (asprintf(&id, "%s ", id_str) == -1) {
5283 err = got_error_from_errno("asprintf");
5284 free(id_str);
5285 goto done;
5287 free(id_str);
5289 err = print_entry(te, id, path, root_path, repo);
5290 free(id);
5291 if (err)
5292 goto done;
5294 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5295 char *child_path;
5296 if (asprintf(&child_path, "%s%s%s", path,
5297 path[0] == '/' && path[1] == '\0' ? "" : "/",
5298 got_tree_entry_get_name(te)) == -1) {
5299 err = got_error_from_errno("asprintf");
5300 goto done;
5302 err = print_tree(child_path, commit, show_ids, 1,
5303 root_path, repo);
5304 free(child_path);
5305 if (err)
5306 goto done;
5309 done:
5310 if (tree)
5311 got_object_tree_close(tree);
5312 free(tree_id);
5313 return err;
5316 static const struct got_error *
5317 cmd_tree(int argc, char *argv[])
5319 const struct got_error *error;
5320 struct got_repository *repo = NULL;
5321 struct got_worktree *worktree = NULL;
5322 const char *path, *refname = NULL;
5323 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5324 struct got_object_id *commit_id = NULL;
5325 struct got_commit_object *commit = NULL;
5326 char *commit_id_str = NULL;
5327 int show_ids = 0, recurse = 0;
5328 int ch;
5330 #ifndef PROFILE
5331 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5332 NULL) == -1)
5333 err(1, "pledge");
5334 #endif
5336 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5337 switch (ch) {
5338 case 'c':
5339 commit_id_str = optarg;
5340 break;
5341 case 'r':
5342 repo_path = realpath(optarg, NULL);
5343 if (repo_path == NULL)
5344 return got_error_from_errno2("realpath",
5345 optarg);
5346 got_path_strip_trailing_slashes(repo_path);
5347 break;
5348 case 'i':
5349 show_ids = 1;
5350 break;
5351 case 'R':
5352 recurse = 1;
5353 break;
5354 default:
5355 usage_tree();
5356 /* NOTREACHED */
5360 argc -= optind;
5361 argv += optind;
5363 if (argc == 1)
5364 path = argv[0];
5365 else if (argc > 1)
5366 usage_tree();
5367 else
5368 path = NULL;
5370 cwd = getcwd(NULL, 0);
5371 if (cwd == NULL) {
5372 error = got_error_from_errno("getcwd");
5373 goto done;
5375 if (repo_path == NULL) {
5376 error = got_worktree_open(&worktree, cwd);
5377 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5378 goto done;
5379 else
5380 error = NULL;
5381 if (worktree) {
5382 repo_path =
5383 strdup(got_worktree_get_repo_path(worktree));
5384 if (repo_path == NULL)
5385 error = got_error_from_errno("strdup");
5386 if (error)
5387 goto done;
5388 } else {
5389 repo_path = strdup(cwd);
5390 if (repo_path == NULL) {
5391 error = got_error_from_errno("strdup");
5392 goto done;
5397 error = got_repo_open(&repo, repo_path, NULL);
5398 if (error != NULL)
5399 goto done;
5401 if (worktree) {
5402 const char *prefix = got_worktree_get_path_prefix(worktree);
5403 char *p;
5405 if (path == NULL)
5406 path = "";
5407 error = got_worktree_resolve_path(&p, worktree, path);
5408 if (error)
5409 goto done;
5410 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5411 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5412 p) == -1) {
5413 error = got_error_from_errno("asprintf");
5414 free(p);
5415 goto done;
5417 free(p);
5418 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5419 if (error)
5420 goto done;
5421 } else {
5422 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5423 if (error)
5424 goto done;
5425 if (path == NULL)
5426 path = "/";
5427 error = got_repo_map_path(&in_repo_path, repo, path);
5428 if (error != NULL)
5429 goto done;
5432 if (commit_id_str == NULL) {
5433 struct got_reference *head_ref;
5434 if (worktree)
5435 refname = got_worktree_get_head_ref_name(worktree);
5436 else
5437 refname = GOT_REF_HEAD;
5438 error = got_ref_open(&head_ref, repo, refname, 0);
5439 if (error != NULL)
5440 goto done;
5441 error = got_ref_resolve(&commit_id, repo, head_ref);
5442 got_ref_close(head_ref);
5443 if (error != NULL)
5444 goto done;
5445 } else {
5446 struct got_reflist_head refs;
5447 TAILQ_INIT(&refs);
5448 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5449 NULL);
5450 if (error)
5451 goto done;
5452 error = got_repo_match_object_id(&commit_id, NULL,
5453 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5454 got_ref_list_free(&refs);
5455 if (error)
5456 goto done;
5459 if (worktree) {
5460 /* Release work tree lock. */
5461 got_worktree_close(worktree);
5462 worktree = NULL;
5465 error = got_object_open_as_commit(&commit, repo, commit_id);
5466 if (error)
5467 goto done;
5469 error = print_tree(in_repo_path, commit, show_ids, recurse,
5470 in_repo_path, repo);
5471 done:
5472 free(in_repo_path);
5473 free(repo_path);
5474 free(cwd);
5475 free(commit_id);
5476 if (commit)
5477 got_object_commit_close(commit);
5478 if (worktree)
5479 got_worktree_close(worktree);
5480 if (repo) {
5481 const struct got_error *close_err = got_repo_close(repo);
5482 if (error == NULL)
5483 error = close_err;
5485 return error;
5488 __dead static void
5489 usage_status(void)
5491 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5492 "[-S status-codes] [path ...]\n", getprogname());
5493 exit(1);
5496 struct got_status_arg {
5497 char *status_codes;
5498 int suppress;
5501 static const struct got_error *
5502 print_status(void *arg, unsigned char status, unsigned char staged_status,
5503 const char *path, struct got_object_id *blob_id,
5504 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5505 int dirfd, const char *de_name)
5507 struct got_status_arg *st = arg;
5509 if (status == staged_status && (status == GOT_STATUS_DELETE))
5510 status = GOT_STATUS_NO_CHANGE;
5511 if (st != NULL && st->status_codes) {
5512 size_t ncodes = strlen(st->status_codes);
5513 int i, j = 0;
5515 for (i = 0; i < ncodes ; i++) {
5516 if (st->suppress) {
5517 if (status == st->status_codes[i] ||
5518 staged_status == st->status_codes[i]) {
5519 j++;
5520 continue;
5522 } else {
5523 if (status == st->status_codes[i] ||
5524 staged_status == st->status_codes[i])
5525 break;
5529 if (st->suppress && j == 0)
5530 goto print;
5532 if (i == ncodes)
5533 return NULL;
5535 print:
5536 printf("%c%c %s\n", status, staged_status, path);
5537 return NULL;
5540 static const struct got_error *
5541 cmd_status(int argc, char *argv[])
5543 const struct got_error *error = NULL;
5544 struct got_repository *repo = NULL;
5545 struct got_worktree *worktree = NULL;
5546 struct got_status_arg st;
5547 char *cwd = NULL;
5548 struct got_pathlist_head paths;
5549 struct got_pathlist_entry *pe;
5550 int ch, i, no_ignores = 0;
5552 TAILQ_INIT(&paths);
5554 memset(&st, 0, sizeof(st));
5555 st.status_codes = NULL;
5556 st.suppress = 0;
5558 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5559 switch (ch) {
5560 case 'I':
5561 no_ignores = 1;
5562 break;
5563 case 'S':
5564 if (st.status_codes != NULL && st.suppress == 0)
5565 option_conflict('S', 's');
5566 st.suppress = 1;
5567 /* fallthrough */
5568 case 's':
5569 for (i = 0; i < strlen(optarg); i++) {
5570 switch (optarg[i]) {
5571 case GOT_STATUS_MODIFY:
5572 case GOT_STATUS_ADD:
5573 case GOT_STATUS_DELETE:
5574 case GOT_STATUS_CONFLICT:
5575 case GOT_STATUS_MISSING:
5576 case GOT_STATUS_OBSTRUCTED:
5577 case GOT_STATUS_UNVERSIONED:
5578 case GOT_STATUS_MODE_CHANGE:
5579 case GOT_STATUS_NONEXISTENT:
5580 break;
5581 default:
5582 errx(1, "invalid status code '%c'",
5583 optarg[i]);
5586 if (ch == 's' && st.suppress)
5587 option_conflict('s', 'S');
5588 st.status_codes = optarg;
5589 break;
5590 default:
5591 usage_status();
5592 /* NOTREACHED */
5596 argc -= optind;
5597 argv += optind;
5599 #ifndef PROFILE
5600 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5601 NULL) == -1)
5602 err(1, "pledge");
5603 #endif
5604 cwd = getcwd(NULL, 0);
5605 if (cwd == NULL) {
5606 error = got_error_from_errno("getcwd");
5607 goto done;
5610 error = got_worktree_open(&worktree, cwd);
5611 if (error) {
5612 if (error->code == GOT_ERR_NOT_WORKTREE)
5613 error = wrap_not_worktree_error(error, "status", cwd);
5614 goto done;
5617 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5618 NULL);
5619 if (error != NULL)
5620 goto done;
5622 error = apply_unveil(got_repo_get_path(repo), 1,
5623 got_worktree_get_root_path(worktree));
5624 if (error)
5625 goto done;
5627 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5628 if (error)
5629 goto done;
5631 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5632 print_status, &st, check_cancelled, NULL);
5633 done:
5634 TAILQ_FOREACH(pe, &paths, entry)
5635 free((char *)pe->path);
5636 got_pathlist_free(&paths);
5637 free(cwd);
5638 return error;
5641 __dead static void
5642 usage_ref(void)
5644 fprintf(stderr,
5645 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5646 "[-s reference] [-d] [name]\n",
5647 getprogname());
5648 exit(1);
5651 static const struct got_error *
5652 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5654 static const struct got_error *err = NULL;
5655 struct got_reflist_head refs;
5656 struct got_reflist_entry *re;
5658 TAILQ_INIT(&refs);
5659 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5660 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5661 repo);
5662 if (err)
5663 return err;
5665 TAILQ_FOREACH(re, &refs, entry) {
5666 char *refstr;
5667 refstr = got_ref_to_str(re->ref);
5668 if (refstr == NULL) {
5669 err = got_error_from_errno("got_ref_to_str");
5670 break;
5672 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5673 free(refstr);
5676 got_ref_list_free(&refs);
5677 return err;
5680 static const struct got_error *
5681 delete_ref_by_name(struct got_repository *repo, const char *refname)
5683 const struct got_error *err;
5684 struct got_reference *ref;
5686 err = got_ref_open(&ref, repo, refname, 0);
5687 if (err)
5688 return err;
5690 err = delete_ref(repo, ref);
5691 got_ref_close(ref);
5692 return err;
5695 static const struct got_error *
5696 add_ref(struct got_repository *repo, const char *refname, const char *target)
5698 const struct got_error *err = NULL;
5699 struct got_object_id *id = NULL;
5700 struct got_reference *ref = NULL;
5701 struct got_reflist_head refs;
5704 * Don't let the user create a reference name with a leading '-'.
5705 * While technically a valid reference name, this case is usually
5706 * an unintended typo.
5708 if (refname[0] == '-')
5709 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5711 TAILQ_INIT(&refs);
5712 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5713 if (err)
5714 goto done;
5715 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5716 &refs, repo);
5717 got_ref_list_free(&refs);
5718 if (err)
5719 goto done;
5721 err = got_ref_alloc(&ref, refname, id);
5722 if (err)
5723 goto done;
5725 err = got_ref_write(ref, repo);
5726 done:
5727 if (ref)
5728 got_ref_close(ref);
5729 free(id);
5730 return err;
5733 static const struct got_error *
5734 add_symref(struct got_repository *repo, const char *refname, const char *target)
5736 const struct got_error *err = NULL;
5737 struct got_reference *ref = NULL;
5738 struct got_reference *target_ref = NULL;
5741 * Don't let the user create a reference name with a leading '-'.
5742 * While technically a valid reference name, this case is usually
5743 * an unintended typo.
5745 if (refname[0] == '-')
5746 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5748 err = got_ref_open(&target_ref, repo, target, 0);
5749 if (err)
5750 return err;
5752 err = got_ref_alloc_symref(&ref, refname, target_ref);
5753 if (err)
5754 goto done;
5756 err = got_ref_write(ref, repo);
5757 done:
5758 if (target_ref)
5759 got_ref_close(target_ref);
5760 if (ref)
5761 got_ref_close(ref);
5762 return err;
5765 static const struct got_error *
5766 cmd_ref(int argc, char *argv[])
5768 const struct got_error *error = NULL;
5769 struct got_repository *repo = NULL;
5770 struct got_worktree *worktree = NULL;
5771 char *cwd = NULL, *repo_path = NULL;
5772 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5773 const char *obj_arg = NULL, *symref_target= NULL;
5774 char *refname = NULL;
5776 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5777 switch (ch) {
5778 case 'c':
5779 obj_arg = optarg;
5780 break;
5781 case 'd':
5782 do_delete = 1;
5783 break;
5784 case 'r':
5785 repo_path = realpath(optarg, NULL);
5786 if (repo_path == NULL)
5787 return got_error_from_errno2("realpath",
5788 optarg);
5789 got_path_strip_trailing_slashes(repo_path);
5790 break;
5791 case 'l':
5792 do_list = 1;
5793 break;
5794 case 's':
5795 symref_target = optarg;
5796 break;
5797 case 't':
5798 sort_by_time = 1;
5799 break;
5800 default:
5801 usage_ref();
5802 /* NOTREACHED */
5806 if (obj_arg && do_list)
5807 option_conflict('c', 'l');
5808 if (obj_arg && do_delete)
5809 option_conflict('c', 'd');
5810 if (obj_arg && symref_target)
5811 option_conflict('c', 's');
5812 if (symref_target && do_delete)
5813 option_conflict('s', 'd');
5814 if (symref_target && do_list)
5815 option_conflict('s', 'l');
5816 if (do_delete && do_list)
5817 option_conflict('d', 'l');
5818 if (sort_by_time && !do_list)
5819 errx(1, "-t option requires -l option");
5821 argc -= optind;
5822 argv += optind;
5824 if (do_list) {
5825 if (argc != 0 && argc != 1)
5826 usage_ref();
5827 if (argc == 1) {
5828 refname = strdup(argv[0]);
5829 if (refname == NULL) {
5830 error = got_error_from_errno("strdup");
5831 goto done;
5834 } else {
5835 if (argc != 1)
5836 usage_ref();
5837 refname = strdup(argv[0]);
5838 if (refname == NULL) {
5839 error = got_error_from_errno("strdup");
5840 goto done;
5844 if (refname)
5845 got_path_strip_trailing_slashes(refname);
5847 #ifndef PROFILE
5848 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5849 "sendfd unveil", NULL) == -1)
5850 err(1, "pledge");
5851 #endif
5852 cwd = getcwd(NULL, 0);
5853 if (cwd == NULL) {
5854 error = got_error_from_errno("getcwd");
5855 goto done;
5858 if (repo_path == NULL) {
5859 error = got_worktree_open(&worktree, cwd);
5860 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5861 goto done;
5862 else
5863 error = NULL;
5864 if (worktree) {
5865 repo_path =
5866 strdup(got_worktree_get_repo_path(worktree));
5867 if (repo_path == NULL)
5868 error = got_error_from_errno("strdup");
5869 if (error)
5870 goto done;
5871 } else {
5872 repo_path = strdup(cwd);
5873 if (repo_path == NULL) {
5874 error = got_error_from_errno("strdup");
5875 goto done;
5880 error = got_repo_open(&repo, repo_path, NULL);
5881 if (error != NULL)
5882 goto done;
5884 #ifndef PROFILE
5885 if (do_list) {
5886 /* Remove "cpath" promise. */
5887 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5888 NULL) == -1)
5889 err(1, "pledge");
5891 #endif
5893 error = apply_unveil(got_repo_get_path(repo), do_list,
5894 worktree ? got_worktree_get_root_path(worktree) : NULL);
5895 if (error)
5896 goto done;
5898 if (do_list)
5899 error = list_refs(repo, refname, sort_by_time);
5900 else if (do_delete)
5901 error = delete_ref_by_name(repo, refname);
5902 else if (symref_target)
5903 error = add_symref(repo, refname, symref_target);
5904 else {
5905 if (obj_arg == NULL)
5906 usage_ref();
5907 error = add_ref(repo, refname, obj_arg);
5909 done:
5910 free(refname);
5911 if (repo) {
5912 const struct got_error *close_err = got_repo_close(repo);
5913 if (error == NULL)
5914 error = close_err;
5916 if (worktree)
5917 got_worktree_close(worktree);
5918 free(cwd);
5919 free(repo_path);
5920 return error;
5923 __dead static void
5924 usage_branch(void)
5926 fprintf(stderr,
5927 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5928 "[-n] [name]\n", getprogname());
5929 exit(1);
5932 static const struct got_error *
5933 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5934 struct got_reference *ref)
5936 const struct got_error *err = NULL;
5937 const char *refname, *marker = " ";
5938 char *refstr;
5940 refname = got_ref_get_name(ref);
5941 if (worktree && strcmp(refname,
5942 got_worktree_get_head_ref_name(worktree)) == 0) {
5943 struct got_object_id *id = NULL;
5945 err = got_ref_resolve(&id, repo, ref);
5946 if (err)
5947 return err;
5948 if (got_object_id_cmp(id,
5949 got_worktree_get_base_commit_id(worktree)) == 0)
5950 marker = "* ";
5951 else
5952 marker = "~ ";
5953 free(id);
5956 if (strncmp(refname, "refs/heads/", 11) == 0)
5957 refname += 11;
5958 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5959 refname += 18;
5960 if (strncmp(refname, "refs/remotes/", 13) == 0)
5961 refname += 13;
5963 refstr = got_ref_to_str(ref);
5964 if (refstr == NULL)
5965 return got_error_from_errno("got_ref_to_str");
5967 printf("%s%s: %s\n", marker, refname, refstr);
5968 free(refstr);
5969 return NULL;
5972 static const struct got_error *
5973 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5975 const char *refname;
5977 if (worktree == NULL)
5978 return got_error(GOT_ERR_NOT_WORKTREE);
5980 refname = got_worktree_get_head_ref_name(worktree);
5982 if (strncmp(refname, "refs/heads/", 11) == 0)
5983 refname += 11;
5984 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5985 refname += 18;
5987 printf("%s\n", refname);
5989 return NULL;
5992 static const struct got_error *
5993 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5994 int sort_by_time)
5996 static const struct got_error *err = NULL;
5997 struct got_reflist_head refs;
5998 struct got_reflist_entry *re;
5999 struct got_reference *temp_ref = NULL;
6000 int rebase_in_progress, histedit_in_progress;
6002 TAILQ_INIT(&refs);
6004 if (worktree) {
6005 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6006 worktree);
6007 if (err)
6008 return err;
6010 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6011 worktree);
6012 if (err)
6013 return err;
6015 if (rebase_in_progress || histedit_in_progress) {
6016 err = got_ref_open(&temp_ref, repo,
6017 got_worktree_get_head_ref_name(worktree), 0);
6018 if (err)
6019 return err;
6020 list_branch(repo, worktree, temp_ref);
6021 got_ref_close(temp_ref);
6025 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6026 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6027 repo);
6028 if (err)
6029 return err;
6031 TAILQ_FOREACH(re, &refs, entry)
6032 list_branch(repo, worktree, re->ref);
6034 got_ref_list_free(&refs);
6036 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6037 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6038 repo);
6039 if (err)
6040 return err;
6042 TAILQ_FOREACH(re, &refs, entry)
6043 list_branch(repo, worktree, re->ref);
6045 got_ref_list_free(&refs);
6047 return NULL;
6050 static const struct got_error *
6051 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6052 const char *branch_name)
6054 const struct got_error *err = NULL;
6055 struct got_reference *ref = NULL;
6056 char *refname, *remote_refname = NULL;
6058 if (strncmp(branch_name, "refs/", 5) == 0)
6059 branch_name += 5;
6060 if (strncmp(branch_name, "heads/", 6) == 0)
6061 branch_name += 6;
6062 else if (strncmp(branch_name, "remotes/", 8) == 0)
6063 branch_name += 8;
6065 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6066 return got_error_from_errno("asprintf");
6068 if (asprintf(&remote_refname, "refs/remotes/%s",
6069 branch_name) == -1) {
6070 err = got_error_from_errno("asprintf");
6071 goto done;
6074 err = got_ref_open(&ref, repo, refname, 0);
6075 if (err) {
6076 const struct got_error *err2;
6077 if (err->code != GOT_ERR_NOT_REF)
6078 goto done;
6080 * Keep 'err' intact such that if neither branch exists
6081 * we report "refs/heads" rather than "refs/remotes" in
6082 * our error message.
6084 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6085 if (err2)
6086 goto done;
6087 err = NULL;
6090 if (worktree &&
6091 strcmp(got_worktree_get_head_ref_name(worktree),
6092 got_ref_get_name(ref)) == 0) {
6093 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6094 "will not delete this work tree's current branch");
6095 goto done;
6098 err = delete_ref(repo, ref);
6099 done:
6100 if (ref)
6101 got_ref_close(ref);
6102 free(refname);
6103 free(remote_refname);
6104 return err;
6107 static const struct got_error *
6108 add_branch(struct got_repository *repo, const char *branch_name,
6109 struct got_object_id *base_commit_id)
6111 const struct got_error *err = NULL;
6112 struct got_reference *ref = NULL;
6113 char *base_refname = NULL, *refname = NULL;
6116 * Don't let the user create a branch name with a leading '-'.
6117 * While technically a valid reference name, this case is usually
6118 * an unintended typo.
6120 if (branch_name[0] == '-')
6121 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6123 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6124 branch_name += 11;
6126 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6127 err = got_error_from_errno("asprintf");
6128 goto done;
6131 err = got_ref_open(&ref, repo, refname, 0);
6132 if (err == NULL) {
6133 err = got_error(GOT_ERR_BRANCH_EXISTS);
6134 goto done;
6135 } else if (err->code != GOT_ERR_NOT_REF)
6136 goto done;
6138 err = got_ref_alloc(&ref, refname, base_commit_id);
6139 if (err)
6140 goto done;
6142 err = got_ref_write(ref, repo);
6143 done:
6144 if (ref)
6145 got_ref_close(ref);
6146 free(base_refname);
6147 free(refname);
6148 return err;
6151 static const struct got_error *
6152 cmd_branch(int argc, char *argv[])
6154 const struct got_error *error = NULL;
6155 struct got_repository *repo = NULL;
6156 struct got_worktree *worktree = NULL;
6157 char *cwd = NULL, *repo_path = NULL;
6158 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6159 const char *delref = NULL, *commit_id_arg = NULL;
6160 struct got_reference *ref = NULL;
6161 struct got_pathlist_head paths;
6162 struct got_pathlist_entry *pe;
6163 struct got_object_id *commit_id = NULL;
6164 char *commit_id_str = NULL;
6166 TAILQ_INIT(&paths);
6168 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6169 switch (ch) {
6170 case 'c':
6171 commit_id_arg = optarg;
6172 break;
6173 case 'd':
6174 delref = optarg;
6175 break;
6176 case 'r':
6177 repo_path = realpath(optarg, NULL);
6178 if (repo_path == NULL)
6179 return got_error_from_errno2("realpath",
6180 optarg);
6181 got_path_strip_trailing_slashes(repo_path);
6182 break;
6183 case 'l':
6184 do_list = 1;
6185 break;
6186 case 'n':
6187 do_update = 0;
6188 break;
6189 case 't':
6190 sort_by_time = 1;
6191 break;
6192 default:
6193 usage_branch();
6194 /* NOTREACHED */
6198 if (do_list && delref)
6199 option_conflict('l', 'd');
6200 if (sort_by_time && !do_list)
6201 errx(1, "-t option requires -l option");
6203 argc -= optind;
6204 argv += optind;
6206 if (!do_list && !delref && argc == 0)
6207 do_show = 1;
6209 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6210 errx(1, "-c option can only be used when creating a branch");
6212 if (do_list || delref) {
6213 if (argc > 0)
6214 usage_branch();
6215 } else if (!do_show && argc != 1)
6216 usage_branch();
6218 #ifndef PROFILE
6219 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6220 "sendfd unveil", NULL) == -1)
6221 err(1, "pledge");
6222 #endif
6223 cwd = getcwd(NULL, 0);
6224 if (cwd == NULL) {
6225 error = got_error_from_errno("getcwd");
6226 goto done;
6229 if (repo_path == NULL) {
6230 error = got_worktree_open(&worktree, cwd);
6231 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6232 goto done;
6233 else
6234 error = NULL;
6235 if (worktree) {
6236 repo_path =
6237 strdup(got_worktree_get_repo_path(worktree));
6238 if (repo_path == NULL)
6239 error = got_error_from_errno("strdup");
6240 if (error)
6241 goto done;
6242 } else {
6243 repo_path = strdup(cwd);
6244 if (repo_path == NULL) {
6245 error = got_error_from_errno("strdup");
6246 goto done;
6251 error = got_repo_open(&repo, repo_path, NULL);
6252 if (error != NULL)
6253 goto done;
6255 #ifndef PROFILE
6256 if (do_list || do_show) {
6257 /* Remove "cpath" promise. */
6258 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6259 NULL) == -1)
6260 err(1, "pledge");
6262 #endif
6264 error = apply_unveil(got_repo_get_path(repo), do_list,
6265 worktree ? got_worktree_get_root_path(worktree) : NULL);
6266 if (error)
6267 goto done;
6269 if (do_show)
6270 error = show_current_branch(repo, worktree);
6271 else if (do_list)
6272 error = list_branches(repo, worktree, sort_by_time);
6273 else if (delref)
6274 error = delete_branch(repo, worktree, delref);
6275 else {
6276 struct got_reflist_head refs;
6277 TAILQ_INIT(&refs);
6278 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6279 NULL);
6280 if (error)
6281 goto done;
6282 if (commit_id_arg == NULL)
6283 commit_id_arg = worktree ?
6284 got_worktree_get_head_ref_name(worktree) :
6285 GOT_REF_HEAD;
6286 error = got_repo_match_object_id(&commit_id, NULL,
6287 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6288 got_ref_list_free(&refs);
6289 if (error)
6290 goto done;
6291 error = add_branch(repo, argv[0], commit_id);
6292 if (error)
6293 goto done;
6294 if (worktree && do_update) {
6295 struct got_update_progress_arg upa;
6296 char *branch_refname = NULL;
6298 error = got_object_id_str(&commit_id_str, commit_id);
6299 if (error)
6300 goto done;
6301 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6302 worktree);
6303 if (error)
6304 goto done;
6305 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6306 == -1) {
6307 error = got_error_from_errno("asprintf");
6308 goto done;
6310 error = got_ref_open(&ref, repo, branch_refname, 0);
6311 free(branch_refname);
6312 if (error)
6313 goto done;
6314 error = switch_head_ref(ref, commit_id, worktree,
6315 repo);
6316 if (error)
6317 goto done;
6318 error = got_worktree_set_base_commit_id(worktree, repo,
6319 commit_id);
6320 if (error)
6321 goto done;
6322 memset(&upa, 0, sizeof(upa));
6323 error = got_worktree_checkout_files(worktree, &paths,
6324 repo, update_progress, &upa, check_cancelled,
6325 NULL);
6326 if (error)
6327 goto done;
6328 if (upa.did_something) {
6329 printf("Updated to %s: %s\n",
6330 got_worktree_get_head_ref_name(worktree),
6331 commit_id_str);
6333 print_update_progress_stats(&upa);
6336 done:
6337 if (ref)
6338 got_ref_close(ref);
6339 if (repo) {
6340 const struct got_error *close_err = got_repo_close(repo);
6341 if (error == NULL)
6342 error = close_err;
6344 if (worktree)
6345 got_worktree_close(worktree);
6346 free(cwd);
6347 free(repo_path);
6348 free(commit_id);
6349 free(commit_id_str);
6350 TAILQ_FOREACH(pe, &paths, entry)
6351 free((char *)pe->path);
6352 got_pathlist_free(&paths);
6353 return error;
6357 __dead static void
6358 usage_tag(void)
6360 fprintf(stderr,
6361 "usage: %s tag [-c commit] [-r repository] [-l] "
6362 "[-m message] name\n", getprogname());
6363 exit(1);
6366 #if 0
6367 static const struct got_error *
6368 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6370 const struct got_error *err = NULL;
6371 struct got_reflist_entry *re, *se, *new;
6372 struct got_object_id *re_id, *se_id;
6373 struct got_tag_object *re_tag, *se_tag;
6374 time_t re_time, se_time;
6376 STAILQ_FOREACH(re, tags, entry) {
6377 se = STAILQ_FIRST(sorted);
6378 if (se == NULL) {
6379 err = got_reflist_entry_dup(&new, re);
6380 if (err)
6381 return err;
6382 STAILQ_INSERT_HEAD(sorted, new, entry);
6383 continue;
6384 } else {
6385 err = got_ref_resolve(&re_id, repo, re->ref);
6386 if (err)
6387 break;
6388 err = got_object_open_as_tag(&re_tag, repo, re_id);
6389 free(re_id);
6390 if (err)
6391 break;
6392 re_time = got_object_tag_get_tagger_time(re_tag);
6393 got_object_tag_close(re_tag);
6396 while (se) {
6397 err = got_ref_resolve(&se_id, repo, re->ref);
6398 if (err)
6399 break;
6400 err = got_object_open_as_tag(&se_tag, repo, se_id);
6401 free(se_id);
6402 if (err)
6403 break;
6404 se_time = got_object_tag_get_tagger_time(se_tag);
6405 got_object_tag_close(se_tag);
6407 if (se_time > re_time) {
6408 err = got_reflist_entry_dup(&new, re);
6409 if (err)
6410 return err;
6411 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6412 break;
6414 se = STAILQ_NEXT(se, entry);
6415 continue;
6418 done:
6419 return err;
6421 #endif
6423 static const struct got_error *
6424 list_tags(struct got_repository *repo)
6426 static const struct got_error *err = NULL;
6427 struct got_reflist_head refs;
6428 struct got_reflist_entry *re;
6430 TAILQ_INIT(&refs);
6432 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6433 if (err)
6434 return err;
6436 TAILQ_FOREACH(re, &refs, entry) {
6437 const char *refname;
6438 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6439 char datebuf[26];
6440 const char *tagger;
6441 time_t tagger_time;
6442 struct got_object_id *id;
6443 struct got_tag_object *tag;
6444 struct got_commit_object *commit = NULL;
6446 refname = got_ref_get_name(re->ref);
6447 if (strncmp(refname, "refs/tags/", 10) != 0)
6448 continue;
6449 refname += 10;
6450 refstr = got_ref_to_str(re->ref);
6451 if (refstr == NULL) {
6452 err = got_error_from_errno("got_ref_to_str");
6453 break;
6455 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6456 free(refstr);
6458 err = got_ref_resolve(&id, repo, re->ref);
6459 if (err)
6460 break;
6461 err = got_object_open_as_tag(&tag, repo, id);
6462 if (err) {
6463 if (err->code != GOT_ERR_OBJ_TYPE) {
6464 free(id);
6465 break;
6467 /* "lightweight" tag */
6468 err = got_object_open_as_commit(&commit, repo, id);
6469 if (err) {
6470 free(id);
6471 break;
6473 tagger = got_object_commit_get_committer(commit);
6474 tagger_time =
6475 got_object_commit_get_committer_time(commit);
6476 err = got_object_id_str(&id_str, id);
6477 free(id);
6478 if (err)
6479 break;
6480 } else {
6481 free(id);
6482 tagger = got_object_tag_get_tagger(tag);
6483 tagger_time = got_object_tag_get_tagger_time(tag);
6484 err = got_object_id_str(&id_str,
6485 got_object_tag_get_object_id(tag));
6486 if (err)
6487 break;
6489 printf("from: %s\n", tagger);
6490 datestr = get_datestr(&tagger_time, datebuf);
6491 if (datestr)
6492 printf("date: %s UTC\n", datestr);
6493 if (commit)
6494 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6495 else {
6496 switch (got_object_tag_get_object_type(tag)) {
6497 case GOT_OBJ_TYPE_BLOB:
6498 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6499 id_str);
6500 break;
6501 case GOT_OBJ_TYPE_TREE:
6502 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6503 id_str);
6504 break;
6505 case GOT_OBJ_TYPE_COMMIT:
6506 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6507 id_str);
6508 break;
6509 case GOT_OBJ_TYPE_TAG:
6510 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6511 id_str);
6512 break;
6513 default:
6514 break;
6517 free(id_str);
6518 if (commit) {
6519 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6520 if (err)
6521 break;
6522 got_object_commit_close(commit);
6523 } else {
6524 tagmsg0 = strdup(got_object_tag_get_message(tag));
6525 got_object_tag_close(tag);
6526 if (tagmsg0 == NULL) {
6527 err = got_error_from_errno("strdup");
6528 break;
6532 tagmsg = tagmsg0;
6533 do {
6534 line = strsep(&tagmsg, "\n");
6535 if (line)
6536 printf(" %s\n", line);
6537 } while (line);
6538 free(tagmsg0);
6541 got_ref_list_free(&refs);
6542 return NULL;
6545 static const struct got_error *
6546 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6547 const char *tag_name, const char *repo_path)
6549 const struct got_error *err = NULL;
6550 char *template = NULL, *initial_content = NULL;
6551 char *editor = NULL;
6552 int initial_content_len;
6553 int fd = -1;
6555 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6556 err = got_error_from_errno("asprintf");
6557 goto done;
6560 initial_content_len = asprintf(&initial_content,
6561 "\n# tagging commit %s as %s\n",
6562 commit_id_str, tag_name);
6563 if (initial_content_len == -1) {
6564 err = got_error_from_errno("asprintf");
6565 goto done;
6568 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6569 if (err)
6570 goto done;
6572 if (write(fd, initial_content, initial_content_len) == -1) {
6573 err = got_error_from_errno2("write", *tagmsg_path);
6574 goto done;
6577 err = get_editor(&editor);
6578 if (err)
6579 goto done;
6580 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6581 initial_content_len, 1);
6582 done:
6583 free(initial_content);
6584 free(template);
6585 free(editor);
6587 if (fd != -1 && close(fd) == -1 && err == NULL)
6588 err = got_error_from_errno2("close", *tagmsg_path);
6590 /* Editor is done; we can now apply unveil(2) */
6591 if (err == NULL)
6592 err = apply_unveil(repo_path, 0, NULL);
6593 if (err) {
6594 free(*tagmsg);
6595 *tagmsg = NULL;
6597 return err;
6600 static const struct got_error *
6601 add_tag(struct got_repository *repo, const char *tagger,
6602 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6604 const struct got_error *err = NULL;
6605 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6606 char *label = NULL, *commit_id_str = NULL;
6607 struct got_reference *ref = NULL;
6608 char *refname = NULL, *tagmsg = NULL;
6609 char *tagmsg_path = NULL, *tag_id_str = NULL;
6610 int preserve_tagmsg = 0;
6611 struct got_reflist_head refs;
6613 TAILQ_INIT(&refs);
6616 * Don't let the user create a tag name with a leading '-'.
6617 * While technically a valid reference name, this case is usually
6618 * an unintended typo.
6620 if (tag_name[0] == '-')
6621 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6623 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6624 if (err)
6625 goto done;
6627 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6628 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6629 if (err)
6630 goto done;
6632 err = got_object_id_str(&commit_id_str, commit_id);
6633 if (err)
6634 goto done;
6636 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6637 refname = strdup(tag_name);
6638 if (refname == NULL) {
6639 err = got_error_from_errno("strdup");
6640 goto done;
6642 tag_name += 10;
6643 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6644 err = got_error_from_errno("asprintf");
6645 goto done;
6648 err = got_ref_open(&ref, repo, refname, 0);
6649 if (err == NULL) {
6650 err = got_error(GOT_ERR_TAG_EXISTS);
6651 goto done;
6652 } else if (err->code != GOT_ERR_NOT_REF)
6653 goto done;
6655 if (tagmsg_arg == NULL) {
6656 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6657 tag_name, got_repo_get_path(repo));
6658 if (err) {
6659 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6660 tagmsg_path != NULL)
6661 preserve_tagmsg = 1;
6662 goto done;
6666 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6667 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6668 if (err) {
6669 if (tagmsg_path)
6670 preserve_tagmsg = 1;
6671 goto done;
6674 err = got_ref_alloc(&ref, refname, tag_id);
6675 if (err) {
6676 if (tagmsg_path)
6677 preserve_tagmsg = 1;
6678 goto done;
6681 err = got_ref_write(ref, repo);
6682 if (err) {
6683 if (tagmsg_path)
6684 preserve_tagmsg = 1;
6685 goto done;
6688 err = got_object_id_str(&tag_id_str, tag_id);
6689 if (err) {
6690 if (tagmsg_path)
6691 preserve_tagmsg = 1;
6692 goto done;
6694 printf("Created tag %s\n", tag_id_str);
6695 done:
6696 if (preserve_tagmsg) {
6697 fprintf(stderr, "%s: tag message preserved in %s\n",
6698 getprogname(), tagmsg_path);
6699 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6700 err = got_error_from_errno2("unlink", tagmsg_path);
6701 free(tag_id_str);
6702 if (ref)
6703 got_ref_close(ref);
6704 free(commit_id);
6705 free(commit_id_str);
6706 free(refname);
6707 free(tagmsg);
6708 free(tagmsg_path);
6709 got_ref_list_free(&refs);
6710 return err;
6713 static const struct got_error *
6714 cmd_tag(int argc, char *argv[])
6716 const struct got_error *error = NULL;
6717 struct got_repository *repo = NULL;
6718 struct got_worktree *worktree = NULL;
6719 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6720 char *gitconfig_path = NULL, *tagger = NULL;
6721 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6722 int ch, do_list = 0;
6724 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6725 switch (ch) {
6726 case 'c':
6727 commit_id_arg = optarg;
6728 break;
6729 case 'm':
6730 tagmsg = optarg;
6731 break;
6732 case 'r':
6733 repo_path = realpath(optarg, NULL);
6734 if (repo_path == NULL)
6735 return got_error_from_errno2("realpath",
6736 optarg);
6737 got_path_strip_trailing_slashes(repo_path);
6738 break;
6739 case 'l':
6740 do_list = 1;
6741 break;
6742 default:
6743 usage_tag();
6744 /* NOTREACHED */
6748 argc -= optind;
6749 argv += optind;
6751 if (do_list) {
6752 if (commit_id_arg != NULL)
6753 errx(1,
6754 "-c option can only be used when creating a tag");
6755 if (tagmsg)
6756 option_conflict('l', 'm');
6757 if (argc > 0)
6758 usage_tag();
6759 } else if (argc != 1)
6760 usage_tag();
6762 tag_name = argv[0];
6764 #ifndef PROFILE
6765 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6766 "sendfd unveil", NULL) == -1)
6767 err(1, "pledge");
6768 #endif
6769 cwd = getcwd(NULL, 0);
6770 if (cwd == NULL) {
6771 error = got_error_from_errno("getcwd");
6772 goto done;
6775 if (repo_path == NULL) {
6776 error = got_worktree_open(&worktree, cwd);
6777 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6778 goto done;
6779 else
6780 error = NULL;
6781 if (worktree) {
6782 repo_path =
6783 strdup(got_worktree_get_repo_path(worktree));
6784 if (repo_path == NULL)
6785 error = got_error_from_errno("strdup");
6786 if (error)
6787 goto done;
6788 } else {
6789 repo_path = strdup(cwd);
6790 if (repo_path == NULL) {
6791 error = got_error_from_errno("strdup");
6792 goto done;
6797 if (do_list) {
6798 if (worktree) {
6799 /* Release work tree lock. */
6800 got_worktree_close(worktree);
6801 worktree = NULL;
6803 error = got_repo_open(&repo, repo_path, NULL);
6804 if (error != NULL)
6805 goto done;
6806 #ifndef PROFILE
6807 /* Remove "cpath" promise. */
6808 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6809 NULL) == -1)
6810 err(1, "pledge");
6811 #endif
6812 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6813 if (error)
6814 goto done;
6815 error = list_tags(repo);
6816 } else {
6817 error = get_gitconfig_path(&gitconfig_path);
6818 if (error)
6819 goto done;
6820 error = got_repo_open(&repo, repo_path, gitconfig_path);
6821 if (error != NULL)
6822 goto done;
6824 error = get_author(&tagger, repo, worktree);
6825 if (error)
6826 goto done;
6827 if (worktree) {
6828 /* Release work tree lock. */
6829 got_worktree_close(worktree);
6830 worktree = NULL;
6833 if (tagmsg) {
6834 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6835 if (error)
6836 goto done;
6839 if (commit_id_arg == NULL) {
6840 struct got_reference *head_ref;
6841 struct got_object_id *commit_id;
6842 error = got_ref_open(&head_ref, repo,
6843 worktree ? got_worktree_get_head_ref_name(worktree)
6844 : GOT_REF_HEAD, 0);
6845 if (error)
6846 goto done;
6847 error = got_ref_resolve(&commit_id, repo, head_ref);
6848 got_ref_close(head_ref);
6849 if (error)
6850 goto done;
6851 error = got_object_id_str(&commit_id_str, commit_id);
6852 free(commit_id);
6853 if (error)
6854 goto done;
6857 error = add_tag(repo, tagger, tag_name,
6858 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6860 done:
6861 if (repo) {
6862 const struct got_error *close_err = got_repo_close(repo);
6863 if (error == NULL)
6864 error = close_err;
6866 if (worktree)
6867 got_worktree_close(worktree);
6868 free(cwd);
6869 free(repo_path);
6870 free(gitconfig_path);
6871 free(commit_id_str);
6872 free(tagger);
6873 return error;
6876 __dead static void
6877 usage_add(void)
6879 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6880 getprogname());
6881 exit(1);
6884 static const struct got_error *
6885 add_progress(void *arg, unsigned char status, const char *path)
6887 while (path[0] == '/')
6888 path++;
6889 printf("%c %s\n", status, path);
6890 return NULL;
6893 static const struct got_error *
6894 cmd_add(int argc, char *argv[])
6896 const struct got_error *error = NULL;
6897 struct got_repository *repo = NULL;
6898 struct got_worktree *worktree = NULL;
6899 char *cwd = NULL;
6900 struct got_pathlist_head paths;
6901 struct got_pathlist_entry *pe;
6902 int ch, can_recurse = 0, no_ignores = 0;
6904 TAILQ_INIT(&paths);
6906 while ((ch = getopt(argc, argv, "IR")) != -1) {
6907 switch (ch) {
6908 case 'I':
6909 no_ignores = 1;
6910 break;
6911 case 'R':
6912 can_recurse = 1;
6913 break;
6914 default:
6915 usage_add();
6916 /* NOTREACHED */
6920 argc -= optind;
6921 argv += optind;
6923 #ifndef PROFILE
6924 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6925 NULL) == -1)
6926 err(1, "pledge");
6927 #endif
6928 if (argc < 1)
6929 usage_add();
6931 cwd = getcwd(NULL, 0);
6932 if (cwd == NULL) {
6933 error = got_error_from_errno("getcwd");
6934 goto done;
6937 error = got_worktree_open(&worktree, cwd);
6938 if (error) {
6939 if (error->code == GOT_ERR_NOT_WORKTREE)
6940 error = wrap_not_worktree_error(error, "add", cwd);
6941 goto done;
6944 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6945 NULL);
6946 if (error != NULL)
6947 goto done;
6949 error = apply_unveil(got_repo_get_path(repo), 1,
6950 got_worktree_get_root_path(worktree));
6951 if (error)
6952 goto done;
6954 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6955 if (error)
6956 goto done;
6958 if (!can_recurse) {
6959 char *ondisk_path;
6960 struct stat sb;
6961 TAILQ_FOREACH(pe, &paths, entry) {
6962 if (asprintf(&ondisk_path, "%s/%s",
6963 got_worktree_get_root_path(worktree),
6964 pe->path) == -1) {
6965 error = got_error_from_errno("asprintf");
6966 goto done;
6968 if (lstat(ondisk_path, &sb) == -1) {
6969 if (errno == ENOENT) {
6970 free(ondisk_path);
6971 continue;
6973 error = got_error_from_errno2("lstat",
6974 ondisk_path);
6975 free(ondisk_path);
6976 goto done;
6978 free(ondisk_path);
6979 if (S_ISDIR(sb.st_mode)) {
6980 error = got_error_msg(GOT_ERR_BAD_PATH,
6981 "adding directories requires -R option");
6982 goto done;
6987 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6988 NULL, repo, no_ignores);
6989 done:
6990 if (repo) {
6991 const struct got_error *close_err = got_repo_close(repo);
6992 if (error == NULL)
6993 error = close_err;
6995 if (worktree)
6996 got_worktree_close(worktree);
6997 TAILQ_FOREACH(pe, &paths, entry)
6998 free((char *)pe->path);
6999 got_pathlist_free(&paths);
7000 free(cwd);
7001 return error;
7004 __dead static void
7005 usage_remove(void)
7007 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7008 "path ...\n", getprogname());
7009 exit(1);
7012 static const struct got_error *
7013 print_remove_status(void *arg, unsigned char status,
7014 unsigned char staged_status, const char *path)
7016 while (path[0] == '/')
7017 path++;
7018 if (status == GOT_STATUS_NONEXISTENT)
7019 return NULL;
7020 if (status == staged_status && (status == GOT_STATUS_DELETE))
7021 status = GOT_STATUS_NO_CHANGE;
7022 printf("%c%c %s\n", status, staged_status, path);
7023 return NULL;
7026 static const struct got_error *
7027 cmd_remove(int argc, char *argv[])
7029 const struct got_error *error = NULL;
7030 struct got_worktree *worktree = NULL;
7031 struct got_repository *repo = NULL;
7032 const char *status_codes = NULL;
7033 char *cwd = NULL;
7034 struct got_pathlist_head paths;
7035 struct got_pathlist_entry *pe;
7036 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7037 int ignore_missing_paths = 0;
7039 TAILQ_INIT(&paths);
7041 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7042 switch (ch) {
7043 case 'f':
7044 delete_local_mods = 1;
7045 ignore_missing_paths = 1;
7046 break;
7047 case 'k':
7048 keep_on_disk = 1;
7049 break;
7050 case 'R':
7051 can_recurse = 1;
7052 break;
7053 case 's':
7054 for (i = 0; i < strlen(optarg); i++) {
7055 switch (optarg[i]) {
7056 case GOT_STATUS_MODIFY:
7057 delete_local_mods = 1;
7058 break;
7059 case GOT_STATUS_MISSING:
7060 ignore_missing_paths = 1;
7061 break;
7062 default:
7063 errx(1, "invalid status code '%c'",
7064 optarg[i]);
7067 status_codes = optarg;
7068 break;
7069 default:
7070 usage_remove();
7071 /* NOTREACHED */
7075 argc -= optind;
7076 argv += optind;
7078 #ifndef PROFILE
7079 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7080 NULL) == -1)
7081 err(1, "pledge");
7082 #endif
7083 if (argc < 1)
7084 usage_remove();
7086 cwd = getcwd(NULL, 0);
7087 if (cwd == NULL) {
7088 error = got_error_from_errno("getcwd");
7089 goto done;
7091 error = got_worktree_open(&worktree, cwd);
7092 if (error) {
7093 if (error->code == GOT_ERR_NOT_WORKTREE)
7094 error = wrap_not_worktree_error(error, "remove", cwd);
7095 goto done;
7098 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7099 NULL);
7100 if (error)
7101 goto done;
7103 error = apply_unveil(got_repo_get_path(repo), 1,
7104 got_worktree_get_root_path(worktree));
7105 if (error)
7106 goto done;
7108 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7109 if (error)
7110 goto done;
7112 if (!can_recurse) {
7113 char *ondisk_path;
7114 struct stat sb;
7115 TAILQ_FOREACH(pe, &paths, entry) {
7116 if (asprintf(&ondisk_path, "%s/%s",
7117 got_worktree_get_root_path(worktree),
7118 pe->path) == -1) {
7119 error = got_error_from_errno("asprintf");
7120 goto done;
7122 if (lstat(ondisk_path, &sb) == -1) {
7123 if (errno == ENOENT) {
7124 free(ondisk_path);
7125 continue;
7127 error = got_error_from_errno2("lstat",
7128 ondisk_path);
7129 free(ondisk_path);
7130 goto done;
7132 free(ondisk_path);
7133 if (S_ISDIR(sb.st_mode)) {
7134 error = got_error_msg(GOT_ERR_BAD_PATH,
7135 "removing directories requires -R option");
7136 goto done;
7141 error = got_worktree_schedule_delete(worktree, &paths,
7142 delete_local_mods, status_codes, print_remove_status, NULL,
7143 repo, keep_on_disk, ignore_missing_paths);
7144 done:
7145 if (repo) {
7146 const struct got_error *close_err = got_repo_close(repo);
7147 if (error == NULL)
7148 error = close_err;
7150 if (worktree)
7151 got_worktree_close(worktree);
7152 TAILQ_FOREACH(pe, &paths, entry)
7153 free((char *)pe->path);
7154 got_pathlist_free(&paths);
7155 free(cwd);
7156 return error;
7159 __dead static void
7160 usage_patch(void)
7162 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7163 "[-R] [patchfile]\n", getprogname());
7164 exit(1);
7167 static const struct got_error *
7168 patch_from_stdin(int *patchfd)
7170 const struct got_error *err = NULL;
7171 ssize_t r;
7172 char *path, buf[BUFSIZ];
7173 sig_t sighup, sigint, sigquit;
7175 err = got_opentemp_named_fd(&path, patchfd,
7176 GOT_TMPDIR_STR "/got-patch");
7177 if (err)
7178 return err;
7179 unlink(path);
7180 free(path);
7182 sighup = signal(SIGHUP, SIG_DFL);
7183 sigint = signal(SIGINT, SIG_DFL);
7184 sigquit = signal(SIGQUIT, SIG_DFL);
7186 for (;;) {
7187 r = read(0, buf, sizeof(buf));
7188 if (r == -1) {
7189 err = got_error_from_errno("read");
7190 break;
7192 if (r == 0)
7193 break;
7194 if (write(*patchfd, buf, r) == -1) {
7195 err = got_error_from_errno("write");
7196 break;
7200 signal(SIGHUP, sighup);
7201 signal(SIGINT, sigint);
7202 signal(SIGQUIT, sigquit);
7204 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7205 err = got_error_from_errno("lseek");
7207 if (err != NULL) {
7208 close(*patchfd);
7209 *patchfd = -1;
7212 return err;
7215 static const struct got_error *
7216 patch_progress(void *arg, const char *old, const char *new,
7217 unsigned char status, const struct got_error *error, long old_from,
7218 long old_lines, long new_from, long new_lines, long offset,
7219 const struct got_error *hunk_err)
7221 const char *path = new == NULL ? old : new;
7223 while (*path == '/')
7224 path++;
7226 if (status != 0)
7227 printf("%c %s\n", status, path);
7229 if (error != NULL)
7230 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7232 if (offset != 0 || hunk_err != NULL) {
7233 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7234 old_lines, new_from, new_lines);
7235 if (hunk_err != NULL)
7236 printf("%s\n", hunk_err->msg);
7237 else
7238 printf("applied with offset %ld\n", offset);
7241 return NULL;
7244 static const struct got_error *
7245 cmd_patch(int argc, char *argv[])
7247 const struct got_error *error = NULL, *close_error = NULL;
7248 struct got_worktree *worktree = NULL;
7249 struct got_repository *repo = NULL;
7250 const char *errstr;
7251 char *cwd = NULL;
7252 int ch, nop = 0, strip = -1, reverse = 0;
7253 int patchfd;
7255 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7256 switch (ch) {
7257 case 'n':
7258 nop = 1;
7259 break;
7260 case 'p':
7261 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7262 if (errstr != NULL)
7263 errx(1, "pathname strip count is %s: %s",
7264 errstr, optarg);
7265 break;
7266 case 'R':
7267 reverse = 1;
7268 break;
7269 default:
7270 usage_patch();
7271 /* NOTREACHED */
7275 argc -= optind;
7276 argv += optind;
7278 if (argc == 0) {
7279 error = patch_from_stdin(&patchfd);
7280 if (error)
7281 return error;
7282 } else if (argc == 1) {
7283 patchfd = open(argv[0], O_RDONLY);
7284 if (patchfd == -1) {
7285 error = got_error_from_errno2("open", argv[0]);
7286 return error;
7288 } else
7289 usage_patch();
7291 if ((cwd = getcwd(NULL, 0)) == NULL) {
7292 error = got_error_from_errno("getcwd");
7293 goto done;
7296 error = got_worktree_open(&worktree, cwd);
7297 if (error != NULL)
7298 goto done;
7300 const char *repo_path = got_worktree_get_repo_path(worktree);
7301 error = got_repo_open(&repo, repo_path, NULL);
7302 if (error != NULL)
7303 goto done;
7305 error = apply_unveil(got_repo_get_path(repo), 0,
7306 got_worktree_get_root_path(worktree));
7307 if (error != NULL)
7308 goto done;
7310 #ifndef PROFILE
7311 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7312 NULL) == -1)
7313 err(1, "pledge");
7314 #endif
7316 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7317 &patch_progress, NULL, check_cancelled, NULL);
7319 done:
7320 if (repo) {
7321 close_error = got_repo_close(repo);
7322 if (error == NULL)
7323 error = close_error;
7325 if (worktree != NULL) {
7326 close_error = got_worktree_close(worktree);
7327 if (error == NULL)
7328 error = close_error;
7330 free(cwd);
7331 return error;
7334 __dead static void
7335 usage_revert(void)
7337 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7338 "path ...\n", getprogname());
7339 exit(1);
7342 static const struct got_error *
7343 revert_progress(void *arg, unsigned char status, const char *path)
7345 if (status == GOT_STATUS_UNVERSIONED)
7346 return NULL;
7348 while (path[0] == '/')
7349 path++;
7350 printf("%c %s\n", status, path);
7351 return NULL;
7354 struct choose_patch_arg {
7355 FILE *patch_script_file;
7356 const char *action;
7359 static const struct got_error *
7360 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7361 int nchanges, const char *action)
7363 char *line = NULL;
7364 size_t linesize = 0;
7365 ssize_t linelen;
7367 switch (status) {
7368 case GOT_STATUS_ADD:
7369 printf("A %s\n%s this addition? [y/n] ", path, action);
7370 break;
7371 case GOT_STATUS_DELETE:
7372 printf("D %s\n%s this deletion? [y/n] ", path, action);
7373 break;
7374 case GOT_STATUS_MODIFY:
7375 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7376 return got_error_from_errno("fseek");
7377 printf(GOT_COMMIT_SEP_STR);
7378 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7379 printf("%s", line);
7380 if (ferror(patch_file))
7381 return got_error_from_errno("getline");
7382 printf(GOT_COMMIT_SEP_STR);
7383 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7384 path, n, nchanges, action);
7385 break;
7386 default:
7387 return got_error_path(path, GOT_ERR_FILE_STATUS);
7390 return NULL;
7393 static const struct got_error *
7394 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7395 FILE *patch_file, int n, int nchanges)
7397 const struct got_error *err = NULL;
7398 char *line = NULL;
7399 size_t linesize = 0;
7400 ssize_t linelen;
7401 int resp = ' ';
7402 struct choose_patch_arg *a = arg;
7404 *choice = GOT_PATCH_CHOICE_NONE;
7406 if (a->patch_script_file) {
7407 char *nl;
7408 err = show_change(status, path, patch_file, n, nchanges,
7409 a->action);
7410 if (err)
7411 return err;
7412 linelen = getline(&line, &linesize, a->patch_script_file);
7413 if (linelen == -1) {
7414 if (ferror(a->patch_script_file))
7415 return got_error_from_errno("getline");
7416 return NULL;
7418 nl = strchr(line, '\n');
7419 if (nl)
7420 *nl = '\0';
7421 if (strcmp(line, "y") == 0) {
7422 *choice = GOT_PATCH_CHOICE_YES;
7423 printf("y\n");
7424 } else if (strcmp(line, "n") == 0) {
7425 *choice = GOT_PATCH_CHOICE_NO;
7426 printf("n\n");
7427 } else if (strcmp(line, "q") == 0 &&
7428 status == GOT_STATUS_MODIFY) {
7429 *choice = GOT_PATCH_CHOICE_QUIT;
7430 printf("q\n");
7431 } else
7432 printf("invalid response '%s'\n", line);
7433 free(line);
7434 return NULL;
7437 while (resp != 'y' && resp != 'n' && resp != 'q') {
7438 err = show_change(status, path, patch_file, n, nchanges,
7439 a->action);
7440 if (err)
7441 return err;
7442 resp = getchar();
7443 if (resp == '\n')
7444 resp = getchar();
7445 if (status == GOT_STATUS_MODIFY) {
7446 if (resp != 'y' && resp != 'n' && resp != 'q') {
7447 printf("invalid response '%c'\n", resp);
7448 resp = ' ';
7450 } else if (resp != 'y' && resp != 'n') {
7451 printf("invalid response '%c'\n", resp);
7452 resp = ' ';
7456 if (resp == 'y')
7457 *choice = GOT_PATCH_CHOICE_YES;
7458 else if (resp == 'n')
7459 *choice = GOT_PATCH_CHOICE_NO;
7460 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7461 *choice = GOT_PATCH_CHOICE_QUIT;
7463 return NULL;
7466 static const struct got_error *
7467 cmd_revert(int argc, char *argv[])
7469 const struct got_error *error = NULL;
7470 struct got_worktree *worktree = NULL;
7471 struct got_repository *repo = NULL;
7472 char *cwd = NULL, *path = NULL;
7473 struct got_pathlist_head paths;
7474 struct got_pathlist_entry *pe;
7475 int ch, can_recurse = 0, pflag = 0;
7476 FILE *patch_script_file = NULL;
7477 const char *patch_script_path = NULL;
7478 struct choose_patch_arg cpa;
7480 TAILQ_INIT(&paths);
7482 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7483 switch (ch) {
7484 case 'p':
7485 pflag = 1;
7486 break;
7487 case 'F':
7488 patch_script_path = optarg;
7489 break;
7490 case 'R':
7491 can_recurse = 1;
7492 break;
7493 default:
7494 usage_revert();
7495 /* NOTREACHED */
7499 argc -= optind;
7500 argv += optind;
7502 #ifndef PROFILE
7503 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7504 "unveil", NULL) == -1)
7505 err(1, "pledge");
7506 #endif
7507 if (argc < 1)
7508 usage_revert();
7509 if (patch_script_path && !pflag)
7510 errx(1, "-F option can only be used together with -p option");
7512 cwd = getcwd(NULL, 0);
7513 if (cwd == NULL) {
7514 error = got_error_from_errno("getcwd");
7515 goto done;
7517 error = got_worktree_open(&worktree, cwd);
7518 if (error) {
7519 if (error->code == GOT_ERR_NOT_WORKTREE)
7520 error = wrap_not_worktree_error(error, "revert", cwd);
7521 goto done;
7524 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7525 NULL);
7526 if (error != NULL)
7527 goto done;
7529 if (patch_script_path) {
7530 patch_script_file = fopen(patch_script_path, "re");
7531 if (patch_script_file == NULL) {
7532 error = got_error_from_errno2("fopen",
7533 patch_script_path);
7534 goto done;
7537 error = apply_unveil(got_repo_get_path(repo), 1,
7538 got_worktree_get_root_path(worktree));
7539 if (error)
7540 goto done;
7542 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7543 if (error)
7544 goto done;
7546 if (!can_recurse) {
7547 char *ondisk_path;
7548 struct stat sb;
7549 TAILQ_FOREACH(pe, &paths, entry) {
7550 if (asprintf(&ondisk_path, "%s/%s",
7551 got_worktree_get_root_path(worktree),
7552 pe->path) == -1) {
7553 error = got_error_from_errno("asprintf");
7554 goto done;
7556 if (lstat(ondisk_path, &sb) == -1) {
7557 if (errno == ENOENT) {
7558 free(ondisk_path);
7559 continue;
7561 error = got_error_from_errno2("lstat",
7562 ondisk_path);
7563 free(ondisk_path);
7564 goto done;
7566 free(ondisk_path);
7567 if (S_ISDIR(sb.st_mode)) {
7568 error = got_error_msg(GOT_ERR_BAD_PATH,
7569 "reverting directories requires -R option");
7570 goto done;
7575 cpa.patch_script_file = patch_script_file;
7576 cpa.action = "revert";
7577 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7578 pflag ? choose_patch : NULL, &cpa, repo);
7579 done:
7580 if (patch_script_file && fclose(patch_script_file) == EOF &&
7581 error == NULL)
7582 error = got_error_from_errno2("fclose", patch_script_path);
7583 if (repo) {
7584 const struct got_error *close_err = got_repo_close(repo);
7585 if (error == NULL)
7586 error = close_err;
7588 if (worktree)
7589 got_worktree_close(worktree);
7590 free(path);
7591 free(cwd);
7592 return error;
7595 __dead static void
7596 usage_commit(void)
7598 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7599 "[path ...]\n", getprogname());
7600 exit(1);
7603 struct collect_commit_logmsg_arg {
7604 const char *cmdline_log;
7605 const char *prepared_log;
7606 int non_interactive;
7607 const char *editor;
7608 const char *worktree_path;
7609 const char *branch_name;
7610 const char *repo_path;
7611 char *logmsg_path;
7615 static const struct got_error *
7616 read_prepared_logmsg(char **logmsg, const char *path)
7618 const struct got_error *err = NULL;
7619 FILE *f = NULL;
7620 struct stat sb;
7621 size_t r;
7623 *logmsg = NULL;
7624 memset(&sb, 0, sizeof(sb));
7626 f = fopen(path, "re");
7627 if (f == NULL)
7628 return got_error_from_errno2("fopen", path);
7630 if (fstat(fileno(f), &sb) == -1) {
7631 err = got_error_from_errno2("fstat", path);
7632 goto done;
7634 if (sb.st_size == 0) {
7635 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7636 goto done;
7639 *logmsg = malloc(sb.st_size + 1);
7640 if (*logmsg == NULL) {
7641 err = got_error_from_errno("malloc");
7642 goto done;
7645 r = fread(*logmsg, 1, sb.st_size, f);
7646 if (r != sb.st_size) {
7647 if (ferror(f))
7648 err = got_error_from_errno2("fread", path);
7649 else
7650 err = got_error(GOT_ERR_IO);
7651 goto done;
7653 (*logmsg)[sb.st_size] = '\0';
7654 done:
7655 if (fclose(f) == EOF && err == NULL)
7656 err = got_error_from_errno2("fclose", path);
7657 if (err) {
7658 free(*logmsg);
7659 *logmsg = NULL;
7661 return err;
7665 static const struct got_error *
7666 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7667 void *arg)
7669 char *initial_content = NULL;
7670 struct got_pathlist_entry *pe;
7671 const struct got_error *err = NULL;
7672 char *template = NULL;
7673 struct collect_commit_logmsg_arg *a = arg;
7674 int initial_content_len;
7675 int fd = -1;
7676 size_t len;
7678 /* if a message was specified on the command line, just use it */
7679 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7680 len = strlen(a->cmdline_log) + 1;
7681 *logmsg = malloc(len + 1);
7682 if (*logmsg == NULL)
7683 return got_error_from_errno("malloc");
7684 strlcpy(*logmsg, a->cmdline_log, len);
7685 return NULL;
7686 } else if (a->prepared_log != NULL && a->non_interactive)
7687 return read_prepared_logmsg(logmsg, a->prepared_log);
7689 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7690 return got_error_from_errno("asprintf");
7692 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7693 if (err)
7694 goto done;
7696 if (a->prepared_log) {
7697 char *msg;
7698 err = read_prepared_logmsg(&msg, a->prepared_log);
7699 if (err)
7700 goto done;
7701 if (write(fd, msg, strlen(msg)) == -1) {
7702 err = got_error_from_errno2("write", a->logmsg_path);
7703 free(msg);
7704 goto done;
7706 free(msg);
7709 initial_content_len = asprintf(&initial_content,
7710 "\n# changes to be committed on branch %s:\n",
7711 a->branch_name);
7712 if (initial_content_len == -1) {
7713 err = got_error_from_errno("asprintf");
7714 goto done;
7717 if (write(fd, initial_content, initial_content_len) == -1) {
7718 err = got_error_from_errno2("write", a->logmsg_path);
7719 goto done;
7722 TAILQ_FOREACH(pe, commitable_paths, entry) {
7723 struct got_commitable *ct = pe->data;
7724 dprintf(fd, "# %c %s\n",
7725 got_commitable_get_status(ct),
7726 got_commitable_get_path(ct));
7729 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7730 initial_content_len, a->prepared_log ? 0 : 1);
7731 done:
7732 free(initial_content);
7733 free(template);
7735 if (fd != -1 && close(fd) == -1 && err == NULL)
7736 err = got_error_from_errno2("close", a->logmsg_path);
7738 /* Editor is done; we can now apply unveil(2) */
7739 if (err == NULL)
7740 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7741 if (err) {
7742 free(*logmsg);
7743 *logmsg = NULL;
7745 return err;
7748 static const struct got_error *
7749 cmd_commit(int argc, char *argv[])
7751 const struct got_error *error = NULL;
7752 struct got_worktree *worktree = NULL;
7753 struct got_repository *repo = NULL;
7754 char *cwd = NULL, *id_str = NULL;
7755 struct got_object_id *id = NULL;
7756 const char *logmsg = NULL;
7757 char *prepared_logmsg = NULL;
7758 struct collect_commit_logmsg_arg cl_arg;
7759 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7760 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7761 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7762 struct got_pathlist_head paths;
7764 TAILQ_INIT(&paths);
7765 cl_arg.logmsg_path = NULL;
7767 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7768 switch (ch) {
7769 case 'F':
7770 if (logmsg != NULL)
7771 option_conflict('F', 'm');
7772 prepared_logmsg = realpath(optarg, NULL);
7773 if (prepared_logmsg == NULL)
7774 return got_error_from_errno2("realpath",
7775 optarg);
7776 break;
7777 case 'm':
7778 if (prepared_logmsg)
7779 option_conflict('m', 'F');
7780 logmsg = optarg;
7781 break;
7782 case 'N':
7783 non_interactive = 1;
7784 break;
7785 case 'S':
7786 allow_bad_symlinks = 1;
7787 break;
7788 default:
7789 usage_commit();
7790 /* NOTREACHED */
7794 argc -= optind;
7795 argv += optind;
7797 #ifndef PROFILE
7798 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7799 "unveil", NULL) == -1)
7800 err(1, "pledge");
7801 #endif
7802 cwd = getcwd(NULL, 0);
7803 if (cwd == NULL) {
7804 error = got_error_from_errno("getcwd");
7805 goto done;
7807 error = got_worktree_open(&worktree, cwd);
7808 if (error) {
7809 if (error->code == GOT_ERR_NOT_WORKTREE)
7810 error = wrap_not_worktree_error(error, "commit", cwd);
7811 goto done;
7814 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7815 if (error)
7816 goto done;
7817 if (rebase_in_progress) {
7818 error = got_error(GOT_ERR_REBASING);
7819 goto done;
7822 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7823 worktree);
7824 if (error)
7825 goto done;
7827 error = get_gitconfig_path(&gitconfig_path);
7828 if (error)
7829 goto done;
7830 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7831 gitconfig_path);
7832 if (error != NULL)
7833 goto done;
7835 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7836 if (error)
7837 goto done;
7838 if (merge_in_progress) {
7839 error = got_error(GOT_ERR_MERGE_BUSY);
7840 goto done;
7843 error = get_author(&author, repo, worktree);
7844 if (error)
7845 return error;
7848 * unveil(2) traverses exec(2); if an editor is used we have
7849 * to apply unveil after the log message has been written.
7851 if (logmsg == NULL || strlen(logmsg) == 0)
7852 error = get_editor(&editor);
7853 else
7854 error = apply_unveil(got_repo_get_path(repo), 0,
7855 got_worktree_get_root_path(worktree));
7856 if (error)
7857 goto done;
7859 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7860 if (error)
7861 goto done;
7863 cl_arg.editor = editor;
7864 cl_arg.cmdline_log = logmsg;
7865 cl_arg.prepared_log = prepared_logmsg;
7866 cl_arg.non_interactive = non_interactive;
7867 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7868 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7869 if (!histedit_in_progress) {
7870 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7871 error = got_error(GOT_ERR_COMMIT_BRANCH);
7872 goto done;
7874 cl_arg.branch_name += 11;
7876 cl_arg.repo_path = got_repo_get_path(repo);
7877 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7878 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7879 print_status, NULL, repo);
7880 if (error) {
7881 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7882 cl_arg.logmsg_path != NULL)
7883 preserve_logmsg = 1;
7884 goto done;
7887 error = got_object_id_str(&id_str, id);
7888 if (error)
7889 goto done;
7890 printf("Created commit %s\n", id_str);
7891 done:
7892 if (preserve_logmsg) {
7893 fprintf(stderr, "%s: log message preserved in %s\n",
7894 getprogname(), cl_arg.logmsg_path);
7895 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7896 error == NULL)
7897 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7898 free(cl_arg.logmsg_path);
7899 if (repo) {
7900 const struct got_error *close_err = got_repo_close(repo);
7901 if (error == NULL)
7902 error = close_err;
7904 if (worktree)
7905 got_worktree_close(worktree);
7906 free(cwd);
7907 free(id_str);
7908 free(gitconfig_path);
7909 free(editor);
7910 free(author);
7911 free(prepared_logmsg);
7912 return error;
7915 __dead static void
7916 usage_send(void)
7918 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7919 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7920 "[remote-repository]\n", getprogname());
7921 exit(1);
7924 static void
7925 print_load_info(int print_colored, int print_found, int print_trees,
7926 int ncolored, int nfound, int ntrees)
7928 if (print_colored) {
7929 printf("%d commit%s colored", ncolored,
7930 ncolored == 1 ? "" : "s");
7932 if (print_found) {
7933 printf("%s%d object%s found",
7934 ncolored > 0 ? "; " : "",
7935 nfound, nfound == 1 ? "" : "s");
7937 if (print_trees) {
7938 printf("; %d tree%s scanned", ntrees,
7939 ntrees == 1 ? "" : "s");
7943 struct got_send_progress_arg {
7944 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7945 int verbosity;
7946 int last_ncolored;
7947 int last_nfound;
7948 int last_ntrees;
7949 int loading_done;
7950 int last_ncommits;
7951 int last_nobj_total;
7952 int last_p_deltify;
7953 int last_p_written;
7954 int last_p_sent;
7955 int printed_something;
7956 int sent_something;
7957 struct got_pathlist_head *delete_branches;
7960 static const struct got_error *
7961 send_progress(void *arg, int ncolored, int nfound, int ntrees,
7962 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
7963 int nobj_written, off_t bytes_sent, const char *refname, int success)
7965 struct got_send_progress_arg *a = arg;
7966 char scaled_packsize[FMT_SCALED_STRSIZE];
7967 char scaled_sent[FMT_SCALED_STRSIZE];
7968 int p_deltify = 0, p_written = 0, p_sent = 0;
7969 int print_colored = 0, print_found = 0, print_trees = 0;
7970 int print_searching = 0, print_total = 0;
7971 int print_deltify = 0, print_written = 0, print_sent = 0;
7973 if (a->verbosity < 0)
7974 return NULL;
7976 if (refname) {
7977 const char *status = success ? "accepted" : "rejected";
7979 if (success) {
7980 struct got_pathlist_entry *pe;
7981 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7982 const char *branchname = pe->path;
7983 if (got_path_cmp(branchname, refname,
7984 strlen(branchname), strlen(refname)) == 0) {
7985 status = "deleted";
7986 a->sent_something = 1;
7987 break;
7992 if (a->printed_something)
7993 putchar('\n');
7994 printf("Server has %s %s", status, refname);
7995 a->printed_something = 1;
7996 return NULL;
7999 if (a->last_ncolored != ncolored) {
8000 print_colored = 1;
8001 a->last_ncolored = ncolored;
8004 if (a->last_nfound != nfound) {
8005 print_colored = 1;
8006 print_found = 1;
8007 a->last_nfound = nfound;
8010 if (a->last_ntrees != ntrees) {
8011 print_colored = 1;
8012 print_found = 1;
8013 print_trees = 1;
8014 a->last_ntrees = ntrees;
8017 if ((print_colored || print_found || print_trees) &&
8018 !a->loading_done) {
8019 printf("\r");
8020 print_load_info(print_colored, print_found, print_trees,
8021 ncolored, nfound, ntrees);
8022 a->printed_something = 1;
8023 fflush(stdout);
8024 return NULL;
8025 } else if (!a->loading_done) {
8026 printf("\r");
8027 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8028 printf("\n");
8029 a->loading_done = 1;
8032 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8033 return got_error_from_errno("fmt_scaled");
8034 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8035 return got_error_from_errno("fmt_scaled");
8037 if (a->last_ncommits != ncommits) {
8038 print_searching = 1;
8039 a->last_ncommits = ncommits;
8042 if (a->last_nobj_total != nobj_total) {
8043 print_searching = 1;
8044 print_total = 1;
8045 a->last_nobj_total = nobj_total;
8048 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8049 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8050 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8051 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8052 return got_error(GOT_ERR_NO_SPACE);
8055 if (nobj_deltify > 0 || nobj_written > 0) {
8056 if (nobj_deltify > 0) {
8057 p_deltify = (nobj_deltify * 100) / nobj_total;
8058 if (p_deltify != a->last_p_deltify) {
8059 a->last_p_deltify = p_deltify;
8060 print_searching = 1;
8061 print_total = 1;
8062 print_deltify = 1;
8065 if (nobj_written > 0) {
8066 p_written = (nobj_written * 100) / nobj_total;
8067 if (p_written != a->last_p_written) {
8068 a->last_p_written = p_written;
8069 print_searching = 1;
8070 print_total = 1;
8071 print_deltify = 1;
8072 print_written = 1;
8077 if (bytes_sent > 0) {
8078 p_sent = (bytes_sent * 100) / packfile_size;
8079 if (p_sent != a->last_p_sent) {
8080 a->last_p_sent = p_sent;
8081 print_searching = 1;
8082 print_total = 1;
8083 print_deltify = 1;
8084 print_written = 1;
8085 print_sent = 1;
8087 a->sent_something = 1;
8090 if (print_searching || print_total || print_deltify || print_written ||
8091 print_sent)
8092 printf("\r");
8093 if (print_searching)
8094 printf("packing %d reference%s", ncommits,
8095 ncommits == 1 ? "" : "s");
8096 if (print_total)
8097 printf("; %d object%s", nobj_total,
8098 nobj_total == 1 ? "" : "s");
8099 if (print_deltify)
8100 printf("; deltify: %d%%", p_deltify);
8101 if (print_sent)
8102 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8103 scaled_packsize, p_sent);
8104 else if (print_written)
8105 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8106 scaled_packsize, p_written);
8107 if (print_searching || print_total || print_deltify ||
8108 print_written || print_sent) {
8109 a->printed_something = 1;
8110 fflush(stdout);
8112 return NULL;
8115 static const struct got_error *
8116 cmd_send(int argc, char *argv[])
8118 const struct got_error *error = NULL;
8119 char *cwd = NULL, *repo_path = NULL;
8120 const char *remote_name;
8121 char *proto = NULL, *host = NULL, *port = NULL;
8122 char *repo_name = NULL, *server_path = NULL;
8123 const struct got_remote_repo *remotes, *remote = NULL;
8124 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8125 struct got_repository *repo = NULL;
8126 struct got_worktree *worktree = NULL;
8127 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8128 struct got_pathlist_head branches;
8129 struct got_pathlist_head tags;
8130 struct got_reflist_head all_branches;
8131 struct got_reflist_head all_tags;
8132 struct got_pathlist_head delete_args;
8133 struct got_pathlist_head delete_branches;
8134 struct got_reflist_entry *re;
8135 struct got_pathlist_entry *pe;
8136 int i, ch, sendfd = -1, sendstatus;
8137 pid_t sendpid = -1;
8138 struct got_send_progress_arg spa;
8139 int verbosity = 0, overwrite_refs = 0;
8140 int send_all_branches = 0, send_all_tags = 0;
8141 struct got_reference *ref = NULL;
8143 TAILQ_INIT(&branches);
8144 TAILQ_INIT(&tags);
8145 TAILQ_INIT(&all_branches);
8146 TAILQ_INIT(&all_tags);
8147 TAILQ_INIT(&delete_args);
8148 TAILQ_INIT(&delete_branches);
8150 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8151 switch (ch) {
8152 case 'a':
8153 send_all_branches = 1;
8154 break;
8155 case 'b':
8156 error = got_pathlist_append(&branches, optarg, NULL);
8157 if (error)
8158 return error;
8159 nbranches++;
8160 break;
8161 case 'd':
8162 error = got_pathlist_append(&delete_args, optarg, NULL);
8163 if (error)
8164 return error;
8165 break;
8166 case 'f':
8167 overwrite_refs = 1;
8168 break;
8169 case 'r':
8170 repo_path = realpath(optarg, NULL);
8171 if (repo_path == NULL)
8172 return got_error_from_errno2("realpath",
8173 optarg);
8174 got_path_strip_trailing_slashes(repo_path);
8175 break;
8176 case 't':
8177 error = got_pathlist_append(&tags, optarg, NULL);
8178 if (error)
8179 return error;
8180 ntags++;
8181 break;
8182 case 'T':
8183 send_all_tags = 1;
8184 break;
8185 case 'v':
8186 if (verbosity < 0)
8187 verbosity = 0;
8188 else if (verbosity < 3)
8189 verbosity++;
8190 break;
8191 case 'q':
8192 verbosity = -1;
8193 break;
8194 default:
8195 usage_send();
8196 /* NOTREACHED */
8199 argc -= optind;
8200 argv += optind;
8202 if (send_all_branches && !TAILQ_EMPTY(&branches))
8203 option_conflict('a', 'b');
8204 if (send_all_tags && !TAILQ_EMPTY(&tags))
8205 option_conflict('T', 't');
8208 if (argc == 0)
8209 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8210 else if (argc == 1)
8211 remote_name = argv[0];
8212 else
8213 usage_send();
8215 cwd = getcwd(NULL, 0);
8216 if (cwd == NULL) {
8217 error = got_error_from_errno("getcwd");
8218 goto done;
8221 if (repo_path == NULL) {
8222 error = got_worktree_open(&worktree, cwd);
8223 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8224 goto done;
8225 else
8226 error = NULL;
8227 if (worktree) {
8228 repo_path =
8229 strdup(got_worktree_get_repo_path(worktree));
8230 if (repo_path == NULL)
8231 error = got_error_from_errno("strdup");
8232 if (error)
8233 goto done;
8234 } else {
8235 repo_path = strdup(cwd);
8236 if (repo_path == NULL) {
8237 error = got_error_from_errno("strdup");
8238 goto done;
8243 error = got_repo_open(&repo, repo_path, NULL);
8244 if (error)
8245 goto done;
8247 if (worktree) {
8248 worktree_conf = got_worktree_get_gotconfig(worktree);
8249 if (worktree_conf) {
8250 got_gotconfig_get_remotes(&nremotes, &remotes,
8251 worktree_conf);
8252 for (i = 0; i < nremotes; i++) {
8253 if (strcmp(remotes[i].name, remote_name) == 0) {
8254 remote = &remotes[i];
8255 break;
8260 if (remote == NULL) {
8261 repo_conf = got_repo_get_gotconfig(repo);
8262 if (repo_conf) {
8263 got_gotconfig_get_remotes(&nremotes, &remotes,
8264 repo_conf);
8265 for (i = 0; i < nremotes; i++) {
8266 if (strcmp(remotes[i].name, remote_name) == 0) {
8267 remote = &remotes[i];
8268 break;
8273 if (remote == NULL) {
8274 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8275 for (i = 0; i < nremotes; i++) {
8276 if (strcmp(remotes[i].name, remote_name) == 0) {
8277 remote = &remotes[i];
8278 break;
8282 if (remote == NULL) {
8283 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8284 goto done;
8287 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8288 &repo_name, remote->send_url);
8289 if (error)
8290 goto done;
8292 if (strcmp(proto, "git") == 0) {
8293 #ifndef PROFILE
8294 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8295 "sendfd dns inet unveil", NULL) == -1)
8296 err(1, "pledge");
8297 #endif
8298 } else if (strcmp(proto, "git+ssh") == 0 ||
8299 strcmp(proto, "ssh") == 0) {
8300 #ifndef PROFILE
8301 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8302 "sendfd unveil", NULL) == -1)
8303 err(1, "pledge");
8304 #endif
8305 } else if (strcmp(proto, "http") == 0 ||
8306 strcmp(proto, "git+http") == 0) {
8307 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8308 goto done;
8309 } else {
8310 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8311 goto done;
8314 error = got_dial_apply_unveil(proto);
8315 if (error)
8316 goto done;
8318 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8319 if (error)
8320 goto done;
8322 if (send_all_branches) {
8323 error = got_ref_list(&all_branches, repo, "refs/heads",
8324 got_ref_cmp_by_name, NULL);
8325 if (error)
8326 goto done;
8327 TAILQ_FOREACH(re, &all_branches, entry) {
8328 const char *branchname = got_ref_get_name(re->ref);
8329 error = got_pathlist_append(&branches,
8330 branchname, NULL);
8331 if (error)
8332 goto done;
8333 nbranches++;
8335 } else if (nbranches == 0) {
8336 for (i = 0; i < remote->nsend_branches; i++) {
8337 got_pathlist_append(&branches,
8338 remote->send_branches[i], NULL);
8342 if (send_all_tags) {
8343 error = got_ref_list(&all_tags, repo, "refs/tags",
8344 got_ref_cmp_by_name, NULL);
8345 if (error)
8346 goto done;
8347 TAILQ_FOREACH(re, &all_tags, entry) {
8348 const char *tagname = got_ref_get_name(re->ref);
8349 error = got_pathlist_append(&tags,
8350 tagname, NULL);
8351 if (error)
8352 goto done;
8353 ntags++;
8358 * To prevent accidents only branches in refs/heads/ can be deleted
8359 * with 'got send -d'.
8360 * Deleting anything else requires local repository access or Git.
8362 TAILQ_FOREACH(pe, &delete_args, entry) {
8363 const char *branchname = pe->path;
8364 char *s;
8365 struct got_pathlist_entry *new;
8366 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8367 s = strdup(branchname);
8368 if (s == NULL) {
8369 error = got_error_from_errno("strdup");
8370 goto done;
8372 } else {
8373 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8374 error = got_error_from_errno("asprintf");
8375 goto done;
8378 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8379 if (error || new == NULL /* duplicate */)
8380 free(s);
8381 if (error)
8382 goto done;
8383 ndelete_branches++;
8386 if (nbranches == 0 && ndelete_branches == 0) {
8387 struct got_reference *head_ref;
8388 if (worktree)
8389 error = got_ref_open(&head_ref, repo,
8390 got_worktree_get_head_ref_name(worktree), 0);
8391 else
8392 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8393 if (error)
8394 goto done;
8395 if (got_ref_is_symbolic(head_ref)) {
8396 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8397 got_ref_close(head_ref);
8398 if (error)
8399 goto done;
8400 } else
8401 ref = head_ref;
8402 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8403 NULL);
8404 if (error)
8405 goto done;
8406 nbranches++;
8409 if (verbosity >= 0)
8410 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8411 port ? ":" : "", port ? port : "");
8413 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8414 server_path, verbosity);
8415 if (error)
8416 goto done;
8418 memset(&spa, 0, sizeof(spa));
8419 spa.last_scaled_packsize[0] = '\0';
8420 spa.last_p_deltify = -1;
8421 spa.last_p_written = -1;
8422 spa.verbosity = verbosity;
8423 spa.delete_branches = &delete_branches;
8424 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8425 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8426 check_cancelled, NULL);
8427 if (spa.printed_something)
8428 putchar('\n');
8429 if (error)
8430 goto done;
8431 if (!spa.sent_something && verbosity >= 0)
8432 printf("Already up-to-date\n");
8433 done:
8434 if (sendpid > 0) {
8435 if (kill(sendpid, SIGTERM) == -1)
8436 error = got_error_from_errno("kill");
8437 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8438 error = got_error_from_errno("waitpid");
8440 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8441 error = got_error_from_errno("close");
8442 if (repo) {
8443 const struct got_error *close_err = got_repo_close(repo);
8444 if (error == NULL)
8445 error = close_err;
8447 if (worktree)
8448 got_worktree_close(worktree);
8449 if (ref)
8450 got_ref_close(ref);
8451 got_pathlist_free(&branches);
8452 got_pathlist_free(&tags);
8453 got_ref_list_free(&all_branches);
8454 got_ref_list_free(&all_tags);
8455 got_pathlist_free(&delete_args);
8456 TAILQ_FOREACH(pe, &delete_branches, entry)
8457 free((char *)pe->path);
8458 got_pathlist_free(&delete_branches);
8459 free(cwd);
8460 free(repo_path);
8461 free(proto);
8462 free(host);
8463 free(port);
8464 free(server_path);
8465 free(repo_name);
8466 return error;
8469 __dead static void
8470 usage_cherrypick(void)
8472 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8473 exit(1);
8476 static const struct got_error *
8477 cmd_cherrypick(int argc, char *argv[])
8479 const struct got_error *error = NULL;
8480 struct got_worktree *worktree = NULL;
8481 struct got_repository *repo = NULL;
8482 char *cwd = NULL, *commit_id_str = NULL;
8483 struct got_object_id *commit_id = NULL;
8484 struct got_commit_object *commit = NULL;
8485 struct got_object_qid *pid;
8486 int ch;
8487 struct got_update_progress_arg upa;
8489 while ((ch = getopt(argc, argv, "")) != -1) {
8490 switch (ch) {
8491 default:
8492 usage_cherrypick();
8493 /* NOTREACHED */
8497 argc -= optind;
8498 argv += optind;
8500 #ifndef PROFILE
8501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8502 "unveil", NULL) == -1)
8503 err(1, "pledge");
8504 #endif
8505 if (argc != 1)
8506 usage_cherrypick();
8508 cwd = getcwd(NULL, 0);
8509 if (cwd == NULL) {
8510 error = got_error_from_errno("getcwd");
8511 goto done;
8513 error = got_worktree_open(&worktree, cwd);
8514 if (error) {
8515 if (error->code == GOT_ERR_NOT_WORKTREE)
8516 error = wrap_not_worktree_error(error, "cherrypick",
8517 cwd);
8518 goto done;
8521 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8522 NULL);
8523 if (error != NULL)
8524 goto done;
8526 error = apply_unveil(got_repo_get_path(repo), 0,
8527 got_worktree_get_root_path(worktree));
8528 if (error)
8529 goto done;
8531 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8532 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8533 if (error)
8534 goto done;
8535 error = got_object_id_str(&commit_id_str, commit_id);
8536 if (error)
8537 goto done;
8539 error = got_object_open_as_commit(&commit, repo, commit_id);
8540 if (error)
8541 goto done;
8542 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8543 memset(&upa, 0, sizeof(upa));
8544 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8545 commit_id, repo, update_progress, &upa, check_cancelled,
8546 NULL);
8547 if (error != NULL)
8548 goto done;
8550 if (upa.did_something)
8551 printf("Merged commit %s\n", commit_id_str);
8552 print_merge_progress_stats(&upa);
8553 done:
8554 if (commit)
8555 got_object_commit_close(commit);
8556 free(commit_id_str);
8557 if (worktree)
8558 got_worktree_close(worktree);
8559 if (repo) {
8560 const struct got_error *close_err = got_repo_close(repo);
8561 if (error == NULL)
8562 error = close_err;
8564 return error;
8567 __dead static void
8568 usage_backout(void)
8570 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8571 exit(1);
8574 static const struct got_error *
8575 cmd_backout(int argc, char *argv[])
8577 const struct got_error *error = NULL;
8578 struct got_worktree *worktree = NULL;
8579 struct got_repository *repo = NULL;
8580 char *cwd = NULL, *commit_id_str = NULL;
8581 struct got_object_id *commit_id = NULL;
8582 struct got_commit_object *commit = NULL;
8583 struct got_object_qid *pid;
8584 int ch;
8585 struct got_update_progress_arg upa;
8587 while ((ch = getopt(argc, argv, "")) != -1) {
8588 switch (ch) {
8589 default:
8590 usage_backout();
8591 /* NOTREACHED */
8595 argc -= optind;
8596 argv += optind;
8598 #ifndef PROFILE
8599 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8600 "unveil", NULL) == -1)
8601 err(1, "pledge");
8602 #endif
8603 if (argc != 1)
8604 usage_backout();
8606 cwd = getcwd(NULL, 0);
8607 if (cwd == NULL) {
8608 error = got_error_from_errno("getcwd");
8609 goto done;
8611 error = got_worktree_open(&worktree, cwd);
8612 if (error) {
8613 if (error->code == GOT_ERR_NOT_WORKTREE)
8614 error = wrap_not_worktree_error(error, "backout", cwd);
8615 goto done;
8618 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8619 NULL);
8620 if (error != NULL)
8621 goto done;
8623 error = apply_unveil(got_repo_get_path(repo), 0,
8624 got_worktree_get_root_path(worktree));
8625 if (error)
8626 goto done;
8628 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8629 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8630 if (error)
8631 goto done;
8632 error = got_object_id_str(&commit_id_str, commit_id);
8633 if (error)
8634 goto done;
8636 error = got_object_open_as_commit(&commit, repo, commit_id);
8637 if (error)
8638 goto done;
8639 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8640 if (pid == NULL) {
8641 error = got_error(GOT_ERR_ROOT_COMMIT);
8642 goto done;
8645 memset(&upa, 0, sizeof(upa));
8646 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8647 repo, update_progress, &upa, check_cancelled, NULL);
8648 if (error != NULL)
8649 goto done;
8651 if (upa.did_something)
8652 printf("Backed out commit %s\n", commit_id_str);
8653 print_merge_progress_stats(&upa);
8654 done:
8655 if (commit)
8656 got_object_commit_close(commit);
8657 free(commit_id_str);
8658 if (worktree)
8659 got_worktree_close(worktree);
8660 if (repo) {
8661 const struct got_error *close_err = got_repo_close(repo);
8662 if (error == NULL)
8663 error = close_err;
8665 return error;
8668 __dead static void
8669 usage_rebase(void)
8671 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8672 getprogname());
8673 exit(1);
8676 void
8677 trim_logmsg(char *logmsg, int limit)
8679 char *nl;
8680 size_t len;
8682 len = strlen(logmsg);
8683 if (len > limit)
8684 len = limit;
8685 logmsg[len] = '\0';
8686 nl = strchr(logmsg, '\n');
8687 if (nl)
8688 *nl = '\0';
8691 static const struct got_error *
8692 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8694 const struct got_error *err;
8695 char *logmsg0 = NULL;
8696 const char *s;
8698 err = got_object_commit_get_logmsg(&logmsg0, commit);
8699 if (err)
8700 return err;
8702 s = logmsg0;
8703 while (isspace((unsigned char)s[0]))
8704 s++;
8706 *logmsg = strdup(s);
8707 if (*logmsg == NULL) {
8708 err = got_error_from_errno("strdup");
8709 goto done;
8712 trim_logmsg(*logmsg, limit);
8713 done:
8714 free(logmsg0);
8715 return err;
8718 static const struct got_error *
8719 show_rebase_merge_conflict(struct got_object_id *id,
8720 struct got_repository *repo)
8722 const struct got_error *err;
8723 struct got_commit_object *commit = NULL;
8724 char *id_str = NULL, *logmsg = NULL;
8726 err = got_object_open_as_commit(&commit, repo, id);
8727 if (err)
8728 return err;
8730 err = got_object_id_str(&id_str, id);
8731 if (err)
8732 goto done;
8734 id_str[12] = '\0';
8736 err = get_short_logmsg(&logmsg, 42, commit);
8737 if (err)
8738 goto done;
8740 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8741 done:
8742 free(id_str);
8743 got_object_commit_close(commit);
8744 free(logmsg);
8745 return err;
8748 static const struct got_error *
8749 show_rebase_progress(struct got_commit_object *commit,
8750 struct got_object_id *old_id, struct got_object_id *new_id)
8752 const struct got_error *err;
8753 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8755 err = got_object_id_str(&old_id_str, old_id);
8756 if (err)
8757 goto done;
8759 if (new_id) {
8760 err = got_object_id_str(&new_id_str, new_id);
8761 if (err)
8762 goto done;
8765 old_id_str[12] = '\0';
8766 if (new_id_str)
8767 new_id_str[12] = '\0';
8769 err = get_short_logmsg(&logmsg, 42, commit);
8770 if (err)
8771 goto done;
8773 printf("%s -> %s: %s\n", old_id_str,
8774 new_id_str ? new_id_str : "no-op change", logmsg);
8775 done:
8776 free(old_id_str);
8777 free(new_id_str);
8778 free(logmsg);
8779 return err;
8782 static const struct got_error *
8783 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8784 struct got_reference *branch, struct got_reference *new_base_branch,
8785 struct got_reference *tmp_branch, struct got_repository *repo,
8786 int create_backup)
8788 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8789 return got_worktree_rebase_complete(worktree, fileindex,
8790 new_base_branch, tmp_branch, branch, repo, create_backup);
8793 static const struct got_error *
8794 rebase_commit(struct got_pathlist_head *merged_paths,
8795 struct got_worktree *worktree, struct got_fileindex *fileindex,
8796 struct got_reference *tmp_branch,
8797 struct got_object_id *commit_id, struct got_repository *repo)
8799 const struct got_error *error;
8800 struct got_commit_object *commit;
8801 struct got_object_id *new_commit_id;
8803 error = got_object_open_as_commit(&commit, repo, commit_id);
8804 if (error)
8805 return error;
8807 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8808 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8809 if (error) {
8810 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8811 goto done;
8812 error = show_rebase_progress(commit, commit_id, NULL);
8813 } else {
8814 error = show_rebase_progress(commit, commit_id, new_commit_id);
8815 free(new_commit_id);
8817 done:
8818 got_object_commit_close(commit);
8819 return error;
8822 struct check_path_prefix_arg {
8823 const char *path_prefix;
8824 size_t len;
8825 int errcode;
8828 static const struct got_error *
8829 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8830 struct got_blob_object *blob2, struct got_object_id *id1,
8831 struct got_object_id *id2, const char *path1, const char *path2,
8832 mode_t mode1, mode_t mode2, struct got_repository *repo)
8834 struct check_path_prefix_arg *a = arg;
8836 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8837 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8838 return got_error(a->errcode);
8840 return NULL;
8843 static const struct got_error *
8844 check_path_prefix(struct got_object_id *parent_id,
8845 struct got_object_id *commit_id, const char *path_prefix,
8846 int errcode, struct got_repository *repo)
8848 const struct got_error *err;
8849 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8850 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8851 struct check_path_prefix_arg cpp_arg;
8853 if (got_path_is_root_dir(path_prefix))
8854 return NULL;
8856 err = got_object_open_as_commit(&commit, repo, commit_id);
8857 if (err)
8858 goto done;
8860 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8861 if (err)
8862 goto done;
8864 err = got_object_open_as_tree(&tree1, repo,
8865 got_object_commit_get_tree_id(parent_commit));
8866 if (err)
8867 goto done;
8869 err = got_object_open_as_tree(&tree2, repo,
8870 got_object_commit_get_tree_id(commit));
8871 if (err)
8872 goto done;
8874 cpp_arg.path_prefix = path_prefix;
8875 while (cpp_arg.path_prefix[0] == '/')
8876 cpp_arg.path_prefix++;
8877 cpp_arg.len = strlen(cpp_arg.path_prefix);
8878 cpp_arg.errcode = errcode;
8879 err = got_diff_tree(tree1, tree2, "", "", repo,
8880 check_path_prefix_in_diff, &cpp_arg, 0);
8881 done:
8882 if (tree1)
8883 got_object_tree_close(tree1);
8884 if (tree2)
8885 got_object_tree_close(tree2);
8886 if (commit)
8887 got_object_commit_close(commit);
8888 if (parent_commit)
8889 got_object_commit_close(parent_commit);
8890 return err;
8893 static const struct got_error *
8894 collect_commits(struct got_object_id_queue *commits,
8895 struct got_object_id *initial_commit_id,
8896 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8897 const char *path_prefix, int path_prefix_errcode,
8898 struct got_repository *repo)
8900 const struct got_error *err = NULL;
8901 struct got_commit_graph *graph = NULL;
8902 struct got_object_id *parent_id = NULL;
8903 struct got_object_qid *qid;
8904 struct got_object_id *commit_id = initial_commit_id;
8906 err = got_commit_graph_open(&graph, "/", 1);
8907 if (err)
8908 return err;
8910 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8911 check_cancelled, NULL);
8912 if (err)
8913 goto done;
8914 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8915 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8916 check_cancelled, NULL);
8917 if (err) {
8918 if (err->code == GOT_ERR_ITER_COMPLETED) {
8919 err = got_error_msg(GOT_ERR_ANCESTRY,
8920 "ran out of commits to rebase before "
8921 "youngest common ancestor commit has "
8922 "been reached?!?");
8924 goto done;
8925 } else {
8926 err = check_path_prefix(parent_id, commit_id,
8927 path_prefix, path_prefix_errcode, repo);
8928 if (err)
8929 goto done;
8931 err = got_object_qid_alloc(&qid, commit_id);
8932 if (err)
8933 goto done;
8934 STAILQ_INSERT_HEAD(commits, qid, entry);
8935 commit_id = parent_id;
8938 done:
8939 got_commit_graph_close(graph);
8940 return err;
8943 static const struct got_error *
8944 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8946 const struct got_error *err = NULL;
8947 time_t committer_time;
8948 struct tm tm;
8949 char datebuf[11]; /* YYYY-MM-DD + NUL */
8950 char *author0 = NULL, *author, *smallerthan;
8951 char *logmsg0 = NULL, *logmsg, *newline;
8953 committer_time = got_object_commit_get_committer_time(commit);
8954 if (gmtime_r(&committer_time, &tm) == NULL)
8955 return got_error_from_errno("gmtime_r");
8956 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8957 return got_error(GOT_ERR_NO_SPACE);
8959 author0 = strdup(got_object_commit_get_author(commit));
8960 if (author0 == NULL)
8961 return got_error_from_errno("strdup");
8962 author = author0;
8963 smallerthan = strchr(author, '<');
8964 if (smallerthan && smallerthan[1] != '\0')
8965 author = smallerthan + 1;
8966 author[strcspn(author, "@>")] = '\0';
8968 err = got_object_commit_get_logmsg(&logmsg0, commit);
8969 if (err)
8970 goto done;
8971 logmsg = logmsg0;
8972 while (*logmsg == '\n')
8973 logmsg++;
8974 newline = strchr(logmsg, '\n');
8975 if (newline)
8976 *newline = '\0';
8978 if (asprintf(brief_str, "%s %s %s",
8979 datebuf, author, logmsg) == -1)
8980 err = got_error_from_errno("asprintf");
8981 done:
8982 free(author0);
8983 free(logmsg0);
8984 return err;
8987 static const struct got_error *
8988 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8989 struct got_repository *repo)
8991 const struct got_error *err;
8992 char *id_str;
8994 err = got_object_id_str(&id_str, id);
8995 if (err)
8996 return err;
8998 err = got_ref_delete(ref, repo);
8999 if (err)
9000 goto done;
9002 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9003 done:
9004 free(id_str);
9005 return err;
9008 static const struct got_error *
9009 print_backup_ref(const char *branch_name, const char *new_id_str,
9010 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9011 struct got_reflist_object_id_map *refs_idmap,
9012 struct got_repository *repo)
9014 const struct got_error *err = NULL;
9015 struct got_reflist_head *refs;
9016 char *refs_str = NULL;
9017 struct got_object_id *new_commit_id = NULL;
9018 struct got_commit_object *new_commit = NULL;
9019 char *new_commit_brief_str = NULL;
9020 struct got_object_id *yca_id = NULL;
9021 struct got_commit_object *yca_commit = NULL;
9022 char *yca_id_str = NULL, *yca_brief_str = NULL;
9023 char *custom_refs_str;
9025 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9026 return got_error_from_errno("asprintf");
9028 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9029 0, 0, refs_idmap, custom_refs_str);
9030 if (err)
9031 goto done;
9033 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9034 if (err)
9035 goto done;
9037 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9038 if (refs) {
9039 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9040 if (err)
9041 goto done;
9044 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9045 if (err)
9046 goto done;
9048 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9049 if (err)
9050 goto done;
9052 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9053 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9054 if (err)
9055 goto done;
9057 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9058 refs_str ? " (" : "", refs_str ? refs_str : "",
9059 refs_str ? ")" : "", new_commit_brief_str);
9060 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9061 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9062 free(refs_str);
9063 refs_str = NULL;
9065 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9066 if (err)
9067 goto done;
9069 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9070 if (err)
9071 goto done;
9073 err = got_object_id_str(&yca_id_str, yca_id);
9074 if (err)
9075 goto done;
9077 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9078 if (refs) {
9079 err = build_refs_str(&refs_str, refs, yca_id, repo);
9080 if (err)
9081 goto done;
9083 printf("history forked at %s%s%s%s\n %s\n",
9084 yca_id_str,
9085 refs_str ? " (" : "", refs_str ? refs_str : "",
9086 refs_str ? ")" : "", yca_brief_str);
9088 done:
9089 free(custom_refs_str);
9090 free(new_commit_id);
9091 free(refs_str);
9092 free(yca_id);
9093 free(yca_id_str);
9094 free(yca_brief_str);
9095 if (new_commit)
9096 got_object_commit_close(new_commit);
9097 if (yca_commit)
9098 got_object_commit_close(yca_commit);
9100 return NULL;
9103 static const struct got_error *
9104 process_backup_refs(const char *backup_ref_prefix,
9105 const char *wanted_branch_name,
9106 int delete, struct got_repository *repo)
9108 const struct got_error *err;
9109 struct got_reflist_head refs, backup_refs;
9110 struct got_reflist_entry *re;
9111 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9112 struct got_object_id *old_commit_id = NULL;
9113 char *branch_name = NULL;
9114 struct got_commit_object *old_commit = NULL;
9115 struct got_reflist_object_id_map *refs_idmap = NULL;
9116 int wanted_branch_found = 0;
9118 TAILQ_INIT(&refs);
9119 TAILQ_INIT(&backup_refs);
9121 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9122 if (err)
9123 return err;
9125 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9126 if (err)
9127 goto done;
9129 if (wanted_branch_name) {
9130 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9131 wanted_branch_name += 11;
9134 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9135 got_ref_cmp_by_commit_timestamp_descending, repo);
9136 if (err)
9137 goto done;
9139 TAILQ_FOREACH(re, &backup_refs, entry) {
9140 const char *refname = got_ref_get_name(re->ref);
9141 char *slash;
9143 err = check_cancelled(NULL);
9144 if (err)
9145 break;
9147 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9148 if (err)
9149 break;
9151 err = got_object_open_as_commit(&old_commit, repo,
9152 old_commit_id);
9153 if (err)
9154 break;
9156 if (strncmp(backup_ref_prefix, refname,
9157 backup_ref_prefix_len) == 0)
9158 refname += backup_ref_prefix_len;
9160 while (refname[0] == '/')
9161 refname++;
9163 branch_name = strdup(refname);
9164 if (branch_name == NULL) {
9165 err = got_error_from_errno("strdup");
9166 break;
9168 slash = strrchr(branch_name, '/');
9169 if (slash) {
9170 *slash = '\0';
9171 refname += strlen(branch_name) + 1;
9174 if (wanted_branch_name == NULL ||
9175 strcmp(wanted_branch_name, branch_name) == 0) {
9176 wanted_branch_found = 1;
9177 if (delete) {
9178 err = delete_backup_ref(re->ref,
9179 old_commit_id, repo);
9180 } else {
9181 err = print_backup_ref(branch_name, refname,
9182 old_commit_id, old_commit, refs_idmap,
9183 repo);
9185 if (err)
9186 break;
9189 free(old_commit_id);
9190 old_commit_id = NULL;
9191 free(branch_name);
9192 branch_name = NULL;
9193 got_object_commit_close(old_commit);
9194 old_commit = NULL;
9197 if (wanted_branch_name && !wanted_branch_found) {
9198 err = got_error_fmt(GOT_ERR_NOT_REF,
9199 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9201 done:
9202 if (refs_idmap)
9203 got_reflist_object_id_map_free(refs_idmap);
9204 got_ref_list_free(&refs);
9205 got_ref_list_free(&backup_refs);
9206 free(old_commit_id);
9207 free(branch_name);
9208 if (old_commit)
9209 got_object_commit_close(old_commit);
9210 return err;
9213 static const struct got_error *
9214 abort_progress(void *arg, unsigned char status, const char *path)
9217 * Unversioned files should not clutter progress output when
9218 * an operation is aborted.
9220 if (status == GOT_STATUS_UNVERSIONED)
9221 return NULL;
9223 return update_progress(arg, status, path);
9226 static const struct got_error *
9227 cmd_rebase(int argc, char *argv[])
9229 const struct got_error *error = NULL;
9230 struct got_worktree *worktree = NULL;
9231 struct got_repository *repo = NULL;
9232 struct got_fileindex *fileindex = NULL;
9233 char *cwd = NULL;
9234 struct got_reference *branch = NULL;
9235 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9236 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9237 struct got_object_id *resume_commit_id = NULL;
9238 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9239 struct got_commit_object *commit = NULL;
9240 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9241 int histedit_in_progress = 0, merge_in_progress = 0;
9242 int create_backup = 1, list_backups = 0, delete_backups = 0;
9243 struct got_object_id_queue commits;
9244 struct got_pathlist_head merged_paths;
9245 const struct got_object_id_queue *parent_ids;
9246 struct got_object_qid *qid, *pid;
9247 struct got_update_progress_arg upa;
9249 STAILQ_INIT(&commits);
9250 TAILQ_INIT(&merged_paths);
9251 memset(&upa, 0, sizeof(upa));
9253 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9254 switch (ch) {
9255 case 'a':
9256 abort_rebase = 1;
9257 break;
9258 case 'c':
9259 continue_rebase = 1;
9260 break;
9261 case 'l':
9262 list_backups = 1;
9263 break;
9264 case 'X':
9265 delete_backups = 1;
9266 break;
9267 default:
9268 usage_rebase();
9269 /* NOTREACHED */
9273 argc -= optind;
9274 argv += optind;
9276 #ifndef PROFILE
9277 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9278 "unveil", NULL) == -1)
9279 err(1, "pledge");
9280 #endif
9281 if (list_backups) {
9282 if (abort_rebase)
9283 option_conflict('l', 'a');
9284 if (continue_rebase)
9285 option_conflict('l', 'c');
9286 if (delete_backups)
9287 option_conflict('l', 'X');
9288 if (argc != 0 && argc != 1)
9289 usage_rebase();
9290 } else if (delete_backups) {
9291 if (abort_rebase)
9292 option_conflict('X', 'a');
9293 if (continue_rebase)
9294 option_conflict('X', 'c');
9295 if (list_backups)
9296 option_conflict('l', 'X');
9297 if (argc != 0 && argc != 1)
9298 usage_rebase();
9299 } else {
9300 if (abort_rebase && continue_rebase)
9301 usage_rebase();
9302 else if (abort_rebase || continue_rebase) {
9303 if (argc != 0)
9304 usage_rebase();
9305 } else if (argc != 1)
9306 usage_rebase();
9309 cwd = getcwd(NULL, 0);
9310 if (cwd == NULL) {
9311 error = got_error_from_errno("getcwd");
9312 goto done;
9314 error = got_worktree_open(&worktree, cwd);
9315 if (error) {
9316 if (list_backups || delete_backups) {
9317 if (error->code != GOT_ERR_NOT_WORKTREE)
9318 goto done;
9319 } else {
9320 if (error->code == GOT_ERR_NOT_WORKTREE)
9321 error = wrap_not_worktree_error(error,
9322 "rebase", cwd);
9323 goto done;
9327 error = got_repo_open(&repo,
9328 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9329 if (error != NULL)
9330 goto done;
9332 error = apply_unveil(got_repo_get_path(repo), 0,
9333 worktree ? got_worktree_get_root_path(worktree) : NULL);
9334 if (error)
9335 goto done;
9337 if (list_backups || delete_backups) {
9338 error = process_backup_refs(
9339 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9340 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9341 goto done; /* nothing else to do */
9344 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9345 worktree);
9346 if (error)
9347 goto done;
9348 if (histedit_in_progress) {
9349 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9350 goto done;
9353 error = got_worktree_merge_in_progress(&merge_in_progress,
9354 worktree, repo);
9355 if (error)
9356 goto done;
9357 if (merge_in_progress) {
9358 error = got_error(GOT_ERR_MERGE_BUSY);
9359 goto done;
9362 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9363 if (error)
9364 goto done;
9366 if (abort_rebase) {
9367 if (!rebase_in_progress) {
9368 error = got_error(GOT_ERR_NOT_REBASING);
9369 goto done;
9371 error = got_worktree_rebase_continue(&resume_commit_id,
9372 &new_base_branch, &tmp_branch, &branch, &fileindex,
9373 worktree, repo);
9374 if (error)
9375 goto done;
9376 printf("Switching work tree to %s\n",
9377 got_ref_get_symref_target(new_base_branch));
9378 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9379 new_base_branch, abort_progress, &upa);
9380 if (error)
9381 goto done;
9382 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9383 print_merge_progress_stats(&upa);
9384 goto done; /* nothing else to do */
9387 if (continue_rebase) {
9388 if (!rebase_in_progress) {
9389 error = got_error(GOT_ERR_NOT_REBASING);
9390 goto done;
9392 error = got_worktree_rebase_continue(&resume_commit_id,
9393 &new_base_branch, &tmp_branch, &branch, &fileindex,
9394 worktree, repo);
9395 if (error)
9396 goto done;
9398 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9399 resume_commit_id, repo);
9400 if (error)
9401 goto done;
9403 yca_id = got_object_id_dup(resume_commit_id);
9404 if (yca_id == NULL) {
9405 error = got_error_from_errno("got_object_id_dup");
9406 goto done;
9408 } else {
9409 error = got_ref_open(&branch, repo, argv[0], 0);
9410 if (error != NULL)
9411 goto done;
9414 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9415 if (error)
9416 goto done;
9418 if (!continue_rebase) {
9419 struct got_object_id *base_commit_id;
9421 base_commit_id = got_worktree_get_base_commit_id(worktree);
9422 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9423 base_commit_id, branch_head_commit_id, 1, repo,
9424 check_cancelled, NULL);
9425 if (error)
9426 goto done;
9427 if (yca_id == NULL) {
9428 error = got_error_msg(GOT_ERR_ANCESTRY,
9429 "specified branch shares no common ancestry "
9430 "with work tree's branch");
9431 goto done;
9434 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9435 if (error) {
9436 if (error->code != GOT_ERR_ANCESTRY)
9437 goto done;
9438 error = NULL;
9439 } else {
9440 struct got_pathlist_head paths;
9441 printf("%s is already based on %s\n",
9442 got_ref_get_name(branch),
9443 got_worktree_get_head_ref_name(worktree));
9444 error = switch_head_ref(branch, branch_head_commit_id,
9445 worktree, repo);
9446 if (error)
9447 goto done;
9448 error = got_worktree_set_base_commit_id(worktree, repo,
9449 branch_head_commit_id);
9450 if (error)
9451 goto done;
9452 TAILQ_INIT(&paths);
9453 error = got_pathlist_append(&paths, "", NULL);
9454 if (error)
9455 goto done;
9456 error = got_worktree_checkout_files(worktree,
9457 &paths, repo, update_progress, &upa,
9458 check_cancelled, NULL);
9459 got_pathlist_free(&paths);
9460 if (error)
9461 goto done;
9462 if (upa.did_something) {
9463 char *id_str;
9464 error = got_object_id_str(&id_str,
9465 branch_head_commit_id);
9466 if (error)
9467 goto done;
9468 printf("Updated to %s: %s\n",
9469 got_worktree_get_head_ref_name(worktree),
9470 id_str);
9471 free(id_str);
9472 } else
9473 printf("Already up-to-date\n");
9474 print_update_progress_stats(&upa);
9475 goto done;
9479 commit_id = branch_head_commit_id;
9480 error = got_object_open_as_commit(&commit, repo, commit_id);
9481 if (error)
9482 goto done;
9484 parent_ids = got_object_commit_get_parent_ids(commit);
9485 pid = STAILQ_FIRST(parent_ids);
9486 if (pid == NULL) {
9487 error = got_error(GOT_ERR_EMPTY_REBASE);
9488 goto done;
9490 error = collect_commits(&commits, commit_id, &pid->id,
9491 yca_id, got_worktree_get_path_prefix(worktree),
9492 GOT_ERR_REBASE_PATH, repo);
9493 got_object_commit_close(commit);
9494 commit = NULL;
9495 if (error)
9496 goto done;
9498 if (!continue_rebase) {
9499 error = got_worktree_rebase_prepare(&new_base_branch,
9500 &tmp_branch, &fileindex, worktree, branch, repo);
9501 if (error)
9502 goto done;
9505 if (STAILQ_EMPTY(&commits)) {
9506 if (continue_rebase) {
9507 error = rebase_complete(worktree, fileindex,
9508 branch, new_base_branch, tmp_branch, repo,
9509 create_backup);
9510 goto done;
9511 } else {
9512 /* Fast-forward the reference of the branch. */
9513 struct got_object_id *new_head_commit_id;
9514 char *id_str;
9515 error = got_ref_resolve(&new_head_commit_id, repo,
9516 new_base_branch);
9517 if (error)
9518 goto done;
9519 error = got_object_id_str(&id_str, new_head_commit_id);
9520 printf("Forwarding %s to commit %s\n",
9521 got_ref_get_name(branch), id_str);
9522 free(id_str);
9523 error = got_ref_change_ref(branch,
9524 new_head_commit_id);
9525 if (error)
9526 goto done;
9527 /* No backup needed since objects did not change. */
9528 create_backup = 0;
9532 pid = NULL;
9533 STAILQ_FOREACH(qid, &commits, entry) {
9535 commit_id = &qid->id;
9536 parent_id = pid ? &pid->id : yca_id;
9537 pid = qid;
9539 memset(&upa, 0, sizeof(upa));
9540 error = got_worktree_rebase_merge_files(&merged_paths,
9541 worktree, fileindex, parent_id, commit_id, repo,
9542 update_progress, &upa, check_cancelled, NULL);
9543 if (error)
9544 goto done;
9546 print_merge_progress_stats(&upa);
9547 if (upa.conflicts > 0 || upa.missing > 0 ||
9548 upa.not_deleted > 0 || upa.unversioned > 0) {
9549 if (upa.conflicts > 0) {
9550 error = show_rebase_merge_conflict(&qid->id,
9551 repo);
9552 if (error)
9553 goto done;
9555 got_worktree_rebase_pathlist_free(&merged_paths);
9556 break;
9559 error = rebase_commit(&merged_paths, worktree, fileindex,
9560 tmp_branch, commit_id, repo);
9561 got_worktree_rebase_pathlist_free(&merged_paths);
9562 if (error)
9563 goto done;
9566 if (upa.conflicts > 0 || upa.missing > 0 ||
9567 upa.not_deleted > 0 || upa.unversioned > 0) {
9568 error = got_worktree_rebase_postpone(worktree, fileindex);
9569 if (error)
9570 goto done;
9571 if (upa.conflicts > 0 && upa.missing == 0 &&
9572 upa.not_deleted == 0 && upa.unversioned == 0) {
9573 error = got_error_msg(GOT_ERR_CONFLICTS,
9574 "conflicts must be resolved before rebasing "
9575 "can continue");
9576 } else if (upa.conflicts > 0) {
9577 error = got_error_msg(GOT_ERR_CONFLICTS,
9578 "conflicts must be resolved before rebasing "
9579 "can continue; changes destined for some "
9580 "files were not yet merged and should be "
9581 "merged manually if required before the "
9582 "rebase operation is continued");
9583 } else {
9584 error = got_error_msg(GOT_ERR_CONFLICTS,
9585 "changes destined for some files were not "
9586 "yet merged and should be merged manually "
9587 "if required before the rebase operation "
9588 "is continued");
9590 } else
9591 error = rebase_complete(worktree, fileindex, branch,
9592 new_base_branch, tmp_branch, repo, create_backup);
9593 done:
9594 got_object_id_queue_free(&commits);
9595 free(branch_head_commit_id);
9596 free(resume_commit_id);
9597 free(yca_id);
9598 if (commit)
9599 got_object_commit_close(commit);
9600 if (branch)
9601 got_ref_close(branch);
9602 if (new_base_branch)
9603 got_ref_close(new_base_branch);
9604 if (tmp_branch)
9605 got_ref_close(tmp_branch);
9606 if (worktree)
9607 got_worktree_close(worktree);
9608 if (repo) {
9609 const struct got_error *close_err = got_repo_close(repo);
9610 if (error == NULL)
9611 error = close_err;
9613 return error;
9616 __dead static void
9617 usage_histedit(void)
9619 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9620 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9621 getprogname());
9622 exit(1);
9625 #define GOT_HISTEDIT_PICK 'p'
9626 #define GOT_HISTEDIT_EDIT 'e'
9627 #define GOT_HISTEDIT_FOLD 'f'
9628 #define GOT_HISTEDIT_DROP 'd'
9629 #define GOT_HISTEDIT_MESG 'm'
9631 static const struct got_histedit_cmd {
9632 unsigned char code;
9633 const char *name;
9634 const char *desc;
9635 } got_histedit_cmds[] = {
9636 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9637 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9638 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9639 "be used" },
9640 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9641 { GOT_HISTEDIT_MESG, "mesg",
9642 "single-line log message for commit above (open editor if empty)" },
9645 struct got_histedit_list_entry {
9646 TAILQ_ENTRY(got_histedit_list_entry) entry;
9647 struct got_object_id *commit_id;
9648 const struct got_histedit_cmd *cmd;
9649 char *logmsg;
9651 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9653 static const struct got_error *
9654 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9655 FILE *f, struct got_repository *repo)
9657 const struct got_error *err = NULL;
9658 char *logmsg = NULL, *id_str = NULL;
9659 struct got_commit_object *commit = NULL;
9660 int n;
9662 err = got_object_open_as_commit(&commit, repo, commit_id);
9663 if (err)
9664 goto done;
9666 err = get_short_logmsg(&logmsg, 34, commit);
9667 if (err)
9668 goto done;
9670 err = got_object_id_str(&id_str, commit_id);
9671 if (err)
9672 goto done;
9674 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9675 if (n < 0)
9676 err = got_ferror(f, GOT_ERR_IO);
9677 done:
9678 if (commit)
9679 got_object_commit_close(commit);
9680 free(id_str);
9681 free(logmsg);
9682 return err;
9685 static const struct got_error *
9686 histedit_write_commit_list(struct got_object_id_queue *commits,
9687 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9688 struct got_repository *repo)
9690 const struct got_error *err = NULL;
9691 struct got_object_qid *qid;
9692 const char *histedit_cmd = NULL;
9694 if (STAILQ_EMPTY(commits))
9695 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9697 STAILQ_FOREACH(qid, commits, entry) {
9698 histedit_cmd = got_histedit_cmds[0].name;
9699 if (edit_only)
9700 histedit_cmd = "edit";
9701 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9702 histedit_cmd = "fold";
9703 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9704 if (err)
9705 break;
9706 if (edit_logmsg_only) {
9707 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9708 if (n < 0) {
9709 err = got_ferror(f, GOT_ERR_IO);
9710 break;
9715 return err;
9718 static const struct got_error *
9719 write_cmd_list(FILE *f, const char *branch_name,
9720 struct got_object_id_queue *commits)
9722 const struct got_error *err = NULL;
9723 size_t i;
9724 int n;
9725 char *id_str;
9726 struct got_object_qid *qid;
9728 qid = STAILQ_FIRST(commits);
9729 err = got_object_id_str(&id_str, &qid->id);
9730 if (err)
9731 return err;
9733 n = fprintf(f,
9734 "# Editing the history of branch '%s' starting at\n"
9735 "# commit %s\n"
9736 "# Commits will be processed in order from top to "
9737 "bottom of this file.\n", branch_name, id_str);
9738 if (n < 0) {
9739 err = got_ferror(f, GOT_ERR_IO);
9740 goto done;
9743 n = fprintf(f, "# Available histedit commands:\n");
9744 if (n < 0) {
9745 err = got_ferror(f, GOT_ERR_IO);
9746 goto done;
9749 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9750 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9751 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9752 cmd->desc);
9753 if (n < 0) {
9754 err = got_ferror(f, GOT_ERR_IO);
9755 break;
9758 done:
9759 free(id_str);
9760 return err;
9763 static const struct got_error *
9764 histedit_syntax_error(int lineno)
9766 static char msg[42];
9767 int ret;
9769 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9770 lineno);
9771 if (ret == -1 || ret >= sizeof(msg))
9772 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9774 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9777 static const struct got_error *
9778 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9779 char *logmsg, struct got_repository *repo)
9781 const struct got_error *err;
9782 struct got_commit_object *folded_commit = NULL;
9783 char *id_str, *folded_logmsg = NULL;
9785 err = got_object_id_str(&id_str, hle->commit_id);
9786 if (err)
9787 return err;
9789 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9790 if (err)
9791 goto done;
9793 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9794 if (err)
9795 goto done;
9796 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9797 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9798 folded_logmsg) == -1) {
9799 err = got_error_from_errno("asprintf");
9801 done:
9802 if (folded_commit)
9803 got_object_commit_close(folded_commit);
9804 free(id_str);
9805 free(folded_logmsg);
9806 return err;
9809 static struct got_histedit_list_entry *
9810 get_folded_commits(struct got_histedit_list_entry *hle)
9812 struct got_histedit_list_entry *prev, *folded = NULL;
9814 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9815 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9816 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9817 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9818 folded = prev;
9819 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9822 return folded;
9825 static const struct got_error *
9826 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9827 struct got_repository *repo)
9829 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9830 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9831 const struct got_error *err = NULL;
9832 struct got_commit_object *commit = NULL;
9833 int logmsg_len;
9834 int fd;
9835 struct got_histedit_list_entry *folded = NULL;
9837 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9838 if (err)
9839 return err;
9841 folded = get_folded_commits(hle);
9842 if (folded) {
9843 while (folded != hle) {
9844 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9845 folded = TAILQ_NEXT(folded, entry);
9846 continue;
9848 err = append_folded_commit_msg(&new_msg, folded,
9849 logmsg, repo);
9850 if (err)
9851 goto done;
9852 free(logmsg);
9853 logmsg = new_msg;
9854 folded = TAILQ_NEXT(folded, entry);
9858 err = got_object_id_str(&id_str, hle->commit_id);
9859 if (err)
9860 goto done;
9861 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9862 if (err)
9863 goto done;
9864 logmsg_len = asprintf(&new_msg,
9865 "%s\n# original log message of commit %s: %s",
9866 logmsg ? logmsg : "", id_str, orig_logmsg);
9867 if (logmsg_len == -1) {
9868 err = got_error_from_errno("asprintf");
9869 goto done;
9871 free(logmsg);
9872 logmsg = new_msg;
9874 err = got_object_id_str(&id_str, hle->commit_id);
9875 if (err)
9876 goto done;
9878 err = got_opentemp_named_fd(&logmsg_path, &fd,
9879 GOT_TMPDIR_STR "/got-logmsg");
9880 if (err)
9881 goto done;
9883 write(fd, logmsg, logmsg_len);
9884 close(fd);
9886 err = get_editor(&editor);
9887 if (err)
9888 goto done;
9890 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9891 logmsg_len, 0);
9892 if (err) {
9893 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9894 goto done;
9895 err = NULL;
9896 hle->logmsg = strdup(new_msg);
9897 if (hle->logmsg == NULL)
9898 err = got_error_from_errno("strdup");
9900 done:
9901 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9902 err = got_error_from_errno2("unlink", logmsg_path);
9903 free(logmsg_path);
9904 free(logmsg);
9905 free(orig_logmsg);
9906 free(editor);
9907 if (commit)
9908 got_object_commit_close(commit);
9909 return err;
9912 static const struct got_error *
9913 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9914 FILE *f, struct got_repository *repo)
9916 const struct got_error *err = NULL;
9917 char *line = NULL, *p, *end;
9918 size_t i, size;
9919 ssize_t len;
9920 int lineno = 0;
9921 const struct got_histedit_cmd *cmd;
9922 struct got_object_id *commit_id = NULL;
9923 struct got_histedit_list_entry *hle = NULL;
9925 for (;;) {
9926 len = getline(&line, &size, f);
9927 if (len == -1) {
9928 const struct got_error *getline_err;
9929 if (feof(f))
9930 break;
9931 getline_err = got_error_from_errno("getline");
9932 err = got_ferror(f, getline_err->code);
9933 break;
9935 lineno++;
9936 p = line;
9937 while (isspace((unsigned char)p[0]))
9938 p++;
9939 if (p[0] == '#' || p[0] == '\0') {
9940 free(line);
9941 line = NULL;
9942 continue;
9944 cmd = NULL;
9945 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9946 cmd = &got_histedit_cmds[i];
9947 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9948 isspace((unsigned char)p[strlen(cmd->name)])) {
9949 p += strlen(cmd->name);
9950 break;
9952 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9953 p++;
9954 break;
9957 if (i == nitems(got_histedit_cmds)) {
9958 err = histedit_syntax_error(lineno);
9959 break;
9961 while (isspace((unsigned char)p[0]))
9962 p++;
9963 if (cmd->code == GOT_HISTEDIT_MESG) {
9964 if (hle == NULL || hle->logmsg != NULL) {
9965 err = got_error(GOT_ERR_HISTEDIT_CMD);
9966 break;
9968 if (p[0] == '\0') {
9969 err = histedit_edit_logmsg(hle, repo);
9970 if (err)
9971 break;
9972 } else {
9973 hle->logmsg = strdup(p);
9974 if (hle->logmsg == NULL) {
9975 err = got_error_from_errno("strdup");
9976 break;
9979 free(line);
9980 line = NULL;
9981 continue;
9982 } else {
9983 end = p;
9984 while (end[0] && !isspace((unsigned char)end[0]))
9985 end++;
9986 *end = '\0';
9988 err = got_object_resolve_id_str(&commit_id, repo, p);
9989 if (err) {
9990 /* override error code */
9991 err = histedit_syntax_error(lineno);
9992 break;
9995 hle = malloc(sizeof(*hle));
9996 if (hle == NULL) {
9997 err = got_error_from_errno("malloc");
9998 break;
10000 hle->cmd = cmd;
10001 hle->commit_id = commit_id;
10002 hle->logmsg = NULL;
10003 commit_id = NULL;
10004 free(line);
10005 line = NULL;
10006 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10009 free(line);
10010 free(commit_id);
10011 return err;
10014 static const struct got_error *
10015 histedit_check_script(struct got_histedit_list *histedit_cmds,
10016 struct got_object_id_queue *commits, struct got_repository *repo)
10018 const struct got_error *err = NULL;
10019 struct got_object_qid *qid;
10020 struct got_histedit_list_entry *hle;
10021 static char msg[92];
10022 char *id_str;
10024 if (TAILQ_EMPTY(histedit_cmds))
10025 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10026 "histedit script contains no commands");
10027 if (STAILQ_EMPTY(commits))
10028 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10030 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10031 struct got_histedit_list_entry *hle2;
10032 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10033 if (hle == hle2)
10034 continue;
10035 if (got_object_id_cmp(hle->commit_id,
10036 hle2->commit_id) != 0)
10037 continue;
10038 err = got_object_id_str(&id_str, hle->commit_id);
10039 if (err)
10040 return err;
10041 snprintf(msg, sizeof(msg), "commit %s is listed "
10042 "more than once in histedit script", id_str);
10043 free(id_str);
10044 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10048 STAILQ_FOREACH(qid, commits, entry) {
10049 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10050 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10051 break;
10053 if (hle == NULL) {
10054 err = got_object_id_str(&id_str, &qid->id);
10055 if (err)
10056 return err;
10057 snprintf(msg, sizeof(msg),
10058 "commit %s missing from histedit script", id_str);
10059 free(id_str);
10060 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10064 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10065 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10066 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10067 "last commit in histedit script cannot be folded");
10069 return NULL;
10072 static const struct got_error *
10073 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10074 const char *path, struct got_object_id_queue *commits,
10075 struct got_repository *repo)
10077 const struct got_error *err = NULL;
10078 char *editor;
10079 FILE *f = NULL;
10081 err = get_editor(&editor);
10082 if (err)
10083 return err;
10085 if (spawn_editor(editor, path) == -1) {
10086 err = got_error_from_errno("failed spawning editor");
10087 goto done;
10090 f = fopen(path, "re");
10091 if (f == NULL) {
10092 err = got_error_from_errno("fopen");
10093 goto done;
10095 err = histedit_parse_list(histedit_cmds, f, repo);
10096 if (err)
10097 goto done;
10099 err = histedit_check_script(histedit_cmds, commits, repo);
10100 done:
10101 if (f && fclose(f) == EOF && err == NULL)
10102 err = got_error_from_errno("fclose");
10103 free(editor);
10104 return err;
10107 static const struct got_error *
10108 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10109 struct got_object_id_queue *, const char *, const char *,
10110 struct got_repository *);
10112 static const struct got_error *
10113 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10114 struct got_object_id_queue *commits, const char *branch_name,
10115 int edit_logmsg_only, int fold_only, int edit_only,
10116 struct got_repository *repo)
10118 const struct got_error *err;
10119 FILE *f = NULL;
10120 char *path = NULL;
10122 err = got_opentemp_named(&path, &f, "got-histedit");
10123 if (err)
10124 return err;
10126 err = write_cmd_list(f, branch_name, commits);
10127 if (err)
10128 goto done;
10130 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10131 fold_only, edit_only, repo);
10132 if (err)
10133 goto done;
10135 if (edit_logmsg_only || fold_only || edit_only) {
10136 rewind(f);
10137 err = histedit_parse_list(histedit_cmds, f, repo);
10138 } else {
10139 if (fclose(f) == EOF) {
10140 err = got_error_from_errno("fclose");
10141 goto done;
10143 f = NULL;
10144 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10145 if (err) {
10146 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10147 err->code != GOT_ERR_HISTEDIT_CMD)
10148 goto done;
10149 err = histedit_edit_list_retry(histedit_cmds, err,
10150 commits, path, branch_name, repo);
10153 done:
10154 if (f && fclose(f) == EOF && err == NULL)
10155 err = got_error_from_errno("fclose");
10156 if (path && unlink(path) != 0 && err == NULL)
10157 err = got_error_from_errno2("unlink", path);
10158 free(path);
10159 return err;
10162 static const struct got_error *
10163 histedit_save_list(struct got_histedit_list *histedit_cmds,
10164 struct got_worktree *worktree, struct got_repository *repo)
10166 const struct got_error *err = NULL;
10167 char *path = NULL;
10168 FILE *f = NULL;
10169 struct got_histedit_list_entry *hle;
10170 struct got_commit_object *commit = NULL;
10172 err = got_worktree_get_histedit_script_path(&path, worktree);
10173 if (err)
10174 return err;
10176 f = fopen(path, "we");
10177 if (f == NULL) {
10178 err = got_error_from_errno2("fopen", path);
10179 goto done;
10181 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10182 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10183 repo);
10184 if (err)
10185 break;
10187 if (hle->logmsg) {
10188 int n = fprintf(f, "%c %s\n",
10189 GOT_HISTEDIT_MESG, hle->logmsg);
10190 if (n < 0) {
10191 err = got_ferror(f, GOT_ERR_IO);
10192 break;
10196 done:
10197 if (f && fclose(f) == EOF && err == NULL)
10198 err = got_error_from_errno("fclose");
10199 free(path);
10200 if (commit)
10201 got_object_commit_close(commit);
10202 return err;
10205 void
10206 histedit_free_list(struct got_histedit_list *histedit_cmds)
10208 struct got_histedit_list_entry *hle;
10210 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10211 TAILQ_REMOVE(histedit_cmds, hle, entry);
10212 free(hle);
10216 static const struct got_error *
10217 histedit_load_list(struct got_histedit_list *histedit_cmds,
10218 const char *path, struct got_repository *repo)
10220 const struct got_error *err = NULL;
10221 FILE *f = NULL;
10223 f = fopen(path, "re");
10224 if (f == NULL) {
10225 err = got_error_from_errno2("fopen", path);
10226 goto done;
10229 err = histedit_parse_list(histedit_cmds, f, repo);
10230 done:
10231 if (f && fclose(f) == EOF && err == NULL)
10232 err = got_error_from_errno("fclose");
10233 return err;
10236 static const struct got_error *
10237 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10238 const struct got_error *edit_err, struct got_object_id_queue *commits,
10239 const char *path, const char *branch_name, struct got_repository *repo)
10241 const struct got_error *err = NULL, *prev_err = edit_err;
10242 int resp = ' ';
10244 while (resp != 'c' && resp != 'r' && resp != 'a') {
10245 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10246 "or (a)bort: ", getprogname(), prev_err->msg);
10247 resp = getchar();
10248 if (resp == '\n')
10249 resp = getchar();
10250 if (resp == 'c') {
10251 histedit_free_list(histedit_cmds);
10252 err = histedit_run_editor(histedit_cmds, path, commits,
10253 repo);
10254 if (err) {
10255 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10256 err->code != GOT_ERR_HISTEDIT_CMD)
10257 break;
10258 prev_err = err;
10259 resp = ' ';
10260 continue;
10262 break;
10263 } else if (resp == 'r') {
10264 histedit_free_list(histedit_cmds);
10265 err = histedit_edit_script(histedit_cmds,
10266 commits, branch_name, 0, 0, 0, repo);
10267 if (err) {
10268 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10269 err->code != GOT_ERR_HISTEDIT_CMD)
10270 break;
10271 prev_err = err;
10272 resp = ' ';
10273 continue;
10275 break;
10276 } else if (resp == 'a') {
10277 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10278 break;
10279 } else
10280 printf("invalid response '%c'\n", resp);
10283 return err;
10286 static const struct got_error *
10287 histedit_complete(struct got_worktree *worktree,
10288 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10289 struct got_reference *branch, struct got_repository *repo)
10291 printf("Switching work tree to %s\n",
10292 got_ref_get_symref_target(branch));
10293 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10294 branch, repo);
10297 static const struct got_error *
10298 show_histedit_progress(struct got_commit_object *commit,
10299 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10301 const struct got_error *err;
10302 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10304 err = got_object_id_str(&old_id_str, hle->commit_id);
10305 if (err)
10306 goto done;
10308 if (new_id) {
10309 err = got_object_id_str(&new_id_str, new_id);
10310 if (err)
10311 goto done;
10314 old_id_str[12] = '\0';
10315 if (new_id_str)
10316 new_id_str[12] = '\0';
10318 if (hle->logmsg) {
10319 logmsg = strdup(hle->logmsg);
10320 if (logmsg == NULL) {
10321 err = got_error_from_errno("strdup");
10322 goto done;
10324 trim_logmsg(logmsg, 42);
10325 } else {
10326 err = get_short_logmsg(&logmsg, 42, commit);
10327 if (err)
10328 goto done;
10331 switch (hle->cmd->code) {
10332 case GOT_HISTEDIT_PICK:
10333 case GOT_HISTEDIT_EDIT:
10334 printf("%s -> %s: %s\n", old_id_str,
10335 new_id_str ? new_id_str : "no-op change", logmsg);
10336 break;
10337 case GOT_HISTEDIT_DROP:
10338 case GOT_HISTEDIT_FOLD:
10339 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10340 logmsg);
10341 break;
10342 default:
10343 break;
10345 done:
10346 free(old_id_str);
10347 free(new_id_str);
10348 return err;
10351 static const struct got_error *
10352 histedit_commit(struct got_pathlist_head *merged_paths,
10353 struct got_worktree *worktree, struct got_fileindex *fileindex,
10354 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10355 struct got_repository *repo)
10357 const struct got_error *err;
10358 struct got_commit_object *commit;
10359 struct got_object_id *new_commit_id;
10361 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10362 && hle->logmsg == NULL) {
10363 err = histedit_edit_logmsg(hle, repo);
10364 if (err)
10365 return err;
10368 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10369 if (err)
10370 return err;
10372 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10373 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10374 hle->logmsg, repo);
10375 if (err) {
10376 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10377 goto done;
10378 err = show_histedit_progress(commit, hle, NULL);
10379 } else {
10380 err = show_histedit_progress(commit, hle, new_commit_id);
10381 free(new_commit_id);
10383 done:
10384 got_object_commit_close(commit);
10385 return err;
10388 static const struct got_error *
10389 histedit_skip_commit(struct got_histedit_list_entry *hle,
10390 struct got_worktree *worktree, struct got_repository *repo)
10392 const struct got_error *error;
10393 struct got_commit_object *commit;
10395 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10396 repo);
10397 if (error)
10398 return error;
10400 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10401 if (error)
10402 return error;
10404 error = show_histedit_progress(commit, hle, NULL);
10405 got_object_commit_close(commit);
10406 return error;
10409 static const struct got_error *
10410 check_local_changes(void *arg, unsigned char status,
10411 unsigned char staged_status, const char *path,
10412 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10413 struct got_object_id *commit_id, int dirfd, const char *de_name)
10415 int *have_local_changes = arg;
10417 switch (status) {
10418 case GOT_STATUS_ADD:
10419 case GOT_STATUS_DELETE:
10420 case GOT_STATUS_MODIFY:
10421 case GOT_STATUS_CONFLICT:
10422 *have_local_changes = 1;
10423 return got_error(GOT_ERR_CANCELLED);
10424 default:
10425 break;
10428 switch (staged_status) {
10429 case GOT_STATUS_ADD:
10430 case GOT_STATUS_DELETE:
10431 case GOT_STATUS_MODIFY:
10432 *have_local_changes = 1;
10433 return got_error(GOT_ERR_CANCELLED);
10434 default:
10435 break;
10438 return NULL;
10441 static const struct got_error *
10442 cmd_histedit(int argc, char *argv[])
10444 const struct got_error *error = NULL;
10445 struct got_worktree *worktree = NULL;
10446 struct got_fileindex *fileindex = NULL;
10447 struct got_repository *repo = NULL;
10448 char *cwd = NULL;
10449 struct got_reference *branch = NULL;
10450 struct got_reference *tmp_branch = NULL;
10451 struct got_object_id *resume_commit_id = NULL;
10452 struct got_object_id *base_commit_id = NULL;
10453 struct got_object_id *head_commit_id = NULL;
10454 struct got_commit_object *commit = NULL;
10455 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10456 struct got_update_progress_arg upa;
10457 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10458 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10459 int list_backups = 0, delete_backups = 0;
10460 const char *edit_script_path = NULL;
10461 struct got_object_id_queue commits;
10462 struct got_pathlist_head merged_paths;
10463 const struct got_object_id_queue *parent_ids;
10464 struct got_object_qid *pid;
10465 struct got_histedit_list histedit_cmds;
10466 struct got_histedit_list_entry *hle;
10468 STAILQ_INIT(&commits);
10469 TAILQ_INIT(&histedit_cmds);
10470 TAILQ_INIT(&merged_paths);
10471 memset(&upa, 0, sizeof(upa));
10473 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10474 switch (ch) {
10475 case 'a':
10476 abort_edit = 1;
10477 break;
10478 case 'c':
10479 continue_edit = 1;
10480 break;
10481 case 'e':
10482 edit_only = 1;
10483 break;
10484 case 'f':
10485 fold_only = 1;
10486 break;
10487 case 'F':
10488 edit_script_path = optarg;
10489 break;
10490 case 'm':
10491 edit_logmsg_only = 1;
10492 break;
10493 case 'l':
10494 list_backups = 1;
10495 break;
10496 case 'X':
10497 delete_backups = 1;
10498 break;
10499 default:
10500 usage_histedit();
10501 /* NOTREACHED */
10505 argc -= optind;
10506 argv += optind;
10508 #ifndef PROFILE
10509 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10510 "unveil", NULL) == -1)
10511 err(1, "pledge");
10512 #endif
10513 if (abort_edit && continue_edit)
10514 option_conflict('a', 'c');
10515 if (edit_script_path && edit_logmsg_only)
10516 option_conflict('F', 'm');
10517 if (abort_edit && edit_logmsg_only)
10518 option_conflict('a', 'm');
10519 if (continue_edit && edit_logmsg_only)
10520 option_conflict('c', 'm');
10521 if (abort_edit && fold_only)
10522 option_conflict('a', 'f');
10523 if (continue_edit && fold_only)
10524 option_conflict('c', 'f');
10525 if (fold_only && edit_logmsg_only)
10526 option_conflict('f', 'm');
10527 if (edit_script_path && fold_only)
10528 option_conflict('F', 'f');
10529 if (abort_edit && edit_only)
10530 option_conflict('a', 'e');
10531 if (continue_edit && edit_only)
10532 option_conflict('c', 'e');
10533 if (edit_only && edit_logmsg_only)
10534 option_conflict('e', 'm');
10535 if (edit_script_path && edit_only)
10536 option_conflict('F', 'e');
10537 if (list_backups) {
10538 if (abort_edit)
10539 option_conflict('l', 'a');
10540 if (continue_edit)
10541 option_conflict('l', 'c');
10542 if (edit_script_path)
10543 option_conflict('l', 'F');
10544 if (edit_logmsg_only)
10545 option_conflict('l', 'm');
10546 if (fold_only)
10547 option_conflict('l', 'f');
10548 if (edit_only)
10549 option_conflict('l', 'e');
10550 if (delete_backups)
10551 option_conflict('l', 'X');
10552 if (argc != 0 && argc != 1)
10553 usage_histedit();
10554 } else if (delete_backups) {
10555 if (abort_edit)
10556 option_conflict('X', 'a');
10557 if (continue_edit)
10558 option_conflict('X', 'c');
10559 if (edit_script_path)
10560 option_conflict('X', 'F');
10561 if (edit_logmsg_only)
10562 option_conflict('X', 'm');
10563 if (fold_only)
10564 option_conflict('X', 'f');
10565 if (edit_only)
10566 option_conflict('X', 'e');
10567 if (list_backups)
10568 option_conflict('X', 'l');
10569 if (argc != 0 && argc != 1)
10570 usage_histedit();
10571 } else if (argc != 0)
10572 usage_histedit();
10575 * This command cannot apply unveil(2) in all cases because the
10576 * user may choose to run an editor to edit the histedit script
10577 * and to edit individual commit log messages.
10578 * unveil(2) traverses exec(2); if an editor is used we have to
10579 * apply unveil after edit script and log messages have been written.
10580 * XXX TODO: Make use of unveil(2) where possible.
10583 cwd = getcwd(NULL, 0);
10584 if (cwd == NULL) {
10585 error = got_error_from_errno("getcwd");
10586 goto done;
10588 error = got_worktree_open(&worktree, cwd);
10589 if (error) {
10590 if (list_backups || delete_backups) {
10591 if (error->code != GOT_ERR_NOT_WORKTREE)
10592 goto done;
10593 } else {
10594 if (error->code == GOT_ERR_NOT_WORKTREE)
10595 error = wrap_not_worktree_error(error,
10596 "histedit", cwd);
10597 goto done;
10601 if (list_backups || delete_backups) {
10602 error = got_repo_open(&repo,
10603 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10604 NULL);
10605 if (error != NULL)
10606 goto done;
10607 error = apply_unveil(got_repo_get_path(repo), 0,
10608 worktree ? got_worktree_get_root_path(worktree) : NULL);
10609 if (error)
10610 goto done;
10611 error = process_backup_refs(
10612 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10613 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10614 goto done; /* nothing else to do */
10617 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10618 NULL);
10619 if (error != NULL)
10620 goto done;
10622 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10623 if (error)
10624 goto done;
10625 if (rebase_in_progress) {
10626 error = got_error(GOT_ERR_REBASING);
10627 goto done;
10630 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10631 repo);
10632 if (error)
10633 goto done;
10634 if (merge_in_progress) {
10635 error = got_error(GOT_ERR_MERGE_BUSY);
10636 goto done;
10639 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10640 if (error)
10641 goto done;
10643 if (edit_in_progress && edit_logmsg_only) {
10644 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10645 "histedit operation is in progress in this "
10646 "work tree and must be continued or aborted "
10647 "before the -m option can be used");
10648 goto done;
10650 if (edit_in_progress && fold_only) {
10651 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10652 "histedit operation is in progress in this "
10653 "work tree and must be continued or aborted "
10654 "before the -f option can be used");
10655 goto done;
10657 if (edit_in_progress && edit_only) {
10658 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10659 "histedit operation is in progress in this "
10660 "work tree and must be continued or aborted "
10661 "before the -e option can be used");
10662 goto done;
10665 if (edit_in_progress && abort_edit) {
10666 error = got_worktree_histedit_continue(&resume_commit_id,
10667 &tmp_branch, &branch, &base_commit_id, &fileindex,
10668 worktree, repo);
10669 if (error)
10670 goto done;
10671 printf("Switching work tree to %s\n",
10672 got_ref_get_symref_target(branch));
10673 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10674 branch, base_commit_id, abort_progress, &upa);
10675 if (error)
10676 goto done;
10677 printf("Histedit of %s aborted\n",
10678 got_ref_get_symref_target(branch));
10679 print_merge_progress_stats(&upa);
10680 goto done; /* nothing else to do */
10681 } else if (abort_edit) {
10682 error = got_error(GOT_ERR_NOT_HISTEDIT);
10683 goto done;
10686 if (continue_edit) {
10687 char *path;
10689 if (!edit_in_progress) {
10690 error = got_error(GOT_ERR_NOT_HISTEDIT);
10691 goto done;
10694 error = got_worktree_get_histedit_script_path(&path, worktree);
10695 if (error)
10696 goto done;
10698 error = histedit_load_list(&histedit_cmds, path, repo);
10699 free(path);
10700 if (error)
10701 goto done;
10703 error = got_worktree_histedit_continue(&resume_commit_id,
10704 &tmp_branch, &branch, &base_commit_id, &fileindex,
10705 worktree, repo);
10706 if (error)
10707 goto done;
10709 error = got_ref_resolve(&head_commit_id, repo, branch);
10710 if (error)
10711 goto done;
10713 error = got_object_open_as_commit(&commit, repo,
10714 head_commit_id);
10715 if (error)
10716 goto done;
10717 parent_ids = got_object_commit_get_parent_ids(commit);
10718 pid = STAILQ_FIRST(parent_ids);
10719 if (pid == NULL) {
10720 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10721 goto done;
10723 error = collect_commits(&commits, head_commit_id, &pid->id,
10724 base_commit_id, got_worktree_get_path_prefix(worktree),
10725 GOT_ERR_HISTEDIT_PATH, repo);
10726 got_object_commit_close(commit);
10727 commit = NULL;
10728 if (error)
10729 goto done;
10730 } else {
10731 if (edit_in_progress) {
10732 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10733 goto done;
10736 error = got_ref_open(&branch, repo,
10737 got_worktree_get_head_ref_name(worktree), 0);
10738 if (error != NULL)
10739 goto done;
10741 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10742 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10743 "will not edit commit history of a branch outside "
10744 "the \"refs/heads/\" reference namespace");
10745 goto done;
10748 error = got_ref_resolve(&head_commit_id, repo, branch);
10749 got_ref_close(branch);
10750 branch = NULL;
10751 if (error)
10752 goto done;
10754 error = got_object_open_as_commit(&commit, repo,
10755 head_commit_id);
10756 if (error)
10757 goto done;
10758 parent_ids = got_object_commit_get_parent_ids(commit);
10759 pid = STAILQ_FIRST(parent_ids);
10760 if (pid == NULL) {
10761 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10762 goto done;
10764 error = collect_commits(&commits, head_commit_id, &pid->id,
10765 got_worktree_get_base_commit_id(worktree),
10766 got_worktree_get_path_prefix(worktree),
10767 GOT_ERR_HISTEDIT_PATH, repo);
10768 got_object_commit_close(commit);
10769 commit = NULL;
10770 if (error)
10771 goto done;
10773 if (STAILQ_EMPTY(&commits)) {
10774 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10775 goto done;
10778 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10779 &base_commit_id, &fileindex, worktree, repo);
10780 if (error)
10781 goto done;
10783 if (edit_script_path) {
10784 error = histedit_load_list(&histedit_cmds,
10785 edit_script_path, repo);
10786 if (error) {
10787 got_worktree_histedit_abort(worktree, fileindex,
10788 repo, branch, base_commit_id,
10789 abort_progress, &upa);
10790 print_merge_progress_stats(&upa);
10791 goto done;
10793 } else {
10794 const char *branch_name;
10795 branch_name = got_ref_get_symref_target(branch);
10796 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10797 branch_name += 11;
10798 error = histedit_edit_script(&histedit_cmds, &commits,
10799 branch_name, edit_logmsg_only, fold_only,
10800 edit_only, repo);
10801 if (error) {
10802 got_worktree_histedit_abort(worktree, fileindex,
10803 repo, branch, base_commit_id,
10804 abort_progress, &upa);
10805 print_merge_progress_stats(&upa);
10806 goto done;
10811 error = histedit_save_list(&histedit_cmds, worktree,
10812 repo);
10813 if (error) {
10814 got_worktree_histedit_abort(worktree, fileindex,
10815 repo, branch, base_commit_id,
10816 abort_progress, &upa);
10817 print_merge_progress_stats(&upa);
10818 goto done;
10823 error = histedit_check_script(&histedit_cmds, &commits, repo);
10824 if (error)
10825 goto done;
10827 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10828 if (resume_commit_id) {
10829 if (got_object_id_cmp(hle->commit_id,
10830 resume_commit_id) != 0)
10831 continue;
10833 resume_commit_id = NULL;
10834 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10835 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10836 error = histedit_skip_commit(hle, worktree,
10837 repo);
10838 if (error)
10839 goto done;
10840 } else {
10841 struct got_pathlist_head paths;
10842 int have_changes = 0;
10844 TAILQ_INIT(&paths);
10845 error = got_pathlist_append(&paths, "", NULL);
10846 if (error)
10847 goto done;
10848 error = got_worktree_status(worktree, &paths,
10849 repo, 0, check_local_changes, &have_changes,
10850 check_cancelled, NULL);
10851 got_pathlist_free(&paths);
10852 if (error) {
10853 if (error->code != GOT_ERR_CANCELLED)
10854 goto done;
10855 if (sigint_received || sigpipe_received)
10856 goto done;
10858 if (have_changes) {
10859 error = histedit_commit(NULL, worktree,
10860 fileindex, tmp_branch, hle, repo);
10861 if (error)
10862 goto done;
10863 } else {
10864 error = got_object_open_as_commit(
10865 &commit, repo, hle->commit_id);
10866 if (error)
10867 goto done;
10868 error = show_histedit_progress(commit,
10869 hle, NULL);
10870 got_object_commit_close(commit);
10871 commit = NULL;
10872 if (error)
10873 goto done;
10876 continue;
10879 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10880 error = histedit_skip_commit(hle, worktree, repo);
10881 if (error)
10882 goto done;
10883 continue;
10886 error = got_object_open_as_commit(&commit, repo,
10887 hle->commit_id);
10888 if (error)
10889 goto done;
10890 parent_ids = got_object_commit_get_parent_ids(commit);
10891 pid = STAILQ_FIRST(parent_ids);
10893 error = got_worktree_histedit_merge_files(&merged_paths,
10894 worktree, fileindex, &pid->id, hle->commit_id, repo,
10895 update_progress, &upa, check_cancelled, NULL);
10896 if (error)
10897 goto done;
10898 got_object_commit_close(commit);
10899 commit = NULL;
10901 print_merge_progress_stats(&upa);
10902 if (upa.conflicts > 0 || upa.missing > 0 ||
10903 upa.not_deleted > 0 || upa.unversioned > 0) {
10904 if (upa.conflicts > 0) {
10905 error = show_rebase_merge_conflict(
10906 hle->commit_id, repo);
10907 if (error)
10908 goto done;
10910 got_worktree_rebase_pathlist_free(&merged_paths);
10911 break;
10914 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10915 char *id_str;
10916 error = got_object_id_str(&id_str, hle->commit_id);
10917 if (error)
10918 goto done;
10919 printf("Stopping histedit for amending commit %s\n",
10920 id_str);
10921 free(id_str);
10922 got_worktree_rebase_pathlist_free(&merged_paths);
10923 error = got_worktree_histedit_postpone(worktree,
10924 fileindex);
10925 goto done;
10928 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10929 error = histedit_skip_commit(hle, worktree, repo);
10930 if (error)
10931 goto done;
10932 continue;
10935 error = histedit_commit(&merged_paths, worktree, fileindex,
10936 tmp_branch, hle, repo);
10937 got_worktree_rebase_pathlist_free(&merged_paths);
10938 if (error)
10939 goto done;
10942 if (upa.conflicts > 0 || upa.missing > 0 ||
10943 upa.not_deleted > 0 || upa.unversioned > 0) {
10944 error = got_worktree_histedit_postpone(worktree, fileindex);
10945 if (error)
10946 goto done;
10947 if (upa.conflicts > 0 && upa.missing == 0 &&
10948 upa.not_deleted == 0 && upa.unversioned == 0) {
10949 error = got_error_msg(GOT_ERR_CONFLICTS,
10950 "conflicts must be resolved before histedit "
10951 "can continue");
10952 } else if (upa.conflicts > 0) {
10953 error = got_error_msg(GOT_ERR_CONFLICTS,
10954 "conflicts must be resolved before histedit "
10955 "can continue; changes destined for some "
10956 "files were not yet merged and should be "
10957 "merged manually if required before the "
10958 "histedit operation is continued");
10959 } else {
10960 error = got_error_msg(GOT_ERR_CONFLICTS,
10961 "changes destined for some files were not "
10962 "yet merged and should be merged manually "
10963 "if required before the histedit operation "
10964 "is continued");
10966 } else
10967 error = histedit_complete(worktree, fileindex, tmp_branch,
10968 branch, repo);
10969 done:
10970 got_object_id_queue_free(&commits);
10971 histedit_free_list(&histedit_cmds);
10972 free(head_commit_id);
10973 free(base_commit_id);
10974 free(resume_commit_id);
10975 if (commit)
10976 got_object_commit_close(commit);
10977 if (branch)
10978 got_ref_close(branch);
10979 if (tmp_branch)
10980 got_ref_close(tmp_branch);
10981 if (worktree)
10982 got_worktree_close(worktree);
10983 if (repo) {
10984 const struct got_error *close_err = got_repo_close(repo);
10985 if (error == NULL)
10986 error = close_err;
10988 return error;
10991 __dead static void
10992 usage_integrate(void)
10994 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10995 exit(1);
10998 static const struct got_error *
10999 cmd_integrate(int argc, char *argv[])
11001 const struct got_error *error = NULL;
11002 struct got_repository *repo = NULL;
11003 struct got_worktree *worktree = NULL;
11004 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11005 const char *branch_arg = NULL;
11006 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11007 struct got_fileindex *fileindex = NULL;
11008 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11009 int ch;
11010 struct got_update_progress_arg upa;
11012 while ((ch = getopt(argc, argv, "")) != -1) {
11013 switch (ch) {
11014 default:
11015 usage_integrate();
11016 /* NOTREACHED */
11020 argc -= optind;
11021 argv += optind;
11023 if (argc != 1)
11024 usage_integrate();
11025 branch_arg = argv[0];
11026 #ifndef PROFILE
11027 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11028 "unveil", NULL) == -1)
11029 err(1, "pledge");
11030 #endif
11031 cwd = getcwd(NULL, 0);
11032 if (cwd == NULL) {
11033 error = got_error_from_errno("getcwd");
11034 goto done;
11037 error = got_worktree_open(&worktree, cwd);
11038 if (error) {
11039 if (error->code == GOT_ERR_NOT_WORKTREE)
11040 error = wrap_not_worktree_error(error, "integrate",
11041 cwd);
11042 goto done;
11045 error = check_rebase_or_histedit_in_progress(worktree);
11046 if (error)
11047 goto done;
11049 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11050 NULL);
11051 if (error != NULL)
11052 goto done;
11054 error = apply_unveil(got_repo_get_path(repo), 0,
11055 got_worktree_get_root_path(worktree));
11056 if (error)
11057 goto done;
11059 error = check_merge_in_progress(worktree, repo);
11060 if (error)
11061 goto done;
11063 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11064 error = got_error_from_errno("asprintf");
11065 goto done;
11068 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11069 &base_branch_ref, worktree, refname, repo);
11070 if (error)
11071 goto done;
11073 refname = strdup(got_ref_get_name(branch_ref));
11074 if (refname == NULL) {
11075 error = got_error_from_errno("strdup");
11076 got_worktree_integrate_abort(worktree, fileindex, repo,
11077 branch_ref, base_branch_ref);
11078 goto done;
11080 base_refname = strdup(got_ref_get_name(base_branch_ref));
11081 if (base_refname == NULL) {
11082 error = got_error_from_errno("strdup");
11083 got_worktree_integrate_abort(worktree, fileindex, repo,
11084 branch_ref, base_branch_ref);
11085 goto done;
11088 error = got_ref_resolve(&commit_id, repo, branch_ref);
11089 if (error)
11090 goto done;
11092 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11093 if (error)
11094 goto done;
11096 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11097 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11098 "specified branch has already been integrated");
11099 got_worktree_integrate_abort(worktree, fileindex, repo,
11100 branch_ref, base_branch_ref);
11101 goto done;
11104 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11105 if (error) {
11106 if (error->code == GOT_ERR_ANCESTRY)
11107 error = got_error(GOT_ERR_REBASE_REQUIRED);
11108 got_worktree_integrate_abort(worktree, fileindex, repo,
11109 branch_ref, base_branch_ref);
11110 goto done;
11113 memset(&upa, 0, sizeof(upa));
11114 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11115 branch_ref, base_branch_ref, update_progress, &upa,
11116 check_cancelled, NULL);
11117 if (error)
11118 goto done;
11120 printf("Integrated %s into %s\n", refname, base_refname);
11121 print_update_progress_stats(&upa);
11122 done:
11123 if (repo) {
11124 const struct got_error *close_err = got_repo_close(repo);
11125 if (error == NULL)
11126 error = close_err;
11128 if (worktree)
11129 got_worktree_close(worktree);
11130 free(cwd);
11131 free(base_commit_id);
11132 free(commit_id);
11133 free(refname);
11134 free(base_refname);
11135 return error;
11138 __dead static void
11139 usage_merge(void)
11141 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11142 getprogname());
11143 exit(1);
11146 static const struct got_error *
11147 cmd_merge(int argc, char *argv[])
11149 const struct got_error *error = NULL;
11150 struct got_worktree *worktree = NULL;
11151 struct got_repository *repo = NULL;
11152 struct got_fileindex *fileindex = NULL;
11153 char *cwd = NULL, *id_str = NULL, *author = NULL;
11154 struct got_reference *branch = NULL, *wt_branch = NULL;
11155 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11156 struct got_object_id *wt_branch_tip = NULL;
11157 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11158 int interrupt_merge = 0;
11159 struct got_update_progress_arg upa;
11160 struct got_object_id *merge_commit_id = NULL;
11161 char *branch_name = NULL;
11163 memset(&upa, 0, sizeof(upa));
11165 while ((ch = getopt(argc, argv, "acn")) != -1) {
11166 switch (ch) {
11167 case 'a':
11168 abort_merge = 1;
11169 break;
11170 case 'c':
11171 continue_merge = 1;
11172 break;
11173 case 'n':
11174 interrupt_merge = 1;
11175 break;
11176 default:
11177 usage_rebase();
11178 /* NOTREACHED */
11182 argc -= optind;
11183 argv += optind;
11185 #ifndef PROFILE
11186 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11187 "unveil", NULL) == -1)
11188 err(1, "pledge");
11189 #endif
11191 if (abort_merge && continue_merge)
11192 option_conflict('a', 'c');
11193 if (abort_merge || continue_merge) {
11194 if (argc != 0)
11195 usage_merge();
11196 } else if (argc != 1)
11197 usage_merge();
11199 cwd = getcwd(NULL, 0);
11200 if (cwd == NULL) {
11201 error = got_error_from_errno("getcwd");
11202 goto done;
11205 error = got_worktree_open(&worktree, cwd);
11206 if (error) {
11207 if (error->code == GOT_ERR_NOT_WORKTREE)
11208 error = wrap_not_worktree_error(error,
11209 "merge", cwd);
11210 goto done;
11213 error = got_repo_open(&repo,
11214 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11215 if (error != NULL)
11216 goto done;
11218 error = apply_unveil(got_repo_get_path(repo), 0,
11219 worktree ? got_worktree_get_root_path(worktree) : NULL);
11220 if (error)
11221 goto done;
11223 error = check_rebase_or_histedit_in_progress(worktree);
11224 if (error)
11225 goto done;
11227 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11228 repo);
11229 if (error)
11230 goto done;
11232 if (abort_merge) {
11233 if (!merge_in_progress) {
11234 error = got_error(GOT_ERR_NOT_MERGING);
11235 goto done;
11237 error = got_worktree_merge_continue(&branch_name,
11238 &branch_tip, &fileindex, worktree, repo);
11239 if (error)
11240 goto done;
11241 error = got_worktree_merge_abort(worktree, fileindex, repo,
11242 abort_progress, &upa);
11243 if (error)
11244 goto done;
11245 printf("Merge of %s aborted\n", branch_name);
11246 goto done; /* nothing else to do */
11249 error = get_author(&author, repo, worktree);
11250 if (error)
11251 goto done;
11253 if (continue_merge) {
11254 if (!merge_in_progress) {
11255 error = got_error(GOT_ERR_NOT_MERGING);
11256 goto done;
11258 error = got_worktree_merge_continue(&branch_name,
11259 &branch_tip, &fileindex, worktree, repo);
11260 if (error)
11261 goto done;
11262 } else {
11263 error = got_ref_open(&branch, repo, argv[0], 0);
11264 if (error != NULL)
11265 goto done;
11266 branch_name = strdup(got_ref_get_name(branch));
11267 if (branch_name == NULL) {
11268 error = got_error_from_errno("strdup");
11269 goto done;
11271 error = got_ref_resolve(&branch_tip, repo, branch);
11272 if (error)
11273 goto done;
11276 error = got_ref_open(&wt_branch, repo,
11277 got_worktree_get_head_ref_name(worktree), 0);
11278 if (error)
11279 goto done;
11280 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11281 if (error)
11282 goto done;
11283 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11284 wt_branch_tip, branch_tip, 0, repo,
11285 check_cancelled, NULL);
11286 if (error && error->code != GOT_ERR_ANCESTRY)
11287 goto done;
11289 if (!continue_merge) {
11290 error = check_path_prefix(wt_branch_tip, branch_tip,
11291 got_worktree_get_path_prefix(worktree),
11292 GOT_ERR_MERGE_PATH, repo);
11293 if (error)
11294 goto done;
11295 if (yca_id) {
11296 error = check_same_branch(wt_branch_tip, branch,
11297 yca_id, repo);
11298 if (error) {
11299 if (error->code != GOT_ERR_ANCESTRY)
11300 goto done;
11301 error = NULL;
11302 } else {
11303 static char msg[512];
11304 snprintf(msg, sizeof(msg),
11305 "cannot create a merge commit because "
11306 "%s is based on %s; %s can be integrated "
11307 "with 'got integrate' instead", branch_name,
11308 got_worktree_get_head_ref_name(worktree),
11309 branch_name);
11310 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11311 goto done;
11314 error = got_worktree_merge_prepare(&fileindex, worktree,
11315 branch, repo);
11316 if (error)
11317 goto done;
11319 error = got_worktree_merge_branch(worktree, fileindex,
11320 yca_id, branch_tip, repo, update_progress, &upa,
11321 check_cancelled, NULL);
11322 if (error)
11323 goto done;
11324 print_merge_progress_stats(&upa);
11325 if (!upa.did_something) {
11326 error = got_worktree_merge_abort(worktree, fileindex,
11327 repo, abort_progress, &upa);
11328 if (error)
11329 goto done;
11330 printf("Already up-to-date\n");
11331 goto done;
11335 if (interrupt_merge) {
11336 error = got_worktree_merge_postpone(worktree, fileindex);
11337 if (error)
11338 goto done;
11339 printf("Merge of %s interrupted on request\n", branch_name);
11340 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11341 upa.not_deleted > 0 || upa.unversioned > 0) {
11342 error = got_worktree_merge_postpone(worktree, fileindex);
11343 if (error)
11344 goto done;
11345 if (upa.conflicts > 0 && upa.missing == 0 &&
11346 upa.not_deleted == 0 && upa.unversioned == 0) {
11347 error = got_error_msg(GOT_ERR_CONFLICTS,
11348 "conflicts must be resolved before merging "
11349 "can continue");
11350 } else if (upa.conflicts > 0) {
11351 error = got_error_msg(GOT_ERR_CONFLICTS,
11352 "conflicts must be resolved before merging "
11353 "can continue; changes destined for some "
11354 "files were not yet merged and "
11355 "should be merged manually if required before the "
11356 "merge operation is continued");
11357 } else {
11358 error = got_error_msg(GOT_ERR_CONFLICTS,
11359 "changes destined for some "
11360 "files were not yet merged and should be "
11361 "merged manually if required before the "
11362 "merge operation is continued");
11364 goto done;
11365 } else {
11366 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11367 fileindex, author, NULL, 1, branch_tip, branch_name,
11368 repo, continue_merge ? print_status : NULL, NULL);
11369 if (error)
11370 goto done;
11371 error = got_worktree_merge_complete(worktree, fileindex, repo);
11372 if (error)
11373 goto done;
11374 error = got_object_id_str(&id_str, merge_commit_id);
11375 if (error)
11376 goto done;
11377 printf("Merged %s into %s: %s\n", branch_name,
11378 got_worktree_get_head_ref_name(worktree),
11379 id_str);
11382 done:
11383 free(id_str);
11384 free(merge_commit_id);
11385 free(author);
11386 free(branch_tip);
11387 free(branch_name);
11388 free(yca_id);
11389 if (branch)
11390 got_ref_close(branch);
11391 if (wt_branch)
11392 got_ref_close(wt_branch);
11393 if (worktree)
11394 got_worktree_close(worktree);
11395 if (repo) {
11396 const struct got_error *close_err = got_repo_close(repo);
11397 if (error == NULL)
11398 error = close_err;
11400 return error;
11403 __dead static void
11404 usage_stage(void)
11406 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11407 "[-S] [file-path ...]\n",
11408 getprogname());
11409 exit(1);
11412 static const struct got_error *
11413 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11414 const char *path, struct got_object_id *blob_id,
11415 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11416 int dirfd, const char *de_name)
11418 const struct got_error *err = NULL;
11419 char *id_str = NULL;
11421 if (staged_status != GOT_STATUS_ADD &&
11422 staged_status != GOT_STATUS_MODIFY &&
11423 staged_status != GOT_STATUS_DELETE)
11424 return NULL;
11426 if (staged_status == GOT_STATUS_ADD ||
11427 staged_status == GOT_STATUS_MODIFY)
11428 err = got_object_id_str(&id_str, staged_blob_id);
11429 else
11430 err = got_object_id_str(&id_str, blob_id);
11431 if (err)
11432 return err;
11434 printf("%s %c %s\n", id_str, staged_status, path);
11435 free(id_str);
11436 return NULL;
11439 static const struct got_error *
11440 cmd_stage(int argc, char *argv[])
11442 const struct got_error *error = NULL;
11443 struct got_repository *repo = NULL;
11444 struct got_worktree *worktree = NULL;
11445 char *cwd = NULL;
11446 struct got_pathlist_head paths;
11447 struct got_pathlist_entry *pe;
11448 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11449 FILE *patch_script_file = NULL;
11450 const char *patch_script_path = NULL;
11451 struct choose_patch_arg cpa;
11453 TAILQ_INIT(&paths);
11455 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11456 switch (ch) {
11457 case 'l':
11458 list_stage = 1;
11459 break;
11460 case 'p':
11461 pflag = 1;
11462 break;
11463 case 'F':
11464 patch_script_path = optarg;
11465 break;
11466 case 'S':
11467 allow_bad_symlinks = 1;
11468 break;
11469 default:
11470 usage_stage();
11471 /* NOTREACHED */
11475 argc -= optind;
11476 argv += optind;
11478 #ifndef PROFILE
11479 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11480 "unveil", NULL) == -1)
11481 err(1, "pledge");
11482 #endif
11483 if (list_stage && (pflag || patch_script_path))
11484 errx(1, "-l option cannot be used with other options");
11485 if (patch_script_path && !pflag)
11486 errx(1, "-F option can only be used together with -p option");
11488 cwd = getcwd(NULL, 0);
11489 if (cwd == NULL) {
11490 error = got_error_from_errno("getcwd");
11491 goto done;
11494 error = got_worktree_open(&worktree, cwd);
11495 if (error) {
11496 if (error->code == GOT_ERR_NOT_WORKTREE)
11497 error = wrap_not_worktree_error(error, "stage", cwd);
11498 goto done;
11501 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11502 NULL);
11503 if (error != NULL)
11504 goto done;
11506 if (patch_script_path) {
11507 patch_script_file = fopen(patch_script_path, "re");
11508 if (patch_script_file == NULL) {
11509 error = got_error_from_errno2("fopen",
11510 patch_script_path);
11511 goto done;
11514 error = apply_unveil(got_repo_get_path(repo), 0,
11515 got_worktree_get_root_path(worktree));
11516 if (error)
11517 goto done;
11519 error = check_merge_in_progress(worktree, repo);
11520 if (error)
11521 goto done;
11523 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11524 if (error)
11525 goto done;
11527 if (list_stage)
11528 error = got_worktree_status(worktree, &paths, repo, 0,
11529 print_stage, NULL, check_cancelled, NULL);
11530 else {
11531 cpa.patch_script_file = patch_script_file;
11532 cpa.action = "stage";
11533 error = got_worktree_stage(worktree, &paths,
11534 pflag ? NULL : print_status, NULL,
11535 pflag ? choose_patch : NULL, &cpa,
11536 allow_bad_symlinks, repo);
11538 done:
11539 if (patch_script_file && fclose(patch_script_file) == EOF &&
11540 error == NULL)
11541 error = got_error_from_errno2("fclose", patch_script_path);
11542 if (repo) {
11543 const struct got_error *close_err = got_repo_close(repo);
11544 if (error == NULL)
11545 error = close_err;
11547 if (worktree)
11548 got_worktree_close(worktree);
11549 TAILQ_FOREACH(pe, &paths, entry)
11550 free((char *)pe->path);
11551 got_pathlist_free(&paths);
11552 free(cwd);
11553 return error;
11556 __dead static void
11557 usage_unstage(void)
11559 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11560 "[file-path ...]\n",
11561 getprogname());
11562 exit(1);
11566 static const struct got_error *
11567 cmd_unstage(int argc, char *argv[])
11569 const struct got_error *error = NULL;
11570 struct got_repository *repo = NULL;
11571 struct got_worktree *worktree = NULL;
11572 char *cwd = NULL;
11573 struct got_pathlist_head paths;
11574 struct got_pathlist_entry *pe;
11575 int ch, pflag = 0;
11576 struct got_update_progress_arg upa;
11577 FILE *patch_script_file = NULL;
11578 const char *patch_script_path = NULL;
11579 struct choose_patch_arg cpa;
11581 TAILQ_INIT(&paths);
11583 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11584 switch (ch) {
11585 case 'p':
11586 pflag = 1;
11587 break;
11588 case 'F':
11589 patch_script_path = optarg;
11590 break;
11591 default:
11592 usage_unstage();
11593 /* NOTREACHED */
11597 argc -= optind;
11598 argv += optind;
11600 #ifndef PROFILE
11601 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11602 "unveil", NULL) == -1)
11603 err(1, "pledge");
11604 #endif
11605 if (patch_script_path && !pflag)
11606 errx(1, "-F option can only be used together with -p option");
11608 cwd = getcwd(NULL, 0);
11609 if (cwd == NULL) {
11610 error = got_error_from_errno("getcwd");
11611 goto done;
11614 error = got_worktree_open(&worktree, cwd);
11615 if (error) {
11616 if (error->code == GOT_ERR_NOT_WORKTREE)
11617 error = wrap_not_worktree_error(error, "unstage", cwd);
11618 goto done;
11621 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11622 NULL);
11623 if (error != NULL)
11624 goto done;
11626 if (patch_script_path) {
11627 patch_script_file = fopen(patch_script_path, "re");
11628 if (patch_script_file == NULL) {
11629 error = got_error_from_errno2("fopen",
11630 patch_script_path);
11631 goto done;
11635 error = apply_unveil(got_repo_get_path(repo), 0,
11636 got_worktree_get_root_path(worktree));
11637 if (error)
11638 goto done;
11640 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11641 if (error)
11642 goto done;
11644 cpa.patch_script_file = patch_script_file;
11645 cpa.action = "unstage";
11646 memset(&upa, 0, sizeof(upa));
11647 error = got_worktree_unstage(worktree, &paths, update_progress,
11648 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11649 if (!error)
11650 print_merge_progress_stats(&upa);
11651 done:
11652 if (patch_script_file && fclose(patch_script_file) == EOF &&
11653 error == NULL)
11654 error = got_error_from_errno2("fclose", patch_script_path);
11655 if (repo) {
11656 const struct got_error *close_err = got_repo_close(repo);
11657 if (error == NULL)
11658 error = close_err;
11660 if (worktree)
11661 got_worktree_close(worktree);
11662 TAILQ_FOREACH(pe, &paths, entry)
11663 free((char *)pe->path);
11664 got_pathlist_free(&paths);
11665 free(cwd);
11666 return error;
11669 __dead static void
11670 usage_cat(void)
11672 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11673 "arg1 [arg2 ...]\n", getprogname());
11674 exit(1);
11677 static const struct got_error *
11678 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11680 const struct got_error *err;
11681 struct got_blob_object *blob;
11683 err = got_object_open_as_blob(&blob, repo, id, 8192);
11684 if (err)
11685 return err;
11687 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11688 got_object_blob_close(blob);
11689 return err;
11692 static const struct got_error *
11693 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11695 const struct got_error *err;
11696 struct got_tree_object *tree;
11697 int nentries, i;
11699 err = got_object_open_as_tree(&tree, repo, id);
11700 if (err)
11701 return err;
11703 nentries = got_object_tree_get_nentries(tree);
11704 for (i = 0; i < nentries; i++) {
11705 struct got_tree_entry *te;
11706 char *id_str;
11707 if (sigint_received || sigpipe_received)
11708 break;
11709 te = got_object_tree_get_entry(tree, i);
11710 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11711 if (err)
11712 break;
11713 fprintf(outfile, "%s %.7o %s\n", id_str,
11714 got_tree_entry_get_mode(te),
11715 got_tree_entry_get_name(te));
11716 free(id_str);
11719 got_object_tree_close(tree);
11720 return err;
11723 static void
11724 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11726 long long h, m;
11727 char sign = '+';
11729 if (gmtoff < 0) {
11730 sign = '-';
11731 gmtoff = -gmtoff;
11734 h = (long long)gmtoff / 3600;
11735 m = ((long long)gmtoff - h*3600) / 60;
11736 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11739 static const struct got_error *
11740 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11742 const struct got_error *err;
11743 struct got_commit_object *commit;
11744 const struct got_object_id_queue *parent_ids;
11745 struct got_object_qid *pid;
11746 char *id_str = NULL;
11747 const char *logmsg = NULL;
11748 char gmtoff[6];
11750 err = got_object_open_as_commit(&commit, repo, id);
11751 if (err)
11752 return err;
11754 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11755 if (err)
11756 goto done;
11758 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11759 parent_ids = got_object_commit_get_parent_ids(commit);
11760 fprintf(outfile, "numparents %d\n",
11761 got_object_commit_get_nparents(commit));
11762 STAILQ_FOREACH(pid, parent_ids, entry) {
11763 char *pid_str;
11764 err = got_object_id_str(&pid_str, &pid->id);
11765 if (err)
11766 goto done;
11767 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11768 free(pid_str);
11770 format_gmtoff(gmtoff, sizeof(gmtoff),
11771 got_object_commit_get_author_gmtoff(commit));
11772 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11773 got_object_commit_get_author(commit),
11774 (long long)got_object_commit_get_author_time(commit),
11775 gmtoff);
11777 format_gmtoff(gmtoff, sizeof(gmtoff),
11778 got_object_commit_get_committer_gmtoff(commit));
11779 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11780 got_object_commit_get_author(commit),
11781 (long long)got_object_commit_get_committer_time(commit),
11782 gmtoff);
11784 logmsg = got_object_commit_get_logmsg_raw(commit);
11785 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11786 fprintf(outfile, "%s", logmsg);
11787 done:
11788 free(id_str);
11789 got_object_commit_close(commit);
11790 return err;
11793 static const struct got_error *
11794 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11796 const struct got_error *err;
11797 struct got_tag_object *tag;
11798 char *id_str = NULL;
11799 const char *tagmsg = NULL;
11800 char gmtoff[6];
11802 err = got_object_open_as_tag(&tag, repo, id);
11803 if (err)
11804 return err;
11806 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11807 if (err)
11808 goto done;
11810 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11812 switch (got_object_tag_get_object_type(tag)) {
11813 case GOT_OBJ_TYPE_BLOB:
11814 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11815 GOT_OBJ_LABEL_BLOB);
11816 break;
11817 case GOT_OBJ_TYPE_TREE:
11818 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11819 GOT_OBJ_LABEL_TREE);
11820 break;
11821 case GOT_OBJ_TYPE_COMMIT:
11822 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11823 GOT_OBJ_LABEL_COMMIT);
11824 break;
11825 case GOT_OBJ_TYPE_TAG:
11826 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11827 GOT_OBJ_LABEL_TAG);
11828 break;
11829 default:
11830 break;
11833 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11834 got_object_tag_get_name(tag));
11836 format_gmtoff(gmtoff, sizeof(gmtoff),
11837 got_object_tag_get_tagger_gmtoff(tag));
11838 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11839 got_object_tag_get_tagger(tag),
11840 (long long)got_object_tag_get_tagger_time(tag),
11841 gmtoff);
11843 tagmsg = got_object_tag_get_message(tag);
11844 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11845 fprintf(outfile, "%s", tagmsg);
11846 done:
11847 free(id_str);
11848 got_object_tag_close(tag);
11849 return err;
11852 static const struct got_error *
11853 cmd_cat(int argc, char *argv[])
11855 const struct got_error *error;
11856 struct got_repository *repo = NULL;
11857 struct got_worktree *worktree = NULL;
11858 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11859 const char *commit_id_str = NULL;
11860 struct got_object_id *id = NULL, *commit_id = NULL;
11861 struct got_commit_object *commit = NULL;
11862 int ch, obj_type, i, force_path = 0;
11863 struct got_reflist_head refs;
11865 TAILQ_INIT(&refs);
11867 #ifndef PROFILE
11868 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11869 NULL) == -1)
11870 err(1, "pledge");
11871 #endif
11873 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11874 switch (ch) {
11875 case 'c':
11876 commit_id_str = optarg;
11877 break;
11878 case 'r':
11879 repo_path = realpath(optarg, NULL);
11880 if (repo_path == NULL)
11881 return got_error_from_errno2("realpath",
11882 optarg);
11883 got_path_strip_trailing_slashes(repo_path);
11884 break;
11885 case 'P':
11886 force_path = 1;
11887 break;
11888 default:
11889 usage_cat();
11890 /* NOTREACHED */
11894 argc -= optind;
11895 argv += optind;
11897 cwd = getcwd(NULL, 0);
11898 if (cwd == NULL) {
11899 error = got_error_from_errno("getcwd");
11900 goto done;
11903 if (repo_path == NULL) {
11904 error = got_worktree_open(&worktree, cwd);
11905 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11906 goto done;
11907 if (worktree) {
11908 repo_path = strdup(
11909 got_worktree_get_repo_path(worktree));
11910 if (repo_path == NULL) {
11911 error = got_error_from_errno("strdup");
11912 goto done;
11915 /* Release work tree lock. */
11916 got_worktree_close(worktree);
11917 worktree = NULL;
11921 if (repo_path == NULL) {
11922 repo_path = strdup(cwd);
11923 if (repo_path == NULL)
11924 return got_error_from_errno("strdup");
11927 error = got_repo_open(&repo, repo_path, NULL);
11928 free(repo_path);
11929 if (error != NULL)
11930 goto done;
11932 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11933 if (error)
11934 goto done;
11936 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11937 if (error)
11938 goto done;
11940 if (commit_id_str == NULL)
11941 commit_id_str = GOT_REF_HEAD;
11942 error = got_repo_match_object_id(&commit_id, NULL,
11943 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11944 if (error)
11945 goto done;
11947 error = got_object_open_as_commit(&commit, repo, commit_id);
11948 if (error)
11949 goto done;
11951 for (i = 0; i < argc; i++) {
11952 if (force_path) {
11953 error = got_object_id_by_path(&id, repo, commit,
11954 argv[i]);
11955 if (error)
11956 break;
11957 } else {
11958 error = got_repo_match_object_id(&id, &label, argv[i],
11959 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11960 repo);
11961 if (error) {
11962 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11963 error->code != GOT_ERR_NOT_REF)
11964 break;
11965 error = got_object_id_by_path(&id, repo,
11966 commit, argv[i]);
11967 if (error)
11968 break;
11972 error = got_object_get_type(&obj_type, repo, id);
11973 if (error)
11974 break;
11976 switch (obj_type) {
11977 case GOT_OBJ_TYPE_BLOB:
11978 error = cat_blob(id, repo, stdout);
11979 break;
11980 case GOT_OBJ_TYPE_TREE:
11981 error = cat_tree(id, repo, stdout);
11982 break;
11983 case GOT_OBJ_TYPE_COMMIT:
11984 error = cat_commit(id, repo, stdout);
11985 break;
11986 case GOT_OBJ_TYPE_TAG:
11987 error = cat_tag(id, repo, stdout);
11988 break;
11989 default:
11990 error = got_error(GOT_ERR_OBJ_TYPE);
11991 break;
11993 if (error)
11994 break;
11995 free(label);
11996 label = NULL;
11997 free(id);
11998 id = NULL;
12000 done:
12001 free(label);
12002 free(id);
12003 free(commit_id);
12004 if (commit)
12005 got_object_commit_close(commit);
12006 if (worktree)
12007 got_worktree_close(worktree);
12008 if (repo) {
12009 const struct got_error *close_err = got_repo_close(repo);
12010 if (error == NULL)
12011 error = close_err;
12013 got_ref_list_free(&refs);
12014 return error;
12017 __dead static void
12018 usage_info(void)
12020 fprintf(stderr, "usage: %s info [path ...]\n",
12021 getprogname());
12022 exit(1);
12025 static const struct got_error *
12026 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12027 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12028 struct got_object_id *commit_id)
12030 const struct got_error *err = NULL;
12031 char *id_str = NULL;
12032 char datebuf[128];
12033 struct tm mytm, *tm;
12034 struct got_pathlist_head *paths = arg;
12035 struct got_pathlist_entry *pe;
12038 * Clear error indication from any of the path arguments which
12039 * would cause this file index entry to be displayed.
12041 TAILQ_FOREACH(pe, paths, entry) {
12042 if (got_path_cmp(path, pe->path, strlen(path),
12043 pe->path_len) == 0 ||
12044 got_path_is_child(path, pe->path, pe->path_len))
12045 pe->data = NULL; /* no error */
12048 printf(GOT_COMMIT_SEP_STR);
12049 if (S_ISLNK(mode))
12050 printf("symlink: %s\n", path);
12051 else if (S_ISREG(mode)) {
12052 printf("file: %s\n", path);
12053 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12054 } else if (S_ISDIR(mode))
12055 printf("directory: %s\n", path);
12056 else
12057 printf("something: %s\n", path);
12059 tm = localtime_r(&mtime, &mytm);
12060 if (tm == NULL)
12061 return NULL;
12062 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12063 return got_error(GOT_ERR_NO_SPACE);
12064 printf("timestamp: %s\n", datebuf);
12066 if (blob_id) {
12067 err = got_object_id_str(&id_str, blob_id);
12068 if (err)
12069 return err;
12070 printf("based on blob: %s\n", id_str);
12071 free(id_str);
12074 if (staged_blob_id) {
12075 err = got_object_id_str(&id_str, staged_blob_id);
12076 if (err)
12077 return err;
12078 printf("based on staged blob: %s\n", id_str);
12079 free(id_str);
12082 if (commit_id) {
12083 err = got_object_id_str(&id_str, commit_id);
12084 if (err)
12085 return err;
12086 printf("based on commit: %s\n", id_str);
12087 free(id_str);
12090 return NULL;
12093 static const struct got_error *
12094 cmd_info(int argc, char *argv[])
12096 const struct got_error *error = NULL;
12097 struct got_worktree *worktree = NULL;
12098 char *cwd = NULL, *id_str = NULL;
12099 struct got_pathlist_head paths;
12100 struct got_pathlist_entry *pe;
12101 char *uuidstr = NULL;
12102 int ch, show_files = 0;
12104 TAILQ_INIT(&paths);
12106 while ((ch = getopt(argc, argv, "")) != -1) {
12107 switch (ch) {
12108 default:
12109 usage_info();
12110 /* NOTREACHED */
12114 argc -= optind;
12115 argv += optind;
12117 #ifndef PROFILE
12118 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12119 NULL) == -1)
12120 err(1, "pledge");
12121 #endif
12122 cwd = getcwd(NULL, 0);
12123 if (cwd == NULL) {
12124 error = got_error_from_errno("getcwd");
12125 goto done;
12128 error = got_worktree_open(&worktree, cwd);
12129 if (error) {
12130 if (error->code == GOT_ERR_NOT_WORKTREE)
12131 error = wrap_not_worktree_error(error, "info", cwd);
12132 goto done;
12135 #ifndef PROFILE
12136 /* Remove "cpath" promise. */
12137 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12138 NULL) == -1)
12139 err(1, "pledge");
12140 #endif
12141 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12142 if (error)
12143 goto done;
12145 if (argc >= 1) {
12146 error = get_worktree_paths_from_argv(&paths, argc, argv,
12147 worktree);
12148 if (error)
12149 goto done;
12150 show_files = 1;
12153 error = got_object_id_str(&id_str,
12154 got_worktree_get_base_commit_id(worktree));
12155 if (error)
12156 goto done;
12158 error = got_worktree_get_uuid(&uuidstr, worktree);
12159 if (error)
12160 goto done;
12162 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12163 printf("work tree base commit: %s\n", id_str);
12164 printf("work tree path prefix: %s\n",
12165 got_worktree_get_path_prefix(worktree));
12166 printf("work tree branch reference: %s\n",
12167 got_worktree_get_head_ref_name(worktree));
12168 printf("work tree UUID: %s\n", uuidstr);
12169 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12171 if (show_files) {
12172 struct got_pathlist_entry *pe;
12173 TAILQ_FOREACH(pe, &paths, entry) {
12174 if (pe->path_len == 0)
12175 continue;
12177 * Assume this path will fail. This will be corrected
12178 * in print_path_info() in case the path does suceeed.
12180 pe->data = (void *)got_error_path(pe->path,
12181 GOT_ERR_BAD_PATH);
12183 error = got_worktree_path_info(worktree, &paths,
12184 print_path_info, &paths, check_cancelled, NULL);
12185 if (error)
12186 goto done;
12187 TAILQ_FOREACH(pe, &paths, entry) {
12188 if (pe->data != NULL) {
12189 error = pe->data; /* bad path */
12190 break;
12194 done:
12195 TAILQ_FOREACH(pe, &paths, entry)
12196 free((char *)pe->path);
12197 got_pathlist_free(&paths);
12198 free(cwd);
12199 free(id_str);
12200 free(uuidstr);
12201 return error;