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/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 int
408 spawn_editor(const char *editor, const char *file)
410 pid_t pid;
411 sig_t sighup, sigint, sigquit;
412 int st = -1;
414 sighup = signal(SIGHUP, SIG_IGN);
415 sigint = signal(SIGINT, SIG_IGN);
416 sigquit = signal(SIGQUIT, SIG_IGN);
418 switch (pid = fork()) {
419 case -1:
420 goto doneediting;
421 case 0:
422 execl(editor, editor, file, (char *)NULL);
423 _exit(127);
426 while (waitpid(pid, &st, 0) == -1)
427 if (errno != EINTR)
428 break;
430 doneediting:
431 (void)signal(SIGHUP, sighup);
432 (void)signal(SIGINT, sigint);
433 (void)signal(SIGQUIT, sigquit);
435 if (!WIFEXITED(st)) {
436 errno = EINTR;
437 return -1;
440 return WEXITSTATUS(st);
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 char *line = NULL;
450 size_t linesize = 0;
451 ssize_t linelen;
452 struct stat st, st2;
453 FILE *fp = NULL;
454 size_t len, logmsg_len;
455 char *initial_content_stripped = NULL, *buf = NULL, *s;
457 *logmsg = NULL;
459 if (stat(logmsg_path, &st) == -1)
460 return got_error_from_errno2("stat", logmsg_path);
462 if (spawn_editor(editor, logmsg_path) == -1)
463 return got_error_from_errno("failed spawning editor");
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification &&
469 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 /*
474 * Set up a stripped version of the initial content without comments
475 * and blank lines. We need this in order to check if the message
476 * has in fact been edited.
477 */
478 initial_content_stripped = malloc(initial_content_len + 1);
479 if (initial_content_stripped == NULL)
480 return got_error_from_errno("malloc");
481 initial_content_stripped[0] = '\0';
483 buf = strdup(initial_content);
484 if (buf == NULL) {
485 err = got_error_from_errno("strdup");
486 goto done;
488 s = buf;
489 len = 0;
490 while ((line = strsep(&s, "\n")) != NULL) {
491 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
492 continue; /* remove comments and leading empty lines */
493 len = strlcat(initial_content_stripped, line,
494 initial_content_len + 1);
495 if (len >= initial_content_len + 1) {
496 err = got_error(GOT_ERR_NO_SPACE);
497 goto done;
500 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
501 initial_content_stripped[len - 1] = '\0';
502 len--;
505 logmsg_len = st2.st_size;
506 *logmsg = malloc(logmsg_len + 1);
507 if (*logmsg == NULL)
508 return got_error_from_errno("malloc");
509 (*logmsg)[0] = '\0';
511 fp = fopen(logmsg_path, "re");
512 if (fp == NULL) {
513 err = got_error_from_errno("fopen");
514 goto done;
517 len = 0;
518 while ((linelen = getline(&line, &linesize, fp)) != -1) {
519 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
520 continue; /* remove comments and leading empty lines */
521 len = strlcat(*logmsg, line, logmsg_len + 1);
522 if (len >= logmsg_len + 1) {
523 err = got_error(GOT_ERR_NO_SPACE);
524 goto done;
527 free(line);
528 if (ferror(fp)) {
529 err = got_ferror(fp, GOT_ERR_IO);
530 goto done;
532 while (len > 0 && (*logmsg)[len - 1] == '\n') {
533 (*logmsg)[len - 1] = '\0';
534 len--;
537 if (len == 0) {
538 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
539 "commit message cannot be empty, aborting");
540 goto done;
542 if (require_modification &&
543 strcmp(*logmsg, initial_content_stripped) == 0)
544 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
545 "no changes made to commit message, aborting");
546 done:
547 free(initial_content_stripped);
548 free(buf);
549 if (fp && fclose(fp) == EOF && err == NULL)
550 err = got_error_from_errno("fclose");
551 if (err) {
552 free(*logmsg);
553 *logmsg = NULL;
555 return err;
558 static const struct got_error *
559 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
560 const char *path_dir, const char *branch_name)
562 char *initial_content = NULL;
563 const struct got_error *err = NULL;
564 int initial_content_len;
565 int fd = -1;
567 initial_content_len = asprintf(&initial_content,
568 "\n# %s to be imported to branch %s\n", path_dir,
569 branch_name);
570 if (initial_content_len == -1)
571 return got_error_from_errno("asprintf");
573 err = got_opentemp_named_fd(logmsg_path, &fd,
574 GOT_TMPDIR_STR "/got-importmsg");
575 if (err)
576 goto done;
578 if (write(fd, initial_content, initial_content_len) == -1) {
579 err = got_error_from_errno2("write", *logmsg_path);
580 goto done;
583 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
584 initial_content_len, 1);
585 done:
586 if (fd != -1 && close(fd) == -1 && err == NULL)
587 err = got_error_from_errno2("close", *logmsg_path);
588 free(initial_content);
589 if (err) {
590 free(*logmsg_path);
591 *logmsg_path = NULL;
593 return err;
596 static const struct got_error *
597 import_progress(void *arg, const char *path)
599 printf("A %s\n", path);
600 return NULL;
603 static int
604 valid_author(const char *author)
606 /*
607 * Really dumb email address check; we're only doing this to
608 * avoid git's object parser breaking on commits we create.
609 */
610 while (*author && *author != '<')
611 author++;
612 if (*author != '<')
613 return 0;
614 while (*author && *author != '@')
615 author++;
616 if (*author != '@')
617 return 0;
618 while (*author && *author != '>')
619 author++;
620 return *author == '>';
623 static const struct got_error *
624 get_author(char **author, struct got_repository *repo,
625 struct got_worktree *worktree)
627 const struct got_error *err = NULL;
628 const char *got_author = NULL, *name, *email;
629 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
631 *author = NULL;
633 if (worktree)
634 worktree_conf = got_worktree_get_gotconfig(worktree);
635 repo_conf = got_repo_get_gotconfig(repo);
637 /*
638 * Priority of potential author information sources, from most
639 * significant to least significant:
640 * 1) work tree's .got/got.conf file
641 * 2) repository's got.conf file
642 * 3) repository's git config file
643 * 4) environment variables
644 * 5) global git config files (in user's home directory or /etc)
645 */
647 if (worktree_conf)
648 got_author = got_gotconfig_get_author(worktree_conf);
649 if (got_author == NULL)
650 got_author = got_gotconfig_get_author(repo_conf);
651 if (got_author == NULL) {
652 name = got_repo_get_gitconfig_author_name(repo);
653 email = got_repo_get_gitconfig_author_email(repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email) == -1)
656 return got_error_from_errno("asprintf");
657 return NULL;
660 got_author = getenv("GOT_AUTHOR");
661 if (got_author == NULL) {
662 name = got_repo_get_global_gitconfig_author_name(repo);
663 email = got_repo_get_global_gitconfig_author_email(
664 repo);
665 if (name && email) {
666 if (asprintf(author, "%s <%s>", name, email)
667 == -1)
668 return got_error_from_errno("asprintf");
669 return NULL;
671 /* TODO: Look up user in password database? */
672 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
676 *author = strdup(got_author);
677 if (*author == NULL)
678 return got_error_from_errno("strdup");
680 if (!valid_author(*author)) {
681 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
682 free(*author);
683 *author = NULL;
685 return err;
688 static const struct got_error *
689 get_gitconfig_path(char **gitconfig_path)
691 const char *homedir = getenv("HOME");
693 *gitconfig_path = NULL;
694 if (homedir) {
695 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
696 return got_error_from_errno("asprintf");
699 return NULL;
702 static const struct got_error *
703 cmd_import(int argc, char *argv[])
705 const struct got_error *error = NULL;
706 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
707 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
708 const char *branch_name = "main";
709 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
710 struct got_repository *repo = NULL;
711 struct got_reference *branch_ref = NULL, *head_ref = NULL;
712 struct got_object_id *new_commit_id = NULL;
713 int ch;
714 struct got_pathlist_head ignores;
715 struct got_pathlist_entry *pe;
716 int preserve_logmsg = 0;
718 TAILQ_INIT(&ignores);
720 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
721 switch (ch) {
722 case 'b':
723 branch_name = optarg;
724 break;
725 case 'm':
726 logmsg = strdup(optarg);
727 if (logmsg == NULL) {
728 error = got_error_from_errno("strdup");
729 goto done;
731 break;
732 case 'r':
733 repo_path = realpath(optarg, NULL);
734 if (repo_path == NULL) {
735 error = got_error_from_errno2("realpath",
736 optarg);
737 goto done;
739 break;
740 case 'I':
741 if (optarg[0] == '\0')
742 break;
743 error = got_pathlist_insert(&pe, &ignores, optarg,
744 NULL);
745 if (error)
746 goto done;
747 break;
748 default:
749 usage_import();
750 /* NOTREACHED */
754 argc -= optind;
755 argv += optind;
757 #ifndef PROFILE
758 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
759 "unveil",
760 NULL) == -1)
761 err(1, "pledge");
762 #endif
763 if (argc != 1)
764 usage_import();
766 if (repo_path == NULL) {
767 repo_path = getcwd(NULL, 0);
768 if (repo_path == NULL)
769 return got_error_from_errno("getcwd");
771 got_path_strip_trailing_slashes(repo_path);
772 error = get_gitconfig_path(&gitconfig_path);
773 if (error)
774 goto done;
775 error = got_repo_open(&repo, repo_path, gitconfig_path);
776 if (error)
777 goto done;
779 error = get_author(&author, repo, NULL);
780 if (error)
781 return error;
783 /*
784 * Don't let the user create a branch name with a leading '-'.
785 * While technically a valid reference name, this case is usually
786 * an unintended typo.
787 */
788 if (branch_name[0] == '-')
789 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
791 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
792 error = got_error_from_errno("asprintf");
793 goto done;
796 error = got_ref_open(&branch_ref, repo, refname, 0);
797 if (error) {
798 if (error->code != GOT_ERR_NOT_REF)
799 goto done;
800 } else {
801 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
802 "import target branch already exists");
803 goto done;
806 path_dir = realpath(argv[0], NULL);
807 if (path_dir == NULL) {
808 error = got_error_from_errno2("realpath", argv[0]);
809 goto done;
811 got_path_strip_trailing_slashes(path_dir);
813 /*
814 * unveil(2) traverses exec(2); if an editor is used we have
815 * to apply unveil after the log message has been written.
816 */
817 if (logmsg == NULL || strlen(logmsg) == 0) {
818 error = get_editor(&editor);
819 if (error)
820 goto done;
821 free(logmsg);
822 error = collect_import_msg(&logmsg, &logmsg_path, editor,
823 path_dir, refname);
824 if (error) {
825 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
826 logmsg_path != NULL)
827 preserve_logmsg = 1;
828 goto done;
832 if (unveil(path_dir, "r") != 0) {
833 error = got_error_from_errno2("unveil", path_dir);
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_repo_import(&new_commit_id, path_dir, logmsg,
847 author, &ignores, repo, import_progress, NULL);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_write(branch_ref, repo);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_object_id_str(&id_str, new_commit_id);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
876 if (error) {
877 if (error->code != GOT_ERR_NOT_REF) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
884 branch_ref);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
891 error = got_ref_write(head_ref, repo);
892 if (error) {
893 if (logmsg_path)
894 preserve_logmsg = 1;
895 goto done;
899 printf("Created branch %s with commit %s\n",
900 got_ref_get_name(branch_ref), id_str);
901 done:
902 if (preserve_logmsg) {
903 fprintf(stderr, "%s: log message preserved in %s\n",
904 getprogname(), logmsg_path);
905 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
906 error = got_error_from_errno2("unlink", logmsg_path);
907 free(logmsg);
908 free(logmsg_path);
909 free(repo_path);
910 free(editor);
911 free(refname);
912 free(new_commit_id);
913 free(id_str);
914 free(author);
915 free(gitconfig_path);
916 if (branch_ref)
917 got_ref_close(branch_ref);
918 if (head_ref)
919 got_ref_close(head_ref);
920 return error;
923 __dead static void
924 usage_clone(void)
926 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
927 "[-R reference] repository-url [directory]\n", getprogname());
928 exit(1);
931 struct got_fetch_progress_arg {
932 char last_scaled_size[FMT_SCALED_STRSIZE];
933 int last_p_indexed;
934 int last_p_resolved;
935 int verbosity;
937 struct got_repository *repo;
939 int create_configs;
940 int configs_created;
941 struct {
942 struct got_pathlist_head *symrefs;
943 struct got_pathlist_head *wanted_branches;
944 struct got_pathlist_head *wanted_refs;
945 const char *proto;
946 const char *host;
947 const char *port;
948 const char *remote_repo_path;
949 const char *git_url;
950 int fetch_all_branches;
951 int mirror_references;
952 } config_info;
953 };
955 /* XXX forward declaration */
956 static const struct got_error *
957 create_config_files(const char *proto, const char *host, const char *port,
958 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
959 int mirror_references, struct got_pathlist_head *symrefs,
960 struct got_pathlist_head *wanted_branches,
961 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
963 static const struct got_error *
964 fetch_progress(void *arg, const char *message, off_t packfile_size,
965 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
967 const struct got_error *err = NULL;
968 struct got_fetch_progress_arg *a = arg;
969 char scaled_size[FMT_SCALED_STRSIZE];
970 int p_indexed, p_resolved;
971 int print_size = 0, print_indexed = 0, print_resolved = 0;
973 /*
974 * In order to allow a failed clone to be resumed with 'got fetch'
975 * we try to create configuration files as soon as possible.
976 * Once the server has sent information about its default branch
977 * we have all required information.
978 */
979 if (a->create_configs && !a->configs_created &&
980 !TAILQ_EMPTY(a->config_info.symrefs)) {
981 err = create_config_files(a->config_info.proto,
982 a->config_info.host, a->config_info.port,
983 a->config_info.remote_repo_path,
984 a->config_info.git_url,
985 a->config_info.fetch_all_branches,
986 a->config_info.mirror_references,
987 a->config_info.symrefs,
988 a->config_info.wanted_branches,
989 a->config_info.wanted_refs, a->repo);
990 if (err)
991 return err;
992 a->configs_created = 1;
995 if (a->verbosity < 0)
996 return NULL;
998 if (message && message[0] != '\0') {
999 printf("\rserver: %s", message);
1000 fflush(stdout);
1001 return NULL;
1004 if (packfile_size > 0 || nobj_indexed > 0) {
1005 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1006 (a->last_scaled_size[0] == '\0' ||
1007 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1008 print_size = 1;
1009 if (strlcpy(a->last_scaled_size, scaled_size,
1010 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1011 return got_error(GOT_ERR_NO_SPACE);
1013 if (nobj_indexed > 0) {
1014 p_indexed = (nobj_indexed * 100) / nobj_total;
1015 if (p_indexed != a->last_p_indexed) {
1016 a->last_p_indexed = p_indexed;
1017 print_indexed = 1;
1018 print_size = 1;
1021 if (nobj_resolved > 0) {
1022 p_resolved = (nobj_resolved * 100) /
1023 (nobj_total - nobj_loose);
1024 if (p_resolved != a->last_p_resolved) {
1025 a->last_p_resolved = p_resolved;
1026 print_resolved = 1;
1027 print_indexed = 1;
1028 print_size = 1;
1033 if (print_size || print_indexed || print_resolved)
1034 printf("\r");
1035 if (print_size)
1036 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1037 if (print_indexed)
1038 printf("; indexing %d%%", p_indexed);
1039 if (print_resolved)
1040 printf("; resolving deltas %d%%", p_resolved);
1041 if (print_size || print_indexed || print_resolved)
1042 fflush(stdout);
1044 return NULL;
1047 static const struct got_error *
1048 create_symref(const char *refname, struct got_reference *target_ref,
1049 int verbosity, struct got_repository *repo)
1051 const struct got_error *err;
1052 struct got_reference *head_symref;
1054 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1055 if (err)
1056 return err;
1058 err = got_ref_write(head_symref, repo);
1059 if (err == NULL && verbosity > 0) {
1060 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1061 got_ref_get_name(target_ref));
1063 got_ref_close(head_symref);
1064 return err;
1067 static const struct got_error *
1068 list_remote_refs(struct got_pathlist_head *symrefs,
1069 struct got_pathlist_head *refs)
1071 const struct got_error *err;
1072 struct got_pathlist_entry *pe;
1074 TAILQ_FOREACH(pe, symrefs, entry) {
1075 const char *refname = pe->path;
1076 const char *targetref = pe->data;
1078 printf("%s: %s\n", refname, targetref);
1081 TAILQ_FOREACH(pe, refs, entry) {
1082 const char *refname = pe->path;
1083 struct got_object_id *id = pe->data;
1084 char *id_str;
1086 err = got_object_id_str(&id_str, id);
1087 if (err)
1088 return err;
1089 printf("%s: %s\n", refname, id_str);
1090 free(id_str);
1093 return NULL;
1096 static const struct got_error *
1097 create_ref(const char *refname, struct got_object_id *id,
1098 int verbosity, struct got_repository *repo)
1100 const struct got_error *err = NULL;
1101 struct got_reference *ref;
1102 char *id_str;
1104 err = got_object_id_str(&id_str, id);
1105 if (err)
1106 return err;
1108 err = got_ref_alloc(&ref, refname, id);
1109 if (err)
1110 goto done;
1112 err = got_ref_write(ref, repo);
1113 got_ref_close(ref);
1115 if (err == NULL && verbosity >= 0)
1116 printf("Created reference %s: %s\n", refname, id_str);
1117 done:
1118 free(id_str);
1119 return err;
1122 static int
1123 match_wanted_ref(const char *refname, const char *wanted_ref)
1125 if (strncmp(refname, "refs/", 5) != 0)
1126 return 0;
1127 refname += 5;
1130 * Prevent fetching of references that won't make any
1131 * sense outside of the remote repository's context.
1133 if (strncmp(refname, "got/", 4) == 0)
1134 return 0;
1135 if (strncmp(refname, "remotes/", 8) == 0)
1136 return 0;
1138 if (strncmp(wanted_ref, "refs/", 5) == 0)
1139 wanted_ref += 5;
1141 /* Allow prefix match. */
1142 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1143 return 1;
1145 /* Allow exact match. */
1146 return (strcmp(refname, wanted_ref) == 0);
1149 static int
1150 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1152 struct got_pathlist_entry *pe;
1154 TAILQ_FOREACH(pe, wanted_refs, entry) {
1155 if (match_wanted_ref(refname, pe->path))
1156 return 1;
1159 return 0;
1162 static const struct got_error *
1163 create_wanted_ref(const char *refname, struct got_object_id *id,
1164 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1166 const struct got_error *err;
1167 char *remote_refname;
1169 if (strncmp("refs/", refname, 5) == 0)
1170 refname += 5;
1172 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1173 remote_repo_name, refname) == -1)
1174 return got_error_from_errno("asprintf");
1176 err = create_ref(remote_refname, id, verbosity, repo);
1177 free(remote_refname);
1178 return err;
1181 static const struct got_error *
1182 create_gotconfig(const char *proto, const char *host, const char *port,
1183 const char *remote_repo_path, const char *default_branch,
1184 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1185 struct got_pathlist_head *wanted_refs, int mirror_references,
1186 struct got_repository *repo)
1188 const struct got_error *err = NULL;
1189 char *gotconfig_path = NULL;
1190 char *gotconfig = NULL;
1191 FILE *gotconfig_file = NULL;
1192 const char *branchname = NULL;
1193 char *branches = NULL, *refs = NULL;
1194 ssize_t n;
1196 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1197 struct got_pathlist_entry *pe;
1198 TAILQ_FOREACH(pe, wanted_branches, entry) {
1199 char *s;
1200 branchname = pe->path;
1201 if (strncmp(branchname, "refs/heads/", 11) == 0)
1202 branchname += 11;
1203 if (asprintf(&s, "%s\"%s\" ",
1204 branches ? branches : "", branchname) == -1) {
1205 err = got_error_from_errno("asprintf");
1206 goto done;
1208 free(branches);
1209 branches = s;
1211 } else if (!fetch_all_branches && default_branch) {
1212 branchname = default_branch;
1213 if (strncmp(branchname, "refs/heads/", 11) == 0)
1214 branchname += 11;
1215 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1220 if (!TAILQ_EMPTY(wanted_refs)) {
1221 struct got_pathlist_entry *pe;
1222 TAILQ_FOREACH(pe, wanted_refs, entry) {
1223 char *s;
1224 const char *refname = pe->path;
1225 if (strncmp(refname, "refs/", 5) == 0)
1226 branchname += 5;
1227 if (asprintf(&s, "%s\"%s\" ",
1228 refs ? refs : "", refname) == -1) {
1229 err = got_error_from_errno("asprintf");
1230 goto done;
1232 free(refs);
1233 refs = s;
1237 /* Create got.conf(5). */
1238 gotconfig_path = got_repo_get_path_gotconfig(repo);
1239 if (gotconfig_path == NULL) {
1240 err = got_error_from_errno("got_repo_get_path_gotconfig");
1241 goto done;
1243 gotconfig_file = fopen(gotconfig_path, "ae");
1244 if (gotconfig_file == NULL) {
1245 err = got_error_from_errno2("fopen", gotconfig_path);
1246 goto done;
1248 if (asprintf(&gotconfig,
1249 "remote \"%s\" {\n"
1250 "\tserver %s\n"
1251 "\tprotocol %s\n"
1252 "%s%s%s"
1253 "\trepository \"%s\"\n"
1254 "%s%s%s"
1255 "%s%s%s"
1256 "%s"
1257 "%s"
1258 "}\n",
1259 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1260 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1261 remote_repo_path, branches ? "\tbranch { " : "",
1262 branches ? branches : "", branches ? "}\n" : "",
1263 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1264 mirror_references ? "\tmirror-references yes\n" : "",
1265 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1269 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1270 if (n != strlen(gotconfig)) {
1271 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1272 goto done;
1275 done:
1276 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1277 err = got_error_from_errno2("fclose", gotconfig_path);
1278 free(gotconfig_path);
1279 free(branches);
1280 return err;
1283 static const struct got_error *
1284 create_gitconfig(const char *git_url, const char *default_branch,
1285 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1286 struct got_pathlist_head *wanted_refs, int mirror_references,
1287 struct got_repository *repo)
1289 const struct got_error *err = NULL;
1290 char *gitconfig_path = NULL;
1291 char *gitconfig = NULL;
1292 FILE *gitconfig_file = NULL;
1293 char *branches = NULL, *refs = NULL;
1294 const char *branchname;
1295 ssize_t n;
1297 /* Create a config file Git can understand. */
1298 gitconfig_path = got_repo_get_path_gitconfig(repo);
1299 if (gitconfig_path == NULL) {
1300 err = got_error_from_errno("got_repo_get_path_gitconfig");
1301 goto done;
1303 gitconfig_file = fopen(gitconfig_path, "ae");
1304 if (gitconfig_file == NULL) {
1305 err = got_error_from_errno2("fopen", gitconfig_path);
1306 goto done;
1308 if (fetch_all_branches) {
1309 if (mirror_references) {
1310 if (asprintf(&branches,
1311 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 } else if (asprintf(&branches,
1316 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1317 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1318 err = got_error_from_errno("asprintf");
1319 goto done;
1321 } else if (!TAILQ_EMPTY(wanted_branches)) {
1322 struct got_pathlist_entry *pe;
1323 TAILQ_FOREACH(pe, wanted_branches, entry) {
1324 char *s;
1325 branchname = pe->path;
1326 if (strncmp(branchname, "refs/heads/", 11) == 0)
1327 branchname += 11;
1328 if (mirror_references) {
1329 if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1331 branches ? branches : "",
1332 branchname, branchname) == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 } else if (asprintf(&s,
1337 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1338 branches ? branches : "",
1339 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1340 branchname) == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 free(branches);
1345 branches = s;
1347 } else {
1349 * If the server specified a default branch, use just that one.
1350 * Otherwise fall back to fetching all branches on next fetch.
1352 if (default_branch) {
1353 branchname = default_branch;
1354 if (strncmp(branchname, "refs/heads/", 11) == 0)
1355 branchname += 11;
1356 } else
1357 branchname = "*"; /* fall back to all branches */
1358 if (mirror_references) {
1359 if (asprintf(&branches,
1360 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1361 branchname, branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1365 } else if (asprintf(&branches,
1366 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1367 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1368 branchname) == -1) {
1369 err = got_error_from_errno("asprintf");
1370 goto done;
1373 if (!TAILQ_EMPTY(wanted_refs)) {
1374 struct got_pathlist_entry *pe;
1375 TAILQ_FOREACH(pe, wanted_refs, entry) {
1376 char *s;
1377 const char *refname = pe->path;
1378 if (strncmp(refname, "refs/", 5) == 0)
1379 refname += 5;
1380 if (mirror_references) {
1381 if (asprintf(&s,
1382 "%s\tfetch = refs/%s:refs/%s\n",
1383 refs ? refs : "", refname, refname) == -1) {
1384 err = got_error_from_errno("asprintf");
1385 goto done;
1387 } else if (asprintf(&s,
1388 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1389 refs ? refs : "",
1390 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1391 refname) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 free(refs);
1396 refs = s;
1400 if (asprintf(&gitconfig,
1401 "[remote \"%s\"]\n"
1402 "\turl = %s\n"
1403 "%s"
1404 "%s"
1405 "\tfetch = refs/tags/*:refs/tags/*\n",
1406 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1407 refs ? refs : "") == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1412 if (n != strlen(gitconfig)) {
1413 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1414 goto done;
1416 done:
1417 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1418 err = got_error_from_errno2("fclose", gitconfig_path);
1419 free(gitconfig_path);
1420 free(branches);
1421 return err;
1424 static const struct got_error *
1425 create_config_files(const char *proto, const char *host, const char *port,
1426 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1427 int mirror_references, struct got_pathlist_head *symrefs,
1428 struct got_pathlist_head *wanted_branches,
1429 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1431 const struct got_error *err = NULL;
1432 const char *default_branch = NULL;
1433 struct got_pathlist_entry *pe;
1436 * If we asked for a set of wanted branches then use the first
1437 * one of those.
1439 if (!TAILQ_EMPTY(wanted_branches)) {
1440 pe = TAILQ_FIRST(wanted_branches);
1441 default_branch = pe->path;
1442 } else {
1443 /* First HEAD ref listed by server is the default branch. */
1444 TAILQ_FOREACH(pe, symrefs, entry) {
1445 const char *refname = pe->path;
1446 const char *target = pe->data;
1448 if (strcmp(refname, GOT_REF_HEAD) != 0)
1449 continue;
1451 default_branch = target;
1452 break;
1456 /* Create got.conf(5). */
1457 err = create_gotconfig(proto, host, port, remote_repo_path,
1458 default_branch, fetch_all_branches, wanted_branches,
1459 wanted_refs, mirror_references, repo);
1460 if (err)
1461 return err;
1463 /* Create a config file Git can understand. */
1464 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1465 wanted_branches, wanted_refs, mirror_references, repo);
1468 static const struct got_error *
1469 cmd_clone(int argc, char *argv[])
1471 const struct got_error *error = NULL;
1472 const char *uri, *dirname;
1473 char *proto, *host, *port, *repo_name, *server_path;
1474 char *default_destdir = NULL, *id_str = NULL;
1475 const char *repo_path;
1476 struct got_repository *repo = NULL;
1477 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1478 struct got_pathlist_entry *pe;
1479 struct got_object_id *pack_hash = NULL;
1480 int ch, fetchfd = -1, fetchstatus;
1481 pid_t fetchpid = -1;
1482 struct got_fetch_progress_arg fpa;
1483 char *git_url = NULL;
1484 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1485 int list_refs_only = 0;
1487 TAILQ_INIT(&refs);
1488 TAILQ_INIT(&symrefs);
1489 TAILQ_INIT(&wanted_branches);
1490 TAILQ_INIT(&wanted_refs);
1492 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1493 switch (ch) {
1494 case 'a':
1495 fetch_all_branches = 1;
1496 break;
1497 case 'b':
1498 error = got_pathlist_append(&wanted_branches,
1499 optarg, NULL);
1500 if (error)
1501 return error;
1502 break;
1503 case 'l':
1504 list_refs_only = 1;
1505 break;
1506 case 'm':
1507 mirror_references = 1;
1508 break;
1509 case 'v':
1510 if (verbosity < 0)
1511 verbosity = 0;
1512 else if (verbosity < 3)
1513 verbosity++;
1514 break;
1515 case 'q':
1516 verbosity = -1;
1517 break;
1518 case 'R':
1519 error = got_pathlist_append(&wanted_refs,
1520 optarg, NULL);
1521 if (error)
1522 return error;
1523 break;
1524 default:
1525 usage_clone();
1526 break;
1529 argc -= optind;
1530 argv += optind;
1532 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1533 option_conflict('a', 'b');
1534 if (list_refs_only) {
1535 if (!TAILQ_EMPTY(&wanted_branches))
1536 option_conflict('l', 'b');
1537 if (fetch_all_branches)
1538 option_conflict('l', 'a');
1539 if (mirror_references)
1540 option_conflict('l', 'm');
1541 if (!TAILQ_EMPTY(&wanted_refs))
1542 option_conflict('l', 'R');
1545 uri = argv[0];
1547 if (argc == 1)
1548 dirname = NULL;
1549 else if (argc == 2)
1550 dirname = argv[1];
1551 else
1552 usage_clone();
1554 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1555 &repo_name, uri);
1556 if (error)
1557 goto done;
1559 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1560 host, port ? ":" : "", port ? port : "",
1561 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1562 error = got_error_from_errno("asprintf");
1563 goto done;
1566 if (strcmp(proto, "git") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd dns inet unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "git+ssh") == 0 ||
1573 strcmp(proto, "ssh") == 0) {
1574 #ifndef PROFILE
1575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1576 "sendfd unveil", NULL) == -1)
1577 err(1, "pledge");
1578 #endif
1579 } else if (strcmp(proto, "http") == 0 ||
1580 strcmp(proto, "git+http") == 0) {
1581 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1582 goto done;
1583 } else {
1584 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1585 goto done;
1587 if (dirname == NULL) {
1588 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1589 error = got_error_from_errno("asprintf");
1590 goto done;
1592 repo_path = default_destdir;
1593 } else
1594 repo_path = dirname;
1596 if (!list_refs_only) {
1597 error = got_path_mkdir(repo_path);
1598 if (error &&
1599 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1600 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1601 goto done;
1602 if (!got_path_dir_is_empty(repo_path)) {
1603 error = got_error_path(repo_path,
1604 GOT_ERR_DIR_NOT_EMPTY);
1605 goto done;
1609 error = got_dial_apply_unveil(proto);
1610 if (error)
1611 goto done;
1613 error = apply_unveil(repo_path, 0, NULL);
1614 if (error)
1615 goto done;
1617 if (verbosity >= 0)
1618 printf("Connecting to %s%s%s\n", host,
1619 port ? ":" : "", port ? port : "");
1621 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1622 server_path, verbosity);
1623 if (error)
1624 goto done;
1626 if (!list_refs_only) {
1627 error = got_repo_init(repo_path);
1628 if (error)
1629 goto done;
1630 error = got_repo_open(&repo, repo_path, NULL);
1631 if (error)
1632 goto done;
1635 fpa.last_scaled_size[0] = '\0';
1636 fpa.last_p_indexed = -1;
1637 fpa.last_p_resolved = -1;
1638 fpa.verbosity = verbosity;
1639 fpa.create_configs = 1;
1640 fpa.configs_created = 0;
1641 fpa.repo = repo;
1642 fpa.config_info.symrefs = &symrefs;
1643 fpa.config_info.wanted_branches = &wanted_branches;
1644 fpa.config_info.wanted_refs = &wanted_refs;
1645 fpa.config_info.proto = proto;
1646 fpa.config_info.host = host;
1647 fpa.config_info.port = port;
1648 fpa.config_info.remote_repo_path = server_path;
1649 fpa.config_info.git_url = git_url;
1650 fpa.config_info.fetch_all_branches = fetch_all_branches;
1651 fpa.config_info.mirror_references = mirror_references;
1652 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1653 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1654 fetch_all_branches, &wanted_branches, &wanted_refs,
1655 list_refs_only, verbosity, fetchfd, repo,
1656 fetch_progress, &fpa);
1657 if (error)
1658 goto done;
1660 if (list_refs_only) {
1661 error = list_remote_refs(&symrefs, &refs);
1662 goto done;
1665 if (pack_hash == NULL) {
1666 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1667 "server sent an empty pack file");
1668 goto done;
1670 error = got_object_id_str(&id_str, pack_hash);
1671 if (error)
1672 goto done;
1673 if (verbosity >= 0)
1674 printf("\nFetched %s.pack\n", id_str);
1675 free(id_str);
1677 /* Set up references provided with the pack file. */
1678 TAILQ_FOREACH(pe, &refs, entry) {
1679 const char *refname = pe->path;
1680 struct got_object_id *id = pe->data;
1681 char *remote_refname;
1683 if (is_wanted_ref(&wanted_refs, refname) &&
1684 !mirror_references) {
1685 error = create_wanted_ref(refname, id,
1686 GOT_FETCH_DEFAULT_REMOTE_NAME,
1687 verbosity - 1, repo);
1688 if (error)
1689 goto done;
1690 continue;
1693 error = create_ref(refname, id, verbosity - 1, repo);
1694 if (error)
1695 goto done;
1697 if (mirror_references)
1698 continue;
1700 if (strncmp("refs/heads/", refname, 11) != 0)
1701 continue;
1703 if (asprintf(&remote_refname,
1704 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1705 refname + 11) == -1) {
1706 error = got_error_from_errno("asprintf");
1707 goto done;
1709 error = create_ref(remote_refname, id, verbosity - 1, repo);
1710 free(remote_refname);
1711 if (error)
1712 goto done;
1715 /* Set the HEAD reference if the server provided one. */
1716 TAILQ_FOREACH(pe, &symrefs, entry) {
1717 struct got_reference *target_ref;
1718 const char *refname = pe->path;
1719 const char *target = pe->data;
1720 char *remote_refname = NULL, *remote_target = NULL;
1722 if (strcmp(refname, GOT_REF_HEAD) != 0)
1723 continue;
1725 error = got_ref_open(&target_ref, repo, target, 0);
1726 if (error) {
1727 if (error->code == GOT_ERR_NOT_REF) {
1728 error = NULL;
1729 continue;
1731 goto done;
1734 error = create_symref(refname, target_ref, verbosity, repo);
1735 got_ref_close(target_ref);
1736 if (error)
1737 goto done;
1739 if (mirror_references)
1740 continue;
1742 if (strncmp("refs/heads/", target, 11) != 0)
1743 continue;
1745 if (asprintf(&remote_refname,
1746 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1747 refname) == -1) {
1748 error = got_error_from_errno("asprintf");
1749 goto done;
1751 if (asprintf(&remote_target,
1752 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1753 target + 11) == -1) {
1754 error = got_error_from_errno("asprintf");
1755 free(remote_refname);
1756 goto done;
1758 error = got_ref_open(&target_ref, repo, remote_target, 0);
1759 if (error) {
1760 free(remote_refname);
1761 free(remote_target);
1762 if (error->code == GOT_ERR_NOT_REF) {
1763 error = NULL;
1764 continue;
1766 goto done;
1768 error = create_symref(remote_refname, target_ref,
1769 verbosity - 1, repo);
1770 free(remote_refname);
1771 free(remote_target);
1772 got_ref_close(target_ref);
1773 if (error)
1774 goto done;
1776 if (pe == NULL) {
1778 * We failed to set the HEAD reference. If we asked for
1779 * a set of wanted branches use the first of one of those
1780 * which could be fetched instead.
1782 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1783 const char *target = pe->path;
1784 struct got_reference *target_ref;
1786 error = got_ref_open(&target_ref, repo, target, 0);
1787 if (error) {
1788 if (error->code == GOT_ERR_NOT_REF) {
1789 error = NULL;
1790 continue;
1792 goto done;
1795 error = create_symref(GOT_REF_HEAD, target_ref,
1796 verbosity, repo);
1797 got_ref_close(target_ref);
1798 if (error)
1799 goto done;
1800 break;
1804 if (verbosity >= 0)
1805 printf("Created %s repository '%s'\n",
1806 mirror_references ? "mirrored" : "cloned", repo_path);
1807 done:
1808 if (fetchpid > 0) {
1809 if (kill(fetchpid, SIGTERM) == -1)
1810 error = got_error_from_errno("kill");
1811 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1812 error = got_error_from_errno("waitpid");
1814 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1815 error = got_error_from_errno("close");
1816 if (repo) {
1817 const struct got_error *close_err = got_repo_close(repo);
1818 if (error == NULL)
1819 error = close_err;
1821 TAILQ_FOREACH(pe, &refs, entry) {
1822 free((void *)pe->path);
1823 free(pe->data);
1825 got_pathlist_free(&refs);
1826 TAILQ_FOREACH(pe, &symrefs, entry) {
1827 free((void *)pe->path);
1828 free(pe->data);
1830 got_pathlist_free(&symrefs);
1831 got_pathlist_free(&wanted_branches);
1832 got_pathlist_free(&wanted_refs);
1833 free(pack_hash);
1834 free(proto);
1835 free(host);
1836 free(port);
1837 free(server_path);
1838 free(repo_name);
1839 free(default_destdir);
1840 free(git_url);
1841 return error;
1844 static const struct got_error *
1845 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1846 int replace_tags, int verbosity, struct got_repository *repo)
1848 const struct got_error *err = NULL;
1849 char *new_id_str = NULL;
1850 struct got_object_id *old_id = NULL;
1852 err = got_object_id_str(&new_id_str, new_id);
1853 if (err)
1854 goto done;
1856 if (!replace_tags &&
1857 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1858 err = got_ref_resolve(&old_id, repo, ref);
1859 if (err)
1860 goto done;
1861 if (got_object_id_cmp(old_id, new_id) == 0)
1862 goto done;
1863 if (verbosity >= 0) {
1864 printf("Rejecting update of existing tag %s: %s\n",
1865 got_ref_get_name(ref), new_id_str);
1867 goto done;
1870 if (got_ref_is_symbolic(ref)) {
1871 if (verbosity >= 0) {
1872 printf("Replacing reference %s: %s\n",
1873 got_ref_get_name(ref),
1874 got_ref_get_symref_target(ref));
1876 err = got_ref_change_symref_to_ref(ref, new_id);
1877 if (err)
1878 goto done;
1879 err = got_ref_write(ref, repo);
1880 if (err)
1881 goto done;
1882 } else {
1883 err = got_ref_resolve(&old_id, repo, ref);
1884 if (err)
1885 goto done;
1886 if (got_object_id_cmp(old_id, new_id) == 0)
1887 goto done;
1889 err = got_ref_change_ref(ref, new_id);
1890 if (err)
1891 goto done;
1892 err = got_ref_write(ref, repo);
1893 if (err)
1894 goto done;
1897 if (verbosity >= 0)
1898 printf("Updated %s: %s\n", got_ref_get_name(ref),
1899 new_id_str);
1900 done:
1901 free(old_id);
1902 free(new_id_str);
1903 return err;
1906 static const struct got_error *
1907 update_symref(const char *refname, struct got_reference *target_ref,
1908 int verbosity, struct got_repository *repo)
1910 const struct got_error *err = NULL, *unlock_err;
1911 struct got_reference *symref;
1912 int symref_is_locked = 0;
1914 err = got_ref_open(&symref, repo, refname, 1);
1915 if (err) {
1916 if (err->code != GOT_ERR_NOT_REF)
1917 return err;
1918 err = got_ref_alloc_symref(&symref, refname, target_ref);
1919 if (err)
1920 goto done;
1922 err = got_ref_write(symref, repo);
1923 if (err)
1924 goto done;
1926 if (verbosity >= 0)
1927 printf("Created reference %s: %s\n",
1928 got_ref_get_name(symref),
1929 got_ref_get_symref_target(symref));
1930 } else {
1931 symref_is_locked = 1;
1933 if (strcmp(got_ref_get_symref_target(symref),
1934 got_ref_get_name(target_ref)) == 0)
1935 goto done;
1937 err = got_ref_change_symref(symref,
1938 got_ref_get_name(target_ref));
1939 if (err)
1940 goto done;
1942 err = got_ref_write(symref, repo);
1943 if (err)
1944 goto done;
1946 if (verbosity >= 0)
1947 printf("Updated %s: %s\n", got_ref_get_name(symref),
1948 got_ref_get_symref_target(symref));
1951 done:
1952 if (symref_is_locked) {
1953 unlock_err = got_ref_unlock(symref);
1954 if (unlock_err && err == NULL)
1955 err = unlock_err;
1957 got_ref_close(symref);
1958 return err;
1961 __dead static void
1962 usage_fetch(void)
1964 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1965 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1966 "[remote-repository-name]\n",
1967 getprogname());
1968 exit(1);
1971 static const struct got_error *
1972 delete_missing_ref(struct got_reference *ref,
1973 int verbosity, struct got_repository *repo)
1975 const struct got_error *err = NULL;
1976 struct got_object_id *id = NULL;
1977 char *id_str = NULL;
1979 if (got_ref_is_symbolic(ref)) {
1980 err = got_ref_delete(ref, repo);
1981 if (err)
1982 return err;
1983 if (verbosity >= 0) {
1984 printf("Deleted %s: %s\n",
1985 got_ref_get_name(ref),
1986 got_ref_get_symref_target(ref));
1988 } else {
1989 err = got_ref_resolve(&id, repo, ref);
1990 if (err)
1991 return err;
1992 err = got_object_id_str(&id_str, id);
1993 if (err)
1994 goto done;
1996 err = got_ref_delete(ref, repo);
1997 if (err)
1998 goto done;
1999 if (verbosity >= 0) {
2000 printf("Deleted %s: %s\n",
2001 got_ref_get_name(ref), id_str);
2004 done:
2005 free(id);
2006 free(id_str);
2007 return NULL;
2010 static const struct got_error *
2011 delete_missing_refs(struct got_pathlist_head *their_refs,
2012 struct got_pathlist_head *their_symrefs,
2013 const struct got_remote_repo *remote,
2014 int verbosity, struct got_repository *repo)
2016 const struct got_error *err = NULL, *unlock_err;
2017 struct got_reflist_head my_refs;
2018 struct got_reflist_entry *re;
2019 struct got_pathlist_entry *pe;
2020 char *remote_namespace = NULL;
2021 char *local_refname = NULL;
2023 TAILQ_INIT(&my_refs);
2025 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2026 == -1)
2027 return got_error_from_errno("asprintf");
2029 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2030 if (err)
2031 goto done;
2033 TAILQ_FOREACH(re, &my_refs, entry) {
2034 const char *refname = got_ref_get_name(re->ref);
2035 const char *their_refname;
2037 if (remote->mirror_references) {
2038 their_refname = refname;
2039 } else {
2040 if (strncmp(refname, remote_namespace,
2041 strlen(remote_namespace)) == 0) {
2042 if (strcmp(refname + strlen(remote_namespace),
2043 GOT_REF_HEAD) == 0)
2044 continue;
2045 if (asprintf(&local_refname, "refs/heads/%s",
2046 refname + strlen(remote_namespace)) == -1) {
2047 err = got_error_from_errno("asprintf");
2048 goto done;
2050 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2051 continue;
2053 their_refname = local_refname;
2056 TAILQ_FOREACH(pe, their_refs, entry) {
2057 if (strcmp(their_refname, pe->path) == 0)
2058 break;
2060 if (pe != NULL)
2061 continue;
2063 TAILQ_FOREACH(pe, their_symrefs, entry) {
2064 if (strcmp(their_refname, pe->path) == 0)
2065 break;
2067 if (pe != NULL)
2068 continue;
2070 err = delete_missing_ref(re->ref, verbosity, repo);
2071 if (err)
2072 break;
2074 if (local_refname) {
2075 struct got_reference *ref;
2076 err = got_ref_open(&ref, repo, local_refname, 1);
2077 if (err) {
2078 if (err->code != GOT_ERR_NOT_REF)
2079 break;
2080 free(local_refname);
2081 local_refname = NULL;
2082 continue;
2084 err = delete_missing_ref(ref, verbosity, repo);
2085 if (err)
2086 break;
2087 unlock_err = got_ref_unlock(ref);
2088 got_ref_close(ref);
2089 if (unlock_err && err == NULL) {
2090 err = unlock_err;
2091 break;
2094 free(local_refname);
2095 local_refname = NULL;
2098 done:
2099 free(remote_namespace);
2100 free(local_refname);
2101 return err;
2104 static const struct got_error *
2105 update_wanted_ref(const char *refname, struct got_object_id *id,
2106 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2108 const struct got_error *err, *unlock_err;
2109 char *remote_refname;
2110 struct got_reference *ref;
2112 if (strncmp("refs/", refname, 5) == 0)
2113 refname += 5;
2115 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2116 remote_repo_name, refname) == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_open(&ref, repo, remote_refname, 1);
2120 if (err) {
2121 if (err->code != GOT_ERR_NOT_REF)
2122 goto done;
2123 err = create_ref(remote_refname, id, verbosity, repo);
2124 } else {
2125 err = update_ref(ref, id, 0, verbosity, repo);
2126 unlock_err = got_ref_unlock(ref);
2127 if (unlock_err && err == NULL)
2128 err = unlock_err;
2129 got_ref_close(ref);
2131 done:
2132 free(remote_refname);
2133 return err;
2136 static const struct got_error *
2137 delete_ref(struct got_repository *repo, struct got_reference *ref)
2139 const struct got_error *err = NULL;
2140 struct got_object_id *id = NULL;
2141 char *id_str = NULL;
2142 const char *target;
2144 if (got_ref_is_symbolic(ref)) {
2145 target = got_ref_get_symref_target(ref);
2146 } else {
2147 err = got_ref_resolve(&id, repo, ref);
2148 if (err)
2149 goto done;
2150 err = got_object_id_str(&id_str, id);
2151 if (err)
2152 goto done;
2153 target = id_str;
2156 err = got_ref_delete(ref, repo);
2157 if (err)
2158 goto done;
2160 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2161 done:
2162 free(id);
2163 free(id_str);
2164 return err;
2167 static const struct got_error *
2168 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2170 const struct got_error *err = NULL;
2171 struct got_reflist_head refs;
2172 struct got_reflist_entry *re;
2173 char *prefix;
2175 TAILQ_INIT(&refs);
2177 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2178 err = got_error_from_errno("asprintf");
2179 goto done;
2181 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2182 if (err)
2183 goto done;
2185 TAILQ_FOREACH(re, &refs, entry)
2186 delete_ref(repo, re->ref);
2187 done:
2188 got_ref_list_free(&refs);
2189 return err;
2192 static const struct got_error *
2193 cmd_fetch(int argc, char *argv[])
2195 const struct got_error *error = NULL, *unlock_err;
2196 char *cwd = NULL, *repo_path = NULL;
2197 const char *remote_name;
2198 char *proto = NULL, *host = NULL, *port = NULL;
2199 char *repo_name = NULL, *server_path = NULL;
2200 const struct got_remote_repo *remotes, *remote = NULL;
2201 int nremotes;
2202 char *id_str = NULL;
2203 struct got_repository *repo = NULL;
2204 struct got_worktree *worktree = NULL;
2205 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2206 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2207 struct got_pathlist_entry *pe;
2208 struct got_object_id *pack_hash = NULL;
2209 int i, ch, fetchfd = -1, fetchstatus;
2210 pid_t fetchpid = -1;
2211 struct got_fetch_progress_arg fpa;
2212 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2213 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2215 TAILQ_INIT(&refs);
2216 TAILQ_INIT(&symrefs);
2217 TAILQ_INIT(&wanted_branches);
2218 TAILQ_INIT(&wanted_refs);
2220 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2221 switch (ch) {
2222 case 'a':
2223 fetch_all_branches = 1;
2224 break;
2225 case 'b':
2226 error = got_pathlist_append(&wanted_branches,
2227 optarg, NULL);
2228 if (error)
2229 return error;
2230 break;
2231 case 'd':
2232 delete_refs = 1;
2233 break;
2234 case 'l':
2235 list_refs_only = 1;
2236 break;
2237 case 'r':
2238 repo_path = realpath(optarg, NULL);
2239 if (repo_path == NULL)
2240 return got_error_from_errno2("realpath",
2241 optarg);
2242 got_path_strip_trailing_slashes(repo_path);
2243 break;
2244 case 't':
2245 replace_tags = 1;
2246 break;
2247 case 'v':
2248 if (verbosity < 0)
2249 verbosity = 0;
2250 else if (verbosity < 3)
2251 verbosity++;
2252 break;
2253 case 'q':
2254 verbosity = -1;
2255 break;
2256 case 'R':
2257 error = got_pathlist_append(&wanted_refs,
2258 optarg, NULL);
2259 if (error)
2260 return error;
2261 break;
2262 case 'X':
2263 delete_remote = 1;
2264 break;
2265 default:
2266 usage_fetch();
2267 break;
2270 argc -= optind;
2271 argv += optind;
2273 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2274 option_conflict('a', 'b');
2275 if (list_refs_only) {
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('l', 'b');
2278 if (fetch_all_branches)
2279 option_conflict('l', 'a');
2280 if (delete_refs)
2281 option_conflict('l', 'd');
2282 if (delete_remote)
2283 option_conflict('l', 'X');
2285 if (delete_remote) {
2286 if (fetch_all_branches)
2287 option_conflict('X', 'a');
2288 if (!TAILQ_EMPTY(&wanted_branches))
2289 option_conflict('X', 'b');
2290 if (delete_refs)
2291 option_conflict('X', 'd');
2292 if (replace_tags)
2293 option_conflict('X', 't');
2294 if (!TAILQ_EMPTY(&wanted_refs))
2295 option_conflict('X', 'R');
2298 if (argc == 0) {
2299 if (delete_remote)
2300 errx(1, "-X option requires a remote name");
2301 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2302 } else if (argc == 1)
2303 remote_name = argv[0];
2304 else
2305 usage_fetch();
2307 cwd = getcwd(NULL, 0);
2308 if (cwd == NULL) {
2309 error = got_error_from_errno("getcwd");
2310 goto done;
2313 if (repo_path == NULL) {
2314 error = got_worktree_open(&worktree, cwd);
2315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2316 goto done;
2317 else
2318 error = NULL;
2319 if (worktree) {
2320 repo_path =
2321 strdup(got_worktree_get_repo_path(worktree));
2322 if (repo_path == NULL)
2323 error = got_error_from_errno("strdup");
2324 if (error)
2325 goto done;
2326 } else {
2327 repo_path = strdup(cwd);
2328 if (repo_path == NULL) {
2329 error = got_error_from_errno("strdup");
2330 goto done;
2335 error = got_repo_open(&repo, repo_path, NULL);
2336 if (error)
2337 goto done;
2339 if (delete_remote) {
2340 error = delete_refs_for_remote(repo, remote_name);
2341 goto done; /* nothing else to do */
2344 if (worktree) {
2345 worktree_conf = got_worktree_get_gotconfig(worktree);
2346 if (worktree_conf) {
2347 got_gotconfig_get_remotes(&nremotes, &remotes,
2348 worktree_conf);
2349 for (i = 0; i < nremotes; i++) {
2350 if (strcmp(remotes[i].name, remote_name) == 0) {
2351 remote = &remotes[i];
2352 break;
2357 if (remote == NULL) {
2358 repo_conf = got_repo_get_gotconfig(repo);
2359 if (repo_conf) {
2360 got_gotconfig_get_remotes(&nremotes, &remotes,
2361 repo_conf);
2362 for (i = 0; i < nremotes; i++) {
2363 if (strcmp(remotes[i].name, remote_name) == 0) {
2364 remote = &remotes[i];
2365 break;
2370 if (remote == NULL) {
2371 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2372 for (i = 0; i < nremotes; i++) {
2373 if (strcmp(remotes[i].name, remote_name) == 0) {
2374 remote = &remotes[i];
2375 break;
2379 if (remote == NULL) {
2380 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2381 goto done;
2384 if (TAILQ_EMPTY(&wanted_branches)) {
2385 if (!fetch_all_branches)
2386 fetch_all_branches = remote->fetch_all_branches;
2387 for (i = 0; i < remote->nfetch_branches; i++) {
2388 got_pathlist_append(&wanted_branches,
2389 remote->fetch_branches[i], NULL);
2392 if (TAILQ_EMPTY(&wanted_refs)) {
2393 for (i = 0; i < remote->nfetch_refs; i++) {
2394 got_pathlist_append(&wanted_refs,
2395 remote->fetch_refs[i], NULL);
2399 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2400 &repo_name, remote->fetch_url);
2401 if (error)
2402 goto done;
2404 if (strcmp(proto, "git") == 0) {
2405 #ifndef PROFILE
2406 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2407 "sendfd dns inet unveil", NULL) == -1)
2408 err(1, "pledge");
2409 #endif
2410 } else if (strcmp(proto, "git+ssh") == 0 ||
2411 strcmp(proto, "ssh") == 0) {
2412 #ifndef PROFILE
2413 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2414 "sendfd unveil", NULL) == -1)
2415 err(1, "pledge");
2416 #endif
2417 } else if (strcmp(proto, "http") == 0 ||
2418 strcmp(proto, "git+http") == 0) {
2419 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2420 goto done;
2421 } else {
2422 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2423 goto done;
2426 error = got_dial_apply_unveil(proto);
2427 if (error)
2428 goto done;
2430 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2431 if (error)
2432 goto done;
2434 if (verbosity >= 0)
2435 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2436 port ? ":" : "", port ? port : "");
2438 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2439 server_path, verbosity);
2440 if (error)
2441 goto done;
2443 fpa.last_scaled_size[0] = '\0';
2444 fpa.last_p_indexed = -1;
2445 fpa.last_p_resolved = -1;
2446 fpa.verbosity = verbosity;
2447 fpa.repo = repo;
2448 fpa.create_configs = 0;
2449 fpa.configs_created = 0;
2450 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2451 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2452 remote->mirror_references, fetch_all_branches, &wanted_branches,
2453 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2454 fetch_progress, &fpa);
2455 if (error)
2456 goto done;
2458 if (list_refs_only) {
2459 error = list_remote_refs(&symrefs, &refs);
2460 goto done;
2463 if (pack_hash == NULL) {
2464 if (verbosity >= 0)
2465 printf("Already up-to-date\n");
2466 } else if (verbosity >= 0) {
2467 error = got_object_id_str(&id_str, pack_hash);
2468 if (error)
2469 goto done;
2470 printf("\nFetched %s.pack\n", id_str);
2471 free(id_str);
2472 id_str = NULL;
2475 /* Update references provided with the pack file. */
2476 TAILQ_FOREACH(pe, &refs, entry) {
2477 const char *refname = pe->path;
2478 struct got_object_id *id = pe->data;
2479 struct got_reference *ref;
2480 char *remote_refname;
2482 if (is_wanted_ref(&wanted_refs, refname) &&
2483 !remote->mirror_references) {
2484 error = update_wanted_ref(refname, id,
2485 remote->name, verbosity, repo);
2486 if (error)
2487 goto done;
2488 continue;
2491 if (remote->mirror_references ||
2492 strncmp("refs/tags/", refname, 10) == 0) {
2493 error = got_ref_open(&ref, repo, refname, 1);
2494 if (error) {
2495 if (error->code != GOT_ERR_NOT_REF)
2496 goto done;
2497 error = create_ref(refname, id, verbosity,
2498 repo);
2499 if (error)
2500 goto done;
2501 } else {
2502 error = update_ref(ref, id, replace_tags,
2503 verbosity, repo);
2504 unlock_err = got_ref_unlock(ref);
2505 if (unlock_err && error == NULL)
2506 error = unlock_err;
2507 got_ref_close(ref);
2508 if (error)
2509 goto done;
2511 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2512 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2513 remote_name, refname + 11) == -1) {
2514 error = got_error_from_errno("asprintf");
2515 goto done;
2518 error = got_ref_open(&ref, repo, remote_refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(remote_refname, id,
2523 verbosity, repo);
2524 if (error)
2525 goto done;
2526 } else {
2527 error = update_ref(ref, id, replace_tags,
2528 verbosity, repo);
2529 unlock_err = got_ref_unlock(ref);
2530 if (unlock_err && error == NULL)
2531 error = unlock_err;
2532 got_ref_close(ref);
2533 if (error)
2534 goto done;
2537 /* Also create a local branch if none exists yet. */
2538 error = got_ref_open(&ref, repo, refname, 1);
2539 if (error) {
2540 if (error->code != GOT_ERR_NOT_REF)
2541 goto done;
2542 error = create_ref(refname, id, verbosity,
2543 repo);
2544 if (error)
2545 goto done;
2546 } else {
2547 unlock_err = got_ref_unlock(ref);
2548 if (unlock_err && error == NULL)
2549 error = unlock_err;
2550 got_ref_close(ref);
2554 if (delete_refs) {
2555 error = delete_missing_refs(&refs, &symrefs, remote,
2556 verbosity, repo);
2557 if (error)
2558 goto done;
2561 if (!remote->mirror_references) {
2562 /* Update remote HEAD reference if the server provided one. */
2563 TAILQ_FOREACH(pe, &symrefs, entry) {
2564 struct got_reference *target_ref;
2565 const char *refname = pe->path;
2566 const char *target = pe->data;
2567 char *remote_refname = NULL, *remote_target = NULL;
2569 if (strcmp(refname, GOT_REF_HEAD) != 0)
2570 continue;
2572 if (strncmp("refs/heads/", target, 11) != 0)
2573 continue;
2575 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2576 remote->name, refname) == -1) {
2577 error = got_error_from_errno("asprintf");
2578 goto done;
2580 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2581 remote->name, target + 11) == -1) {
2582 error = got_error_from_errno("asprintf");
2583 free(remote_refname);
2584 goto done;
2587 error = got_ref_open(&target_ref, repo, remote_target,
2588 0);
2589 if (error) {
2590 free(remote_refname);
2591 free(remote_target);
2592 if (error->code == GOT_ERR_NOT_REF) {
2593 error = NULL;
2594 continue;
2596 goto done;
2598 error = update_symref(remote_refname, target_ref,
2599 verbosity, repo);
2600 free(remote_refname);
2601 free(remote_target);
2602 got_ref_close(target_ref);
2603 if (error)
2604 goto done;
2607 done:
2608 if (fetchpid > 0) {
2609 if (kill(fetchpid, SIGTERM) == -1)
2610 error = got_error_from_errno("kill");
2611 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2612 error = got_error_from_errno("waitpid");
2614 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2615 error = got_error_from_errno("close");
2616 if (repo) {
2617 const struct got_error *close_err = got_repo_close(repo);
2618 if (error == NULL)
2619 error = close_err;
2621 if (worktree)
2622 got_worktree_close(worktree);
2623 TAILQ_FOREACH(pe, &refs, entry) {
2624 free((void *)pe->path);
2625 free(pe->data);
2627 got_pathlist_free(&refs);
2628 TAILQ_FOREACH(pe, &symrefs, entry) {
2629 free((void *)pe->path);
2630 free(pe->data);
2632 got_pathlist_free(&symrefs);
2633 got_pathlist_free(&wanted_branches);
2634 got_pathlist_free(&wanted_refs);
2635 free(id_str);
2636 free(cwd);
2637 free(repo_path);
2638 free(pack_hash);
2639 free(proto);
2640 free(host);
2641 free(port);
2642 free(server_path);
2643 free(repo_name);
2644 return error;
2648 __dead static void
2649 usage_checkout(void)
2651 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2652 "[-p prefix] [-q] repository-path [worktree-path]\n",
2653 getprogname());
2654 exit(1);
2657 static void
2658 show_worktree_base_ref_warning(void)
2660 fprintf(stderr, "%s: warning: could not create a reference "
2661 "to the work tree's base commit; the commit could be "
2662 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2663 "repository writable and running 'got update' will prevent this\n",
2664 getprogname());
2667 struct got_checkout_progress_arg {
2668 const char *worktree_path;
2669 int had_base_commit_ref_error;
2670 int verbosity;
2673 static const struct got_error *
2674 checkout_progress(void *arg, unsigned char status, const char *path)
2676 struct got_checkout_progress_arg *a = arg;
2678 /* Base commit bump happens silently. */
2679 if (status == GOT_STATUS_BUMP_BASE)
2680 return NULL;
2682 if (status == GOT_STATUS_BASE_REF_ERR) {
2683 a->had_base_commit_ref_error = 1;
2684 return NULL;
2687 while (path[0] == '/')
2688 path++;
2690 if (a->verbosity >= 0)
2691 printf("%c %s/%s\n", status, a->worktree_path, path);
2693 return NULL;
2696 static const struct got_error *
2697 check_cancelled(void *arg)
2699 if (sigint_received || sigpipe_received)
2700 return got_error(GOT_ERR_CANCELLED);
2701 return NULL;
2704 static const struct got_error *
2705 check_linear_ancestry(struct got_object_id *commit_id,
2706 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2707 struct got_repository *repo)
2709 const struct got_error *err = NULL;
2710 struct got_object_id *yca_id;
2712 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2713 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2714 if (err)
2715 return err;
2717 if (yca_id == NULL)
2718 return got_error(GOT_ERR_ANCESTRY);
2721 * Require a straight line of history between the target commit
2722 * and the work tree's base commit.
2724 * Non-linear situations such as this require a rebase:
2726 * (commit) D F (base_commit)
2727 * \ /
2728 * C E
2729 * \ /
2730 * B (yca)
2731 * |
2732 * A
2734 * 'got update' only handles linear cases:
2735 * Update forwards in time: A (base/yca) - B - C - D (commit)
2736 * Update backwards in time: D (base) - C - B - A (commit/yca)
2738 if (allow_forwards_in_time_only) {
2739 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2740 return got_error(GOT_ERR_ANCESTRY);
2741 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2742 got_object_id_cmp(base_commit_id, yca_id) != 0)
2743 return got_error(GOT_ERR_ANCESTRY);
2745 free(yca_id);
2746 return NULL;
2749 static const struct got_error *
2750 check_same_branch(struct got_object_id *commit_id,
2751 struct got_reference *head_ref, struct got_object_id *yca_id,
2752 struct got_repository *repo)
2754 const struct got_error *err = NULL;
2755 struct got_commit_graph *graph = NULL;
2756 struct got_object_id *head_commit_id = NULL;
2757 int is_same_branch = 0;
2759 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2760 if (err)
2761 goto done;
2763 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2764 is_same_branch = 1;
2765 goto done;
2767 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2768 is_same_branch = 1;
2769 goto done;
2772 err = got_commit_graph_open(&graph, "/", 1);
2773 if (err)
2774 goto done;
2776 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2777 check_cancelled, NULL);
2778 if (err)
2779 goto done;
2781 for (;;) {
2782 struct got_object_id *id;
2783 err = got_commit_graph_iter_next(&id, graph, repo,
2784 check_cancelled, NULL);
2785 if (err) {
2786 if (err->code == GOT_ERR_ITER_COMPLETED)
2787 err = NULL;
2788 break;
2791 if (id) {
2792 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2793 break;
2794 if (got_object_id_cmp(id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 break;
2800 done:
2801 if (graph)
2802 got_commit_graph_close(graph);
2803 free(head_commit_id);
2804 if (!err && !is_same_branch)
2805 err = got_error(GOT_ERR_ANCESTRY);
2806 return err;
2809 static const struct got_error *
2810 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2812 static char msg[512];
2813 const char *branch_name;
2815 if (got_ref_is_symbolic(ref))
2816 branch_name = got_ref_get_symref_target(ref);
2817 else
2818 branch_name = got_ref_get_name(ref);
2820 if (strncmp("refs/heads/", branch_name, 11) == 0)
2821 branch_name += 11;
2823 snprintf(msg, sizeof(msg),
2824 "target commit is not contained in branch '%s'; "
2825 "the branch to use must be specified with -b; "
2826 "if necessary a new branch can be created for "
2827 "this commit with 'got branch -c %s BRANCH_NAME'",
2828 branch_name, commit_id_str);
2830 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2833 static const struct got_error *
2834 cmd_checkout(int argc, char *argv[])
2836 const struct got_error *error = NULL;
2837 struct got_repository *repo = NULL;
2838 struct got_reference *head_ref = NULL, *ref = NULL;
2839 struct got_worktree *worktree = NULL;
2840 char *repo_path = NULL;
2841 char *worktree_path = NULL;
2842 const char *path_prefix = "";
2843 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2844 char *commit_id_str = NULL;
2845 struct got_object_id *commit_id = NULL;
2846 char *cwd = NULL;
2847 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2848 struct got_pathlist_head paths;
2849 struct got_checkout_progress_arg cpa;
2851 TAILQ_INIT(&paths);
2853 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2854 switch (ch) {
2855 case 'b':
2856 branch_name = optarg;
2857 break;
2858 case 'c':
2859 commit_id_str = strdup(optarg);
2860 if (commit_id_str == NULL)
2861 return got_error_from_errno("strdup");
2862 break;
2863 case 'E':
2864 allow_nonempty = 1;
2865 break;
2866 case 'p':
2867 path_prefix = optarg;
2868 break;
2869 case 'q':
2870 verbosity = -1;
2871 break;
2872 default:
2873 usage_checkout();
2874 /* NOTREACHED */
2878 argc -= optind;
2879 argv += optind;
2881 #ifndef PROFILE
2882 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2883 "unveil", NULL) == -1)
2884 err(1, "pledge");
2885 #endif
2886 if (argc == 1) {
2887 char *base, *dotgit;
2888 const char *path;
2889 repo_path = realpath(argv[0], NULL);
2890 if (repo_path == NULL)
2891 return got_error_from_errno2("realpath", argv[0]);
2892 cwd = getcwd(NULL, 0);
2893 if (cwd == NULL) {
2894 error = got_error_from_errno("getcwd");
2895 goto done;
2897 if (path_prefix[0])
2898 path = path_prefix;
2899 else
2900 path = repo_path;
2901 error = got_path_basename(&base, path);
2902 if (error)
2903 goto done;
2904 dotgit = strstr(base, ".git");
2905 if (dotgit)
2906 *dotgit = '\0';
2907 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2908 error = got_error_from_errno("asprintf");
2909 free(base);
2910 goto done;
2912 free(base);
2913 } else if (argc == 2) {
2914 repo_path = realpath(argv[0], NULL);
2915 if (repo_path == NULL) {
2916 error = got_error_from_errno2("realpath", argv[0]);
2917 goto done;
2919 worktree_path = realpath(argv[1], NULL);
2920 if (worktree_path == NULL) {
2921 if (errno != ENOENT) {
2922 error = got_error_from_errno2("realpath",
2923 argv[1]);
2924 goto done;
2926 worktree_path = strdup(argv[1]);
2927 if (worktree_path == NULL) {
2928 error = got_error_from_errno("strdup");
2929 goto done;
2932 } else
2933 usage_checkout();
2935 got_path_strip_trailing_slashes(repo_path);
2936 got_path_strip_trailing_slashes(worktree_path);
2938 error = got_repo_open(&repo, repo_path, NULL);
2939 if (error != NULL)
2940 goto done;
2942 /* Pre-create work tree path for unveil(2) */
2943 error = got_path_mkdir(worktree_path);
2944 if (error) {
2945 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2946 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2947 goto done;
2948 if (!allow_nonempty &&
2949 !got_path_dir_is_empty(worktree_path)) {
2950 error = got_error_path(worktree_path,
2951 GOT_ERR_DIR_NOT_EMPTY);
2952 goto done;
2956 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2957 if (error)
2958 goto done;
2960 error = got_ref_open(&head_ref, repo, branch_name, 0);
2961 if (error != NULL)
2962 goto done;
2964 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2965 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2966 goto done;
2968 error = got_worktree_open(&worktree, worktree_path);
2969 if (error != NULL)
2970 goto done;
2972 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2973 path_prefix);
2974 if (error != NULL)
2975 goto done;
2976 if (!same_path_prefix) {
2977 error = got_error(GOT_ERR_PATH_PREFIX);
2978 goto done;
2981 if (commit_id_str) {
2982 struct got_reflist_head refs;
2983 TAILQ_INIT(&refs);
2984 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2985 NULL);
2986 if (error)
2987 goto done;
2988 error = got_repo_match_object_id(&commit_id, NULL,
2989 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2990 got_ref_list_free(&refs);
2991 if (error)
2992 goto done;
2993 error = check_linear_ancestry(commit_id,
2994 got_worktree_get_base_commit_id(worktree), 0, repo);
2995 if (error != NULL) {
2996 if (error->code == GOT_ERR_ANCESTRY) {
2997 error = checkout_ancestry_error(
2998 head_ref, commit_id_str);
3000 goto done;
3002 error = check_same_branch(commit_id, head_ref, NULL, repo);
3003 if (error) {
3004 if (error->code == GOT_ERR_ANCESTRY) {
3005 error = checkout_ancestry_error(
3006 head_ref, commit_id_str);
3008 goto done;
3010 error = got_worktree_set_base_commit_id(worktree, repo,
3011 commit_id);
3012 if (error)
3013 goto done;
3014 /* Expand potentially abbreviated commit ID string. */
3015 free(commit_id_str);
3016 error = got_object_id_str(&commit_id_str, commit_id);
3017 if (error)
3018 goto done;
3019 } else {
3020 commit_id = got_object_id_dup(
3021 got_worktree_get_base_commit_id(worktree));
3022 if (commit_id == NULL) {
3023 error = got_error_from_errno("got_object_id_dup");
3024 goto done;
3026 error = got_object_id_str(&commit_id_str, commit_id);
3027 if (error)
3028 goto done;
3031 error = got_pathlist_append(&paths, "", NULL);
3032 if (error)
3033 goto done;
3034 cpa.worktree_path = worktree_path;
3035 cpa.had_base_commit_ref_error = 0;
3036 cpa.verbosity = verbosity;
3037 error = got_worktree_checkout_files(worktree, &paths, repo,
3038 checkout_progress, &cpa, check_cancelled, NULL);
3039 if (error != NULL)
3040 goto done;
3042 if (got_ref_is_symbolic(head_ref)) {
3043 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3044 if (error)
3045 goto done;
3046 refname = got_ref_get_name(ref);
3047 } else
3048 refname = got_ref_get_name(head_ref);
3049 printf("Checked out %s: %s\n", refname, commit_id_str);
3050 printf("Now shut up and hack\n");
3051 if (cpa.had_base_commit_ref_error)
3052 show_worktree_base_ref_warning();
3053 done:
3054 if (head_ref)
3055 got_ref_close(head_ref);
3056 if (ref)
3057 got_ref_close(ref);
3058 got_pathlist_free(&paths);
3059 free(commit_id_str);
3060 free(commit_id);
3061 free(repo_path);
3062 free(worktree_path);
3063 free(cwd);
3064 return error;
3067 struct got_update_progress_arg {
3068 int did_something;
3069 int conflicts;
3070 int obstructed;
3071 int not_updated;
3072 int missing;
3073 int not_deleted;
3074 int unversioned;
3075 int verbosity;
3078 void
3079 print_update_progress_stats(struct got_update_progress_arg *upa)
3081 if (!upa->did_something)
3082 return;
3084 if (upa->conflicts > 0)
3085 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3086 if (upa->obstructed > 0)
3087 printf("File paths obstructed by a non-regular file: %d\n",
3088 upa->obstructed);
3089 if (upa->not_updated > 0)
3090 printf("Files not updated because of existing merge "
3091 "conflicts: %d\n", upa->not_updated);
3095 * The meaning of some status codes differs between merge-style operations and
3096 * update operations. For example, the ! status code means "file was missing"
3097 * if changes were merged into the work tree, and "missing file was restored"
3098 * if the work tree was updated. This function should be used by any operation
3099 * which merges changes into the work tree without updating the work tree.
3101 void
3102 print_merge_progress_stats(struct got_update_progress_arg *upa)
3104 if (!upa->did_something)
3105 return;
3107 if (upa->conflicts > 0)
3108 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3109 if (upa->obstructed > 0)
3110 printf("File paths obstructed by a non-regular file: %d\n",
3111 upa->obstructed);
3112 if (upa->missing > 0)
3113 printf("Files which had incoming changes but could not be "
3114 "found in the work tree: %d\n", upa->missing);
3115 if (upa->not_deleted > 0)
3116 printf("Files not deleted due to differences in deleted "
3117 "content: %d\n", upa->not_deleted);
3118 if (upa->unversioned > 0)
3119 printf("Files not merged because an unversioned file was "
3120 "found in the work tree: %d\n", upa->unversioned);
3123 __dead static void
3124 usage_update(void)
3126 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3127 "[path ...]\n",
3128 getprogname());
3129 exit(1);
3132 static const struct got_error *
3133 update_progress(void *arg, unsigned char status, const char *path)
3135 struct got_update_progress_arg *upa = arg;
3137 if (status == GOT_STATUS_EXISTS ||
3138 status == GOT_STATUS_BASE_REF_ERR)
3139 return NULL;
3141 upa->did_something = 1;
3143 /* Base commit bump happens silently. */
3144 if (status == GOT_STATUS_BUMP_BASE)
3145 return NULL;
3147 if (status == GOT_STATUS_CONFLICT)
3148 upa->conflicts++;
3149 if (status == GOT_STATUS_OBSTRUCTED)
3150 upa->obstructed++;
3151 if (status == GOT_STATUS_CANNOT_UPDATE)
3152 upa->not_updated++;
3153 if (status == GOT_STATUS_MISSING)
3154 upa->missing++;
3155 if (status == GOT_STATUS_CANNOT_DELETE)
3156 upa->not_deleted++;
3157 if (status == GOT_STATUS_UNVERSIONED)
3158 upa->unversioned++;
3160 while (path[0] == '/')
3161 path++;
3162 if (upa->verbosity >= 0)
3163 printf("%c %s\n", status, path);
3165 return NULL;
3168 static const struct got_error *
3169 switch_head_ref(struct got_reference *head_ref,
3170 struct got_object_id *commit_id, struct got_worktree *worktree,
3171 struct got_repository *repo)
3173 const struct got_error *err = NULL;
3174 char *base_id_str;
3175 int ref_has_moved = 0;
3177 /* Trivial case: switching between two different references. */
3178 if (strcmp(got_ref_get_name(head_ref),
3179 got_worktree_get_head_ref_name(worktree)) != 0) {
3180 printf("Switching work tree from %s to %s\n",
3181 got_worktree_get_head_ref_name(worktree),
3182 got_ref_get_name(head_ref));
3183 return got_worktree_set_head_ref(worktree, head_ref);
3186 err = check_linear_ancestry(commit_id,
3187 got_worktree_get_base_commit_id(worktree), 0, repo);
3188 if (err) {
3189 if (err->code != GOT_ERR_ANCESTRY)
3190 return err;
3191 ref_has_moved = 1;
3193 if (!ref_has_moved)
3194 return NULL;
3196 /* Switching to a rebased branch with the same reference name. */
3197 err = got_object_id_str(&base_id_str,
3198 got_worktree_get_base_commit_id(worktree));
3199 if (err)
3200 return err;
3201 printf("Reference %s now points at a different branch\n",
3202 got_worktree_get_head_ref_name(worktree));
3203 printf("Switching work tree from %s to %s\n", base_id_str,
3204 got_worktree_get_head_ref_name(worktree));
3205 return NULL;
3208 static const struct got_error *
3209 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3211 const struct got_error *err;
3212 int in_progress;
3214 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3215 if (err)
3216 return err;
3217 if (in_progress)
3218 return got_error(GOT_ERR_REBASING);
3220 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3221 if (err)
3222 return err;
3223 if (in_progress)
3224 return got_error(GOT_ERR_HISTEDIT_BUSY);
3226 return NULL;
3229 static const struct got_error *
3230 check_merge_in_progress(struct got_worktree *worktree,
3231 struct got_repository *repo)
3233 const struct got_error *err;
3234 int in_progress;
3236 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3237 if (err)
3238 return err;
3239 if (in_progress)
3240 return got_error(GOT_ERR_MERGE_BUSY);
3242 return NULL;
3245 static const struct got_error *
3246 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3247 char *argv[], struct got_worktree *worktree)
3249 const struct got_error *err = NULL;
3250 char *path;
3251 struct got_pathlist_entry *new;
3252 int i;
3254 if (argc == 0) {
3255 path = strdup("");
3256 if (path == NULL)
3257 return got_error_from_errno("strdup");
3258 return got_pathlist_append(paths, path, NULL);
3261 for (i = 0; i < argc; i++) {
3262 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3263 if (err)
3264 break;
3265 err = got_pathlist_insert(&new, paths, path, NULL);
3266 if (err || new == NULL /* duplicate */) {
3267 free(path);
3268 if (err)
3269 break;
3273 return err;
3276 static const struct got_error *
3277 wrap_not_worktree_error(const struct got_error *orig_err,
3278 const char *cmdname, const char *path)
3280 const struct got_error *err;
3281 struct got_repository *repo;
3282 static char msg[512];
3284 err = got_repo_open(&repo, path, NULL);
3285 if (err)
3286 return orig_err;
3288 snprintf(msg, sizeof(msg),
3289 "'got %s' needs a work tree in addition to a git repository\n"
3290 "Work trees can be checked out from this Git repository with "
3291 "'got checkout'.\n"
3292 "The got(1) manual page contains more information.", cmdname);
3293 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3294 got_repo_close(repo);
3295 return err;
3298 static const struct got_error *
3299 cmd_update(int argc, char *argv[])
3301 const struct got_error *error = NULL;
3302 struct got_repository *repo = NULL;
3303 struct got_worktree *worktree = NULL;
3304 char *worktree_path = NULL;
3305 struct got_object_id *commit_id = NULL;
3306 char *commit_id_str = NULL;
3307 const char *branch_name = NULL;
3308 struct got_reference *head_ref = NULL;
3309 struct got_pathlist_head paths;
3310 struct got_pathlist_entry *pe;
3311 int ch, verbosity = 0;
3312 struct got_update_progress_arg upa;
3314 TAILQ_INIT(&paths);
3316 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3317 switch (ch) {
3318 case 'b':
3319 branch_name = optarg;
3320 break;
3321 case 'c':
3322 commit_id_str = strdup(optarg);
3323 if (commit_id_str == NULL)
3324 return got_error_from_errno("strdup");
3325 break;
3326 case 'q':
3327 verbosity = -1;
3328 break;
3329 default:
3330 usage_update();
3331 /* NOTREACHED */
3335 argc -= optind;
3336 argv += optind;
3338 #ifndef PROFILE
3339 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3340 "unveil", NULL) == -1)
3341 err(1, "pledge");
3342 #endif
3343 worktree_path = getcwd(NULL, 0);
3344 if (worktree_path == NULL) {
3345 error = got_error_from_errno("getcwd");
3346 goto done;
3348 error = got_worktree_open(&worktree, worktree_path);
3349 if (error) {
3350 if (error->code == GOT_ERR_NOT_WORKTREE)
3351 error = wrap_not_worktree_error(error, "update",
3352 worktree_path);
3353 goto done;
3356 error = check_rebase_or_histedit_in_progress(worktree);
3357 if (error)
3358 goto done;
3360 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3361 NULL);
3362 if (error != NULL)
3363 goto done;
3365 error = apply_unveil(got_repo_get_path(repo), 0,
3366 got_worktree_get_root_path(worktree));
3367 if (error)
3368 goto done;
3370 error = check_merge_in_progress(worktree, repo);
3371 if (error)
3372 goto done;
3374 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3375 if (error)
3376 goto done;
3378 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3379 got_worktree_get_head_ref_name(worktree), 0);
3380 if (error != NULL)
3381 goto done;
3382 if (commit_id_str == NULL) {
3383 error = got_ref_resolve(&commit_id, repo, head_ref);
3384 if (error != NULL)
3385 goto done;
3386 error = got_object_id_str(&commit_id_str, commit_id);
3387 if (error != NULL)
3388 goto done;
3389 } else {
3390 struct got_reflist_head refs;
3391 TAILQ_INIT(&refs);
3392 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3393 NULL);
3394 if (error)
3395 goto done;
3396 error = got_repo_match_object_id(&commit_id, NULL,
3397 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3398 got_ref_list_free(&refs);
3399 free(commit_id_str);
3400 commit_id_str = NULL;
3401 if (error)
3402 goto done;
3403 error = got_object_id_str(&commit_id_str, commit_id);
3404 if (error)
3405 goto done;
3408 if (branch_name) {
3409 struct got_object_id *head_commit_id;
3410 TAILQ_FOREACH(pe, &paths, entry) {
3411 if (pe->path_len == 0)
3412 continue;
3413 error = got_error_msg(GOT_ERR_BAD_PATH,
3414 "switching between branches requires that "
3415 "the entire work tree gets updated");
3416 goto done;
3418 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3419 if (error)
3420 goto done;
3421 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3422 repo);
3423 free(head_commit_id);
3424 if (error != NULL)
3425 goto done;
3426 error = check_same_branch(commit_id, head_ref, NULL, repo);
3427 if (error)
3428 goto done;
3429 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3430 if (error)
3431 goto done;
3432 } else {
3433 error = check_linear_ancestry(commit_id,
3434 got_worktree_get_base_commit_id(worktree), 0, repo);
3435 if (error != NULL) {
3436 if (error->code == GOT_ERR_ANCESTRY)
3437 error = got_error(GOT_ERR_BRANCH_MOVED);
3438 goto done;
3440 error = check_same_branch(commit_id, head_ref, NULL, repo);
3441 if (error)
3442 goto done;
3445 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3446 commit_id) != 0) {
3447 error = got_worktree_set_base_commit_id(worktree, repo,
3448 commit_id);
3449 if (error)
3450 goto done;
3453 memset(&upa, 0, sizeof(upa));
3454 upa.verbosity = verbosity;
3455 error = got_worktree_checkout_files(worktree, &paths, repo,
3456 update_progress, &upa, check_cancelled, NULL);
3457 if (error != NULL)
3458 goto done;
3460 if (upa.did_something) {
3461 printf("Updated to %s: %s\n",
3462 got_worktree_get_head_ref_name(worktree), commit_id_str);
3463 } else
3464 printf("Already up-to-date\n");
3465 print_update_progress_stats(&upa);
3466 done:
3467 free(worktree_path);
3468 TAILQ_FOREACH(pe, &paths, entry)
3469 free((char *)pe->path);
3470 got_pathlist_free(&paths);
3471 free(commit_id);
3472 free(commit_id_str);
3473 return error;
3476 static const struct got_error *
3477 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3478 const char *path, int diff_context, int ignore_whitespace,
3479 int force_text_diff, struct got_repository *repo)
3481 const struct got_error *err = NULL;
3482 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3484 if (blob_id1) {
3485 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3486 if (err)
3487 goto done;
3490 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3491 if (err)
3492 goto done;
3494 while (path[0] == '/')
3495 path++;
3496 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3497 diff_context, ignore_whitespace, force_text_diff, stdout);
3498 done:
3499 if (blob1)
3500 got_object_blob_close(blob1);
3501 got_object_blob_close(blob2);
3502 return err;
3505 static const struct got_error *
3506 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3507 const char *path, int diff_context, int ignore_whitespace,
3508 int force_text_diff, struct got_repository *repo)
3510 const struct got_error *err = NULL;
3511 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3512 struct got_diff_blob_output_unidiff_arg arg;
3514 if (tree_id1) {
3515 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3516 if (err)
3517 goto done;
3520 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3521 if (err)
3522 goto done;
3524 arg.diff_context = diff_context;
3525 arg.ignore_whitespace = ignore_whitespace;
3526 arg.force_text_diff = force_text_diff;
3527 arg.outfile = stdout;
3528 arg.line_offsets = NULL;
3529 arg.nlines = 0;
3530 while (path[0] == '/')
3531 path++;
3532 err = got_diff_tree(tree1, tree2, path, path, repo,
3533 got_diff_blob_output_unidiff, &arg, 1);
3534 done:
3535 if (tree1)
3536 got_object_tree_close(tree1);
3537 if (tree2)
3538 got_object_tree_close(tree2);
3539 return err;
3542 static const struct got_error *
3543 get_changed_paths(struct got_pathlist_head *paths,
3544 struct got_commit_object *commit, struct got_repository *repo)
3546 const struct got_error *err = NULL;
3547 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3548 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3549 struct got_object_qid *qid;
3551 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3552 if (qid != NULL) {
3553 struct got_commit_object *pcommit;
3554 err = got_object_open_as_commit(&pcommit, repo,
3555 qid->id);
3556 if (err)
3557 return err;
3559 tree_id1 = got_object_id_dup(
3560 got_object_commit_get_tree_id(pcommit));
3561 if (tree_id1 == NULL) {
3562 got_object_commit_close(pcommit);
3563 return got_error_from_errno("got_object_id_dup");
3565 got_object_commit_close(pcommit);
3569 if (tree_id1) {
3570 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3571 if (err)
3572 goto done;
3575 tree_id2 = got_object_commit_get_tree_id(commit);
3576 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3577 if (err)
3578 goto done;
3580 err = got_diff_tree(tree1, tree2, "", "", repo,
3581 got_diff_tree_collect_changed_paths, paths, 0);
3582 done:
3583 if (tree1)
3584 got_object_tree_close(tree1);
3585 if (tree2)
3586 got_object_tree_close(tree2);
3587 free(tree_id1);
3588 return err;
3591 static const struct got_error *
3592 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3593 const char *path, int diff_context, struct got_repository *repo)
3595 const struct got_error *err = NULL;
3596 struct got_commit_object *pcommit = NULL;
3597 char *id_str1 = NULL, *id_str2 = NULL;
3598 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3599 struct got_object_qid *qid;
3601 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3602 if (qid != NULL) {
3603 err = got_object_open_as_commit(&pcommit, repo,
3604 qid->id);
3605 if (err)
3606 return err;
3609 if (path && path[0] != '\0') {
3610 int obj_type;
3611 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3612 if (err)
3613 goto done;
3614 err = got_object_id_str(&id_str2, obj_id2);
3615 if (err) {
3616 free(obj_id2);
3617 goto done;
3619 if (pcommit) {
3620 err = got_object_id_by_path(&obj_id1, repo,
3621 pcommit, path);
3622 if (err) {
3623 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3624 free(obj_id2);
3625 goto done;
3627 } else {
3628 err = got_object_id_str(&id_str1, obj_id1);
3629 if (err) {
3630 free(obj_id2);
3631 goto done;
3635 err = got_object_get_type(&obj_type, repo, obj_id2);
3636 if (err) {
3637 free(obj_id2);
3638 goto done;
3640 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3641 switch (obj_type) {
3642 case GOT_OBJ_TYPE_BLOB:
3643 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3644 0, 0, repo);
3645 break;
3646 case GOT_OBJ_TYPE_TREE:
3647 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3648 0, 0, repo);
3649 break;
3650 default:
3651 err = got_error(GOT_ERR_OBJ_TYPE);
3652 break;
3654 free(obj_id1);
3655 free(obj_id2);
3656 } else {
3657 obj_id2 = got_object_commit_get_tree_id(commit);
3658 err = got_object_id_str(&id_str2, obj_id2);
3659 if (err)
3660 goto done;
3661 if (pcommit) {
3662 obj_id1 = got_object_commit_get_tree_id(pcommit);
3663 err = got_object_id_str(&id_str1, obj_id1);
3664 if (err)
3665 goto done;
3667 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3668 id_str2);
3669 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3670 repo);
3672 done:
3673 free(id_str1);
3674 free(id_str2);
3675 if (pcommit)
3676 got_object_commit_close(pcommit);
3677 return err;
3680 static char *
3681 get_datestr(time_t *time, char *datebuf)
3683 struct tm mytm, *tm;
3684 char *p, *s;
3686 tm = gmtime_r(time, &mytm);
3687 if (tm == NULL)
3688 return NULL;
3689 s = asctime_r(tm, datebuf);
3690 if (s == NULL)
3691 return NULL;
3692 p = strchr(s, '\n');
3693 if (p)
3694 *p = '\0';
3695 return s;
3698 static const struct got_error *
3699 match_logmsg(int *have_match, struct got_object_id *id,
3700 struct got_commit_object *commit, regex_t *regex)
3702 const struct got_error *err = NULL;
3703 regmatch_t regmatch;
3704 char *id_str = NULL, *logmsg = NULL;
3706 *have_match = 0;
3708 err = got_object_id_str(&id_str, id);
3709 if (err)
3710 return err;
3712 err = got_object_commit_get_logmsg(&logmsg, commit);
3713 if (err)
3714 goto done;
3716 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3717 *have_match = 1;
3718 done:
3719 free(id_str);
3720 free(logmsg);
3721 return err;
3724 static void
3725 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3726 regex_t *regex)
3728 regmatch_t regmatch;
3729 struct got_pathlist_entry *pe;
3731 *have_match = 0;
3733 TAILQ_FOREACH(pe, changed_paths, entry) {
3734 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3735 *have_match = 1;
3736 break;
3741 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3743 static const struct got_error*
3744 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3745 struct got_object_id *id, struct got_repository *repo)
3747 static const struct got_error *err = NULL;
3748 struct got_reflist_entry *re;
3749 char *s;
3750 const char *name;
3752 *refs_str = NULL;
3754 TAILQ_FOREACH(re, refs, entry) {
3755 struct got_tag_object *tag = NULL;
3756 struct got_object_id *ref_id;
3757 int cmp;
3759 name = got_ref_get_name(re->ref);
3760 if (strcmp(name, GOT_REF_HEAD) == 0)
3761 continue;
3762 if (strncmp(name, "refs/", 5) == 0)
3763 name += 5;
3764 if (strncmp(name, "got/", 4) == 0)
3765 continue;
3766 if (strncmp(name, "heads/", 6) == 0)
3767 name += 6;
3768 if (strncmp(name, "remotes/", 8) == 0) {
3769 name += 8;
3770 s = strstr(name, "/" GOT_REF_HEAD);
3771 if (s != NULL && s[strlen(s)] == '\0')
3772 continue;
3774 err = got_ref_resolve(&ref_id, repo, re->ref);
3775 if (err)
3776 break;
3777 if (strncmp(name, "tags/", 5) == 0) {
3778 err = got_object_open_as_tag(&tag, repo, ref_id);
3779 if (err) {
3780 if (err->code != GOT_ERR_OBJ_TYPE) {
3781 free(ref_id);
3782 break;
3784 /* Ref points at something other than a tag. */
3785 err = NULL;
3786 tag = NULL;
3789 cmp = got_object_id_cmp(tag ?
3790 got_object_tag_get_object_id(tag) : ref_id, id);
3791 free(ref_id);
3792 if (tag)
3793 got_object_tag_close(tag);
3794 if (cmp != 0)
3795 continue;
3796 s = *refs_str;
3797 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3798 s ? ", " : "", name) == -1) {
3799 err = got_error_from_errno("asprintf");
3800 free(s);
3801 *refs_str = NULL;
3802 break;
3804 free(s);
3807 return err;
3810 static const struct got_error *
3811 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3812 struct got_repository *repo, const char *path,
3813 struct got_pathlist_head *changed_paths, int show_patch,
3814 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3815 const char *custom_refs_str)
3817 const struct got_error *err = NULL;
3818 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3819 char datebuf[26];
3820 time_t committer_time;
3821 const char *author, *committer;
3822 char *refs_str = NULL;
3824 err = got_object_id_str(&id_str, id);
3825 if (err)
3826 return err;
3828 if (custom_refs_str == NULL) {
3829 struct got_reflist_head *refs;
3830 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3831 if (refs) {
3832 err = build_refs_str(&refs_str, refs, id, repo);
3833 if (err)
3834 goto done;
3838 printf(GOT_COMMIT_SEP_STR);
3839 if (custom_refs_str)
3840 printf("commit %s (%s)\n", id_str, custom_refs_str);
3841 else
3842 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3843 refs_str ? refs_str : "", refs_str ? ")" : "");
3844 free(id_str);
3845 id_str = NULL;
3846 free(refs_str);
3847 refs_str = NULL;
3848 printf("from: %s\n", got_object_commit_get_author(commit));
3849 committer_time = got_object_commit_get_committer_time(commit);
3850 datestr = get_datestr(&committer_time, datebuf);
3851 if (datestr)
3852 printf("date: %s UTC\n", datestr);
3853 author = got_object_commit_get_author(commit);
3854 committer = got_object_commit_get_committer(commit);
3855 if (strcmp(author, committer) != 0)
3856 printf("via: %s\n", committer);
3857 if (got_object_commit_get_nparents(commit) > 1) {
3858 const struct got_object_id_queue *parent_ids;
3859 struct got_object_qid *qid;
3860 int n = 1;
3861 parent_ids = got_object_commit_get_parent_ids(commit);
3862 STAILQ_FOREACH(qid, parent_ids, entry) {
3863 err = got_object_id_str(&id_str, qid->id);
3864 if (err)
3865 goto done;
3866 printf("parent %d: %s\n", n++, id_str);
3867 free(id_str);
3868 id_str = NULL;
3872 err = got_object_commit_get_logmsg(&logmsg0, commit);
3873 if (err)
3874 goto done;
3876 logmsg = logmsg0;
3877 do {
3878 line = strsep(&logmsg, "\n");
3879 if (line)
3880 printf(" %s\n", line);
3881 } while (line);
3882 free(logmsg0);
3884 if (changed_paths) {
3885 struct got_pathlist_entry *pe;
3886 TAILQ_FOREACH(pe, changed_paths, entry) {
3887 struct got_diff_changed_path *cp = pe->data;
3888 printf(" %c %s\n", cp->status, pe->path);
3890 printf("\n");
3892 if (show_patch) {
3893 err = print_patch(commit, id, path, diff_context, repo);
3894 if (err == 0)
3895 printf("\n");
3898 if (fflush(stdout) != 0 && err == NULL)
3899 err = got_error_from_errno("fflush");
3900 done:
3901 free(id_str);
3902 free(refs_str);
3903 return err;
3906 static const struct got_error *
3907 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3908 struct got_repository *repo, const char *path, int show_changed_paths,
3909 int show_patch, const char *search_pattern, int diff_context, int limit,
3910 int log_branches, int reverse_display_order,
3911 struct got_reflist_object_id_map *refs_idmap)
3913 const struct got_error *err;
3914 struct got_commit_graph *graph;
3915 regex_t regex;
3916 int have_match;
3917 struct got_object_id_queue reversed_commits;
3918 struct got_object_qid *qid;
3919 struct got_commit_object *commit;
3920 struct got_pathlist_head changed_paths;
3921 struct got_pathlist_entry *pe;
3923 STAILQ_INIT(&reversed_commits);
3924 TAILQ_INIT(&changed_paths);
3926 if (search_pattern && regcomp(&regex, search_pattern,
3927 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3928 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3930 err = got_commit_graph_open(&graph, path, !log_branches);
3931 if (err)
3932 return err;
3933 err = got_commit_graph_iter_start(graph, root_id, repo,
3934 check_cancelled, NULL);
3935 if (err)
3936 goto done;
3937 for (;;) {
3938 struct got_object_id *id;
3940 if (sigint_received || sigpipe_received)
3941 break;
3943 err = got_commit_graph_iter_next(&id, graph, repo,
3944 check_cancelled, NULL);
3945 if (err) {
3946 if (err->code == GOT_ERR_ITER_COMPLETED)
3947 err = NULL;
3948 break;
3950 if (id == NULL)
3951 break;
3953 err = got_object_open_as_commit(&commit, repo, id);
3954 if (err)
3955 break;
3957 if (show_changed_paths && !reverse_display_order) {
3958 err = get_changed_paths(&changed_paths, commit, repo);
3959 if (err)
3960 break;
3963 if (search_pattern) {
3964 err = match_logmsg(&have_match, id, commit, &regex);
3965 if (err) {
3966 got_object_commit_close(commit);
3967 break;
3969 if (have_match == 0 && show_changed_paths)
3970 match_changed_paths(&have_match,
3971 &changed_paths, &regex);
3972 if (have_match == 0) {
3973 got_object_commit_close(commit);
3974 TAILQ_FOREACH(pe, &changed_paths, entry) {
3975 free((char *)pe->path);
3976 free(pe->data);
3978 got_pathlist_free(&changed_paths);
3979 continue;
3983 if (reverse_display_order) {
3984 err = got_object_qid_alloc(&qid, id);
3985 if (err)
3986 break;
3987 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3988 got_object_commit_close(commit);
3989 } else {
3990 err = print_commit(commit, id, repo, path,
3991 show_changed_paths ? &changed_paths : NULL,
3992 show_patch, diff_context, refs_idmap, NULL);
3993 got_object_commit_close(commit);
3994 if (err)
3995 break;
3997 if ((limit && --limit == 0) ||
3998 (end_id && got_object_id_cmp(id, end_id) == 0))
3999 break;
4001 TAILQ_FOREACH(pe, &changed_paths, entry) {
4002 free((char *)pe->path);
4003 free(pe->data);
4005 got_pathlist_free(&changed_paths);
4007 if (reverse_display_order) {
4008 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4009 err = got_object_open_as_commit(&commit, repo, qid->id);
4010 if (err)
4011 break;
4012 if (show_changed_paths) {
4013 err = get_changed_paths(&changed_paths,
4014 commit, repo);
4015 if (err)
4016 break;
4018 err = print_commit(commit, qid->id, repo, path,
4019 show_changed_paths ? &changed_paths : NULL,
4020 show_patch, diff_context, refs_idmap, NULL);
4021 got_object_commit_close(commit);
4022 if (err)
4023 break;
4024 TAILQ_FOREACH(pe, &changed_paths, entry) {
4025 free((char *)pe->path);
4026 free(pe->data);
4028 got_pathlist_free(&changed_paths);
4031 done:
4032 while (!STAILQ_EMPTY(&reversed_commits)) {
4033 qid = STAILQ_FIRST(&reversed_commits);
4034 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4035 got_object_qid_free(qid);
4037 TAILQ_FOREACH(pe, &changed_paths, entry) {
4038 free((char *)pe->path);
4039 free(pe->data);
4041 got_pathlist_free(&changed_paths);
4042 if (search_pattern)
4043 regfree(&regex);
4044 got_commit_graph_close(graph);
4045 return err;
4048 __dead static void
4049 usage_log(void)
4051 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4052 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4053 "[-R] [path]\n", getprogname());
4054 exit(1);
4057 static int
4058 get_default_log_limit(void)
4060 const char *got_default_log_limit;
4061 long long n;
4062 const char *errstr;
4064 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4065 if (got_default_log_limit == NULL)
4066 return 0;
4067 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4068 if (errstr != NULL)
4069 return 0;
4070 return n;
4073 static const struct got_error *
4074 cmd_log(int argc, char *argv[])
4076 const struct got_error *error;
4077 struct got_repository *repo = NULL;
4078 struct got_worktree *worktree = NULL;
4079 struct got_object_id *start_id = NULL, *end_id = NULL;
4080 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4081 const char *start_commit = NULL, *end_commit = NULL;
4082 const char *search_pattern = NULL;
4083 int diff_context = -1, ch;
4084 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4085 int reverse_display_order = 0;
4086 const char *errstr;
4087 struct got_reflist_head refs;
4088 struct got_reflist_object_id_map *refs_idmap = NULL;
4090 TAILQ_INIT(&refs);
4092 #ifndef PROFILE
4093 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4094 NULL)
4095 == -1)
4096 err(1, "pledge");
4097 #endif
4099 limit = get_default_log_limit();
4101 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4102 switch (ch) {
4103 case 'p':
4104 show_patch = 1;
4105 break;
4106 case 'P':
4107 show_changed_paths = 1;
4108 break;
4109 case 'c':
4110 start_commit = optarg;
4111 break;
4112 case 'C':
4113 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4114 &errstr);
4115 if (errstr != NULL)
4116 errx(1, "number of context lines is %s: %s",
4117 errstr, optarg);
4118 break;
4119 case 'l':
4120 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4121 if (errstr != NULL)
4122 errx(1, "number of commits is %s: %s",
4123 errstr, optarg);
4124 break;
4125 case 'b':
4126 log_branches = 1;
4127 break;
4128 case 'r':
4129 repo_path = realpath(optarg, NULL);
4130 if (repo_path == NULL)
4131 return got_error_from_errno2("realpath",
4132 optarg);
4133 got_path_strip_trailing_slashes(repo_path);
4134 break;
4135 case 'R':
4136 reverse_display_order = 1;
4137 break;
4138 case 's':
4139 search_pattern = optarg;
4140 break;
4141 case 'x':
4142 end_commit = optarg;
4143 break;
4144 default:
4145 usage_log();
4146 /* NOTREACHED */
4150 argc -= optind;
4151 argv += optind;
4153 if (diff_context == -1)
4154 diff_context = 3;
4155 else if (!show_patch)
4156 errx(1, "-C requires -p");
4158 cwd = getcwd(NULL, 0);
4159 if (cwd == NULL) {
4160 error = got_error_from_errno("getcwd");
4161 goto done;
4164 if (repo_path == NULL) {
4165 error = got_worktree_open(&worktree, cwd);
4166 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4167 goto done;
4168 error = NULL;
4171 if (argc == 1) {
4172 if (worktree) {
4173 error = got_worktree_resolve_path(&path, worktree,
4174 argv[0]);
4175 if (error)
4176 goto done;
4177 } else {
4178 path = strdup(argv[0]);
4179 if (path == NULL) {
4180 error = got_error_from_errno("strdup");
4181 goto done;
4184 } else if (argc != 0)
4185 usage_log();
4187 if (repo_path == NULL) {
4188 repo_path = worktree ?
4189 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4191 if (repo_path == NULL) {
4192 error = got_error_from_errno("strdup");
4193 goto done;
4196 error = got_repo_open(&repo, repo_path, NULL);
4197 if (error != NULL)
4198 goto done;
4200 error = apply_unveil(got_repo_get_path(repo), 1,
4201 worktree ? got_worktree_get_root_path(worktree) : NULL);
4202 if (error)
4203 goto done;
4205 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4206 if (error)
4207 goto done;
4209 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4210 if (error)
4211 goto done;
4213 if (start_commit == NULL) {
4214 struct got_reference *head_ref;
4215 struct got_commit_object *commit = NULL;
4216 error = got_ref_open(&head_ref, repo,
4217 worktree ? got_worktree_get_head_ref_name(worktree)
4218 : GOT_REF_HEAD, 0);
4219 if (error != NULL)
4220 goto done;
4221 error = got_ref_resolve(&start_id, repo, head_ref);
4222 got_ref_close(head_ref);
4223 if (error != NULL)
4224 goto done;
4225 error = got_object_open_as_commit(&commit, repo,
4226 start_id);
4227 if (error != NULL)
4228 goto done;
4229 got_object_commit_close(commit);
4230 } else {
4231 error = got_repo_match_object_id(&start_id, NULL,
4232 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4233 if (error != NULL)
4234 goto done;
4236 if (end_commit != NULL) {
4237 error = got_repo_match_object_id(&end_id, NULL,
4238 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4239 if (error != NULL)
4240 goto done;
4243 if (worktree) {
4245 * If a path was specified on the command line it was resolved
4246 * to a path in the work tree above. Prepend the work tree's
4247 * path prefix to obtain the corresponding in-repository path.
4249 if (path) {
4250 const char *prefix;
4251 prefix = got_worktree_get_path_prefix(worktree);
4252 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4253 (path[0] != '\0') ? "/" : "", path) == -1) {
4254 error = got_error_from_errno("asprintf");
4255 goto done;
4258 } else
4259 error = got_repo_map_path(&in_repo_path, repo,
4260 path ? path : "");
4261 if (error != NULL)
4262 goto done;
4263 if (in_repo_path) {
4264 free(path);
4265 path = in_repo_path;
4268 if (worktree) {
4269 /* Release work tree lock. */
4270 got_worktree_close(worktree);
4271 worktree = NULL;
4274 error = print_commits(start_id, end_id, repo, path ? path : "",
4275 show_changed_paths, show_patch, search_pattern, diff_context,
4276 limit, log_branches, reverse_display_order, refs_idmap);
4277 done:
4278 free(path);
4279 free(repo_path);
4280 free(cwd);
4281 if (worktree)
4282 got_worktree_close(worktree);
4283 if (repo) {
4284 const struct got_error *close_err = got_repo_close(repo);
4285 if (error == NULL)
4286 error = close_err;
4288 if (refs_idmap)
4289 got_reflist_object_id_map_free(refs_idmap);
4290 got_ref_list_free(&refs);
4291 return error;
4294 __dead static void
4295 usage_diff(void)
4297 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4298 "[-r repository-path] [-s] [-w] [-P] "
4299 "[object1 object2 | path ...]\n", getprogname());
4300 exit(1);
4303 struct print_diff_arg {
4304 struct got_repository *repo;
4305 struct got_worktree *worktree;
4306 int diff_context;
4307 const char *id_str;
4308 int header_shown;
4309 int diff_staged;
4310 int ignore_whitespace;
4311 int force_text_diff;
4315 * Create a file which contains the target path of a symlink so we can feed
4316 * it as content to the diff engine.
4318 static const struct got_error *
4319 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4320 const char *abspath)
4322 const struct got_error *err = NULL;
4323 char target_path[PATH_MAX];
4324 ssize_t target_len, outlen;
4326 *fd = -1;
4328 if (dirfd != -1) {
4329 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4330 if (target_len == -1)
4331 return got_error_from_errno2("readlinkat", abspath);
4332 } else {
4333 target_len = readlink(abspath, target_path, PATH_MAX);
4334 if (target_len == -1)
4335 return got_error_from_errno2("readlink", abspath);
4338 *fd = got_opentempfd();
4339 if (*fd == -1)
4340 return got_error_from_errno("got_opentempfd");
4342 outlen = write(*fd, target_path, target_len);
4343 if (outlen == -1) {
4344 err = got_error_from_errno("got_opentempfd");
4345 goto done;
4348 if (lseek(*fd, 0, SEEK_SET) == -1) {
4349 err = got_error_from_errno2("lseek", abspath);
4350 goto done;
4352 done:
4353 if (err) {
4354 close(*fd);
4355 *fd = -1;
4357 return err;
4360 static const struct got_error *
4361 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4362 const char *path, struct got_object_id *blob_id,
4363 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4364 int dirfd, const char *de_name)
4366 struct print_diff_arg *a = arg;
4367 const struct got_error *err = NULL;
4368 struct got_blob_object *blob1 = NULL;
4369 int fd = -1;
4370 FILE *f2 = NULL;
4371 char *abspath = NULL, *label1 = NULL;
4372 struct stat sb;
4374 if (a->diff_staged) {
4375 if (staged_status != GOT_STATUS_MODIFY &&
4376 staged_status != GOT_STATUS_ADD &&
4377 staged_status != GOT_STATUS_DELETE)
4378 return NULL;
4379 } else {
4380 if (staged_status == GOT_STATUS_DELETE)
4381 return NULL;
4382 if (status == GOT_STATUS_NONEXISTENT)
4383 return got_error_set_errno(ENOENT, path);
4384 if (status != GOT_STATUS_MODIFY &&
4385 status != GOT_STATUS_ADD &&
4386 status != GOT_STATUS_DELETE &&
4387 status != GOT_STATUS_CONFLICT)
4388 return NULL;
4391 if (!a->header_shown) {
4392 printf("diff %s %s%s\n", a->id_str,
4393 got_worktree_get_root_path(a->worktree),
4394 a->diff_staged ? " (staged changes)" : "");
4395 a->header_shown = 1;
4398 if (a->diff_staged) {
4399 const char *label1 = NULL, *label2 = NULL;
4400 switch (staged_status) {
4401 case GOT_STATUS_MODIFY:
4402 label1 = path;
4403 label2 = path;
4404 break;
4405 case GOT_STATUS_ADD:
4406 label2 = path;
4407 break;
4408 case GOT_STATUS_DELETE:
4409 label1 = path;
4410 break;
4411 default:
4412 return got_error(GOT_ERR_FILE_STATUS);
4414 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4415 staged_blob_id, label1, label2, a->diff_context,
4416 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4419 if (staged_status == GOT_STATUS_ADD ||
4420 staged_status == GOT_STATUS_MODIFY) {
4421 char *id_str;
4422 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4423 8192);
4424 if (err)
4425 goto done;
4426 err = got_object_id_str(&id_str, staged_blob_id);
4427 if (err)
4428 goto done;
4429 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4430 err = got_error_from_errno("asprintf");
4431 free(id_str);
4432 goto done;
4434 free(id_str);
4435 } else if (status != GOT_STATUS_ADD) {
4436 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4437 if (err)
4438 goto done;
4441 if (status != GOT_STATUS_DELETE) {
4442 if (asprintf(&abspath, "%s/%s",
4443 got_worktree_get_root_path(a->worktree), path) == -1) {
4444 err = got_error_from_errno("asprintf");
4445 goto done;
4448 if (dirfd != -1) {
4449 fd = openat(dirfd, de_name,
4450 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4451 if (fd == -1) {
4452 if (!got_err_open_nofollow_on_symlink()) {
4453 err = got_error_from_errno2("openat",
4454 abspath);
4455 goto done;
4457 err = get_symlink_target_file(&fd, dirfd,
4458 de_name, abspath);
4459 if (err)
4460 goto done;
4462 } else {
4463 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4464 if (fd == -1) {
4465 if (!got_err_open_nofollow_on_symlink()) {
4466 err = got_error_from_errno2("open",
4467 abspath);
4468 goto done;
4470 err = get_symlink_target_file(&fd, dirfd,
4471 de_name, abspath);
4472 if (err)
4473 goto done;
4476 if (fstat(fd, &sb) == -1) {
4477 err = got_error_from_errno2("fstat", abspath);
4478 goto done;
4480 f2 = fdopen(fd, "r");
4481 if (f2 == NULL) {
4482 err = got_error_from_errno2("fdopen", abspath);
4483 goto done;
4485 fd = -1;
4486 } else
4487 sb.st_size = 0;
4489 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4490 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4491 done:
4492 if (blob1)
4493 got_object_blob_close(blob1);
4494 if (f2 && fclose(f2) == EOF && err == NULL)
4495 err = got_error_from_errno("fclose");
4496 if (fd != -1 && close(fd) == -1 && err == NULL)
4497 err = got_error_from_errno("close");
4498 free(abspath);
4499 return err;
4502 static const struct got_error *
4503 cmd_diff(int argc, char *argv[])
4505 const struct got_error *error;
4506 struct got_repository *repo = NULL;
4507 struct got_worktree *worktree = NULL;
4508 char *cwd = NULL, *repo_path = NULL;
4509 const char *commit_args[2] = { NULL, NULL };
4510 int ncommit_args = 0;
4511 struct got_object_id *ids[2] = { NULL, NULL };
4512 char *labels[2] = { NULL, NULL };
4513 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4514 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4515 int force_text_diff = 0, force_path = 0, rflag = 0;
4516 const char *errstr;
4517 struct got_reflist_head refs;
4518 struct got_pathlist_head paths;
4519 struct got_pathlist_entry *pe;
4521 TAILQ_INIT(&refs);
4522 TAILQ_INIT(&paths);
4524 #ifndef PROFILE
4525 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4526 NULL) == -1)
4527 err(1, "pledge");
4528 #endif
4530 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4531 switch (ch) {
4532 case 'a':
4533 force_text_diff = 1;
4534 break;
4535 case 'c':
4536 if (ncommit_args >= 2)
4537 errx(1, "too many -c options used");
4538 commit_args[ncommit_args++] = optarg;
4539 break;
4540 case 'C':
4541 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4542 &errstr);
4543 if (errstr != NULL)
4544 errx(1, "number of context lines is %s: %s",
4545 errstr, optarg);
4546 break;
4547 case 'r':
4548 repo_path = realpath(optarg, NULL);
4549 if (repo_path == NULL)
4550 return got_error_from_errno2("realpath",
4551 optarg);
4552 got_path_strip_trailing_slashes(repo_path);
4553 rflag = 1;
4554 break;
4555 case 's':
4556 diff_staged = 1;
4557 break;
4558 case 'w':
4559 ignore_whitespace = 1;
4560 break;
4561 case 'P':
4562 force_path = 1;
4563 break;
4564 default:
4565 usage_diff();
4566 /* NOTREACHED */
4570 argc -= optind;
4571 argv += optind;
4573 cwd = getcwd(NULL, 0);
4574 if (cwd == NULL) {
4575 error = got_error_from_errno("getcwd");
4576 goto done;
4579 if (repo_path == NULL) {
4580 error = got_worktree_open(&worktree, cwd);
4581 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4582 goto done;
4583 else
4584 error = NULL;
4585 if (worktree) {
4586 repo_path =
4587 strdup(got_worktree_get_repo_path(worktree));
4588 if (repo_path == NULL) {
4589 error = got_error_from_errno("strdup");
4590 goto done;
4592 } else {
4593 repo_path = strdup(cwd);
4594 if (repo_path == NULL) {
4595 error = got_error_from_errno("strdup");
4596 goto done;
4601 error = got_repo_open(&repo, repo_path, NULL);
4602 free(repo_path);
4603 if (error != NULL)
4604 goto done;
4606 if (rflag || worktree == NULL || ncommit_args > 0) {
4607 if (force_path) {
4608 error = got_error_msg(GOT_ERR_NOT_IMPL,
4609 "-P option can only be used when diffing "
4610 "a work tree");
4611 goto done;
4613 if (diff_staged) {
4614 error = got_error_msg(GOT_ERR_NOT_IMPL,
4615 "-s option can only be used when diffing "
4616 "a work tree");
4617 goto done;
4621 error = apply_unveil(got_repo_get_path(repo), 1,
4622 worktree ? got_worktree_get_root_path(worktree) : NULL);
4623 if (error)
4624 goto done;
4626 if ((!force_path && argc == 2) || ncommit_args > 0) {
4627 int obj_type = (ncommit_args > 0 ?
4628 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4629 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4630 NULL);
4631 if (error)
4632 goto done;
4633 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4634 const char *arg;
4635 if (ncommit_args > 0)
4636 arg = commit_args[i];
4637 else
4638 arg = argv[i];
4639 error = got_repo_match_object_id(&ids[i], &labels[i],
4640 arg, obj_type, &refs, repo);
4641 if (error) {
4642 if (error->code != GOT_ERR_NOT_REF &&
4643 error->code != GOT_ERR_NO_OBJ)
4644 goto done;
4645 if (ncommit_args > 0)
4646 goto done;
4647 error = NULL;
4648 break;
4653 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4654 struct print_diff_arg arg;
4655 char *id_str;
4657 if (worktree == NULL) {
4658 if (argc == 2 && ids[0] == NULL) {
4659 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4660 goto done;
4661 } else if (argc == 2 && ids[1] == NULL) {
4662 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4663 goto done;
4664 } else if (argc > 0) {
4665 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4666 "%s", "specified paths cannot be resolved");
4667 goto done;
4668 } else {
4669 error = got_error(GOT_ERR_NOT_WORKTREE);
4670 goto done;
4674 error = get_worktree_paths_from_argv(&paths, argc, argv,
4675 worktree);
4676 if (error)
4677 goto done;
4679 error = got_object_id_str(&id_str,
4680 got_worktree_get_base_commit_id(worktree));
4681 if (error)
4682 goto done;
4683 arg.repo = repo;
4684 arg.worktree = worktree;
4685 arg.diff_context = diff_context;
4686 arg.id_str = id_str;
4687 arg.header_shown = 0;
4688 arg.diff_staged = diff_staged;
4689 arg.ignore_whitespace = ignore_whitespace;
4690 arg.force_text_diff = force_text_diff;
4692 error = got_worktree_status(worktree, &paths, repo, 0,
4693 print_diff, &arg, check_cancelled, NULL);
4694 free(id_str);
4695 goto done;
4698 if (ncommit_args == 1) {
4699 struct got_commit_object *commit;
4700 error = got_object_open_as_commit(&commit, repo, ids[0]);
4701 if (error)
4702 goto done;
4704 labels[1] = labels[0];
4705 ids[1] = ids[0];
4706 if (got_object_commit_get_nparents(commit) > 0) {
4707 const struct got_object_id_queue *pids;
4708 struct got_object_qid *pid;
4709 pids = got_object_commit_get_parent_ids(commit);
4710 pid = STAILQ_FIRST(pids);
4711 ids[0] = got_object_id_dup(pid->id);
4712 if (ids[0] == NULL) {
4713 error = got_error_from_errno(
4714 "got_object_id_dup");
4715 got_object_commit_close(commit);
4716 goto done;
4718 error = got_object_id_str(&labels[0], ids[0]);
4719 if (error) {
4720 got_object_commit_close(commit);
4721 goto done;
4723 } else {
4724 ids[0] = NULL;
4725 labels[0] = strdup("/dev/null");
4726 if (labels[0] == NULL) {
4727 error = got_error_from_errno("strdup");
4728 got_object_commit_close(commit);
4729 goto done;
4733 got_object_commit_close(commit);
4736 if (ncommit_args == 0 && argc > 2) {
4737 error = got_error_msg(GOT_ERR_BAD_PATH,
4738 "path arguments cannot be used when diffing two objects");
4739 goto done;
4742 if (ids[0]) {
4743 error = got_object_get_type(&type1, repo, ids[0]);
4744 if (error)
4745 goto done;
4748 error = got_object_get_type(&type2, repo, ids[1]);
4749 if (error)
4750 goto done;
4751 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4752 error = got_error(GOT_ERR_OBJ_TYPE);
4753 goto done;
4755 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4756 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4757 "path arguments cannot be used when diffing blobs");
4758 goto done;
4761 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4762 char *in_repo_path;
4763 struct got_pathlist_entry *new;
4764 if (worktree) {
4765 const char *prefix;
4766 char *p;
4767 error = got_worktree_resolve_path(&p, worktree,
4768 argv[i]);
4769 if (error)
4770 goto done;
4771 prefix = got_worktree_get_path_prefix(worktree);
4772 while (prefix[0] == '/')
4773 prefix++;
4774 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4775 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4776 p) == -1) {
4777 error = got_error_from_errno("asprintf");
4778 free(p);
4779 goto done;
4781 free(p);
4782 } else {
4783 char *mapped_path, *s;
4784 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4785 if (error)
4786 goto done;
4787 s = mapped_path;
4788 while (s[0] == '/')
4789 s++;
4790 in_repo_path = strdup(s);
4791 if (in_repo_path == NULL) {
4792 error = got_error_from_errno("asprintf");
4793 free(mapped_path);
4794 goto done;
4796 free(mapped_path);
4799 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4800 if (error || new == NULL /* duplicate */)
4801 free(in_repo_path);
4802 if (error)
4803 goto done;
4806 if (worktree) {
4807 /* Release work tree lock. */
4808 got_worktree_close(worktree);
4809 worktree = NULL;
4812 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4813 case GOT_OBJ_TYPE_BLOB:
4814 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4815 NULL, NULL, diff_context, ignore_whitespace,
4816 force_text_diff, repo, stdout);
4817 break;
4818 case GOT_OBJ_TYPE_TREE:
4819 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4820 &paths, "", "", diff_context, ignore_whitespace,
4821 force_text_diff, repo, stdout);
4822 break;
4823 case GOT_OBJ_TYPE_COMMIT:
4824 printf("diff %s %s\n", labels[0], labels[1]);
4825 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4826 &paths, diff_context, ignore_whitespace, force_text_diff,
4827 repo, stdout);
4828 break;
4829 default:
4830 error = got_error(GOT_ERR_OBJ_TYPE);
4832 done:
4833 free(labels[0]);
4834 free(labels[1]);
4835 free(ids[0]);
4836 free(ids[1]);
4837 if (worktree)
4838 got_worktree_close(worktree);
4839 if (repo) {
4840 const struct got_error *close_err = got_repo_close(repo);
4841 if (error == NULL)
4842 error = close_err;
4844 TAILQ_FOREACH(pe, &paths, entry)
4845 free((char *)pe->path);
4846 got_pathlist_free(&paths);
4847 got_ref_list_free(&refs);
4848 return error;
4851 __dead static void
4852 usage_blame(void)
4854 fprintf(stderr,
4855 "usage: %s blame [-c commit] [-r repository-path] path\n",
4856 getprogname());
4857 exit(1);
4860 struct blame_line {
4861 int annotated;
4862 char *id_str;
4863 char *committer;
4864 char datebuf[11]; /* YYYY-MM-DD + NUL */
4867 struct blame_cb_args {
4868 struct blame_line *lines;
4869 int nlines;
4870 int nlines_prec;
4871 int lineno_cur;
4872 off_t *line_offsets;
4873 FILE *f;
4874 struct got_repository *repo;
4877 static const struct got_error *
4878 blame_cb(void *arg, int nlines, int lineno,
4879 struct got_commit_object *commit, struct got_object_id *id)
4881 const struct got_error *err = NULL;
4882 struct blame_cb_args *a = arg;
4883 struct blame_line *bline;
4884 char *line = NULL;
4885 size_t linesize = 0;
4886 off_t offset;
4887 struct tm tm;
4888 time_t committer_time;
4890 if (nlines != a->nlines ||
4891 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4892 return got_error(GOT_ERR_RANGE);
4894 if (sigint_received)
4895 return got_error(GOT_ERR_ITER_COMPLETED);
4897 if (lineno == -1)
4898 return NULL; /* no change in this commit */
4900 /* Annotate this line. */
4901 bline = &a->lines[lineno - 1];
4902 if (bline->annotated)
4903 return NULL;
4904 err = got_object_id_str(&bline->id_str, id);
4905 if (err)
4906 return err;
4908 bline->committer = strdup(got_object_commit_get_committer(commit));
4909 if (bline->committer == NULL) {
4910 err = got_error_from_errno("strdup");
4911 goto done;
4914 committer_time = got_object_commit_get_committer_time(commit);
4915 if (gmtime_r(&committer_time, &tm) == NULL)
4916 return got_error_from_errno("gmtime_r");
4917 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4918 &tm) == 0) {
4919 err = got_error(GOT_ERR_NO_SPACE);
4920 goto done;
4922 bline->annotated = 1;
4924 /* Print lines annotated so far. */
4925 bline = &a->lines[a->lineno_cur - 1];
4926 if (!bline->annotated)
4927 goto done;
4929 offset = a->line_offsets[a->lineno_cur - 1];
4930 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4931 err = got_error_from_errno("fseeko");
4932 goto done;
4935 while (bline->annotated) {
4936 char *smallerthan, *at, *nl, *committer;
4937 size_t len;
4939 if (getline(&line, &linesize, a->f) == -1) {
4940 if (ferror(a->f))
4941 err = got_error_from_errno("getline");
4942 break;
4945 committer = bline->committer;
4946 smallerthan = strchr(committer, '<');
4947 if (smallerthan && smallerthan[1] != '\0')
4948 committer = smallerthan + 1;
4949 at = strchr(committer, '@');
4950 if (at)
4951 *at = '\0';
4952 len = strlen(committer);
4953 if (len >= 9)
4954 committer[8] = '\0';
4956 nl = strchr(line, '\n');
4957 if (nl)
4958 *nl = '\0';
4959 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4960 bline->id_str, bline->datebuf, committer, line);
4962 a->lineno_cur++;
4963 bline = &a->lines[a->lineno_cur - 1];
4965 done:
4966 free(line);
4967 return err;
4970 static const struct got_error *
4971 cmd_blame(int argc, char *argv[])
4973 const struct got_error *error;
4974 struct got_repository *repo = NULL;
4975 struct got_worktree *worktree = NULL;
4976 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4977 char *link_target = NULL;
4978 struct got_object_id *obj_id = NULL;
4979 struct got_object_id *commit_id = NULL;
4980 struct got_commit_object *commit = NULL;
4981 struct got_blob_object *blob = NULL;
4982 char *commit_id_str = NULL;
4983 struct blame_cb_args bca;
4984 int ch, obj_type, i;
4985 off_t filesize;
4987 memset(&bca, 0, sizeof(bca));
4989 #ifndef PROFILE
4990 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4991 NULL) == -1)
4992 err(1, "pledge");
4993 #endif
4995 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4996 switch (ch) {
4997 case 'c':
4998 commit_id_str = optarg;
4999 break;
5000 case 'r':
5001 repo_path = realpath(optarg, NULL);
5002 if (repo_path == NULL)
5003 return got_error_from_errno2("realpath",
5004 optarg);
5005 got_path_strip_trailing_slashes(repo_path);
5006 break;
5007 default:
5008 usage_blame();
5009 /* NOTREACHED */
5013 argc -= optind;
5014 argv += optind;
5016 if (argc == 1)
5017 path = argv[0];
5018 else
5019 usage_blame();
5021 cwd = getcwd(NULL, 0);
5022 if (cwd == NULL) {
5023 error = got_error_from_errno("getcwd");
5024 goto done;
5026 if (repo_path == NULL) {
5027 error = got_worktree_open(&worktree, cwd);
5028 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5029 goto done;
5030 else
5031 error = NULL;
5032 if (worktree) {
5033 repo_path =
5034 strdup(got_worktree_get_repo_path(worktree));
5035 if (repo_path == NULL) {
5036 error = got_error_from_errno("strdup");
5037 if (error)
5038 goto done;
5040 } else {
5041 repo_path = strdup(cwd);
5042 if (repo_path == NULL) {
5043 error = got_error_from_errno("strdup");
5044 goto done;
5049 error = got_repo_open(&repo, repo_path, NULL);
5050 if (error != NULL)
5051 goto done;
5053 if (worktree) {
5054 const char *prefix = got_worktree_get_path_prefix(worktree);
5055 char *p;
5057 error = got_worktree_resolve_path(&p, worktree, path);
5058 if (error)
5059 goto done;
5060 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5061 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5062 p) == -1) {
5063 error = got_error_from_errno("asprintf");
5064 free(p);
5065 goto done;
5067 free(p);
5068 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5069 } else {
5070 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5071 if (error)
5072 goto done;
5073 error = got_repo_map_path(&in_repo_path, repo, path);
5075 if (error)
5076 goto done;
5078 if (commit_id_str == NULL) {
5079 struct got_reference *head_ref;
5080 error = got_ref_open(&head_ref, repo, worktree ?
5081 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5082 if (error != NULL)
5083 goto done;
5084 error = got_ref_resolve(&commit_id, repo, head_ref);
5085 got_ref_close(head_ref);
5086 if (error != NULL)
5087 goto done;
5088 } else {
5089 struct got_reflist_head refs;
5090 TAILQ_INIT(&refs);
5091 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5092 NULL);
5093 if (error)
5094 goto done;
5095 error = got_repo_match_object_id(&commit_id, NULL,
5096 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5097 got_ref_list_free(&refs);
5098 if (error)
5099 goto done;
5102 if (worktree) {
5103 /* Release work tree lock. */
5104 got_worktree_close(worktree);
5105 worktree = NULL;
5108 error = got_object_open_as_commit(&commit, repo, commit_id);
5109 if (error)
5110 goto done;
5112 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5113 commit, repo);
5114 if (error)
5115 goto done;
5117 error = got_object_id_by_path(&obj_id, repo, commit,
5118 link_target ? link_target : in_repo_path);
5119 if (error)
5120 goto done;
5122 error = got_object_get_type(&obj_type, repo, obj_id);
5123 if (error)
5124 goto done;
5126 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5127 error = got_error_path(link_target ? link_target : in_repo_path,
5128 GOT_ERR_OBJ_TYPE);
5129 goto done;
5132 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5133 if (error)
5134 goto done;
5135 bca.f = got_opentemp();
5136 if (bca.f == NULL) {
5137 error = got_error_from_errno("got_opentemp");
5138 goto done;
5140 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5141 &bca.line_offsets, bca.f, blob);
5142 if (error || bca.nlines == 0)
5143 goto done;
5145 /* Don't include \n at EOF in the blame line count. */
5146 if (bca.line_offsets[bca.nlines - 1] == filesize)
5147 bca.nlines--;
5149 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5150 if (bca.lines == NULL) {
5151 error = got_error_from_errno("calloc");
5152 goto done;
5154 bca.lineno_cur = 1;
5155 bca.nlines_prec = 0;
5156 i = bca.nlines;
5157 while (i > 0) {
5158 i /= 10;
5159 bca.nlines_prec++;
5161 bca.repo = repo;
5163 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5164 repo, blame_cb, &bca, check_cancelled, NULL);
5165 done:
5166 free(in_repo_path);
5167 free(link_target);
5168 free(repo_path);
5169 free(cwd);
5170 free(commit_id);
5171 free(obj_id);
5172 if (commit)
5173 got_object_commit_close(commit);
5174 if (blob)
5175 got_object_blob_close(blob);
5176 if (worktree)
5177 got_worktree_close(worktree);
5178 if (repo) {
5179 const struct got_error *close_err = got_repo_close(repo);
5180 if (error == NULL)
5181 error = close_err;
5183 if (bca.lines) {
5184 for (i = 0; i < bca.nlines; i++) {
5185 struct blame_line *bline = &bca.lines[i];
5186 free(bline->id_str);
5187 free(bline->committer);
5189 free(bca.lines);
5191 free(bca.line_offsets);
5192 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5193 error = got_error_from_errno("fclose");
5194 return error;
5197 __dead static void
5198 usage_tree(void)
5200 fprintf(stderr,
5201 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5202 getprogname());
5203 exit(1);
5206 static const struct got_error *
5207 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5208 const char *root_path, struct got_repository *repo)
5210 const struct got_error *err = NULL;
5211 int is_root_path = (strcmp(path, root_path) == 0);
5212 const char *modestr = "";
5213 mode_t mode = got_tree_entry_get_mode(te);
5214 char *link_target = NULL;
5216 path += strlen(root_path);
5217 while (path[0] == '/')
5218 path++;
5220 if (got_object_tree_entry_is_submodule(te))
5221 modestr = "$";
5222 else if (S_ISLNK(mode)) {
5223 int i;
5225 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5226 if (err)
5227 return err;
5228 for (i = 0; i < strlen(link_target); i++) {
5229 if (!isprint((unsigned char)link_target[i]))
5230 link_target[i] = '?';
5233 modestr = "@";
5235 else if (S_ISDIR(mode))
5236 modestr = "/";
5237 else if (mode & S_IXUSR)
5238 modestr = "*";
5240 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5241 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5242 link_target ? " -> ": "", link_target ? link_target : "");
5244 free(link_target);
5245 return NULL;
5248 static const struct got_error *
5249 print_tree(const char *path, struct got_commit_object *commit,
5250 int show_ids, int recurse, const char *root_path,
5251 struct got_repository *repo)
5253 const struct got_error *err = NULL;
5254 struct got_object_id *tree_id = NULL;
5255 struct got_tree_object *tree = NULL;
5256 int nentries, i;
5258 err = got_object_id_by_path(&tree_id, repo, commit, path);
5259 if (err)
5260 goto done;
5262 err = got_object_open_as_tree(&tree, repo, tree_id);
5263 if (err)
5264 goto done;
5265 nentries = got_object_tree_get_nentries(tree);
5266 for (i = 0; i < nentries; i++) {
5267 struct got_tree_entry *te;
5268 char *id = NULL;
5270 if (sigint_received || sigpipe_received)
5271 break;
5273 te = got_object_tree_get_entry(tree, i);
5274 if (show_ids) {
5275 char *id_str;
5276 err = got_object_id_str(&id_str,
5277 got_tree_entry_get_id(te));
5278 if (err)
5279 goto done;
5280 if (asprintf(&id, "%s ", id_str) == -1) {
5281 err = got_error_from_errno("asprintf");
5282 free(id_str);
5283 goto done;
5285 free(id_str);
5287 err = print_entry(te, id, path, root_path, repo);
5288 free(id);
5289 if (err)
5290 goto done;
5292 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5293 char *child_path;
5294 if (asprintf(&child_path, "%s%s%s", path,
5295 path[0] == '/' && path[1] == '\0' ? "" : "/",
5296 got_tree_entry_get_name(te)) == -1) {
5297 err = got_error_from_errno("asprintf");
5298 goto done;
5300 err = print_tree(child_path, commit, show_ids, 1,
5301 root_path, repo);
5302 free(child_path);
5303 if (err)
5304 goto done;
5307 done:
5308 if (tree)
5309 got_object_tree_close(tree);
5310 free(tree_id);
5311 return err;
5314 static const struct got_error *
5315 cmd_tree(int argc, char *argv[])
5317 const struct got_error *error;
5318 struct got_repository *repo = NULL;
5319 struct got_worktree *worktree = NULL;
5320 const char *path, *refname = NULL;
5321 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5322 struct got_object_id *commit_id = NULL;
5323 struct got_commit_object *commit = NULL;
5324 char *commit_id_str = NULL;
5325 int show_ids = 0, recurse = 0;
5326 int ch;
5328 #ifndef PROFILE
5329 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5330 NULL) == -1)
5331 err(1, "pledge");
5332 #endif
5334 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5335 switch (ch) {
5336 case 'c':
5337 commit_id_str = optarg;
5338 break;
5339 case 'r':
5340 repo_path = realpath(optarg, NULL);
5341 if (repo_path == NULL)
5342 return got_error_from_errno2("realpath",
5343 optarg);
5344 got_path_strip_trailing_slashes(repo_path);
5345 break;
5346 case 'i':
5347 show_ids = 1;
5348 break;
5349 case 'R':
5350 recurse = 1;
5351 break;
5352 default:
5353 usage_tree();
5354 /* NOTREACHED */
5358 argc -= optind;
5359 argv += optind;
5361 if (argc == 1)
5362 path = argv[0];
5363 else if (argc > 1)
5364 usage_tree();
5365 else
5366 path = NULL;
5368 cwd = getcwd(NULL, 0);
5369 if (cwd == NULL) {
5370 error = got_error_from_errno("getcwd");
5371 goto done;
5373 if (repo_path == NULL) {
5374 error = got_worktree_open(&worktree, cwd);
5375 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5376 goto done;
5377 else
5378 error = NULL;
5379 if (worktree) {
5380 repo_path =
5381 strdup(got_worktree_get_repo_path(worktree));
5382 if (repo_path == NULL)
5383 error = got_error_from_errno("strdup");
5384 if (error)
5385 goto done;
5386 } else {
5387 repo_path = strdup(cwd);
5388 if (repo_path == NULL) {
5389 error = got_error_from_errno("strdup");
5390 goto done;
5395 error = got_repo_open(&repo, repo_path, NULL);
5396 if (error != NULL)
5397 goto done;
5399 if (worktree) {
5400 const char *prefix = got_worktree_get_path_prefix(worktree);
5401 char *p;
5403 if (path == NULL)
5404 path = "";
5405 error = got_worktree_resolve_path(&p, worktree, path);
5406 if (error)
5407 goto done;
5408 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5409 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5410 p) == -1) {
5411 error = got_error_from_errno("asprintf");
5412 free(p);
5413 goto done;
5415 free(p);
5416 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5417 if (error)
5418 goto done;
5419 } else {
5420 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5421 if (error)
5422 goto done;
5423 if (path == NULL)
5424 path = "/";
5425 error = got_repo_map_path(&in_repo_path, repo, path);
5426 if (error != NULL)
5427 goto done;
5430 if (commit_id_str == NULL) {
5431 struct got_reference *head_ref;
5432 if (worktree)
5433 refname = got_worktree_get_head_ref_name(worktree);
5434 else
5435 refname = GOT_REF_HEAD;
5436 error = got_ref_open(&head_ref, repo, refname, 0);
5437 if (error != NULL)
5438 goto done;
5439 error = got_ref_resolve(&commit_id, repo, head_ref);
5440 got_ref_close(head_ref);
5441 if (error != NULL)
5442 goto done;
5443 } else {
5444 struct got_reflist_head refs;
5445 TAILQ_INIT(&refs);
5446 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5447 NULL);
5448 if (error)
5449 goto done;
5450 error = got_repo_match_object_id(&commit_id, NULL,
5451 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5452 got_ref_list_free(&refs);
5453 if (error)
5454 goto done;
5457 if (worktree) {
5458 /* Release work tree lock. */
5459 got_worktree_close(worktree);
5460 worktree = NULL;
5463 error = got_object_open_as_commit(&commit, repo, commit_id);
5464 if (error)
5465 goto done;
5467 error = print_tree(in_repo_path, commit, show_ids, recurse,
5468 in_repo_path, repo);
5469 done:
5470 free(in_repo_path);
5471 free(repo_path);
5472 free(cwd);
5473 free(commit_id);
5474 if (commit)
5475 got_object_commit_close(commit);
5476 if (worktree)
5477 got_worktree_close(worktree);
5478 if (repo) {
5479 const struct got_error *close_err = got_repo_close(repo);
5480 if (error == NULL)
5481 error = close_err;
5483 return error;
5486 __dead static void
5487 usage_status(void)
5489 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5490 "[-S status-codes] [path ...]\n", getprogname());
5491 exit(1);
5494 struct got_status_arg {
5495 char *status_codes;
5496 int suppress;
5499 static const struct got_error *
5500 print_status(void *arg, unsigned char status, unsigned char staged_status,
5501 const char *path, struct got_object_id *blob_id,
5502 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5503 int dirfd, const char *de_name)
5505 struct got_status_arg *st = arg;
5507 if (status == staged_status && (status == GOT_STATUS_DELETE))
5508 status = GOT_STATUS_NO_CHANGE;
5509 if (st != NULL && st->status_codes) {
5510 size_t ncodes = strlen(st->status_codes);
5511 int i, j = 0;
5513 for (i = 0; i < ncodes ; i++) {
5514 if (st->suppress) {
5515 if (status == st->status_codes[i] ||
5516 staged_status == st->status_codes[i]) {
5517 j++;
5518 continue;
5520 } else {
5521 if (status == st->status_codes[i] ||
5522 staged_status == st->status_codes[i])
5523 break;
5527 if (st->suppress && j == 0)
5528 goto print;
5530 if (i == ncodes)
5531 return NULL;
5533 print:
5534 printf("%c%c %s\n", status, staged_status, path);
5535 return NULL;
5538 static const struct got_error *
5539 cmd_status(int argc, char *argv[])
5541 const struct got_error *error = NULL;
5542 struct got_repository *repo = NULL;
5543 struct got_worktree *worktree = NULL;
5544 struct got_status_arg st;
5545 char *cwd = NULL;
5546 struct got_pathlist_head paths;
5547 struct got_pathlist_entry *pe;
5548 int ch, i, no_ignores = 0;
5550 TAILQ_INIT(&paths);
5552 memset(&st, 0, sizeof(st));
5553 st.status_codes = NULL;
5554 st.suppress = 0;
5556 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5557 switch (ch) {
5558 case 'I':
5559 no_ignores = 1;
5560 break;
5561 case 'S':
5562 if (st.status_codes != NULL && st.suppress == 0)
5563 option_conflict('S', 's');
5564 st.suppress = 1;
5565 /* fallthrough */
5566 case 's':
5567 for (i = 0; i < strlen(optarg); i++) {
5568 switch (optarg[i]) {
5569 case GOT_STATUS_MODIFY:
5570 case GOT_STATUS_ADD:
5571 case GOT_STATUS_DELETE:
5572 case GOT_STATUS_CONFLICT:
5573 case GOT_STATUS_MISSING:
5574 case GOT_STATUS_OBSTRUCTED:
5575 case GOT_STATUS_UNVERSIONED:
5576 case GOT_STATUS_MODE_CHANGE:
5577 case GOT_STATUS_NONEXISTENT:
5578 break;
5579 default:
5580 errx(1, "invalid status code '%c'",
5581 optarg[i]);
5584 if (ch == 's' && st.suppress)
5585 option_conflict('s', 'S');
5586 st.status_codes = optarg;
5587 break;
5588 default:
5589 usage_status();
5590 /* NOTREACHED */
5594 argc -= optind;
5595 argv += optind;
5597 #ifndef PROFILE
5598 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5599 NULL) == -1)
5600 err(1, "pledge");
5601 #endif
5602 cwd = getcwd(NULL, 0);
5603 if (cwd == NULL) {
5604 error = got_error_from_errno("getcwd");
5605 goto done;
5608 error = got_worktree_open(&worktree, cwd);
5609 if (error) {
5610 if (error->code == GOT_ERR_NOT_WORKTREE)
5611 error = wrap_not_worktree_error(error, "status", cwd);
5612 goto done;
5615 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5616 NULL);
5617 if (error != NULL)
5618 goto done;
5620 error = apply_unveil(got_repo_get_path(repo), 1,
5621 got_worktree_get_root_path(worktree));
5622 if (error)
5623 goto done;
5625 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5626 if (error)
5627 goto done;
5629 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5630 print_status, &st, check_cancelled, NULL);
5631 done:
5632 TAILQ_FOREACH(pe, &paths, entry)
5633 free((char *)pe->path);
5634 got_pathlist_free(&paths);
5635 free(cwd);
5636 return error;
5639 __dead static void
5640 usage_ref(void)
5642 fprintf(stderr,
5643 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5644 "[-s reference] [-d] [name]\n",
5645 getprogname());
5646 exit(1);
5649 static const struct got_error *
5650 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5652 static const struct got_error *err = NULL;
5653 struct got_reflist_head refs;
5654 struct got_reflist_entry *re;
5656 TAILQ_INIT(&refs);
5657 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5658 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5659 repo);
5660 if (err)
5661 return err;
5663 TAILQ_FOREACH(re, &refs, entry) {
5664 char *refstr;
5665 refstr = got_ref_to_str(re->ref);
5666 if (refstr == NULL) {
5667 err = got_error_from_errno("got_ref_to_str");
5668 break;
5670 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5671 free(refstr);
5674 got_ref_list_free(&refs);
5675 return err;
5678 static const struct got_error *
5679 delete_ref_by_name(struct got_repository *repo, const char *refname)
5681 const struct got_error *err;
5682 struct got_reference *ref;
5684 err = got_ref_open(&ref, repo, refname, 0);
5685 if (err)
5686 return err;
5688 err = delete_ref(repo, ref);
5689 got_ref_close(ref);
5690 return err;
5693 static const struct got_error *
5694 add_ref(struct got_repository *repo, const char *refname, const char *target)
5696 const struct got_error *err = NULL;
5697 struct got_object_id *id = NULL;
5698 struct got_reference *ref = NULL;
5699 struct got_reflist_head refs;
5702 * Don't let the user create a reference name with a leading '-'.
5703 * While technically a valid reference name, this case is usually
5704 * an unintended typo.
5706 if (refname[0] == '-')
5707 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5709 TAILQ_INIT(&refs);
5710 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5711 if (err)
5712 goto done;
5713 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5714 &refs, repo);
5715 got_ref_list_free(&refs);
5716 if (err)
5717 goto done;
5719 err = got_ref_alloc(&ref, refname, id);
5720 if (err)
5721 goto done;
5723 err = got_ref_write(ref, repo);
5724 done:
5725 if (ref)
5726 got_ref_close(ref);
5727 free(id);
5728 return err;
5731 static const struct got_error *
5732 add_symref(struct got_repository *repo, const char *refname, const char *target)
5734 const struct got_error *err = NULL;
5735 struct got_reference *ref = NULL;
5736 struct got_reference *target_ref = NULL;
5739 * Don't let the user create a reference name with a leading '-'.
5740 * While technically a valid reference name, this case is usually
5741 * an unintended typo.
5743 if (refname[0] == '-')
5744 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5746 err = got_ref_open(&target_ref, repo, target, 0);
5747 if (err)
5748 return err;
5750 err = got_ref_alloc_symref(&ref, refname, target_ref);
5751 if (err)
5752 goto done;
5754 err = got_ref_write(ref, repo);
5755 done:
5756 if (target_ref)
5757 got_ref_close(target_ref);
5758 if (ref)
5759 got_ref_close(ref);
5760 return err;
5763 static const struct got_error *
5764 cmd_ref(int argc, char *argv[])
5766 const struct got_error *error = NULL;
5767 struct got_repository *repo = NULL;
5768 struct got_worktree *worktree = NULL;
5769 char *cwd = NULL, *repo_path = NULL;
5770 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5771 const char *obj_arg = NULL, *symref_target= NULL;
5772 char *refname = NULL;
5774 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5775 switch (ch) {
5776 case 'c':
5777 obj_arg = optarg;
5778 break;
5779 case 'd':
5780 do_delete = 1;
5781 break;
5782 case 'r':
5783 repo_path = realpath(optarg, NULL);
5784 if (repo_path == NULL)
5785 return got_error_from_errno2("realpath",
5786 optarg);
5787 got_path_strip_trailing_slashes(repo_path);
5788 break;
5789 case 'l':
5790 do_list = 1;
5791 break;
5792 case 's':
5793 symref_target = optarg;
5794 break;
5795 case 't':
5796 sort_by_time = 1;
5797 break;
5798 default:
5799 usage_ref();
5800 /* NOTREACHED */
5804 if (obj_arg && do_list)
5805 option_conflict('c', 'l');
5806 if (obj_arg && do_delete)
5807 option_conflict('c', 'd');
5808 if (obj_arg && symref_target)
5809 option_conflict('c', 's');
5810 if (symref_target && do_delete)
5811 option_conflict('s', 'd');
5812 if (symref_target && do_list)
5813 option_conflict('s', 'l');
5814 if (do_delete && do_list)
5815 option_conflict('d', 'l');
5816 if (sort_by_time && !do_list)
5817 errx(1, "-t option requires -l option");
5819 argc -= optind;
5820 argv += optind;
5822 if (do_list) {
5823 if (argc != 0 && argc != 1)
5824 usage_ref();
5825 if (argc == 1) {
5826 refname = strdup(argv[0]);
5827 if (refname == NULL) {
5828 error = got_error_from_errno("strdup");
5829 goto done;
5832 } else {
5833 if (argc != 1)
5834 usage_ref();
5835 refname = strdup(argv[0]);
5836 if (refname == NULL) {
5837 error = got_error_from_errno("strdup");
5838 goto done;
5842 if (refname)
5843 got_path_strip_trailing_slashes(refname);
5845 #ifndef PROFILE
5846 if (do_list) {
5847 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5848 NULL) == -1)
5849 err(1, "pledge");
5850 } else {
5851 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5852 "sendfd unveil", NULL) == -1)
5853 err(1, "pledge");
5855 #endif
5856 cwd = getcwd(NULL, 0);
5857 if (cwd == NULL) {
5858 error = got_error_from_errno("getcwd");
5859 goto done;
5862 if (repo_path == NULL) {
5863 error = got_worktree_open(&worktree, cwd);
5864 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5865 goto done;
5866 else
5867 error = NULL;
5868 if (worktree) {
5869 repo_path =
5870 strdup(got_worktree_get_repo_path(worktree));
5871 if (repo_path == NULL)
5872 error = got_error_from_errno("strdup");
5873 if (error)
5874 goto done;
5875 } else {
5876 repo_path = strdup(cwd);
5877 if (repo_path == NULL) {
5878 error = got_error_from_errno("strdup");
5879 goto done;
5884 error = got_repo_open(&repo, repo_path, NULL);
5885 if (error != NULL)
5886 goto done;
5888 error = apply_unveil(got_repo_get_path(repo), do_list,
5889 worktree ? got_worktree_get_root_path(worktree) : NULL);
5890 if (error)
5891 goto done;
5893 if (do_list)
5894 error = list_refs(repo, refname, sort_by_time);
5895 else if (do_delete)
5896 error = delete_ref_by_name(repo, refname);
5897 else if (symref_target)
5898 error = add_symref(repo, refname, symref_target);
5899 else {
5900 if (obj_arg == NULL)
5901 usage_ref();
5902 error = add_ref(repo, refname, obj_arg);
5904 done:
5905 free(refname);
5906 if (repo) {
5907 const struct got_error *close_err = got_repo_close(repo);
5908 if (error == NULL)
5909 error = close_err;
5911 if (worktree)
5912 got_worktree_close(worktree);
5913 free(cwd);
5914 free(repo_path);
5915 return error;
5918 __dead static void
5919 usage_branch(void)
5921 fprintf(stderr,
5922 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5923 "[-n] [name]\n", getprogname());
5924 exit(1);
5927 static const struct got_error *
5928 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5929 struct got_reference *ref)
5931 const struct got_error *err = NULL;
5932 const char *refname, *marker = " ";
5933 char *refstr;
5935 refname = got_ref_get_name(ref);
5936 if (worktree && strcmp(refname,
5937 got_worktree_get_head_ref_name(worktree)) == 0) {
5938 struct got_object_id *id = NULL;
5940 err = got_ref_resolve(&id, repo, ref);
5941 if (err)
5942 return err;
5943 if (got_object_id_cmp(id,
5944 got_worktree_get_base_commit_id(worktree)) == 0)
5945 marker = "* ";
5946 else
5947 marker = "~ ";
5948 free(id);
5951 if (strncmp(refname, "refs/heads/", 11) == 0)
5952 refname += 11;
5953 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5954 refname += 18;
5955 if (strncmp(refname, "refs/remotes/", 13) == 0)
5956 refname += 13;
5958 refstr = got_ref_to_str(ref);
5959 if (refstr == NULL)
5960 return got_error_from_errno("got_ref_to_str");
5962 printf("%s%s: %s\n", marker, refname, refstr);
5963 free(refstr);
5964 return NULL;
5967 static const struct got_error *
5968 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5970 const char *refname;
5972 if (worktree == NULL)
5973 return got_error(GOT_ERR_NOT_WORKTREE);
5975 refname = got_worktree_get_head_ref_name(worktree);
5977 if (strncmp(refname, "refs/heads/", 11) == 0)
5978 refname += 11;
5979 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5980 refname += 18;
5982 printf("%s\n", refname);
5984 return NULL;
5987 static const struct got_error *
5988 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5989 int sort_by_time)
5991 static const struct got_error *err = NULL;
5992 struct got_reflist_head refs;
5993 struct got_reflist_entry *re;
5994 struct got_reference *temp_ref = NULL;
5995 int rebase_in_progress, histedit_in_progress;
5997 TAILQ_INIT(&refs);
5999 if (worktree) {
6000 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6001 worktree);
6002 if (err)
6003 return err;
6005 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6006 worktree);
6007 if (err)
6008 return err;
6010 if (rebase_in_progress || histedit_in_progress) {
6011 err = got_ref_open(&temp_ref, repo,
6012 got_worktree_get_head_ref_name(worktree), 0);
6013 if (err)
6014 return err;
6015 list_branch(repo, worktree, temp_ref);
6016 got_ref_close(temp_ref);
6020 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6021 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6022 repo);
6023 if (err)
6024 return err;
6026 TAILQ_FOREACH(re, &refs, entry)
6027 list_branch(repo, worktree, re->ref);
6029 got_ref_list_free(&refs);
6031 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6032 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6033 repo);
6034 if (err)
6035 return err;
6037 TAILQ_FOREACH(re, &refs, entry)
6038 list_branch(repo, worktree, re->ref);
6040 got_ref_list_free(&refs);
6042 return NULL;
6045 static const struct got_error *
6046 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6047 const char *branch_name)
6049 const struct got_error *err = NULL;
6050 struct got_reference *ref = NULL;
6051 char *refname, *remote_refname = NULL;
6053 if (strncmp(branch_name, "refs/", 5) == 0)
6054 branch_name += 5;
6055 if (strncmp(branch_name, "heads/", 6) == 0)
6056 branch_name += 6;
6057 else if (strncmp(branch_name, "remotes/", 8) == 0)
6058 branch_name += 8;
6060 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6061 return got_error_from_errno("asprintf");
6063 if (asprintf(&remote_refname, "refs/remotes/%s",
6064 branch_name) == -1) {
6065 err = got_error_from_errno("asprintf");
6066 goto done;
6069 err = got_ref_open(&ref, repo, refname, 0);
6070 if (err) {
6071 const struct got_error *err2;
6072 if (err->code != GOT_ERR_NOT_REF)
6073 goto done;
6075 * Keep 'err' intact such that if neither branch exists
6076 * we report "refs/heads" rather than "refs/remotes" in
6077 * our error message.
6079 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6080 if (err2)
6081 goto done;
6082 err = NULL;
6085 if (worktree &&
6086 strcmp(got_worktree_get_head_ref_name(worktree),
6087 got_ref_get_name(ref)) == 0) {
6088 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6089 "will not delete this work tree's current branch");
6090 goto done;
6093 err = delete_ref(repo, ref);
6094 done:
6095 if (ref)
6096 got_ref_close(ref);
6097 free(refname);
6098 free(remote_refname);
6099 return err;
6102 static const struct got_error *
6103 add_branch(struct got_repository *repo, const char *branch_name,
6104 struct got_object_id *base_commit_id)
6106 const struct got_error *err = NULL;
6107 struct got_reference *ref = NULL;
6108 char *base_refname = NULL, *refname = NULL;
6111 * Don't let the user create a branch name with a leading '-'.
6112 * While technically a valid reference name, this case is usually
6113 * an unintended typo.
6115 if (branch_name[0] == '-')
6116 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6118 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6119 branch_name += 11;
6121 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6122 err = got_error_from_errno("asprintf");
6123 goto done;
6126 err = got_ref_open(&ref, repo, refname, 0);
6127 if (err == NULL) {
6128 err = got_error(GOT_ERR_BRANCH_EXISTS);
6129 goto done;
6130 } else if (err->code != GOT_ERR_NOT_REF)
6131 goto done;
6133 err = got_ref_alloc(&ref, refname, base_commit_id);
6134 if (err)
6135 goto done;
6137 err = got_ref_write(ref, repo);
6138 done:
6139 if (ref)
6140 got_ref_close(ref);
6141 free(base_refname);
6142 free(refname);
6143 return err;
6146 static const struct got_error *
6147 cmd_branch(int argc, char *argv[])
6149 const struct got_error *error = NULL;
6150 struct got_repository *repo = NULL;
6151 struct got_worktree *worktree = NULL;
6152 char *cwd = NULL, *repo_path = NULL;
6153 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6154 const char *delref = NULL, *commit_id_arg = NULL;
6155 struct got_reference *ref = NULL;
6156 struct got_pathlist_head paths;
6157 struct got_pathlist_entry *pe;
6158 struct got_object_id *commit_id = NULL;
6159 char *commit_id_str = NULL;
6161 TAILQ_INIT(&paths);
6163 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6164 switch (ch) {
6165 case 'c':
6166 commit_id_arg = optarg;
6167 break;
6168 case 'd':
6169 delref = optarg;
6170 break;
6171 case 'r':
6172 repo_path = realpath(optarg, NULL);
6173 if (repo_path == NULL)
6174 return got_error_from_errno2("realpath",
6175 optarg);
6176 got_path_strip_trailing_slashes(repo_path);
6177 break;
6178 case 'l':
6179 do_list = 1;
6180 break;
6181 case 'n':
6182 do_update = 0;
6183 break;
6184 case 't':
6185 sort_by_time = 1;
6186 break;
6187 default:
6188 usage_branch();
6189 /* NOTREACHED */
6193 if (do_list && delref)
6194 option_conflict('l', 'd');
6195 if (sort_by_time && !do_list)
6196 errx(1, "-t option requires -l option");
6198 argc -= optind;
6199 argv += optind;
6201 if (!do_list && !delref && argc == 0)
6202 do_show = 1;
6204 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6205 errx(1, "-c option can only be used when creating a branch");
6207 if (do_list || delref) {
6208 if (argc > 0)
6209 usage_branch();
6210 } else if (!do_show && argc != 1)
6211 usage_branch();
6213 #ifndef PROFILE
6214 if (do_list || do_show) {
6215 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6216 NULL) == -1)
6217 err(1, "pledge");
6218 } else {
6219 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6220 "sendfd unveil", NULL) == -1)
6221 err(1, "pledge");
6223 #endif
6224 cwd = getcwd(NULL, 0);
6225 if (cwd == NULL) {
6226 error = got_error_from_errno("getcwd");
6227 goto done;
6230 if (repo_path == NULL) {
6231 error = got_worktree_open(&worktree, cwd);
6232 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6233 goto done;
6234 else
6235 error = NULL;
6236 if (worktree) {
6237 repo_path =
6238 strdup(got_worktree_get_repo_path(worktree));
6239 if (repo_path == NULL)
6240 error = got_error_from_errno("strdup");
6241 if (error)
6242 goto done;
6243 } else {
6244 repo_path = strdup(cwd);
6245 if (repo_path == NULL) {
6246 error = got_error_from_errno("strdup");
6247 goto done;
6252 error = got_repo_open(&repo, repo_path, NULL);
6253 if (error != NULL)
6254 goto done;
6256 error = apply_unveil(got_repo_get_path(repo), do_list,
6257 worktree ? got_worktree_get_root_path(worktree) : NULL);
6258 if (error)
6259 goto done;
6261 if (do_show)
6262 error = show_current_branch(repo, worktree);
6263 else if (do_list)
6264 error = list_branches(repo, worktree, sort_by_time);
6265 else if (delref)
6266 error = delete_branch(repo, worktree, delref);
6267 else {
6268 struct got_reflist_head refs;
6269 TAILQ_INIT(&refs);
6270 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6271 NULL);
6272 if (error)
6273 goto done;
6274 if (commit_id_arg == NULL)
6275 commit_id_arg = worktree ?
6276 got_worktree_get_head_ref_name(worktree) :
6277 GOT_REF_HEAD;
6278 error = got_repo_match_object_id(&commit_id, NULL,
6279 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6280 got_ref_list_free(&refs);
6281 if (error)
6282 goto done;
6283 error = add_branch(repo, argv[0], commit_id);
6284 if (error)
6285 goto done;
6286 if (worktree && do_update) {
6287 struct got_update_progress_arg upa;
6288 char *branch_refname = NULL;
6290 error = got_object_id_str(&commit_id_str, commit_id);
6291 if (error)
6292 goto done;
6293 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6294 worktree);
6295 if (error)
6296 goto done;
6297 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6298 == -1) {
6299 error = got_error_from_errno("asprintf");
6300 goto done;
6302 error = got_ref_open(&ref, repo, branch_refname, 0);
6303 free(branch_refname);
6304 if (error)
6305 goto done;
6306 error = switch_head_ref(ref, commit_id, worktree,
6307 repo);
6308 if (error)
6309 goto done;
6310 error = got_worktree_set_base_commit_id(worktree, repo,
6311 commit_id);
6312 if (error)
6313 goto done;
6314 memset(&upa, 0, sizeof(upa));
6315 error = got_worktree_checkout_files(worktree, &paths,
6316 repo, update_progress, &upa, check_cancelled,
6317 NULL);
6318 if (error)
6319 goto done;
6320 if (upa.did_something) {
6321 printf("Updated to %s: %s\n",
6322 got_worktree_get_head_ref_name(worktree),
6323 commit_id_str);
6325 print_update_progress_stats(&upa);
6328 done:
6329 if (ref)
6330 got_ref_close(ref);
6331 if (repo) {
6332 const struct got_error *close_err = got_repo_close(repo);
6333 if (error == NULL)
6334 error = close_err;
6336 if (worktree)
6337 got_worktree_close(worktree);
6338 free(cwd);
6339 free(repo_path);
6340 free(commit_id);
6341 free(commit_id_str);
6342 TAILQ_FOREACH(pe, &paths, entry)
6343 free((char *)pe->path);
6344 got_pathlist_free(&paths);
6345 return error;
6349 __dead static void
6350 usage_tag(void)
6352 fprintf(stderr,
6353 "usage: %s tag [-c commit] [-r repository] [-l] "
6354 "[-m message] name\n", getprogname());
6355 exit(1);
6358 #if 0
6359 static const struct got_error *
6360 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6362 const struct got_error *err = NULL;
6363 struct got_reflist_entry *re, *se, *new;
6364 struct got_object_id *re_id, *se_id;
6365 struct got_tag_object *re_tag, *se_tag;
6366 time_t re_time, se_time;
6368 STAILQ_FOREACH(re, tags, entry) {
6369 se = STAILQ_FIRST(sorted);
6370 if (se == NULL) {
6371 err = got_reflist_entry_dup(&new, re);
6372 if (err)
6373 return err;
6374 STAILQ_INSERT_HEAD(sorted, new, entry);
6375 continue;
6376 } else {
6377 err = got_ref_resolve(&re_id, repo, re->ref);
6378 if (err)
6379 break;
6380 err = got_object_open_as_tag(&re_tag, repo, re_id);
6381 free(re_id);
6382 if (err)
6383 break;
6384 re_time = got_object_tag_get_tagger_time(re_tag);
6385 got_object_tag_close(re_tag);
6388 while (se) {
6389 err = got_ref_resolve(&se_id, repo, re->ref);
6390 if (err)
6391 break;
6392 err = got_object_open_as_tag(&se_tag, repo, se_id);
6393 free(se_id);
6394 if (err)
6395 break;
6396 se_time = got_object_tag_get_tagger_time(se_tag);
6397 got_object_tag_close(se_tag);
6399 if (se_time > re_time) {
6400 err = got_reflist_entry_dup(&new, re);
6401 if (err)
6402 return err;
6403 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6404 break;
6406 se = STAILQ_NEXT(se, entry);
6407 continue;
6410 done:
6411 return err;
6413 #endif
6415 static const struct got_error *
6416 list_tags(struct got_repository *repo)
6418 static const struct got_error *err = NULL;
6419 struct got_reflist_head refs;
6420 struct got_reflist_entry *re;
6422 TAILQ_INIT(&refs);
6424 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6425 if (err)
6426 return err;
6428 TAILQ_FOREACH(re, &refs, entry) {
6429 const char *refname;
6430 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6431 char datebuf[26];
6432 const char *tagger;
6433 time_t tagger_time;
6434 struct got_object_id *id;
6435 struct got_tag_object *tag;
6436 struct got_commit_object *commit = NULL;
6438 refname = got_ref_get_name(re->ref);
6439 if (strncmp(refname, "refs/tags/", 10) != 0)
6440 continue;
6441 refname += 10;
6442 refstr = got_ref_to_str(re->ref);
6443 if (refstr == NULL) {
6444 err = got_error_from_errno("got_ref_to_str");
6445 break;
6447 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6448 free(refstr);
6450 err = got_ref_resolve(&id, repo, re->ref);
6451 if (err)
6452 break;
6453 err = got_object_open_as_tag(&tag, repo, id);
6454 if (err) {
6455 if (err->code != GOT_ERR_OBJ_TYPE) {
6456 free(id);
6457 break;
6459 /* "lightweight" tag */
6460 err = got_object_open_as_commit(&commit, repo, id);
6461 if (err) {
6462 free(id);
6463 break;
6465 tagger = got_object_commit_get_committer(commit);
6466 tagger_time =
6467 got_object_commit_get_committer_time(commit);
6468 err = got_object_id_str(&id_str, id);
6469 free(id);
6470 if (err)
6471 break;
6472 } else {
6473 free(id);
6474 tagger = got_object_tag_get_tagger(tag);
6475 tagger_time = got_object_tag_get_tagger_time(tag);
6476 err = got_object_id_str(&id_str,
6477 got_object_tag_get_object_id(tag));
6478 if (err)
6479 break;
6481 printf("from: %s\n", tagger);
6482 datestr = get_datestr(&tagger_time, datebuf);
6483 if (datestr)
6484 printf("date: %s UTC\n", datestr);
6485 if (commit)
6486 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6487 else {
6488 switch (got_object_tag_get_object_type(tag)) {
6489 case GOT_OBJ_TYPE_BLOB:
6490 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6491 id_str);
6492 break;
6493 case GOT_OBJ_TYPE_TREE:
6494 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6495 id_str);
6496 break;
6497 case GOT_OBJ_TYPE_COMMIT:
6498 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6499 id_str);
6500 break;
6501 case GOT_OBJ_TYPE_TAG:
6502 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6503 id_str);
6504 break;
6505 default:
6506 break;
6509 free(id_str);
6510 if (commit) {
6511 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6512 if (err)
6513 break;
6514 got_object_commit_close(commit);
6515 } else {
6516 tagmsg0 = strdup(got_object_tag_get_message(tag));
6517 got_object_tag_close(tag);
6518 if (tagmsg0 == NULL) {
6519 err = got_error_from_errno("strdup");
6520 break;
6524 tagmsg = tagmsg0;
6525 do {
6526 line = strsep(&tagmsg, "\n");
6527 if (line)
6528 printf(" %s\n", line);
6529 } while (line);
6530 free(tagmsg0);
6533 got_ref_list_free(&refs);
6534 return NULL;
6537 static const struct got_error *
6538 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6539 const char *tag_name, const char *repo_path)
6541 const struct got_error *err = NULL;
6542 char *template = NULL, *initial_content = NULL;
6543 char *editor = NULL;
6544 int initial_content_len;
6545 int fd = -1;
6547 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6548 err = got_error_from_errno("asprintf");
6549 goto done;
6552 initial_content_len = asprintf(&initial_content,
6553 "\n# tagging commit %s as %s\n",
6554 commit_id_str, tag_name);
6555 if (initial_content_len == -1) {
6556 err = got_error_from_errno("asprintf");
6557 goto done;
6560 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6561 if (err)
6562 goto done;
6564 if (write(fd, initial_content, initial_content_len) == -1) {
6565 err = got_error_from_errno2("write", *tagmsg_path);
6566 goto done;
6569 err = get_editor(&editor);
6570 if (err)
6571 goto done;
6572 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6573 initial_content_len, 1);
6574 done:
6575 free(initial_content);
6576 free(template);
6577 free(editor);
6579 if (fd != -1 && close(fd) == -1 && err == NULL)
6580 err = got_error_from_errno2("close", *tagmsg_path);
6582 /* Editor is done; we can now apply unveil(2) */
6583 if (err == NULL)
6584 err = apply_unveil(repo_path, 0, NULL);
6585 if (err) {
6586 free(*tagmsg);
6587 *tagmsg = NULL;
6589 return err;
6592 static const struct got_error *
6593 add_tag(struct got_repository *repo, const char *tagger,
6594 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6596 const struct got_error *err = NULL;
6597 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6598 char *label = NULL, *commit_id_str = NULL;
6599 struct got_reference *ref = NULL;
6600 char *refname = NULL, *tagmsg = NULL;
6601 char *tagmsg_path = NULL, *tag_id_str = NULL;
6602 int preserve_tagmsg = 0;
6603 struct got_reflist_head refs;
6605 TAILQ_INIT(&refs);
6608 * Don't let the user create a tag name with a leading '-'.
6609 * While technically a valid reference name, this case is usually
6610 * an unintended typo.
6612 if (tag_name[0] == '-')
6613 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6615 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6616 if (err)
6617 goto done;
6619 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6620 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6621 if (err)
6622 goto done;
6624 err = got_object_id_str(&commit_id_str, commit_id);
6625 if (err)
6626 goto done;
6628 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6629 refname = strdup(tag_name);
6630 if (refname == NULL) {
6631 err = got_error_from_errno("strdup");
6632 goto done;
6634 tag_name += 10;
6635 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6636 err = got_error_from_errno("asprintf");
6637 goto done;
6640 err = got_ref_open(&ref, repo, refname, 0);
6641 if (err == NULL) {
6642 err = got_error(GOT_ERR_TAG_EXISTS);
6643 goto done;
6644 } else if (err->code != GOT_ERR_NOT_REF)
6645 goto done;
6647 if (tagmsg_arg == NULL) {
6648 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6649 tag_name, got_repo_get_path(repo));
6650 if (err) {
6651 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6652 tagmsg_path != NULL)
6653 preserve_tagmsg = 1;
6654 goto done;
6658 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6659 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6660 if (err) {
6661 if (tagmsg_path)
6662 preserve_tagmsg = 1;
6663 goto done;
6666 err = got_ref_alloc(&ref, refname, tag_id);
6667 if (err) {
6668 if (tagmsg_path)
6669 preserve_tagmsg = 1;
6670 goto done;
6673 err = got_ref_write(ref, repo);
6674 if (err) {
6675 if (tagmsg_path)
6676 preserve_tagmsg = 1;
6677 goto done;
6680 err = got_object_id_str(&tag_id_str, tag_id);
6681 if (err) {
6682 if (tagmsg_path)
6683 preserve_tagmsg = 1;
6684 goto done;
6686 printf("Created tag %s\n", tag_id_str);
6687 done:
6688 if (preserve_tagmsg) {
6689 fprintf(stderr, "%s: tag message preserved in %s\n",
6690 getprogname(), tagmsg_path);
6691 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6692 err = got_error_from_errno2("unlink", tagmsg_path);
6693 free(tag_id_str);
6694 if (ref)
6695 got_ref_close(ref);
6696 free(commit_id);
6697 free(commit_id_str);
6698 free(refname);
6699 free(tagmsg);
6700 free(tagmsg_path);
6701 got_ref_list_free(&refs);
6702 return err;
6705 static const struct got_error *
6706 cmd_tag(int argc, char *argv[])
6708 const struct got_error *error = NULL;
6709 struct got_repository *repo = NULL;
6710 struct got_worktree *worktree = NULL;
6711 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6712 char *gitconfig_path = NULL, *tagger = NULL;
6713 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6714 int ch, do_list = 0;
6716 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6717 switch (ch) {
6718 case 'c':
6719 commit_id_arg = optarg;
6720 break;
6721 case 'm':
6722 tagmsg = optarg;
6723 break;
6724 case 'r':
6725 repo_path = realpath(optarg, NULL);
6726 if (repo_path == NULL)
6727 return got_error_from_errno2("realpath",
6728 optarg);
6729 got_path_strip_trailing_slashes(repo_path);
6730 break;
6731 case 'l':
6732 do_list = 1;
6733 break;
6734 default:
6735 usage_tag();
6736 /* NOTREACHED */
6740 argc -= optind;
6741 argv += optind;
6743 if (do_list) {
6744 if (commit_id_arg != NULL)
6745 errx(1,
6746 "-c option can only be used when creating a tag");
6747 if (tagmsg)
6748 option_conflict('l', 'm');
6749 if (argc > 0)
6750 usage_tag();
6751 } else if (argc != 1)
6752 usage_tag();
6754 tag_name = argv[0];
6756 #ifndef PROFILE
6757 if (do_list) {
6758 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6759 NULL) == -1)
6760 err(1, "pledge");
6761 } else {
6762 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6763 "sendfd unveil", NULL) == -1)
6764 err(1, "pledge");
6766 #endif
6767 cwd = getcwd(NULL, 0);
6768 if (cwd == NULL) {
6769 error = got_error_from_errno("getcwd");
6770 goto done;
6773 if (repo_path == NULL) {
6774 error = got_worktree_open(&worktree, cwd);
6775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6776 goto done;
6777 else
6778 error = NULL;
6779 if (worktree) {
6780 repo_path =
6781 strdup(got_worktree_get_repo_path(worktree));
6782 if (repo_path == NULL)
6783 error = got_error_from_errno("strdup");
6784 if (error)
6785 goto done;
6786 } else {
6787 repo_path = strdup(cwd);
6788 if (repo_path == NULL) {
6789 error = got_error_from_errno("strdup");
6790 goto done;
6795 if (do_list) {
6796 if (worktree) {
6797 /* Release work tree lock. */
6798 got_worktree_close(worktree);
6799 worktree = NULL;
6801 error = got_repo_open(&repo, repo_path, NULL);
6802 if (error != NULL)
6803 goto done;
6804 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6805 if (error)
6806 goto done;
6807 error = list_tags(repo);
6808 } else {
6809 error = get_gitconfig_path(&gitconfig_path);
6810 if (error)
6811 goto done;
6812 error = got_repo_open(&repo, repo_path, gitconfig_path);
6813 if (error != NULL)
6814 goto done;
6816 error = get_author(&tagger, repo, worktree);
6817 if (error)
6818 goto done;
6819 if (worktree) {
6820 /* Release work tree lock. */
6821 got_worktree_close(worktree);
6822 worktree = NULL;
6825 if (tagmsg) {
6826 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6827 if (error)
6828 goto done;
6831 if (commit_id_arg == NULL) {
6832 struct got_reference *head_ref;
6833 struct got_object_id *commit_id;
6834 error = got_ref_open(&head_ref, repo,
6835 worktree ? got_worktree_get_head_ref_name(worktree)
6836 : GOT_REF_HEAD, 0);
6837 if (error)
6838 goto done;
6839 error = got_ref_resolve(&commit_id, repo, head_ref);
6840 got_ref_close(head_ref);
6841 if (error)
6842 goto done;
6843 error = got_object_id_str(&commit_id_str, commit_id);
6844 free(commit_id);
6845 if (error)
6846 goto done;
6849 error = add_tag(repo, tagger, tag_name,
6850 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6852 done:
6853 if (repo) {
6854 const struct got_error *close_err = got_repo_close(repo);
6855 if (error == NULL)
6856 error = close_err;
6858 if (worktree)
6859 got_worktree_close(worktree);
6860 free(cwd);
6861 free(repo_path);
6862 free(gitconfig_path);
6863 free(commit_id_str);
6864 free(tagger);
6865 return error;
6868 __dead static void
6869 usage_add(void)
6871 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6872 getprogname());
6873 exit(1);
6876 static const struct got_error *
6877 add_progress(void *arg, unsigned char status, const char *path)
6879 while (path[0] == '/')
6880 path++;
6881 printf("%c %s\n", status, path);
6882 return NULL;
6885 static const struct got_error *
6886 cmd_add(int argc, char *argv[])
6888 const struct got_error *error = NULL;
6889 struct got_repository *repo = NULL;
6890 struct got_worktree *worktree = NULL;
6891 char *cwd = NULL;
6892 struct got_pathlist_head paths;
6893 struct got_pathlist_entry *pe;
6894 int ch, can_recurse = 0, no_ignores = 0;
6896 TAILQ_INIT(&paths);
6898 while ((ch = getopt(argc, argv, "IR")) != -1) {
6899 switch (ch) {
6900 case 'I':
6901 no_ignores = 1;
6902 break;
6903 case 'R':
6904 can_recurse = 1;
6905 break;
6906 default:
6907 usage_add();
6908 /* NOTREACHED */
6912 argc -= optind;
6913 argv += optind;
6915 #ifndef PROFILE
6916 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6917 NULL) == -1)
6918 err(1, "pledge");
6919 #endif
6920 if (argc < 1)
6921 usage_add();
6923 cwd = getcwd(NULL, 0);
6924 if (cwd == NULL) {
6925 error = got_error_from_errno("getcwd");
6926 goto done;
6929 error = got_worktree_open(&worktree, cwd);
6930 if (error) {
6931 if (error->code == GOT_ERR_NOT_WORKTREE)
6932 error = wrap_not_worktree_error(error, "add", cwd);
6933 goto done;
6936 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6937 NULL);
6938 if (error != NULL)
6939 goto done;
6941 error = apply_unveil(got_repo_get_path(repo), 1,
6942 got_worktree_get_root_path(worktree));
6943 if (error)
6944 goto done;
6946 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6947 if (error)
6948 goto done;
6950 if (!can_recurse) {
6951 char *ondisk_path;
6952 struct stat sb;
6953 TAILQ_FOREACH(pe, &paths, entry) {
6954 if (asprintf(&ondisk_path, "%s/%s",
6955 got_worktree_get_root_path(worktree),
6956 pe->path) == -1) {
6957 error = got_error_from_errno("asprintf");
6958 goto done;
6960 if (lstat(ondisk_path, &sb) == -1) {
6961 if (errno == ENOENT) {
6962 free(ondisk_path);
6963 continue;
6965 error = got_error_from_errno2("lstat",
6966 ondisk_path);
6967 free(ondisk_path);
6968 goto done;
6970 free(ondisk_path);
6971 if (S_ISDIR(sb.st_mode)) {
6972 error = got_error_msg(GOT_ERR_BAD_PATH,
6973 "adding directories requires -R option");
6974 goto done;
6979 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6980 NULL, repo, no_ignores);
6981 done:
6982 if (repo) {
6983 const struct got_error *close_err = got_repo_close(repo);
6984 if (error == NULL)
6985 error = close_err;
6987 if (worktree)
6988 got_worktree_close(worktree);
6989 TAILQ_FOREACH(pe, &paths, entry)
6990 free((char *)pe->path);
6991 got_pathlist_free(&paths);
6992 free(cwd);
6993 return error;
6996 __dead static void
6997 usage_remove(void)
6999 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7000 "path ...\n", getprogname());
7001 exit(1);
7004 static const struct got_error *
7005 print_remove_status(void *arg, unsigned char status,
7006 unsigned char staged_status, const char *path)
7008 while (path[0] == '/')
7009 path++;
7010 if (status == GOT_STATUS_NONEXISTENT)
7011 return NULL;
7012 if (status == staged_status && (status == GOT_STATUS_DELETE))
7013 status = GOT_STATUS_NO_CHANGE;
7014 printf("%c%c %s\n", status, staged_status, path);
7015 return NULL;
7018 static const struct got_error *
7019 cmd_remove(int argc, char *argv[])
7021 const struct got_error *error = NULL;
7022 struct got_worktree *worktree = NULL;
7023 struct got_repository *repo = NULL;
7024 const char *status_codes = NULL;
7025 char *cwd = NULL;
7026 struct got_pathlist_head paths;
7027 struct got_pathlist_entry *pe;
7028 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7029 int ignore_missing_paths = 0;
7031 TAILQ_INIT(&paths);
7033 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7034 switch (ch) {
7035 case 'f':
7036 delete_local_mods = 1;
7037 ignore_missing_paths = 1;
7038 break;
7039 case 'k':
7040 keep_on_disk = 1;
7041 break;
7042 case 'R':
7043 can_recurse = 1;
7044 break;
7045 case 's':
7046 for (i = 0; i < strlen(optarg); i++) {
7047 switch (optarg[i]) {
7048 case GOT_STATUS_MODIFY:
7049 delete_local_mods = 1;
7050 break;
7051 case GOT_STATUS_MISSING:
7052 ignore_missing_paths = 1;
7053 break;
7054 default:
7055 errx(1, "invalid status code '%c'",
7056 optarg[i]);
7059 status_codes = optarg;
7060 break;
7061 default:
7062 usage_remove();
7063 /* NOTREACHED */
7067 argc -= optind;
7068 argv += optind;
7070 #ifndef PROFILE
7071 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7072 NULL) == -1)
7073 err(1, "pledge");
7074 #endif
7075 if (argc < 1)
7076 usage_remove();
7078 cwd = getcwd(NULL, 0);
7079 if (cwd == NULL) {
7080 error = got_error_from_errno("getcwd");
7081 goto done;
7083 error = got_worktree_open(&worktree, cwd);
7084 if (error) {
7085 if (error->code == GOT_ERR_NOT_WORKTREE)
7086 error = wrap_not_worktree_error(error, "remove", cwd);
7087 goto done;
7090 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7091 NULL);
7092 if (error)
7093 goto done;
7095 error = apply_unveil(got_repo_get_path(repo), 1,
7096 got_worktree_get_root_path(worktree));
7097 if (error)
7098 goto done;
7100 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7101 if (error)
7102 goto done;
7104 if (!can_recurse) {
7105 char *ondisk_path;
7106 struct stat sb;
7107 TAILQ_FOREACH(pe, &paths, entry) {
7108 if (asprintf(&ondisk_path, "%s/%s",
7109 got_worktree_get_root_path(worktree),
7110 pe->path) == -1) {
7111 error = got_error_from_errno("asprintf");
7112 goto done;
7114 if (lstat(ondisk_path, &sb) == -1) {
7115 if (errno == ENOENT) {
7116 free(ondisk_path);
7117 continue;
7119 error = got_error_from_errno2("lstat",
7120 ondisk_path);
7121 free(ondisk_path);
7122 goto done;
7124 free(ondisk_path);
7125 if (S_ISDIR(sb.st_mode)) {
7126 error = got_error_msg(GOT_ERR_BAD_PATH,
7127 "removing directories requires -R option");
7128 goto done;
7133 error = got_worktree_schedule_delete(worktree, &paths,
7134 delete_local_mods, status_codes, print_remove_status, NULL,
7135 repo, keep_on_disk, ignore_missing_paths);
7136 done:
7137 if (repo) {
7138 const struct got_error *close_err = got_repo_close(repo);
7139 if (error == NULL)
7140 error = close_err;
7142 if (worktree)
7143 got_worktree_close(worktree);
7144 TAILQ_FOREACH(pe, &paths, entry)
7145 free((char *)pe->path);
7146 got_pathlist_free(&paths);
7147 free(cwd);
7148 return error;
7151 __dead static void
7152 usage_patch(void)
7154 fprintf(stderr, "usage: %s patch [-n] [patchfile]\n",
7155 getprogname());
7156 exit(1);
7159 static const struct got_error *
7160 patch_from_stdin(int *patchfd)
7162 const struct got_error *err = NULL;
7163 ssize_t r;
7164 char *path, buf[BUFSIZ];
7165 sig_t sighup, sigint, sigquit;
7167 err = got_opentemp_named_fd(&path, patchfd,
7168 GOT_TMPDIR_STR "/got-patch");
7169 if (err)
7170 return err;
7171 unlink(path);
7172 free(path);
7174 sighup = signal(SIGHUP, SIG_DFL);
7175 sigint = signal(SIGINT, SIG_DFL);
7176 sigquit = signal(SIGQUIT, SIG_DFL);
7178 for (;;) {
7179 r = read(0, buf, sizeof(buf));
7180 if (r == -1) {
7181 err = got_error_from_errno("read");
7182 break;
7184 if (r == 0)
7185 break;
7186 if (write(*patchfd, buf, r) == -1) {
7187 err = got_error_from_errno("write");
7188 break;
7192 signal(SIGHUP, sighup);
7193 signal(SIGINT, sigint);
7194 signal(SIGQUIT, sigquit);
7196 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7197 err = got_error_from_errno("lseek");
7199 if (err != NULL) {
7200 close(*patchfd);
7201 *patchfd = -1;
7204 return err;
7207 static const struct got_error *
7208 patch_progress(void *arg, const char *old, const char *new,
7209 unsigned char status, const struct got_error *error, long old_from,
7210 long old_lines, long new_from, long new_lines, long offset,
7211 const struct got_error *hunk_err)
7213 const char *path = new == NULL ? old : new;
7215 while (*path == '/')
7216 path++;
7218 if (status != 0)
7219 printf("%c %s\n", status, path);
7221 if (error != NULL)
7222 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7224 if (offset != 0 || hunk_err != NULL) {
7225 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7226 old_lines, new_from, new_lines);
7227 if (hunk_err != NULL)
7228 printf("%s\n", hunk_err->msg);
7229 else
7230 printf("applied with offset %ld\n", offset);
7233 return NULL;
7236 static const struct got_error *
7237 cmd_patch(int argc, char *argv[])
7239 const struct got_error *error = NULL, *close_error = NULL;
7240 struct got_worktree *worktree = NULL;
7241 struct got_repository *repo = NULL;
7242 const char *errstr;
7243 char *cwd = NULL;
7244 int ch, nop = 0, strip = -1;
7245 int patchfd;
7247 while ((ch = getopt(argc, argv, "np:")) != -1) {
7248 switch (ch) {
7249 case 'n':
7250 nop = 1;
7251 break;
7252 case 'p':
7253 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7254 if (errstr != NULL)
7255 errx(1, "pathname strip count is %s: %s",
7256 errstr, optarg);
7257 break;
7258 default:
7259 usage_patch();
7260 /* NOTREACHED */
7264 argc -= optind;
7265 argv += optind;
7267 if (argc == 0) {
7268 error = patch_from_stdin(&patchfd);
7269 if (error)
7270 return error;
7271 } else if (argc == 1) {
7272 patchfd = open(argv[0], O_RDONLY);
7273 if (patchfd == -1) {
7274 error = got_error_from_errno2("open", argv[0]);
7275 return error;
7277 } else
7278 usage_patch();
7280 if ((cwd = getcwd(NULL, 0)) == NULL) {
7281 error = got_error_from_errno("getcwd");
7282 goto done;
7285 error = got_worktree_open(&worktree, cwd);
7286 if (error != NULL)
7287 goto done;
7289 const char *repo_path = got_worktree_get_repo_path(worktree);
7290 error = got_repo_open(&repo, repo_path, NULL);
7291 if (error != NULL)
7292 goto done;
7294 error = apply_unveil(got_repo_get_path(repo), 0,
7295 worktree ? got_worktree_get_root_path(worktree) : NULL);
7296 if (error != NULL)
7297 goto done;
7299 #ifndef PROFILE
7300 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7301 NULL) == -1)
7302 err(1, "pledge");
7303 #endif
7305 error = got_patch(patchfd, worktree, repo, nop, strip,
7306 &patch_progress, NULL, check_cancelled, NULL);
7308 done:
7309 if (repo) {
7310 close_error = got_repo_close(repo);
7311 if (error == NULL)
7312 error = close_error;
7314 if (worktree != NULL) {
7315 close_error = got_worktree_close(worktree);
7316 if (error == NULL)
7317 error = close_error;
7319 free(cwd);
7320 return error;
7323 __dead static void
7324 usage_revert(void)
7326 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7327 "path ...\n", getprogname());
7328 exit(1);
7331 static const struct got_error *
7332 revert_progress(void *arg, unsigned char status, const char *path)
7334 if (status == GOT_STATUS_UNVERSIONED)
7335 return NULL;
7337 while (path[0] == '/')
7338 path++;
7339 printf("%c %s\n", status, path);
7340 return NULL;
7343 struct choose_patch_arg {
7344 FILE *patch_script_file;
7345 const char *action;
7348 static const struct got_error *
7349 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7350 int nchanges, const char *action)
7352 char *line = NULL;
7353 size_t linesize = 0;
7354 ssize_t linelen;
7356 switch (status) {
7357 case GOT_STATUS_ADD:
7358 printf("A %s\n%s this addition? [y/n] ", path, action);
7359 break;
7360 case GOT_STATUS_DELETE:
7361 printf("D %s\n%s this deletion? [y/n] ", path, action);
7362 break;
7363 case GOT_STATUS_MODIFY:
7364 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7365 return got_error_from_errno("fseek");
7366 printf(GOT_COMMIT_SEP_STR);
7367 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7368 printf("%s", line);
7369 if (ferror(patch_file))
7370 return got_error_from_errno("getline");
7371 printf(GOT_COMMIT_SEP_STR);
7372 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7373 path, n, nchanges, action);
7374 break;
7375 default:
7376 return got_error_path(path, GOT_ERR_FILE_STATUS);
7379 return NULL;
7382 static const struct got_error *
7383 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7384 FILE *patch_file, int n, int nchanges)
7386 const struct got_error *err = NULL;
7387 char *line = NULL;
7388 size_t linesize = 0;
7389 ssize_t linelen;
7390 int resp = ' ';
7391 struct choose_patch_arg *a = arg;
7393 *choice = GOT_PATCH_CHOICE_NONE;
7395 if (a->patch_script_file) {
7396 char *nl;
7397 err = show_change(status, path, patch_file, n, nchanges,
7398 a->action);
7399 if (err)
7400 return err;
7401 linelen = getline(&line, &linesize, a->patch_script_file);
7402 if (linelen == -1) {
7403 if (ferror(a->patch_script_file))
7404 return got_error_from_errno("getline");
7405 return NULL;
7407 nl = strchr(line, '\n');
7408 if (nl)
7409 *nl = '\0';
7410 if (strcmp(line, "y") == 0) {
7411 *choice = GOT_PATCH_CHOICE_YES;
7412 printf("y\n");
7413 } else if (strcmp(line, "n") == 0) {
7414 *choice = GOT_PATCH_CHOICE_NO;
7415 printf("n\n");
7416 } else if (strcmp(line, "q") == 0 &&
7417 status == GOT_STATUS_MODIFY) {
7418 *choice = GOT_PATCH_CHOICE_QUIT;
7419 printf("q\n");
7420 } else
7421 printf("invalid response '%s'\n", line);
7422 free(line);
7423 return NULL;
7426 while (resp != 'y' && resp != 'n' && resp != 'q') {
7427 err = show_change(status, path, patch_file, n, nchanges,
7428 a->action);
7429 if (err)
7430 return err;
7431 resp = getchar();
7432 if (resp == '\n')
7433 resp = getchar();
7434 if (status == GOT_STATUS_MODIFY) {
7435 if (resp != 'y' && resp != 'n' && resp != 'q') {
7436 printf("invalid response '%c'\n", resp);
7437 resp = ' ';
7439 } else if (resp != 'y' && resp != 'n') {
7440 printf("invalid response '%c'\n", resp);
7441 resp = ' ';
7445 if (resp == 'y')
7446 *choice = GOT_PATCH_CHOICE_YES;
7447 else if (resp == 'n')
7448 *choice = GOT_PATCH_CHOICE_NO;
7449 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7450 *choice = GOT_PATCH_CHOICE_QUIT;
7452 return NULL;
7455 static const struct got_error *
7456 cmd_revert(int argc, char *argv[])
7458 const struct got_error *error = NULL;
7459 struct got_worktree *worktree = NULL;
7460 struct got_repository *repo = NULL;
7461 char *cwd = NULL, *path = NULL;
7462 struct got_pathlist_head paths;
7463 struct got_pathlist_entry *pe;
7464 int ch, can_recurse = 0, pflag = 0;
7465 FILE *patch_script_file = NULL;
7466 const char *patch_script_path = NULL;
7467 struct choose_patch_arg cpa;
7469 TAILQ_INIT(&paths);
7471 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7472 switch (ch) {
7473 case 'p':
7474 pflag = 1;
7475 break;
7476 case 'F':
7477 patch_script_path = optarg;
7478 break;
7479 case 'R':
7480 can_recurse = 1;
7481 break;
7482 default:
7483 usage_revert();
7484 /* NOTREACHED */
7488 argc -= optind;
7489 argv += optind;
7491 #ifndef PROFILE
7492 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7493 "unveil", NULL) == -1)
7494 err(1, "pledge");
7495 #endif
7496 if (argc < 1)
7497 usage_revert();
7498 if (patch_script_path && !pflag)
7499 errx(1, "-F option can only be used together with -p option");
7501 cwd = getcwd(NULL, 0);
7502 if (cwd == NULL) {
7503 error = got_error_from_errno("getcwd");
7504 goto done;
7506 error = got_worktree_open(&worktree, cwd);
7507 if (error) {
7508 if (error->code == GOT_ERR_NOT_WORKTREE)
7509 error = wrap_not_worktree_error(error, "revert", cwd);
7510 goto done;
7513 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7514 NULL);
7515 if (error != NULL)
7516 goto done;
7518 if (patch_script_path) {
7519 patch_script_file = fopen(patch_script_path, "re");
7520 if (patch_script_file == NULL) {
7521 error = got_error_from_errno2("fopen",
7522 patch_script_path);
7523 goto done;
7526 error = apply_unveil(got_repo_get_path(repo), 1,
7527 got_worktree_get_root_path(worktree));
7528 if (error)
7529 goto done;
7531 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7532 if (error)
7533 goto done;
7535 if (!can_recurse) {
7536 char *ondisk_path;
7537 struct stat sb;
7538 TAILQ_FOREACH(pe, &paths, entry) {
7539 if (asprintf(&ondisk_path, "%s/%s",
7540 got_worktree_get_root_path(worktree),
7541 pe->path) == -1) {
7542 error = got_error_from_errno("asprintf");
7543 goto done;
7545 if (lstat(ondisk_path, &sb) == -1) {
7546 if (errno == ENOENT) {
7547 free(ondisk_path);
7548 continue;
7550 error = got_error_from_errno2("lstat",
7551 ondisk_path);
7552 free(ondisk_path);
7553 goto done;
7555 free(ondisk_path);
7556 if (S_ISDIR(sb.st_mode)) {
7557 error = got_error_msg(GOT_ERR_BAD_PATH,
7558 "reverting directories requires -R option");
7559 goto done;
7564 cpa.patch_script_file = patch_script_file;
7565 cpa.action = "revert";
7566 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7567 pflag ? choose_patch : NULL, &cpa, repo);
7568 done:
7569 if (patch_script_file && fclose(patch_script_file) == EOF &&
7570 error == NULL)
7571 error = got_error_from_errno2("fclose", patch_script_path);
7572 if (repo) {
7573 const struct got_error *close_err = got_repo_close(repo);
7574 if (error == NULL)
7575 error = close_err;
7577 if (worktree)
7578 got_worktree_close(worktree);
7579 free(path);
7580 free(cwd);
7581 return error;
7584 __dead static void
7585 usage_commit(void)
7587 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7588 "[path ...]\n", getprogname());
7589 exit(1);
7592 struct collect_commit_logmsg_arg {
7593 const char *cmdline_log;
7594 const char *prepared_log;
7595 int non_interactive;
7596 const char *editor;
7597 const char *worktree_path;
7598 const char *branch_name;
7599 const char *repo_path;
7600 char *logmsg_path;
7604 static const struct got_error *
7605 read_prepared_logmsg(char **logmsg, const char *path)
7607 const struct got_error *err = NULL;
7608 FILE *f = NULL;
7609 struct stat sb;
7610 size_t r;
7612 *logmsg = NULL;
7613 memset(&sb, 0, sizeof(sb));
7615 f = fopen(path, "re");
7616 if (f == NULL)
7617 return got_error_from_errno2("fopen", path);
7619 if (fstat(fileno(f), &sb) == -1) {
7620 err = got_error_from_errno2("fstat", path);
7621 goto done;
7623 if (sb.st_size == 0) {
7624 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7625 goto done;
7628 *logmsg = malloc(sb.st_size + 1);
7629 if (*logmsg == NULL) {
7630 err = got_error_from_errno("malloc");
7631 goto done;
7634 r = fread(*logmsg, 1, sb.st_size, f);
7635 if (r != sb.st_size) {
7636 if (ferror(f))
7637 err = got_error_from_errno2("fread", path);
7638 else
7639 err = got_error(GOT_ERR_IO);
7640 goto done;
7642 (*logmsg)[sb.st_size] = '\0';
7643 done:
7644 if (fclose(f) == EOF && err == NULL)
7645 err = got_error_from_errno2("fclose", path);
7646 if (err) {
7647 free(*logmsg);
7648 *logmsg = NULL;
7650 return err;
7654 static const struct got_error *
7655 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7656 void *arg)
7658 char *initial_content = NULL;
7659 struct got_pathlist_entry *pe;
7660 const struct got_error *err = NULL;
7661 char *template = NULL;
7662 struct collect_commit_logmsg_arg *a = arg;
7663 int initial_content_len;
7664 int fd = -1;
7665 size_t len;
7667 /* if a message was specified on the command line, just use it */
7668 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7669 len = strlen(a->cmdline_log) + 1;
7670 *logmsg = malloc(len + 1);
7671 if (*logmsg == NULL)
7672 return got_error_from_errno("malloc");
7673 strlcpy(*logmsg, a->cmdline_log, len);
7674 return NULL;
7675 } else if (a->prepared_log != NULL && a->non_interactive)
7676 return read_prepared_logmsg(logmsg, a->prepared_log);
7678 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7679 return got_error_from_errno("asprintf");
7681 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7682 if (err)
7683 goto done;
7685 if (a->prepared_log) {
7686 char *msg;
7687 err = read_prepared_logmsg(&msg, a->prepared_log);
7688 if (err)
7689 goto done;
7690 if (write(fd, msg, strlen(msg)) == -1) {
7691 err = got_error_from_errno2("write", a->logmsg_path);
7692 free(msg);
7693 goto done;
7695 free(msg);
7698 initial_content_len = asprintf(&initial_content,
7699 "\n# changes to be committed on branch %s:\n",
7700 a->branch_name);
7701 if (initial_content_len == -1) {
7702 err = got_error_from_errno("asprintf");
7703 goto done;
7706 if (write(fd, initial_content, initial_content_len) == -1) {
7707 err = got_error_from_errno2("write", a->logmsg_path);
7708 goto done;
7711 TAILQ_FOREACH(pe, commitable_paths, entry) {
7712 struct got_commitable *ct = pe->data;
7713 dprintf(fd, "# %c %s\n",
7714 got_commitable_get_status(ct),
7715 got_commitable_get_path(ct));
7718 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7719 initial_content_len, a->prepared_log ? 0 : 1);
7720 done:
7721 free(initial_content);
7722 free(template);
7724 if (fd != -1 && close(fd) == -1 && err == NULL)
7725 err = got_error_from_errno2("close", a->logmsg_path);
7727 /* Editor is done; we can now apply unveil(2) */
7728 if (err == NULL)
7729 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7730 if (err) {
7731 free(*logmsg);
7732 *logmsg = NULL;
7734 return err;
7737 static const struct got_error *
7738 cmd_commit(int argc, char *argv[])
7740 const struct got_error *error = NULL;
7741 struct got_worktree *worktree = NULL;
7742 struct got_repository *repo = NULL;
7743 char *cwd = NULL, *id_str = NULL;
7744 struct got_object_id *id = NULL;
7745 const char *logmsg = NULL;
7746 char *prepared_logmsg = NULL;
7747 struct collect_commit_logmsg_arg cl_arg;
7748 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7749 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7750 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7751 struct got_pathlist_head paths;
7753 TAILQ_INIT(&paths);
7754 cl_arg.logmsg_path = NULL;
7756 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7757 switch (ch) {
7758 case 'F':
7759 if (logmsg != NULL)
7760 option_conflict('F', 'm');
7761 prepared_logmsg = realpath(optarg, NULL);
7762 if (prepared_logmsg == NULL)
7763 return got_error_from_errno2("realpath",
7764 optarg);
7765 break;
7766 case 'm':
7767 if (prepared_logmsg)
7768 option_conflict('m', 'F');
7769 logmsg = optarg;
7770 break;
7771 case 'N':
7772 non_interactive = 1;
7773 break;
7774 case 'S':
7775 allow_bad_symlinks = 1;
7776 break;
7777 default:
7778 usage_commit();
7779 /* NOTREACHED */
7783 argc -= optind;
7784 argv += optind;
7786 #ifndef PROFILE
7787 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7788 "unveil", NULL) == -1)
7789 err(1, "pledge");
7790 #endif
7791 cwd = getcwd(NULL, 0);
7792 if (cwd == NULL) {
7793 error = got_error_from_errno("getcwd");
7794 goto done;
7796 error = got_worktree_open(&worktree, cwd);
7797 if (error) {
7798 if (error->code == GOT_ERR_NOT_WORKTREE)
7799 error = wrap_not_worktree_error(error, "commit", cwd);
7800 goto done;
7803 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7804 if (error)
7805 goto done;
7806 if (rebase_in_progress) {
7807 error = got_error(GOT_ERR_REBASING);
7808 goto done;
7811 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7812 worktree);
7813 if (error)
7814 goto done;
7816 error = get_gitconfig_path(&gitconfig_path);
7817 if (error)
7818 goto done;
7819 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7820 gitconfig_path);
7821 if (error != NULL)
7822 goto done;
7824 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7825 if (error)
7826 goto done;
7827 if (merge_in_progress) {
7828 error = got_error(GOT_ERR_MERGE_BUSY);
7829 goto done;
7832 error = get_author(&author, repo, worktree);
7833 if (error)
7834 return error;
7837 * unveil(2) traverses exec(2); if an editor is used we have
7838 * to apply unveil after the log message has been written.
7840 if (logmsg == NULL || strlen(logmsg) == 0)
7841 error = get_editor(&editor);
7842 else
7843 error = apply_unveil(got_repo_get_path(repo), 0,
7844 got_worktree_get_root_path(worktree));
7845 if (error)
7846 goto done;
7848 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7849 if (error)
7850 goto done;
7852 cl_arg.editor = editor;
7853 cl_arg.cmdline_log = logmsg;
7854 cl_arg.prepared_log = prepared_logmsg;
7855 cl_arg.non_interactive = non_interactive;
7856 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7857 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7858 if (!histedit_in_progress) {
7859 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7860 error = got_error(GOT_ERR_COMMIT_BRANCH);
7861 goto done;
7863 cl_arg.branch_name += 11;
7865 cl_arg.repo_path = got_repo_get_path(repo);
7866 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7867 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7868 print_status, NULL, repo);
7869 if (error) {
7870 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7871 cl_arg.logmsg_path != NULL)
7872 preserve_logmsg = 1;
7873 goto done;
7876 error = got_object_id_str(&id_str, id);
7877 if (error)
7878 goto done;
7879 printf("Created commit %s\n", id_str);
7880 done:
7881 if (preserve_logmsg) {
7882 fprintf(stderr, "%s: log message preserved in %s\n",
7883 getprogname(), cl_arg.logmsg_path);
7884 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7885 error == NULL)
7886 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7887 free(cl_arg.logmsg_path);
7888 if (repo) {
7889 const struct got_error *close_err = got_repo_close(repo);
7890 if (error == NULL)
7891 error = close_err;
7893 if (worktree)
7894 got_worktree_close(worktree);
7895 free(cwd);
7896 free(id_str);
7897 free(gitconfig_path);
7898 free(editor);
7899 free(author);
7900 free(prepared_logmsg);
7901 return error;
7904 __dead static void
7905 usage_send(void)
7907 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7908 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7909 "[remote-repository]\n", getprogname());
7910 exit(1);
7913 static void
7914 print_load_info(int print_colored, int print_found, int print_trees,
7915 int ncolored, int nfound, int ntrees)
7917 if (print_colored) {
7918 printf("%d commit%s colored", ncolored,
7919 ncolored == 1 ? "" : "s");
7921 if (print_found) {
7922 printf("%s%d object%s found",
7923 ncolored > 0 ? "; " : "",
7924 nfound, nfound == 1 ? "" : "s");
7926 if (print_trees) {
7927 printf("; %d tree%s scanned", ntrees,
7928 ntrees == 1 ? "" : "s");
7932 struct got_send_progress_arg {
7933 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7934 int verbosity;
7935 int last_ncolored;
7936 int last_nfound;
7937 int last_ntrees;
7938 int loading_done;
7939 int last_ncommits;
7940 int last_nobj_total;
7941 int last_p_deltify;
7942 int last_p_written;
7943 int last_p_sent;
7944 int printed_something;
7945 int sent_something;
7946 struct got_pathlist_head *delete_branches;
7949 static const struct got_error *
7950 send_progress(void *arg, int ncolored, int nfound, int ntrees,
7951 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
7952 int nobj_written, off_t bytes_sent, const char *refname, int success)
7954 struct got_send_progress_arg *a = arg;
7955 char scaled_packsize[FMT_SCALED_STRSIZE];
7956 char scaled_sent[FMT_SCALED_STRSIZE];
7957 int p_deltify = 0, p_written = 0, p_sent = 0;
7958 int print_colored = 0, print_found = 0, print_trees = 0;
7959 int print_searching = 0, print_total = 0;
7960 int print_deltify = 0, print_written = 0, print_sent = 0;
7962 if (a->verbosity < 0)
7963 return NULL;
7965 if (refname) {
7966 const char *status = success ? "accepted" : "rejected";
7968 if (success) {
7969 struct got_pathlist_entry *pe;
7970 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7971 const char *branchname = pe->path;
7972 if (got_path_cmp(branchname, refname,
7973 strlen(branchname), strlen(refname)) == 0) {
7974 status = "deleted";
7975 a->sent_something = 1;
7976 break;
7981 if (a->printed_something)
7982 putchar('\n');
7983 printf("Server has %s %s", status, refname);
7984 a->printed_something = 1;
7985 return NULL;
7988 if (a->last_ncolored != ncolored) {
7989 print_colored = 1;
7990 a->last_ncolored = ncolored;
7993 if (a->last_nfound != nfound) {
7994 print_colored = 1;
7995 print_found = 1;
7996 a->last_nfound = nfound;
7999 if (a->last_ntrees != ntrees) {
8000 print_colored = 1;
8001 print_found = 1;
8002 print_trees = 1;
8003 a->last_ntrees = ntrees;
8006 if ((print_colored || print_found || print_trees) &&
8007 !a->loading_done) {
8008 printf("\r");
8009 print_load_info(print_colored, print_found, print_trees,
8010 ncolored, nfound, ntrees);
8011 a->printed_something = 1;
8012 fflush(stdout);
8013 return NULL;
8014 } else if (!a->loading_done) {
8015 printf("\r");
8016 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8017 printf("\n");
8018 a->loading_done = 1;
8021 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8022 return got_error_from_errno("fmt_scaled");
8023 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8024 return got_error_from_errno("fmt_scaled");
8026 if (a->last_ncommits != ncommits) {
8027 print_searching = 1;
8028 a->last_ncommits = ncommits;
8031 if (a->last_nobj_total != nobj_total) {
8032 print_searching = 1;
8033 print_total = 1;
8034 a->last_nobj_total = nobj_total;
8037 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8038 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8039 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8040 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8041 return got_error(GOT_ERR_NO_SPACE);
8044 if (nobj_deltify > 0 || nobj_written > 0) {
8045 if (nobj_deltify > 0) {
8046 p_deltify = (nobj_deltify * 100) / nobj_total;
8047 if (p_deltify != a->last_p_deltify) {
8048 a->last_p_deltify = p_deltify;
8049 print_searching = 1;
8050 print_total = 1;
8051 print_deltify = 1;
8054 if (nobj_written > 0) {
8055 p_written = (nobj_written * 100) / nobj_total;
8056 if (p_written != a->last_p_written) {
8057 a->last_p_written = p_written;
8058 print_searching = 1;
8059 print_total = 1;
8060 print_deltify = 1;
8061 print_written = 1;
8066 if (bytes_sent > 0) {
8067 p_sent = (bytes_sent * 100) / packfile_size;
8068 if (p_sent != a->last_p_sent) {
8069 a->last_p_sent = p_sent;
8070 print_searching = 1;
8071 print_total = 1;
8072 print_deltify = 1;
8073 print_written = 1;
8074 print_sent = 1;
8076 a->sent_something = 1;
8079 if (print_searching || print_total || print_deltify || print_written ||
8080 print_sent)
8081 printf("\r");
8082 if (print_searching)
8083 printf("packing %d reference%s", ncommits,
8084 ncommits == 1 ? "" : "s");
8085 if (print_total)
8086 printf("; %d object%s", nobj_total,
8087 nobj_total == 1 ? "" : "s");
8088 if (print_deltify)
8089 printf("; deltify: %d%%", p_deltify);
8090 if (print_sent)
8091 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8092 scaled_packsize, p_sent);
8093 else if (print_written)
8094 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8095 scaled_packsize, p_written);
8096 if (print_searching || print_total || print_deltify ||
8097 print_written || print_sent) {
8098 a->printed_something = 1;
8099 fflush(stdout);
8101 return NULL;
8104 static const struct got_error *
8105 cmd_send(int argc, char *argv[])
8107 const struct got_error *error = NULL;
8108 char *cwd = NULL, *repo_path = NULL;
8109 const char *remote_name;
8110 char *proto = NULL, *host = NULL, *port = NULL;
8111 char *repo_name = NULL, *server_path = NULL;
8112 const struct got_remote_repo *remotes, *remote = NULL;
8113 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8114 struct got_repository *repo = NULL;
8115 struct got_worktree *worktree = NULL;
8116 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8117 struct got_pathlist_head branches;
8118 struct got_pathlist_head tags;
8119 struct got_reflist_head all_branches;
8120 struct got_reflist_head all_tags;
8121 struct got_pathlist_head delete_args;
8122 struct got_pathlist_head delete_branches;
8123 struct got_reflist_entry *re;
8124 struct got_pathlist_entry *pe;
8125 int i, ch, sendfd = -1, sendstatus;
8126 pid_t sendpid = -1;
8127 struct got_send_progress_arg spa;
8128 int verbosity = 0, overwrite_refs = 0;
8129 int send_all_branches = 0, send_all_tags = 0;
8130 struct got_reference *ref = NULL;
8132 TAILQ_INIT(&branches);
8133 TAILQ_INIT(&tags);
8134 TAILQ_INIT(&all_branches);
8135 TAILQ_INIT(&all_tags);
8136 TAILQ_INIT(&delete_args);
8137 TAILQ_INIT(&delete_branches);
8139 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8140 switch (ch) {
8141 case 'a':
8142 send_all_branches = 1;
8143 break;
8144 case 'b':
8145 error = got_pathlist_append(&branches, optarg, NULL);
8146 if (error)
8147 return error;
8148 nbranches++;
8149 break;
8150 case 'd':
8151 error = got_pathlist_append(&delete_args, optarg, NULL);
8152 if (error)
8153 return error;
8154 break;
8155 case 'f':
8156 overwrite_refs = 1;
8157 break;
8158 case 'r':
8159 repo_path = realpath(optarg, NULL);
8160 if (repo_path == NULL)
8161 return got_error_from_errno2("realpath",
8162 optarg);
8163 got_path_strip_trailing_slashes(repo_path);
8164 break;
8165 case 't':
8166 error = got_pathlist_append(&tags, optarg, NULL);
8167 if (error)
8168 return error;
8169 ntags++;
8170 break;
8171 case 'T':
8172 send_all_tags = 1;
8173 break;
8174 case 'v':
8175 if (verbosity < 0)
8176 verbosity = 0;
8177 else if (verbosity < 3)
8178 verbosity++;
8179 break;
8180 case 'q':
8181 verbosity = -1;
8182 break;
8183 default:
8184 usage_send();
8185 /* NOTREACHED */
8188 argc -= optind;
8189 argv += optind;
8191 if (send_all_branches && !TAILQ_EMPTY(&branches))
8192 option_conflict('a', 'b');
8193 if (send_all_tags && !TAILQ_EMPTY(&tags))
8194 option_conflict('T', 't');
8197 if (argc == 0)
8198 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8199 else if (argc == 1)
8200 remote_name = argv[0];
8201 else
8202 usage_send();
8204 cwd = getcwd(NULL, 0);
8205 if (cwd == NULL) {
8206 error = got_error_from_errno("getcwd");
8207 goto done;
8210 if (repo_path == NULL) {
8211 error = got_worktree_open(&worktree, cwd);
8212 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8213 goto done;
8214 else
8215 error = NULL;
8216 if (worktree) {
8217 repo_path =
8218 strdup(got_worktree_get_repo_path(worktree));
8219 if (repo_path == NULL)
8220 error = got_error_from_errno("strdup");
8221 if (error)
8222 goto done;
8223 } else {
8224 repo_path = strdup(cwd);
8225 if (repo_path == NULL) {
8226 error = got_error_from_errno("strdup");
8227 goto done;
8232 error = got_repo_open(&repo, repo_path, NULL);
8233 if (error)
8234 goto done;
8236 if (worktree) {
8237 worktree_conf = got_worktree_get_gotconfig(worktree);
8238 if (worktree_conf) {
8239 got_gotconfig_get_remotes(&nremotes, &remotes,
8240 worktree_conf);
8241 for (i = 0; i < nremotes; i++) {
8242 if (strcmp(remotes[i].name, remote_name) == 0) {
8243 remote = &remotes[i];
8244 break;
8249 if (remote == NULL) {
8250 repo_conf = got_repo_get_gotconfig(repo);
8251 if (repo_conf) {
8252 got_gotconfig_get_remotes(&nremotes, &remotes,
8253 repo_conf);
8254 for (i = 0; i < nremotes; i++) {
8255 if (strcmp(remotes[i].name, remote_name) == 0) {
8256 remote = &remotes[i];
8257 break;
8262 if (remote == NULL) {
8263 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8264 for (i = 0; i < nremotes; i++) {
8265 if (strcmp(remotes[i].name, remote_name) == 0) {
8266 remote = &remotes[i];
8267 break;
8271 if (remote == NULL) {
8272 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8273 goto done;
8276 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8277 &repo_name, remote->send_url);
8278 if (error)
8279 goto done;
8281 if (strcmp(proto, "git") == 0) {
8282 #ifndef PROFILE
8283 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8284 "sendfd dns inet unveil", NULL) == -1)
8285 err(1, "pledge");
8286 #endif
8287 } else if (strcmp(proto, "git+ssh") == 0 ||
8288 strcmp(proto, "ssh") == 0) {
8289 #ifndef PROFILE
8290 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8291 "sendfd unveil", NULL) == -1)
8292 err(1, "pledge");
8293 #endif
8294 } else if (strcmp(proto, "http") == 0 ||
8295 strcmp(proto, "git+http") == 0) {
8296 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8297 goto done;
8298 } else {
8299 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8300 goto done;
8303 error = got_dial_apply_unveil(proto);
8304 if (error)
8305 goto done;
8307 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8308 if (error)
8309 goto done;
8311 if (send_all_branches) {
8312 error = got_ref_list(&all_branches, repo, "refs/heads",
8313 got_ref_cmp_by_name, NULL);
8314 if (error)
8315 goto done;
8316 TAILQ_FOREACH(re, &all_branches, entry) {
8317 const char *branchname = got_ref_get_name(re->ref);
8318 error = got_pathlist_append(&branches,
8319 branchname, NULL);
8320 if (error)
8321 goto done;
8322 nbranches++;
8324 } else if (nbranches == 0) {
8325 for (i = 0; i < remote->nsend_branches; i++) {
8326 got_pathlist_append(&branches,
8327 remote->send_branches[i], NULL);
8331 if (send_all_tags) {
8332 error = got_ref_list(&all_tags, repo, "refs/tags",
8333 got_ref_cmp_by_name, NULL);
8334 if (error)
8335 goto done;
8336 TAILQ_FOREACH(re, &all_tags, entry) {
8337 const char *tagname = got_ref_get_name(re->ref);
8338 error = got_pathlist_append(&tags,
8339 tagname, NULL);
8340 if (error)
8341 goto done;
8342 ntags++;
8347 * To prevent accidents only branches in refs/heads/ can be deleted
8348 * with 'got send -d'.
8349 * Deleting anything else requires local repository access or Git.
8351 TAILQ_FOREACH(pe, &delete_args, entry) {
8352 const char *branchname = pe->path;
8353 char *s;
8354 struct got_pathlist_entry *new;
8355 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8356 s = strdup(branchname);
8357 if (s == NULL) {
8358 error = got_error_from_errno("strdup");
8359 goto done;
8361 } else {
8362 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8363 error = got_error_from_errno("asprintf");
8364 goto done;
8367 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8368 if (error || new == NULL /* duplicate */)
8369 free(s);
8370 if (error)
8371 goto done;
8372 ndelete_branches++;
8375 if (nbranches == 0 && ndelete_branches == 0) {
8376 struct got_reference *head_ref;
8377 if (worktree)
8378 error = got_ref_open(&head_ref, repo,
8379 got_worktree_get_head_ref_name(worktree), 0);
8380 else
8381 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8382 if (error)
8383 goto done;
8384 if (got_ref_is_symbolic(head_ref)) {
8385 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8386 got_ref_close(head_ref);
8387 if (error)
8388 goto done;
8389 } else
8390 ref = head_ref;
8391 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8392 NULL);
8393 if (error)
8394 goto done;
8395 nbranches++;
8398 if (verbosity >= 0)
8399 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8400 port ? ":" : "", port ? port : "");
8402 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8403 server_path, verbosity);
8404 if (error)
8405 goto done;
8407 memset(&spa, 0, sizeof(spa));
8408 spa.last_scaled_packsize[0] = '\0';
8409 spa.last_p_deltify = -1;
8410 spa.last_p_written = -1;
8411 spa.verbosity = verbosity;
8412 spa.delete_branches = &delete_branches;
8413 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8414 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8415 check_cancelled, NULL);
8416 if (spa.printed_something)
8417 putchar('\n');
8418 if (error)
8419 goto done;
8420 if (!spa.sent_something && verbosity >= 0)
8421 printf("Already up-to-date\n");
8422 done:
8423 if (sendpid > 0) {
8424 if (kill(sendpid, SIGTERM) == -1)
8425 error = got_error_from_errno("kill");
8426 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8427 error = got_error_from_errno("waitpid");
8429 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8430 error = got_error_from_errno("close");
8431 if (repo) {
8432 const struct got_error *close_err = got_repo_close(repo);
8433 if (error == NULL)
8434 error = close_err;
8436 if (worktree)
8437 got_worktree_close(worktree);
8438 if (ref)
8439 got_ref_close(ref);
8440 got_pathlist_free(&branches);
8441 got_pathlist_free(&tags);
8442 got_ref_list_free(&all_branches);
8443 got_ref_list_free(&all_tags);
8444 got_pathlist_free(&delete_args);
8445 TAILQ_FOREACH(pe, &delete_branches, entry)
8446 free((char *)pe->path);
8447 got_pathlist_free(&delete_branches);
8448 free(cwd);
8449 free(repo_path);
8450 free(proto);
8451 free(host);
8452 free(port);
8453 free(server_path);
8454 free(repo_name);
8455 return error;
8458 __dead static void
8459 usage_cherrypick(void)
8461 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8462 exit(1);
8465 static const struct got_error *
8466 cmd_cherrypick(int argc, char *argv[])
8468 const struct got_error *error = NULL;
8469 struct got_worktree *worktree = NULL;
8470 struct got_repository *repo = NULL;
8471 char *cwd = NULL, *commit_id_str = NULL;
8472 struct got_object_id *commit_id = NULL;
8473 struct got_commit_object *commit = NULL;
8474 struct got_object_qid *pid;
8475 int ch;
8476 struct got_update_progress_arg upa;
8478 while ((ch = getopt(argc, argv, "")) != -1) {
8479 switch (ch) {
8480 default:
8481 usage_cherrypick();
8482 /* NOTREACHED */
8486 argc -= optind;
8487 argv += optind;
8489 #ifndef PROFILE
8490 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8491 "unveil", NULL) == -1)
8492 err(1, "pledge");
8493 #endif
8494 if (argc != 1)
8495 usage_cherrypick();
8497 cwd = getcwd(NULL, 0);
8498 if (cwd == NULL) {
8499 error = got_error_from_errno("getcwd");
8500 goto done;
8502 error = got_worktree_open(&worktree, cwd);
8503 if (error) {
8504 if (error->code == GOT_ERR_NOT_WORKTREE)
8505 error = wrap_not_worktree_error(error, "cherrypick",
8506 cwd);
8507 goto done;
8510 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8511 NULL);
8512 if (error != NULL)
8513 goto done;
8515 error = apply_unveil(got_repo_get_path(repo), 0,
8516 got_worktree_get_root_path(worktree));
8517 if (error)
8518 goto done;
8520 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8521 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8522 if (error)
8523 goto done;
8524 error = got_object_id_str(&commit_id_str, commit_id);
8525 if (error)
8526 goto done;
8528 error = got_object_open_as_commit(&commit, repo, commit_id);
8529 if (error)
8530 goto done;
8531 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8532 memset(&upa, 0, sizeof(upa));
8533 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8534 commit_id, repo, update_progress, &upa, check_cancelled,
8535 NULL);
8536 if (error != NULL)
8537 goto done;
8539 if (upa.did_something)
8540 printf("Merged commit %s\n", commit_id_str);
8541 print_merge_progress_stats(&upa);
8542 done:
8543 if (commit)
8544 got_object_commit_close(commit);
8545 free(commit_id_str);
8546 if (worktree)
8547 got_worktree_close(worktree);
8548 if (repo) {
8549 const struct got_error *close_err = got_repo_close(repo);
8550 if (error == NULL)
8551 error = close_err;
8553 return error;
8556 __dead static void
8557 usage_backout(void)
8559 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8560 exit(1);
8563 static const struct got_error *
8564 cmd_backout(int argc, char *argv[])
8566 const struct got_error *error = NULL;
8567 struct got_worktree *worktree = NULL;
8568 struct got_repository *repo = NULL;
8569 char *cwd = NULL, *commit_id_str = NULL;
8570 struct got_object_id *commit_id = NULL;
8571 struct got_commit_object *commit = NULL;
8572 struct got_object_qid *pid;
8573 int ch;
8574 struct got_update_progress_arg upa;
8576 while ((ch = getopt(argc, argv, "")) != -1) {
8577 switch (ch) {
8578 default:
8579 usage_backout();
8580 /* NOTREACHED */
8584 argc -= optind;
8585 argv += optind;
8587 #ifndef PROFILE
8588 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8589 "unveil", NULL) == -1)
8590 err(1, "pledge");
8591 #endif
8592 if (argc != 1)
8593 usage_backout();
8595 cwd = getcwd(NULL, 0);
8596 if (cwd == NULL) {
8597 error = got_error_from_errno("getcwd");
8598 goto done;
8600 error = got_worktree_open(&worktree, cwd);
8601 if (error) {
8602 if (error->code == GOT_ERR_NOT_WORKTREE)
8603 error = wrap_not_worktree_error(error, "backout", cwd);
8604 goto done;
8607 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8608 NULL);
8609 if (error != NULL)
8610 goto done;
8612 error = apply_unveil(got_repo_get_path(repo), 0,
8613 got_worktree_get_root_path(worktree));
8614 if (error)
8615 goto done;
8617 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8618 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8619 if (error)
8620 goto done;
8621 error = got_object_id_str(&commit_id_str, commit_id);
8622 if (error)
8623 goto done;
8625 error = got_object_open_as_commit(&commit, repo, commit_id);
8626 if (error)
8627 goto done;
8628 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8629 if (pid == NULL) {
8630 error = got_error(GOT_ERR_ROOT_COMMIT);
8631 goto done;
8634 memset(&upa, 0, sizeof(upa));
8635 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8636 repo, update_progress, &upa, check_cancelled, NULL);
8637 if (error != NULL)
8638 goto done;
8640 if (upa.did_something)
8641 printf("Backed out commit %s\n", commit_id_str);
8642 print_merge_progress_stats(&upa);
8643 done:
8644 if (commit)
8645 got_object_commit_close(commit);
8646 free(commit_id_str);
8647 if (worktree)
8648 got_worktree_close(worktree);
8649 if (repo) {
8650 const struct got_error *close_err = got_repo_close(repo);
8651 if (error == NULL)
8652 error = close_err;
8654 return error;
8657 __dead static void
8658 usage_rebase(void)
8660 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8661 getprogname());
8662 exit(1);
8665 void
8666 trim_logmsg(char *logmsg, int limit)
8668 char *nl;
8669 size_t len;
8671 len = strlen(logmsg);
8672 if (len > limit)
8673 len = limit;
8674 logmsg[len] = '\0';
8675 nl = strchr(logmsg, '\n');
8676 if (nl)
8677 *nl = '\0';
8680 static const struct got_error *
8681 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8683 const struct got_error *err;
8684 char *logmsg0 = NULL;
8685 const char *s;
8687 err = got_object_commit_get_logmsg(&logmsg0, commit);
8688 if (err)
8689 return err;
8691 s = logmsg0;
8692 while (isspace((unsigned char)s[0]))
8693 s++;
8695 *logmsg = strdup(s);
8696 if (*logmsg == NULL) {
8697 err = got_error_from_errno("strdup");
8698 goto done;
8701 trim_logmsg(*logmsg, limit);
8702 done:
8703 free(logmsg0);
8704 return err;
8707 static const struct got_error *
8708 show_rebase_merge_conflict(struct got_object_id *id,
8709 struct got_repository *repo)
8711 const struct got_error *err;
8712 struct got_commit_object *commit = NULL;
8713 char *id_str = NULL, *logmsg = NULL;
8715 err = got_object_open_as_commit(&commit, repo, id);
8716 if (err)
8717 return err;
8719 err = got_object_id_str(&id_str, id);
8720 if (err)
8721 goto done;
8723 id_str[12] = '\0';
8725 err = get_short_logmsg(&logmsg, 42, commit);
8726 if (err)
8727 goto done;
8729 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8730 done:
8731 free(id_str);
8732 got_object_commit_close(commit);
8733 free(logmsg);
8734 return err;
8737 static const struct got_error *
8738 show_rebase_progress(struct got_commit_object *commit,
8739 struct got_object_id *old_id, struct got_object_id *new_id)
8741 const struct got_error *err;
8742 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8744 err = got_object_id_str(&old_id_str, old_id);
8745 if (err)
8746 goto done;
8748 if (new_id) {
8749 err = got_object_id_str(&new_id_str, new_id);
8750 if (err)
8751 goto done;
8754 old_id_str[12] = '\0';
8755 if (new_id_str)
8756 new_id_str[12] = '\0';
8758 err = get_short_logmsg(&logmsg, 42, commit);
8759 if (err)
8760 goto done;
8762 printf("%s -> %s: %s\n", old_id_str,
8763 new_id_str ? new_id_str : "no-op change", logmsg);
8764 done:
8765 free(old_id_str);
8766 free(new_id_str);
8767 free(logmsg);
8768 return err;
8771 static const struct got_error *
8772 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8773 struct got_reference *branch, struct got_reference *new_base_branch,
8774 struct got_reference *tmp_branch, struct got_repository *repo,
8775 int create_backup)
8777 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8778 return got_worktree_rebase_complete(worktree, fileindex,
8779 new_base_branch, tmp_branch, branch, repo, create_backup);
8782 static const struct got_error *
8783 rebase_commit(struct got_pathlist_head *merged_paths,
8784 struct got_worktree *worktree, struct got_fileindex *fileindex,
8785 struct got_reference *tmp_branch,
8786 struct got_object_id *commit_id, struct got_repository *repo)
8788 const struct got_error *error;
8789 struct got_commit_object *commit;
8790 struct got_object_id *new_commit_id;
8792 error = got_object_open_as_commit(&commit, repo, commit_id);
8793 if (error)
8794 return error;
8796 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8797 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8798 if (error) {
8799 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8800 goto done;
8801 error = show_rebase_progress(commit, commit_id, NULL);
8802 } else {
8803 error = show_rebase_progress(commit, commit_id, new_commit_id);
8804 free(new_commit_id);
8806 done:
8807 got_object_commit_close(commit);
8808 return error;
8811 struct check_path_prefix_arg {
8812 const char *path_prefix;
8813 size_t len;
8814 int errcode;
8817 static const struct got_error *
8818 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8819 struct got_blob_object *blob2, struct got_object_id *id1,
8820 struct got_object_id *id2, const char *path1, const char *path2,
8821 mode_t mode1, mode_t mode2, struct got_repository *repo)
8823 struct check_path_prefix_arg *a = arg;
8825 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8826 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8827 return got_error(a->errcode);
8829 return NULL;
8832 static const struct got_error *
8833 check_path_prefix(struct got_object_id *parent_id,
8834 struct got_object_id *commit_id, const char *path_prefix,
8835 int errcode, struct got_repository *repo)
8837 const struct got_error *err;
8838 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8839 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8840 struct check_path_prefix_arg cpp_arg;
8842 if (got_path_is_root_dir(path_prefix))
8843 return NULL;
8845 err = got_object_open_as_commit(&commit, repo, commit_id);
8846 if (err)
8847 goto done;
8849 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8850 if (err)
8851 goto done;
8853 err = got_object_open_as_tree(&tree1, repo,
8854 got_object_commit_get_tree_id(parent_commit));
8855 if (err)
8856 goto done;
8858 err = got_object_open_as_tree(&tree2, repo,
8859 got_object_commit_get_tree_id(commit));
8860 if (err)
8861 goto done;
8863 cpp_arg.path_prefix = path_prefix;
8864 while (cpp_arg.path_prefix[0] == '/')
8865 cpp_arg.path_prefix++;
8866 cpp_arg.len = strlen(cpp_arg.path_prefix);
8867 cpp_arg.errcode = errcode;
8868 err = got_diff_tree(tree1, tree2, "", "", repo,
8869 check_path_prefix_in_diff, &cpp_arg, 0);
8870 done:
8871 if (tree1)
8872 got_object_tree_close(tree1);
8873 if (tree2)
8874 got_object_tree_close(tree2);
8875 if (commit)
8876 got_object_commit_close(commit);
8877 if (parent_commit)
8878 got_object_commit_close(parent_commit);
8879 return err;
8882 static const struct got_error *
8883 collect_commits(struct got_object_id_queue *commits,
8884 struct got_object_id *initial_commit_id,
8885 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8886 const char *path_prefix, int path_prefix_errcode,
8887 struct got_repository *repo)
8889 const struct got_error *err = NULL;
8890 struct got_commit_graph *graph = NULL;
8891 struct got_object_id *parent_id = NULL;
8892 struct got_object_qid *qid;
8893 struct got_object_id *commit_id = initial_commit_id;
8895 err = got_commit_graph_open(&graph, "/", 1);
8896 if (err)
8897 return err;
8899 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8900 check_cancelled, NULL);
8901 if (err)
8902 goto done;
8903 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8904 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8905 check_cancelled, NULL);
8906 if (err) {
8907 if (err->code == GOT_ERR_ITER_COMPLETED) {
8908 err = got_error_msg(GOT_ERR_ANCESTRY,
8909 "ran out of commits to rebase before "
8910 "youngest common ancestor commit has "
8911 "been reached?!?");
8913 goto done;
8914 } else {
8915 err = check_path_prefix(parent_id, commit_id,
8916 path_prefix, path_prefix_errcode, repo);
8917 if (err)
8918 goto done;
8920 err = got_object_qid_alloc(&qid, commit_id);
8921 if (err)
8922 goto done;
8923 STAILQ_INSERT_HEAD(commits, qid, entry);
8924 commit_id = parent_id;
8927 done:
8928 got_commit_graph_close(graph);
8929 return err;
8932 static const struct got_error *
8933 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8935 const struct got_error *err = NULL;
8936 time_t committer_time;
8937 struct tm tm;
8938 char datebuf[11]; /* YYYY-MM-DD + NUL */
8939 char *author0 = NULL, *author, *smallerthan;
8940 char *logmsg0 = NULL, *logmsg, *newline;
8942 committer_time = got_object_commit_get_committer_time(commit);
8943 if (gmtime_r(&committer_time, &tm) == NULL)
8944 return got_error_from_errno("gmtime_r");
8945 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8946 return got_error(GOT_ERR_NO_SPACE);
8948 author0 = strdup(got_object_commit_get_author(commit));
8949 if (author0 == NULL)
8950 return got_error_from_errno("strdup");
8951 author = author0;
8952 smallerthan = strchr(author, '<');
8953 if (smallerthan && smallerthan[1] != '\0')
8954 author = smallerthan + 1;
8955 author[strcspn(author, "@>")] = '\0';
8957 err = got_object_commit_get_logmsg(&logmsg0, commit);
8958 if (err)
8959 goto done;
8960 logmsg = logmsg0;
8961 while (*logmsg == '\n')
8962 logmsg++;
8963 newline = strchr(logmsg, '\n');
8964 if (newline)
8965 *newline = '\0';
8967 if (asprintf(brief_str, "%s %s %s",
8968 datebuf, author, logmsg) == -1)
8969 err = got_error_from_errno("asprintf");
8970 done:
8971 free(author0);
8972 free(logmsg0);
8973 return err;
8976 static const struct got_error *
8977 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8978 struct got_repository *repo)
8980 const struct got_error *err;
8981 char *id_str;
8983 err = got_object_id_str(&id_str, id);
8984 if (err)
8985 return err;
8987 err = got_ref_delete(ref, repo);
8988 if (err)
8989 goto done;
8991 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8992 done:
8993 free(id_str);
8994 return err;
8997 static const struct got_error *
8998 print_backup_ref(const char *branch_name, const char *new_id_str,
8999 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9000 struct got_reflist_object_id_map *refs_idmap,
9001 struct got_repository *repo)
9003 const struct got_error *err = NULL;
9004 struct got_reflist_head *refs;
9005 char *refs_str = NULL;
9006 struct got_object_id *new_commit_id = NULL;
9007 struct got_commit_object *new_commit = NULL;
9008 char *new_commit_brief_str = NULL;
9009 struct got_object_id *yca_id = NULL;
9010 struct got_commit_object *yca_commit = NULL;
9011 char *yca_id_str = NULL, *yca_brief_str = NULL;
9012 char *custom_refs_str;
9014 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9015 return got_error_from_errno("asprintf");
9017 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9018 0, 0, refs_idmap, custom_refs_str);
9019 if (err)
9020 goto done;
9022 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9023 if (err)
9024 goto done;
9026 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9027 if (refs) {
9028 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9029 if (err)
9030 goto done;
9033 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9034 if (err)
9035 goto done;
9037 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9038 if (err)
9039 goto done;
9041 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9042 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9043 if (err)
9044 goto done;
9046 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9047 refs_str ? " (" : "", refs_str ? refs_str : "",
9048 refs_str ? ")" : "", new_commit_brief_str);
9049 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9050 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9051 free(refs_str);
9052 refs_str = NULL;
9054 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9055 if (err)
9056 goto done;
9058 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9059 if (err)
9060 goto done;
9062 err = got_object_id_str(&yca_id_str, yca_id);
9063 if (err)
9064 goto done;
9066 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9067 if (refs) {
9068 err = build_refs_str(&refs_str, refs, yca_id, repo);
9069 if (err)
9070 goto done;
9072 printf("history forked at %s%s%s%s\n %s\n",
9073 yca_id_str,
9074 refs_str ? " (" : "", refs_str ? refs_str : "",
9075 refs_str ? ")" : "", yca_brief_str);
9077 done:
9078 free(custom_refs_str);
9079 free(new_commit_id);
9080 free(refs_str);
9081 free(yca_id);
9082 free(yca_id_str);
9083 free(yca_brief_str);
9084 if (new_commit)
9085 got_object_commit_close(new_commit);
9086 if (yca_commit)
9087 got_object_commit_close(yca_commit);
9089 return NULL;
9092 static const struct got_error *
9093 process_backup_refs(const char *backup_ref_prefix,
9094 const char *wanted_branch_name,
9095 int delete, struct got_repository *repo)
9097 const struct got_error *err;
9098 struct got_reflist_head refs, backup_refs;
9099 struct got_reflist_entry *re;
9100 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9101 struct got_object_id *old_commit_id = NULL;
9102 char *branch_name = NULL;
9103 struct got_commit_object *old_commit = NULL;
9104 struct got_reflist_object_id_map *refs_idmap = NULL;
9105 int wanted_branch_found = 0;
9107 TAILQ_INIT(&refs);
9108 TAILQ_INIT(&backup_refs);
9110 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9111 if (err)
9112 return err;
9114 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9115 if (err)
9116 goto done;
9118 if (wanted_branch_name) {
9119 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9120 wanted_branch_name += 11;
9123 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9124 got_ref_cmp_by_commit_timestamp_descending, repo);
9125 if (err)
9126 goto done;
9128 TAILQ_FOREACH(re, &backup_refs, entry) {
9129 const char *refname = got_ref_get_name(re->ref);
9130 char *slash;
9132 err = check_cancelled(NULL);
9133 if (err)
9134 break;
9136 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9137 if (err)
9138 break;
9140 err = got_object_open_as_commit(&old_commit, repo,
9141 old_commit_id);
9142 if (err)
9143 break;
9145 if (strncmp(backup_ref_prefix, refname,
9146 backup_ref_prefix_len) == 0)
9147 refname += backup_ref_prefix_len;
9149 while (refname[0] == '/')
9150 refname++;
9152 branch_name = strdup(refname);
9153 if (branch_name == NULL) {
9154 err = got_error_from_errno("strdup");
9155 break;
9157 slash = strrchr(branch_name, '/');
9158 if (slash) {
9159 *slash = '\0';
9160 refname += strlen(branch_name) + 1;
9163 if (wanted_branch_name == NULL ||
9164 strcmp(wanted_branch_name, branch_name) == 0) {
9165 wanted_branch_found = 1;
9166 if (delete) {
9167 err = delete_backup_ref(re->ref,
9168 old_commit_id, repo);
9169 } else {
9170 err = print_backup_ref(branch_name, refname,
9171 old_commit_id, old_commit, refs_idmap,
9172 repo);
9174 if (err)
9175 break;
9178 free(old_commit_id);
9179 old_commit_id = NULL;
9180 free(branch_name);
9181 branch_name = NULL;
9182 got_object_commit_close(old_commit);
9183 old_commit = NULL;
9186 if (wanted_branch_name && !wanted_branch_found) {
9187 err = got_error_fmt(GOT_ERR_NOT_REF,
9188 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9190 done:
9191 if (refs_idmap)
9192 got_reflist_object_id_map_free(refs_idmap);
9193 got_ref_list_free(&refs);
9194 got_ref_list_free(&backup_refs);
9195 free(old_commit_id);
9196 free(branch_name);
9197 if (old_commit)
9198 got_object_commit_close(old_commit);
9199 return err;
9202 static const struct got_error *
9203 abort_progress(void *arg, unsigned char status, const char *path)
9206 * Unversioned files should not clutter progress output when
9207 * an operation is aborted.
9209 if (status == GOT_STATUS_UNVERSIONED)
9210 return NULL;
9212 return update_progress(arg, status, path);
9215 static const struct got_error *
9216 cmd_rebase(int argc, char *argv[])
9218 const struct got_error *error = NULL;
9219 struct got_worktree *worktree = NULL;
9220 struct got_repository *repo = NULL;
9221 struct got_fileindex *fileindex = NULL;
9222 char *cwd = NULL;
9223 struct got_reference *branch = NULL;
9224 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9225 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9226 struct got_object_id *resume_commit_id = NULL;
9227 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9228 struct got_commit_object *commit = NULL;
9229 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9230 int histedit_in_progress = 0, merge_in_progress = 0;
9231 int create_backup = 1, list_backups = 0, delete_backups = 0;
9232 struct got_object_id_queue commits;
9233 struct got_pathlist_head merged_paths;
9234 const struct got_object_id_queue *parent_ids;
9235 struct got_object_qid *qid, *pid;
9236 struct got_update_progress_arg upa;
9238 STAILQ_INIT(&commits);
9239 TAILQ_INIT(&merged_paths);
9240 memset(&upa, 0, sizeof(upa));
9242 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9243 switch (ch) {
9244 case 'a':
9245 abort_rebase = 1;
9246 break;
9247 case 'c':
9248 continue_rebase = 1;
9249 break;
9250 case 'l':
9251 list_backups = 1;
9252 break;
9253 case 'X':
9254 delete_backups = 1;
9255 break;
9256 default:
9257 usage_rebase();
9258 /* NOTREACHED */
9262 argc -= optind;
9263 argv += optind;
9265 #ifndef PROFILE
9266 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9267 "unveil", NULL) == -1)
9268 err(1, "pledge");
9269 #endif
9270 if (list_backups) {
9271 if (abort_rebase)
9272 option_conflict('l', 'a');
9273 if (continue_rebase)
9274 option_conflict('l', 'c');
9275 if (delete_backups)
9276 option_conflict('l', 'X');
9277 if (argc != 0 && argc != 1)
9278 usage_rebase();
9279 } else if (delete_backups) {
9280 if (abort_rebase)
9281 option_conflict('X', 'a');
9282 if (continue_rebase)
9283 option_conflict('X', 'c');
9284 if (list_backups)
9285 option_conflict('l', 'X');
9286 if (argc != 0 && argc != 1)
9287 usage_rebase();
9288 } else {
9289 if (abort_rebase && continue_rebase)
9290 usage_rebase();
9291 else if (abort_rebase || continue_rebase) {
9292 if (argc != 0)
9293 usage_rebase();
9294 } else if (argc != 1)
9295 usage_rebase();
9298 cwd = getcwd(NULL, 0);
9299 if (cwd == NULL) {
9300 error = got_error_from_errno("getcwd");
9301 goto done;
9303 error = got_worktree_open(&worktree, cwd);
9304 if (error) {
9305 if (list_backups || delete_backups) {
9306 if (error->code != GOT_ERR_NOT_WORKTREE)
9307 goto done;
9308 } else {
9309 if (error->code == GOT_ERR_NOT_WORKTREE)
9310 error = wrap_not_worktree_error(error,
9311 "rebase", cwd);
9312 goto done;
9316 error = got_repo_open(&repo,
9317 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9318 if (error != NULL)
9319 goto done;
9321 error = apply_unveil(got_repo_get_path(repo), 0,
9322 worktree ? got_worktree_get_root_path(worktree) : NULL);
9323 if (error)
9324 goto done;
9326 if (list_backups || delete_backups) {
9327 error = process_backup_refs(
9328 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9329 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9330 goto done; /* nothing else to do */
9333 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9334 worktree);
9335 if (error)
9336 goto done;
9337 if (histedit_in_progress) {
9338 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9339 goto done;
9342 error = got_worktree_merge_in_progress(&merge_in_progress,
9343 worktree, repo);
9344 if (error)
9345 goto done;
9346 if (merge_in_progress) {
9347 error = got_error(GOT_ERR_MERGE_BUSY);
9348 goto done;
9351 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9352 if (error)
9353 goto done;
9355 if (abort_rebase) {
9356 if (!rebase_in_progress) {
9357 error = got_error(GOT_ERR_NOT_REBASING);
9358 goto done;
9360 error = got_worktree_rebase_continue(&resume_commit_id,
9361 &new_base_branch, &tmp_branch, &branch, &fileindex,
9362 worktree, repo);
9363 if (error)
9364 goto done;
9365 printf("Switching work tree to %s\n",
9366 got_ref_get_symref_target(new_base_branch));
9367 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9368 new_base_branch, abort_progress, &upa);
9369 if (error)
9370 goto done;
9371 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9372 print_merge_progress_stats(&upa);
9373 goto done; /* nothing else to do */
9376 if (continue_rebase) {
9377 if (!rebase_in_progress) {
9378 error = got_error(GOT_ERR_NOT_REBASING);
9379 goto done;
9381 error = got_worktree_rebase_continue(&resume_commit_id,
9382 &new_base_branch, &tmp_branch, &branch, &fileindex,
9383 worktree, repo);
9384 if (error)
9385 goto done;
9387 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9388 resume_commit_id, repo);
9389 if (error)
9390 goto done;
9392 yca_id = got_object_id_dup(resume_commit_id);
9393 if (yca_id == NULL) {
9394 error = got_error_from_errno("got_object_id_dup");
9395 goto done;
9397 } else {
9398 error = got_ref_open(&branch, repo, argv[0], 0);
9399 if (error != NULL)
9400 goto done;
9403 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9404 if (error)
9405 goto done;
9407 if (!continue_rebase) {
9408 struct got_object_id *base_commit_id;
9410 base_commit_id = got_worktree_get_base_commit_id(worktree);
9411 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9412 base_commit_id, branch_head_commit_id, 1, repo,
9413 check_cancelled, NULL);
9414 if (error)
9415 goto done;
9416 if (yca_id == NULL) {
9417 error = got_error_msg(GOT_ERR_ANCESTRY,
9418 "specified branch shares no common ancestry "
9419 "with work tree's branch");
9420 goto done;
9423 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9424 if (error) {
9425 if (error->code != GOT_ERR_ANCESTRY)
9426 goto done;
9427 error = NULL;
9428 } else {
9429 struct got_pathlist_head paths;
9430 printf("%s is already based on %s\n",
9431 got_ref_get_name(branch),
9432 got_worktree_get_head_ref_name(worktree));
9433 error = switch_head_ref(branch, branch_head_commit_id,
9434 worktree, repo);
9435 if (error)
9436 goto done;
9437 error = got_worktree_set_base_commit_id(worktree, repo,
9438 branch_head_commit_id);
9439 if (error)
9440 goto done;
9441 TAILQ_INIT(&paths);
9442 error = got_pathlist_append(&paths, "", NULL);
9443 if (error)
9444 goto done;
9445 error = got_worktree_checkout_files(worktree,
9446 &paths, repo, update_progress, &upa,
9447 check_cancelled, NULL);
9448 got_pathlist_free(&paths);
9449 if (error)
9450 goto done;
9451 if (upa.did_something) {
9452 char *id_str;
9453 error = got_object_id_str(&id_str,
9454 branch_head_commit_id);
9455 if (error)
9456 goto done;
9457 printf("Updated to %s: %s\n",
9458 got_worktree_get_head_ref_name(worktree),
9459 id_str);
9460 free(id_str);
9461 } else
9462 printf("Already up-to-date\n");
9463 print_update_progress_stats(&upa);
9464 goto done;
9468 commit_id = branch_head_commit_id;
9469 error = got_object_open_as_commit(&commit, repo, commit_id);
9470 if (error)
9471 goto done;
9473 parent_ids = got_object_commit_get_parent_ids(commit);
9474 pid = STAILQ_FIRST(parent_ids);
9475 if (pid == NULL) {
9476 error = got_error(GOT_ERR_EMPTY_REBASE);
9477 goto done;
9479 error = collect_commits(&commits, commit_id, pid->id,
9480 yca_id, got_worktree_get_path_prefix(worktree),
9481 GOT_ERR_REBASE_PATH, repo);
9482 got_object_commit_close(commit);
9483 commit = NULL;
9484 if (error)
9485 goto done;
9487 if (!continue_rebase) {
9488 error = got_worktree_rebase_prepare(&new_base_branch,
9489 &tmp_branch, &fileindex, worktree, branch, repo);
9490 if (error)
9491 goto done;
9494 if (STAILQ_EMPTY(&commits)) {
9495 if (continue_rebase) {
9496 error = rebase_complete(worktree, fileindex,
9497 branch, new_base_branch, tmp_branch, repo,
9498 create_backup);
9499 goto done;
9500 } else {
9501 /* Fast-forward the reference of the branch. */
9502 struct got_object_id *new_head_commit_id;
9503 char *id_str;
9504 error = got_ref_resolve(&new_head_commit_id, repo,
9505 new_base_branch);
9506 if (error)
9507 goto done;
9508 error = got_object_id_str(&id_str, new_head_commit_id);
9509 printf("Forwarding %s to commit %s\n",
9510 got_ref_get_name(branch), id_str);
9511 free(id_str);
9512 error = got_ref_change_ref(branch,
9513 new_head_commit_id);
9514 if (error)
9515 goto done;
9516 /* No backup needed since objects did not change. */
9517 create_backup = 0;
9521 pid = NULL;
9522 STAILQ_FOREACH(qid, &commits, entry) {
9524 commit_id = qid->id;
9525 parent_id = pid ? pid->id : yca_id;
9526 pid = qid;
9528 memset(&upa, 0, sizeof(upa));
9529 error = got_worktree_rebase_merge_files(&merged_paths,
9530 worktree, fileindex, parent_id, commit_id, repo,
9531 update_progress, &upa, check_cancelled, NULL);
9532 if (error)
9533 goto done;
9535 print_merge_progress_stats(&upa);
9536 if (upa.conflicts > 0 || upa.missing > 0 ||
9537 upa.not_deleted > 0 || upa.unversioned > 0) {
9538 if (upa.conflicts > 0) {
9539 error = show_rebase_merge_conflict(qid->id,
9540 repo);
9541 if (error)
9542 goto done;
9544 got_worktree_rebase_pathlist_free(&merged_paths);
9545 break;
9548 error = rebase_commit(&merged_paths, worktree, fileindex,
9549 tmp_branch, commit_id, repo);
9550 got_worktree_rebase_pathlist_free(&merged_paths);
9551 if (error)
9552 goto done;
9555 if (upa.conflicts > 0 || upa.missing > 0 ||
9556 upa.not_deleted > 0 || upa.unversioned > 0) {
9557 error = got_worktree_rebase_postpone(worktree, fileindex);
9558 if (error)
9559 goto done;
9560 if (upa.conflicts > 0 && upa.missing == 0 &&
9561 upa.not_deleted == 0 && upa.unversioned == 0) {
9562 error = got_error_msg(GOT_ERR_CONFLICTS,
9563 "conflicts must be resolved before rebasing "
9564 "can continue");
9565 } else if (upa.conflicts > 0) {
9566 error = got_error_msg(GOT_ERR_CONFLICTS,
9567 "conflicts must be resolved before rebasing "
9568 "can continue; changes destined for some "
9569 "files were not yet merged and should be "
9570 "merged manually if required before the "
9571 "rebase operation is continued");
9572 } else {
9573 error = got_error_msg(GOT_ERR_CONFLICTS,
9574 "changes destined for some files were not "
9575 "yet merged and should be merged manually "
9576 "if required before the rebase operation "
9577 "is continued");
9579 } else
9580 error = rebase_complete(worktree, fileindex, branch,
9581 new_base_branch, tmp_branch, repo, create_backup);
9582 done:
9583 got_object_id_queue_free(&commits);
9584 free(branch_head_commit_id);
9585 free(resume_commit_id);
9586 free(yca_id);
9587 if (commit)
9588 got_object_commit_close(commit);
9589 if (branch)
9590 got_ref_close(branch);
9591 if (new_base_branch)
9592 got_ref_close(new_base_branch);
9593 if (tmp_branch)
9594 got_ref_close(tmp_branch);
9595 if (worktree)
9596 got_worktree_close(worktree);
9597 if (repo) {
9598 const struct got_error *close_err = got_repo_close(repo);
9599 if (error == NULL)
9600 error = close_err;
9602 return error;
9605 __dead static void
9606 usage_histedit(void)
9608 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9609 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9610 getprogname());
9611 exit(1);
9614 #define GOT_HISTEDIT_PICK 'p'
9615 #define GOT_HISTEDIT_EDIT 'e'
9616 #define GOT_HISTEDIT_FOLD 'f'
9617 #define GOT_HISTEDIT_DROP 'd'
9618 #define GOT_HISTEDIT_MESG 'm'
9620 static const struct got_histedit_cmd {
9621 unsigned char code;
9622 const char *name;
9623 const char *desc;
9624 } got_histedit_cmds[] = {
9625 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9626 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9627 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9628 "be used" },
9629 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9630 { GOT_HISTEDIT_MESG, "mesg",
9631 "single-line log message for commit above (open editor if empty)" },
9634 struct got_histedit_list_entry {
9635 TAILQ_ENTRY(got_histedit_list_entry) entry;
9636 struct got_object_id *commit_id;
9637 const struct got_histedit_cmd *cmd;
9638 char *logmsg;
9640 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9642 static const struct got_error *
9643 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9644 FILE *f, struct got_repository *repo)
9646 const struct got_error *err = NULL;
9647 char *logmsg = NULL, *id_str = NULL;
9648 struct got_commit_object *commit = NULL;
9649 int n;
9651 err = got_object_open_as_commit(&commit, repo, commit_id);
9652 if (err)
9653 goto done;
9655 err = get_short_logmsg(&logmsg, 34, commit);
9656 if (err)
9657 goto done;
9659 err = got_object_id_str(&id_str, commit_id);
9660 if (err)
9661 goto done;
9663 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9664 if (n < 0)
9665 err = got_ferror(f, GOT_ERR_IO);
9666 done:
9667 if (commit)
9668 got_object_commit_close(commit);
9669 free(id_str);
9670 free(logmsg);
9671 return err;
9674 static const struct got_error *
9675 histedit_write_commit_list(struct got_object_id_queue *commits,
9676 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9677 struct got_repository *repo)
9679 const struct got_error *err = NULL;
9680 struct got_object_qid *qid;
9681 const char *histedit_cmd = NULL;
9683 if (STAILQ_EMPTY(commits))
9684 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9686 STAILQ_FOREACH(qid, commits, entry) {
9687 histedit_cmd = got_histedit_cmds[0].name;
9688 if (edit_only)
9689 histedit_cmd = "edit";
9690 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9691 histedit_cmd = "fold";
9692 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9693 if (err)
9694 break;
9695 if (edit_logmsg_only) {
9696 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9697 if (n < 0) {
9698 err = got_ferror(f, GOT_ERR_IO);
9699 break;
9704 return err;
9707 static const struct got_error *
9708 write_cmd_list(FILE *f, const char *branch_name,
9709 struct got_object_id_queue *commits)
9711 const struct got_error *err = NULL;
9712 size_t i;
9713 int n;
9714 char *id_str;
9715 struct got_object_qid *qid;
9717 qid = STAILQ_FIRST(commits);
9718 err = got_object_id_str(&id_str, qid->id);
9719 if (err)
9720 return err;
9722 n = fprintf(f,
9723 "# Editing the history of branch '%s' starting at\n"
9724 "# commit %s\n"
9725 "# Commits will be processed in order from top to "
9726 "bottom of this file.\n", branch_name, id_str);
9727 if (n < 0) {
9728 err = got_ferror(f, GOT_ERR_IO);
9729 goto done;
9732 n = fprintf(f, "# Available histedit commands:\n");
9733 if (n < 0) {
9734 err = got_ferror(f, GOT_ERR_IO);
9735 goto done;
9738 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9739 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9740 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9741 cmd->desc);
9742 if (n < 0) {
9743 err = got_ferror(f, GOT_ERR_IO);
9744 break;
9747 done:
9748 free(id_str);
9749 return err;
9752 static const struct got_error *
9753 histedit_syntax_error(int lineno)
9755 static char msg[42];
9756 int ret;
9758 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9759 lineno);
9760 if (ret == -1 || ret >= sizeof(msg))
9761 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9763 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9766 static const struct got_error *
9767 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9768 char *logmsg, struct got_repository *repo)
9770 const struct got_error *err;
9771 struct got_commit_object *folded_commit = NULL;
9772 char *id_str, *folded_logmsg = NULL;
9774 err = got_object_id_str(&id_str, hle->commit_id);
9775 if (err)
9776 return err;
9778 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9779 if (err)
9780 goto done;
9782 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9783 if (err)
9784 goto done;
9785 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9786 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9787 folded_logmsg) == -1) {
9788 err = got_error_from_errno("asprintf");
9790 done:
9791 if (folded_commit)
9792 got_object_commit_close(folded_commit);
9793 free(id_str);
9794 free(folded_logmsg);
9795 return err;
9798 static struct got_histedit_list_entry *
9799 get_folded_commits(struct got_histedit_list_entry *hle)
9801 struct got_histedit_list_entry *prev, *folded = NULL;
9803 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9804 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9805 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9806 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9807 folded = prev;
9808 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9811 return folded;
9814 static const struct got_error *
9815 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9816 struct got_repository *repo)
9818 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9819 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9820 const struct got_error *err = NULL;
9821 struct got_commit_object *commit = NULL;
9822 int logmsg_len;
9823 int fd;
9824 struct got_histedit_list_entry *folded = NULL;
9826 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9827 if (err)
9828 return err;
9830 folded = get_folded_commits(hle);
9831 if (folded) {
9832 while (folded != hle) {
9833 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9834 folded = TAILQ_NEXT(folded, entry);
9835 continue;
9837 err = append_folded_commit_msg(&new_msg, folded,
9838 logmsg, repo);
9839 if (err)
9840 goto done;
9841 free(logmsg);
9842 logmsg = new_msg;
9843 folded = TAILQ_NEXT(folded, entry);
9847 err = got_object_id_str(&id_str, hle->commit_id);
9848 if (err)
9849 goto done;
9850 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9851 if (err)
9852 goto done;
9853 logmsg_len = asprintf(&new_msg,
9854 "%s\n# original log message of commit %s: %s",
9855 logmsg ? logmsg : "", id_str, orig_logmsg);
9856 if (logmsg_len == -1) {
9857 err = got_error_from_errno("asprintf");
9858 goto done;
9860 free(logmsg);
9861 logmsg = new_msg;
9863 err = got_object_id_str(&id_str, hle->commit_id);
9864 if (err)
9865 goto done;
9867 err = got_opentemp_named_fd(&logmsg_path, &fd,
9868 GOT_TMPDIR_STR "/got-logmsg");
9869 if (err)
9870 goto done;
9872 write(fd, logmsg, logmsg_len);
9873 close(fd);
9875 err = get_editor(&editor);
9876 if (err)
9877 goto done;
9879 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9880 logmsg_len, 0);
9881 if (err) {
9882 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9883 goto done;
9884 err = NULL;
9885 hle->logmsg = strdup(new_msg);
9886 if (hle->logmsg == NULL)
9887 err = got_error_from_errno("strdup");
9889 done:
9890 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9891 err = got_error_from_errno2("unlink", logmsg_path);
9892 free(logmsg_path);
9893 free(logmsg);
9894 free(orig_logmsg);
9895 free(editor);
9896 if (commit)
9897 got_object_commit_close(commit);
9898 return err;
9901 static const struct got_error *
9902 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9903 FILE *f, struct got_repository *repo)
9905 const struct got_error *err = NULL;
9906 char *line = NULL, *p, *end;
9907 size_t i, size;
9908 ssize_t len;
9909 int lineno = 0;
9910 const struct got_histedit_cmd *cmd;
9911 struct got_object_id *commit_id = NULL;
9912 struct got_histedit_list_entry *hle = NULL;
9914 for (;;) {
9915 len = getline(&line, &size, f);
9916 if (len == -1) {
9917 const struct got_error *getline_err;
9918 if (feof(f))
9919 break;
9920 getline_err = got_error_from_errno("getline");
9921 err = got_ferror(f, getline_err->code);
9922 break;
9924 lineno++;
9925 p = line;
9926 while (isspace((unsigned char)p[0]))
9927 p++;
9928 if (p[0] == '#' || p[0] == '\0') {
9929 free(line);
9930 line = NULL;
9931 continue;
9933 cmd = NULL;
9934 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9935 cmd = &got_histedit_cmds[i];
9936 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9937 isspace((unsigned char)p[strlen(cmd->name)])) {
9938 p += strlen(cmd->name);
9939 break;
9941 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9942 p++;
9943 break;
9946 if (i == nitems(got_histedit_cmds)) {
9947 err = histedit_syntax_error(lineno);
9948 break;
9950 while (isspace((unsigned char)p[0]))
9951 p++;
9952 if (cmd->code == GOT_HISTEDIT_MESG) {
9953 if (hle == NULL || hle->logmsg != NULL) {
9954 err = got_error(GOT_ERR_HISTEDIT_CMD);
9955 break;
9957 if (p[0] == '\0') {
9958 err = histedit_edit_logmsg(hle, repo);
9959 if (err)
9960 break;
9961 } else {
9962 hle->logmsg = strdup(p);
9963 if (hle->logmsg == NULL) {
9964 err = got_error_from_errno("strdup");
9965 break;
9968 free(line);
9969 line = NULL;
9970 continue;
9971 } else {
9972 end = p;
9973 while (end[0] && !isspace((unsigned char)end[0]))
9974 end++;
9975 *end = '\0';
9977 err = got_object_resolve_id_str(&commit_id, repo, p);
9978 if (err) {
9979 /* override error code */
9980 err = histedit_syntax_error(lineno);
9981 break;
9984 hle = malloc(sizeof(*hle));
9985 if (hle == NULL) {
9986 err = got_error_from_errno("malloc");
9987 break;
9989 hle->cmd = cmd;
9990 hle->commit_id = commit_id;
9991 hle->logmsg = NULL;
9992 commit_id = NULL;
9993 free(line);
9994 line = NULL;
9995 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9998 free(line);
9999 free(commit_id);
10000 return err;
10003 static const struct got_error *
10004 histedit_check_script(struct got_histedit_list *histedit_cmds,
10005 struct got_object_id_queue *commits, struct got_repository *repo)
10007 const struct got_error *err = NULL;
10008 struct got_object_qid *qid;
10009 struct got_histedit_list_entry *hle;
10010 static char msg[92];
10011 char *id_str;
10013 if (TAILQ_EMPTY(histedit_cmds))
10014 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10015 "histedit script contains no commands");
10016 if (STAILQ_EMPTY(commits))
10017 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10019 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10020 struct got_histedit_list_entry *hle2;
10021 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10022 if (hle == hle2)
10023 continue;
10024 if (got_object_id_cmp(hle->commit_id,
10025 hle2->commit_id) != 0)
10026 continue;
10027 err = got_object_id_str(&id_str, hle->commit_id);
10028 if (err)
10029 return err;
10030 snprintf(msg, sizeof(msg), "commit %s is listed "
10031 "more than once in histedit script", id_str);
10032 free(id_str);
10033 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10037 STAILQ_FOREACH(qid, commits, entry) {
10038 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10039 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
10040 break;
10042 if (hle == NULL) {
10043 err = got_object_id_str(&id_str, qid->id);
10044 if (err)
10045 return err;
10046 snprintf(msg, sizeof(msg),
10047 "commit %s missing from histedit script", id_str);
10048 free(id_str);
10049 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10053 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10054 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10055 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10056 "last commit in histedit script cannot be folded");
10058 return NULL;
10061 static const struct got_error *
10062 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10063 const char *path, struct got_object_id_queue *commits,
10064 struct got_repository *repo)
10066 const struct got_error *err = NULL;
10067 char *editor;
10068 FILE *f = NULL;
10070 err = get_editor(&editor);
10071 if (err)
10072 return err;
10074 if (spawn_editor(editor, path) == -1) {
10075 err = got_error_from_errno("failed spawning editor");
10076 goto done;
10079 f = fopen(path, "re");
10080 if (f == NULL) {
10081 err = got_error_from_errno("fopen");
10082 goto done;
10084 err = histedit_parse_list(histedit_cmds, f, repo);
10085 if (err)
10086 goto done;
10088 err = histedit_check_script(histedit_cmds, commits, repo);
10089 done:
10090 if (f && fclose(f) == EOF && err == NULL)
10091 err = got_error_from_errno("fclose");
10092 free(editor);
10093 return err;
10096 static const struct got_error *
10097 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10098 struct got_object_id_queue *, const char *, const char *,
10099 struct got_repository *);
10101 static const struct got_error *
10102 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10103 struct got_object_id_queue *commits, const char *branch_name,
10104 int edit_logmsg_only, int fold_only, int edit_only,
10105 struct got_repository *repo)
10107 const struct got_error *err;
10108 FILE *f = NULL;
10109 char *path = NULL;
10111 err = got_opentemp_named(&path, &f, "got-histedit");
10112 if (err)
10113 return err;
10115 err = write_cmd_list(f, branch_name, commits);
10116 if (err)
10117 goto done;
10119 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10120 fold_only, edit_only, repo);
10121 if (err)
10122 goto done;
10124 if (edit_logmsg_only || fold_only || edit_only) {
10125 rewind(f);
10126 err = histedit_parse_list(histedit_cmds, f, repo);
10127 } else {
10128 if (fclose(f) == EOF) {
10129 err = got_error_from_errno("fclose");
10130 goto done;
10132 f = NULL;
10133 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10134 if (err) {
10135 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10136 err->code != GOT_ERR_HISTEDIT_CMD)
10137 goto done;
10138 err = histedit_edit_list_retry(histedit_cmds, err,
10139 commits, path, branch_name, repo);
10142 done:
10143 if (f && fclose(f) == EOF && err == NULL)
10144 err = got_error_from_errno("fclose");
10145 if (path && unlink(path) != 0 && err == NULL)
10146 err = got_error_from_errno2("unlink", path);
10147 free(path);
10148 return err;
10151 static const struct got_error *
10152 histedit_save_list(struct got_histedit_list *histedit_cmds,
10153 struct got_worktree *worktree, struct got_repository *repo)
10155 const struct got_error *err = NULL;
10156 char *path = NULL;
10157 FILE *f = NULL;
10158 struct got_histedit_list_entry *hle;
10159 struct got_commit_object *commit = NULL;
10161 err = got_worktree_get_histedit_script_path(&path, worktree);
10162 if (err)
10163 return err;
10165 f = fopen(path, "we");
10166 if (f == NULL) {
10167 err = got_error_from_errno2("fopen", path);
10168 goto done;
10170 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10171 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10172 repo);
10173 if (err)
10174 break;
10176 if (hle->logmsg) {
10177 int n = fprintf(f, "%c %s\n",
10178 GOT_HISTEDIT_MESG, hle->logmsg);
10179 if (n < 0) {
10180 err = got_ferror(f, GOT_ERR_IO);
10181 break;
10185 done:
10186 if (f && fclose(f) == EOF && err == NULL)
10187 err = got_error_from_errno("fclose");
10188 free(path);
10189 if (commit)
10190 got_object_commit_close(commit);
10191 return err;
10194 void
10195 histedit_free_list(struct got_histedit_list *histedit_cmds)
10197 struct got_histedit_list_entry *hle;
10199 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10200 TAILQ_REMOVE(histedit_cmds, hle, entry);
10201 free(hle);
10205 static const struct got_error *
10206 histedit_load_list(struct got_histedit_list *histedit_cmds,
10207 const char *path, struct got_repository *repo)
10209 const struct got_error *err = NULL;
10210 FILE *f = NULL;
10212 f = fopen(path, "re");
10213 if (f == NULL) {
10214 err = got_error_from_errno2("fopen", path);
10215 goto done;
10218 err = histedit_parse_list(histedit_cmds, f, repo);
10219 done:
10220 if (f && fclose(f) == EOF && err == NULL)
10221 err = got_error_from_errno("fclose");
10222 return err;
10225 static const struct got_error *
10226 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10227 const struct got_error *edit_err, struct got_object_id_queue *commits,
10228 const char *path, const char *branch_name, struct got_repository *repo)
10230 const struct got_error *err = NULL, *prev_err = edit_err;
10231 int resp = ' ';
10233 while (resp != 'c' && resp != 'r' && resp != 'a') {
10234 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10235 "or (a)bort: ", getprogname(), prev_err->msg);
10236 resp = getchar();
10237 if (resp == '\n')
10238 resp = getchar();
10239 if (resp == 'c') {
10240 histedit_free_list(histedit_cmds);
10241 err = histedit_run_editor(histedit_cmds, path, commits,
10242 repo);
10243 if (err) {
10244 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10245 err->code != GOT_ERR_HISTEDIT_CMD)
10246 break;
10247 prev_err = err;
10248 resp = ' ';
10249 continue;
10251 break;
10252 } else if (resp == 'r') {
10253 histedit_free_list(histedit_cmds);
10254 err = histedit_edit_script(histedit_cmds,
10255 commits, branch_name, 0, 0, 0, repo);
10256 if (err) {
10257 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10258 err->code != GOT_ERR_HISTEDIT_CMD)
10259 break;
10260 prev_err = err;
10261 resp = ' ';
10262 continue;
10264 break;
10265 } else if (resp == 'a') {
10266 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10267 break;
10268 } else
10269 printf("invalid response '%c'\n", resp);
10272 return err;
10275 static const struct got_error *
10276 histedit_complete(struct got_worktree *worktree,
10277 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10278 struct got_reference *branch, struct got_repository *repo)
10280 printf("Switching work tree to %s\n",
10281 got_ref_get_symref_target(branch));
10282 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10283 branch, repo);
10286 static const struct got_error *
10287 show_histedit_progress(struct got_commit_object *commit,
10288 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10290 const struct got_error *err;
10291 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10293 err = got_object_id_str(&old_id_str, hle->commit_id);
10294 if (err)
10295 goto done;
10297 if (new_id) {
10298 err = got_object_id_str(&new_id_str, new_id);
10299 if (err)
10300 goto done;
10303 old_id_str[12] = '\0';
10304 if (new_id_str)
10305 new_id_str[12] = '\0';
10307 if (hle->logmsg) {
10308 logmsg = strdup(hle->logmsg);
10309 if (logmsg == NULL) {
10310 err = got_error_from_errno("strdup");
10311 goto done;
10313 trim_logmsg(logmsg, 42);
10314 } else {
10315 err = get_short_logmsg(&logmsg, 42, commit);
10316 if (err)
10317 goto done;
10320 switch (hle->cmd->code) {
10321 case GOT_HISTEDIT_PICK:
10322 case GOT_HISTEDIT_EDIT:
10323 printf("%s -> %s: %s\n", old_id_str,
10324 new_id_str ? new_id_str : "no-op change", logmsg);
10325 break;
10326 case GOT_HISTEDIT_DROP:
10327 case GOT_HISTEDIT_FOLD:
10328 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10329 logmsg);
10330 break;
10331 default:
10332 break;
10334 done:
10335 free(old_id_str);
10336 free(new_id_str);
10337 return err;
10340 static const struct got_error *
10341 histedit_commit(struct got_pathlist_head *merged_paths,
10342 struct got_worktree *worktree, struct got_fileindex *fileindex,
10343 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10344 struct got_repository *repo)
10346 const struct got_error *err;
10347 struct got_commit_object *commit;
10348 struct got_object_id *new_commit_id;
10350 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10351 && hle->logmsg == NULL) {
10352 err = histedit_edit_logmsg(hle, repo);
10353 if (err)
10354 return err;
10357 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10358 if (err)
10359 return err;
10361 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10362 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10363 hle->logmsg, repo);
10364 if (err) {
10365 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10366 goto done;
10367 err = show_histedit_progress(commit, hle, NULL);
10368 } else {
10369 err = show_histedit_progress(commit, hle, new_commit_id);
10370 free(new_commit_id);
10372 done:
10373 got_object_commit_close(commit);
10374 return err;
10377 static const struct got_error *
10378 histedit_skip_commit(struct got_histedit_list_entry *hle,
10379 struct got_worktree *worktree, struct got_repository *repo)
10381 const struct got_error *error;
10382 struct got_commit_object *commit;
10384 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10385 repo);
10386 if (error)
10387 return error;
10389 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10390 if (error)
10391 return error;
10393 error = show_histedit_progress(commit, hle, NULL);
10394 got_object_commit_close(commit);
10395 return error;
10398 static const struct got_error *
10399 check_local_changes(void *arg, unsigned char status,
10400 unsigned char staged_status, const char *path,
10401 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10402 struct got_object_id *commit_id, int dirfd, const char *de_name)
10404 int *have_local_changes = arg;
10406 switch (status) {
10407 case GOT_STATUS_ADD:
10408 case GOT_STATUS_DELETE:
10409 case GOT_STATUS_MODIFY:
10410 case GOT_STATUS_CONFLICT:
10411 *have_local_changes = 1;
10412 return got_error(GOT_ERR_CANCELLED);
10413 default:
10414 break;
10417 switch (staged_status) {
10418 case GOT_STATUS_ADD:
10419 case GOT_STATUS_DELETE:
10420 case GOT_STATUS_MODIFY:
10421 *have_local_changes = 1;
10422 return got_error(GOT_ERR_CANCELLED);
10423 default:
10424 break;
10427 return NULL;
10430 static const struct got_error *
10431 cmd_histedit(int argc, char *argv[])
10433 const struct got_error *error = NULL;
10434 struct got_worktree *worktree = NULL;
10435 struct got_fileindex *fileindex = NULL;
10436 struct got_repository *repo = NULL;
10437 char *cwd = NULL;
10438 struct got_reference *branch = NULL;
10439 struct got_reference *tmp_branch = NULL;
10440 struct got_object_id *resume_commit_id = NULL;
10441 struct got_object_id *base_commit_id = NULL;
10442 struct got_object_id *head_commit_id = NULL;
10443 struct got_commit_object *commit = NULL;
10444 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10445 struct got_update_progress_arg upa;
10446 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10447 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10448 int list_backups = 0, delete_backups = 0;
10449 const char *edit_script_path = NULL;
10450 struct got_object_id_queue commits;
10451 struct got_pathlist_head merged_paths;
10452 const struct got_object_id_queue *parent_ids;
10453 struct got_object_qid *pid;
10454 struct got_histedit_list histedit_cmds;
10455 struct got_histedit_list_entry *hle;
10457 STAILQ_INIT(&commits);
10458 TAILQ_INIT(&histedit_cmds);
10459 TAILQ_INIT(&merged_paths);
10460 memset(&upa, 0, sizeof(upa));
10462 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10463 switch (ch) {
10464 case 'a':
10465 abort_edit = 1;
10466 break;
10467 case 'c':
10468 continue_edit = 1;
10469 break;
10470 case 'e':
10471 edit_only = 1;
10472 break;
10473 case 'f':
10474 fold_only = 1;
10475 break;
10476 case 'F':
10477 edit_script_path = optarg;
10478 break;
10479 case 'm':
10480 edit_logmsg_only = 1;
10481 break;
10482 case 'l':
10483 list_backups = 1;
10484 break;
10485 case 'X':
10486 delete_backups = 1;
10487 break;
10488 default:
10489 usage_histedit();
10490 /* NOTREACHED */
10494 argc -= optind;
10495 argv += optind;
10497 #ifndef PROFILE
10498 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10499 "unveil", NULL) == -1)
10500 err(1, "pledge");
10501 #endif
10502 if (abort_edit && continue_edit)
10503 option_conflict('a', 'c');
10504 if (edit_script_path && edit_logmsg_only)
10505 option_conflict('F', 'm');
10506 if (abort_edit && edit_logmsg_only)
10507 option_conflict('a', 'm');
10508 if (continue_edit && edit_logmsg_only)
10509 option_conflict('c', 'm');
10510 if (abort_edit && fold_only)
10511 option_conflict('a', 'f');
10512 if (continue_edit && fold_only)
10513 option_conflict('c', 'f');
10514 if (fold_only && edit_logmsg_only)
10515 option_conflict('f', 'm');
10516 if (edit_script_path && fold_only)
10517 option_conflict('F', 'f');
10518 if (abort_edit && edit_only)
10519 option_conflict('a', 'e');
10520 if (continue_edit && edit_only)
10521 option_conflict('c', 'e');
10522 if (edit_only && edit_logmsg_only)
10523 option_conflict('e', 'm');
10524 if (edit_script_path && edit_only)
10525 option_conflict('F', 'e');
10526 if (list_backups) {
10527 if (abort_edit)
10528 option_conflict('l', 'a');
10529 if (continue_edit)
10530 option_conflict('l', 'c');
10531 if (edit_script_path)
10532 option_conflict('l', 'F');
10533 if (edit_logmsg_only)
10534 option_conflict('l', 'm');
10535 if (fold_only)
10536 option_conflict('l', 'f');
10537 if (edit_only)
10538 option_conflict('l', 'e');
10539 if (delete_backups)
10540 option_conflict('l', 'X');
10541 if (argc != 0 && argc != 1)
10542 usage_histedit();
10543 } else if (delete_backups) {
10544 if (abort_edit)
10545 option_conflict('X', 'a');
10546 if (continue_edit)
10547 option_conflict('X', 'c');
10548 if (edit_script_path)
10549 option_conflict('X', 'F');
10550 if (edit_logmsg_only)
10551 option_conflict('X', 'm');
10552 if (fold_only)
10553 option_conflict('X', 'f');
10554 if (edit_only)
10555 option_conflict('X', 'e');
10556 if (list_backups)
10557 option_conflict('X', 'l');
10558 if (argc != 0 && argc != 1)
10559 usage_histedit();
10560 } else if (argc != 0)
10561 usage_histedit();
10564 * This command cannot apply unveil(2) in all cases because the
10565 * user may choose to run an editor to edit the histedit script
10566 * and to edit individual commit log messages.
10567 * unveil(2) traverses exec(2); if an editor is used we have to
10568 * apply unveil after edit script and log messages have been written.
10569 * XXX TODO: Make use of unveil(2) where possible.
10572 cwd = getcwd(NULL, 0);
10573 if (cwd == NULL) {
10574 error = got_error_from_errno("getcwd");
10575 goto done;
10577 error = got_worktree_open(&worktree, cwd);
10578 if (error) {
10579 if (list_backups || delete_backups) {
10580 if (error->code != GOT_ERR_NOT_WORKTREE)
10581 goto done;
10582 } else {
10583 if (error->code == GOT_ERR_NOT_WORKTREE)
10584 error = wrap_not_worktree_error(error,
10585 "histedit", cwd);
10586 goto done;
10590 if (list_backups || delete_backups) {
10591 error = got_repo_open(&repo,
10592 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10593 NULL);
10594 if (error != NULL)
10595 goto done;
10596 error = apply_unveil(got_repo_get_path(repo), 0,
10597 worktree ? got_worktree_get_root_path(worktree) : NULL);
10598 if (error)
10599 goto done;
10600 error = process_backup_refs(
10601 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10602 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10603 goto done; /* nothing else to do */
10606 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10607 NULL);
10608 if (error != NULL)
10609 goto done;
10611 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10612 if (error)
10613 goto done;
10614 if (rebase_in_progress) {
10615 error = got_error(GOT_ERR_REBASING);
10616 goto done;
10619 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10620 repo);
10621 if (error)
10622 goto done;
10623 if (merge_in_progress) {
10624 error = got_error(GOT_ERR_MERGE_BUSY);
10625 goto done;
10628 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10629 if (error)
10630 goto done;
10632 if (edit_in_progress && edit_logmsg_only) {
10633 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10634 "histedit operation is in progress in this "
10635 "work tree and must be continued or aborted "
10636 "before the -m option can be used");
10637 goto done;
10639 if (edit_in_progress && fold_only) {
10640 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10641 "histedit operation is in progress in this "
10642 "work tree and must be continued or aborted "
10643 "before the -f option can be used");
10644 goto done;
10646 if (edit_in_progress && edit_only) {
10647 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10648 "histedit operation is in progress in this "
10649 "work tree and must be continued or aborted "
10650 "before the -e option can be used");
10651 goto done;
10654 if (edit_in_progress && abort_edit) {
10655 error = got_worktree_histedit_continue(&resume_commit_id,
10656 &tmp_branch, &branch, &base_commit_id, &fileindex,
10657 worktree, repo);
10658 if (error)
10659 goto done;
10660 printf("Switching work tree to %s\n",
10661 got_ref_get_symref_target(branch));
10662 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10663 branch, base_commit_id, abort_progress, &upa);
10664 if (error)
10665 goto done;
10666 printf("Histedit of %s aborted\n",
10667 got_ref_get_symref_target(branch));
10668 print_merge_progress_stats(&upa);
10669 goto done; /* nothing else to do */
10670 } else if (abort_edit) {
10671 error = got_error(GOT_ERR_NOT_HISTEDIT);
10672 goto done;
10675 if (continue_edit) {
10676 char *path;
10678 if (!edit_in_progress) {
10679 error = got_error(GOT_ERR_NOT_HISTEDIT);
10680 goto done;
10683 error = got_worktree_get_histedit_script_path(&path, worktree);
10684 if (error)
10685 goto done;
10687 error = histedit_load_list(&histedit_cmds, path, repo);
10688 free(path);
10689 if (error)
10690 goto done;
10692 error = got_worktree_histedit_continue(&resume_commit_id,
10693 &tmp_branch, &branch, &base_commit_id, &fileindex,
10694 worktree, repo);
10695 if (error)
10696 goto done;
10698 error = got_ref_resolve(&head_commit_id, repo, branch);
10699 if (error)
10700 goto done;
10702 error = got_object_open_as_commit(&commit, repo,
10703 head_commit_id);
10704 if (error)
10705 goto done;
10706 parent_ids = got_object_commit_get_parent_ids(commit);
10707 pid = STAILQ_FIRST(parent_ids);
10708 if (pid == NULL) {
10709 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10710 goto done;
10712 error = collect_commits(&commits, head_commit_id, pid->id,
10713 base_commit_id, got_worktree_get_path_prefix(worktree),
10714 GOT_ERR_HISTEDIT_PATH, repo);
10715 got_object_commit_close(commit);
10716 commit = NULL;
10717 if (error)
10718 goto done;
10719 } else {
10720 if (edit_in_progress) {
10721 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10722 goto done;
10725 error = got_ref_open(&branch, repo,
10726 got_worktree_get_head_ref_name(worktree), 0);
10727 if (error != NULL)
10728 goto done;
10730 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10731 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10732 "will not edit commit history of a branch outside "
10733 "the \"refs/heads/\" reference namespace");
10734 goto done;
10737 error = got_ref_resolve(&head_commit_id, repo, branch);
10738 got_ref_close(branch);
10739 branch = NULL;
10740 if (error)
10741 goto done;
10743 error = got_object_open_as_commit(&commit, repo,
10744 head_commit_id);
10745 if (error)
10746 goto done;
10747 parent_ids = got_object_commit_get_parent_ids(commit);
10748 pid = STAILQ_FIRST(parent_ids);
10749 if (pid == NULL) {
10750 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10751 goto done;
10753 error = collect_commits(&commits, head_commit_id, pid->id,
10754 got_worktree_get_base_commit_id(worktree),
10755 got_worktree_get_path_prefix(worktree),
10756 GOT_ERR_HISTEDIT_PATH, repo);
10757 got_object_commit_close(commit);
10758 commit = NULL;
10759 if (error)
10760 goto done;
10762 if (STAILQ_EMPTY(&commits)) {
10763 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10764 goto done;
10767 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10768 &base_commit_id, &fileindex, worktree, repo);
10769 if (error)
10770 goto done;
10772 if (edit_script_path) {
10773 error = histedit_load_list(&histedit_cmds,
10774 edit_script_path, repo);
10775 if (error) {
10776 got_worktree_histedit_abort(worktree, fileindex,
10777 repo, branch, base_commit_id,
10778 abort_progress, &upa);
10779 print_merge_progress_stats(&upa);
10780 goto done;
10782 } else {
10783 const char *branch_name;
10784 branch_name = got_ref_get_symref_target(branch);
10785 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10786 branch_name += 11;
10787 error = histedit_edit_script(&histedit_cmds, &commits,
10788 branch_name, edit_logmsg_only, fold_only,
10789 edit_only, repo);
10790 if (error) {
10791 got_worktree_histedit_abort(worktree, fileindex,
10792 repo, branch, base_commit_id,
10793 abort_progress, &upa);
10794 print_merge_progress_stats(&upa);
10795 goto done;
10800 error = histedit_save_list(&histedit_cmds, worktree,
10801 repo);
10802 if (error) {
10803 got_worktree_histedit_abort(worktree, fileindex,
10804 repo, branch, base_commit_id,
10805 abort_progress, &upa);
10806 print_merge_progress_stats(&upa);
10807 goto done;
10812 error = histedit_check_script(&histedit_cmds, &commits, repo);
10813 if (error)
10814 goto done;
10816 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10817 if (resume_commit_id) {
10818 if (got_object_id_cmp(hle->commit_id,
10819 resume_commit_id) != 0)
10820 continue;
10822 resume_commit_id = NULL;
10823 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10824 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10825 error = histedit_skip_commit(hle, worktree,
10826 repo);
10827 if (error)
10828 goto done;
10829 } else {
10830 struct got_pathlist_head paths;
10831 int have_changes = 0;
10833 TAILQ_INIT(&paths);
10834 error = got_pathlist_append(&paths, "", NULL);
10835 if (error)
10836 goto done;
10837 error = got_worktree_status(worktree, &paths,
10838 repo, 0, check_local_changes, &have_changes,
10839 check_cancelled, NULL);
10840 got_pathlist_free(&paths);
10841 if (error) {
10842 if (error->code != GOT_ERR_CANCELLED)
10843 goto done;
10844 if (sigint_received || sigpipe_received)
10845 goto done;
10847 if (have_changes) {
10848 error = histedit_commit(NULL, worktree,
10849 fileindex, tmp_branch, hle, repo);
10850 if (error)
10851 goto done;
10852 } else {
10853 error = got_object_open_as_commit(
10854 &commit, repo, hle->commit_id);
10855 if (error)
10856 goto done;
10857 error = show_histedit_progress(commit,
10858 hle, NULL);
10859 got_object_commit_close(commit);
10860 commit = NULL;
10861 if (error)
10862 goto done;
10865 continue;
10868 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10869 error = histedit_skip_commit(hle, worktree, repo);
10870 if (error)
10871 goto done;
10872 continue;
10875 error = got_object_open_as_commit(&commit, repo,
10876 hle->commit_id);
10877 if (error)
10878 goto done;
10879 parent_ids = got_object_commit_get_parent_ids(commit);
10880 pid = STAILQ_FIRST(parent_ids);
10882 error = got_worktree_histedit_merge_files(&merged_paths,
10883 worktree, fileindex, pid->id, hle->commit_id, repo,
10884 update_progress, &upa, check_cancelled, NULL);
10885 if (error)
10886 goto done;
10887 got_object_commit_close(commit);
10888 commit = NULL;
10890 print_merge_progress_stats(&upa);
10891 if (upa.conflicts > 0 || upa.missing > 0 ||
10892 upa.not_deleted > 0 || upa.unversioned > 0) {
10893 if (upa.conflicts > 0) {
10894 error = show_rebase_merge_conflict(
10895 hle->commit_id, repo);
10896 if (error)
10897 goto done;
10899 got_worktree_rebase_pathlist_free(&merged_paths);
10900 break;
10903 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10904 char *id_str;
10905 error = got_object_id_str(&id_str, hle->commit_id);
10906 if (error)
10907 goto done;
10908 printf("Stopping histedit for amending commit %s\n",
10909 id_str);
10910 free(id_str);
10911 got_worktree_rebase_pathlist_free(&merged_paths);
10912 error = got_worktree_histedit_postpone(worktree,
10913 fileindex);
10914 goto done;
10917 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10918 error = histedit_skip_commit(hle, worktree, repo);
10919 if (error)
10920 goto done;
10921 continue;
10924 error = histedit_commit(&merged_paths, worktree, fileindex,
10925 tmp_branch, hle, repo);
10926 got_worktree_rebase_pathlist_free(&merged_paths);
10927 if (error)
10928 goto done;
10931 if (upa.conflicts > 0 || upa.missing > 0 ||
10932 upa.not_deleted > 0 || upa.unversioned > 0) {
10933 error = got_worktree_histedit_postpone(worktree, fileindex);
10934 if (error)
10935 goto done;
10936 if (upa.conflicts > 0 && upa.missing == 0 &&
10937 upa.not_deleted == 0 && upa.unversioned == 0) {
10938 error = got_error_msg(GOT_ERR_CONFLICTS,
10939 "conflicts must be resolved before histedit "
10940 "can continue");
10941 } else if (upa.conflicts > 0) {
10942 error = got_error_msg(GOT_ERR_CONFLICTS,
10943 "conflicts must be resolved before histedit "
10944 "can continue; changes destined for some "
10945 "files were not yet merged and should be "
10946 "merged manually if required before the "
10947 "histedit operation is continued");
10948 } else {
10949 error = got_error_msg(GOT_ERR_CONFLICTS,
10950 "changes destined for some files were not "
10951 "yet merged and should be merged manually "
10952 "if required before the histedit operation "
10953 "is continued");
10955 } else
10956 error = histedit_complete(worktree, fileindex, tmp_branch,
10957 branch, repo);
10958 done:
10959 got_object_id_queue_free(&commits);
10960 histedit_free_list(&histedit_cmds);
10961 free(head_commit_id);
10962 free(base_commit_id);
10963 free(resume_commit_id);
10964 if (commit)
10965 got_object_commit_close(commit);
10966 if (branch)
10967 got_ref_close(branch);
10968 if (tmp_branch)
10969 got_ref_close(tmp_branch);
10970 if (worktree)
10971 got_worktree_close(worktree);
10972 if (repo) {
10973 const struct got_error *close_err = got_repo_close(repo);
10974 if (error == NULL)
10975 error = close_err;
10977 return error;
10980 __dead static void
10981 usage_integrate(void)
10983 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10984 exit(1);
10987 static const struct got_error *
10988 cmd_integrate(int argc, char *argv[])
10990 const struct got_error *error = NULL;
10991 struct got_repository *repo = NULL;
10992 struct got_worktree *worktree = NULL;
10993 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10994 const char *branch_arg = NULL;
10995 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10996 struct got_fileindex *fileindex = NULL;
10997 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10998 int ch;
10999 struct got_update_progress_arg upa;
11001 while ((ch = getopt(argc, argv, "")) != -1) {
11002 switch (ch) {
11003 default:
11004 usage_integrate();
11005 /* NOTREACHED */
11009 argc -= optind;
11010 argv += optind;
11012 if (argc != 1)
11013 usage_integrate();
11014 branch_arg = argv[0];
11015 #ifndef PROFILE
11016 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11017 "unveil", NULL) == -1)
11018 err(1, "pledge");
11019 #endif
11020 cwd = getcwd(NULL, 0);
11021 if (cwd == NULL) {
11022 error = got_error_from_errno("getcwd");
11023 goto done;
11026 error = got_worktree_open(&worktree, cwd);
11027 if (error) {
11028 if (error->code == GOT_ERR_NOT_WORKTREE)
11029 error = wrap_not_worktree_error(error, "integrate",
11030 cwd);
11031 goto done;
11034 error = check_rebase_or_histedit_in_progress(worktree);
11035 if (error)
11036 goto done;
11038 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11039 NULL);
11040 if (error != NULL)
11041 goto done;
11043 error = apply_unveil(got_repo_get_path(repo), 0,
11044 got_worktree_get_root_path(worktree));
11045 if (error)
11046 goto done;
11048 error = check_merge_in_progress(worktree, repo);
11049 if (error)
11050 goto done;
11052 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11053 error = got_error_from_errno("asprintf");
11054 goto done;
11057 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11058 &base_branch_ref, worktree, refname, repo);
11059 if (error)
11060 goto done;
11062 refname = strdup(got_ref_get_name(branch_ref));
11063 if (refname == NULL) {
11064 error = got_error_from_errno("strdup");
11065 got_worktree_integrate_abort(worktree, fileindex, repo,
11066 branch_ref, base_branch_ref);
11067 goto done;
11069 base_refname = strdup(got_ref_get_name(base_branch_ref));
11070 if (base_refname == NULL) {
11071 error = got_error_from_errno("strdup");
11072 got_worktree_integrate_abort(worktree, fileindex, repo,
11073 branch_ref, base_branch_ref);
11074 goto done;
11077 error = got_ref_resolve(&commit_id, repo, branch_ref);
11078 if (error)
11079 goto done;
11081 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11082 if (error)
11083 goto done;
11085 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11086 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11087 "specified branch has already been integrated");
11088 got_worktree_integrate_abort(worktree, fileindex, repo,
11089 branch_ref, base_branch_ref);
11090 goto done;
11093 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11094 if (error) {
11095 if (error->code == GOT_ERR_ANCESTRY)
11096 error = got_error(GOT_ERR_REBASE_REQUIRED);
11097 got_worktree_integrate_abort(worktree, fileindex, repo,
11098 branch_ref, base_branch_ref);
11099 goto done;
11102 memset(&upa, 0, sizeof(upa));
11103 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11104 branch_ref, base_branch_ref, update_progress, &upa,
11105 check_cancelled, NULL);
11106 if (error)
11107 goto done;
11109 printf("Integrated %s into %s\n", refname, base_refname);
11110 print_update_progress_stats(&upa);
11111 done:
11112 if (repo) {
11113 const struct got_error *close_err = got_repo_close(repo);
11114 if (error == NULL)
11115 error = close_err;
11117 if (worktree)
11118 got_worktree_close(worktree);
11119 free(cwd);
11120 free(base_commit_id);
11121 free(commit_id);
11122 free(refname);
11123 free(base_refname);
11124 return error;
11127 __dead static void
11128 usage_merge(void)
11130 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11131 getprogname());
11132 exit(1);
11135 static const struct got_error *
11136 cmd_merge(int argc, char *argv[])
11138 const struct got_error *error = NULL;
11139 struct got_worktree *worktree = NULL;
11140 struct got_repository *repo = NULL;
11141 struct got_fileindex *fileindex = NULL;
11142 char *cwd = NULL, *id_str = NULL, *author = NULL;
11143 struct got_reference *branch = NULL, *wt_branch = NULL;
11144 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11145 struct got_object_id *wt_branch_tip = NULL;
11146 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11147 int interrupt_merge = 0;
11148 struct got_update_progress_arg upa;
11149 struct got_object_id *merge_commit_id = NULL;
11150 char *branch_name = NULL;
11152 memset(&upa, 0, sizeof(upa));
11154 while ((ch = getopt(argc, argv, "acn")) != -1) {
11155 switch (ch) {
11156 case 'a':
11157 abort_merge = 1;
11158 break;
11159 case 'c':
11160 continue_merge = 1;
11161 break;
11162 case 'n':
11163 interrupt_merge = 1;
11164 break;
11165 default:
11166 usage_rebase();
11167 /* NOTREACHED */
11171 argc -= optind;
11172 argv += optind;
11174 #ifndef PROFILE
11175 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11176 "unveil", NULL) == -1)
11177 err(1, "pledge");
11178 #endif
11180 if (abort_merge && continue_merge)
11181 option_conflict('a', 'c');
11182 if (abort_merge || continue_merge) {
11183 if (argc != 0)
11184 usage_merge();
11185 } else if (argc != 1)
11186 usage_merge();
11188 cwd = getcwd(NULL, 0);
11189 if (cwd == NULL) {
11190 error = got_error_from_errno("getcwd");
11191 goto done;
11194 error = got_worktree_open(&worktree, cwd);
11195 if (error) {
11196 if (error->code == GOT_ERR_NOT_WORKTREE)
11197 error = wrap_not_worktree_error(error,
11198 "merge", cwd);
11199 goto done;
11202 error = got_repo_open(&repo,
11203 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11204 if (error != NULL)
11205 goto done;
11207 error = apply_unveil(got_repo_get_path(repo), 0,
11208 worktree ? got_worktree_get_root_path(worktree) : NULL);
11209 if (error)
11210 goto done;
11212 error = check_rebase_or_histedit_in_progress(worktree);
11213 if (error)
11214 goto done;
11216 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11217 repo);
11218 if (error)
11219 goto done;
11221 if (abort_merge) {
11222 if (!merge_in_progress) {
11223 error = got_error(GOT_ERR_NOT_MERGING);
11224 goto done;
11226 error = got_worktree_merge_continue(&branch_name,
11227 &branch_tip, &fileindex, worktree, repo);
11228 if (error)
11229 goto done;
11230 error = got_worktree_merge_abort(worktree, fileindex, repo,
11231 abort_progress, &upa);
11232 if (error)
11233 goto done;
11234 printf("Merge of %s aborted\n", branch_name);
11235 goto done; /* nothing else to do */
11238 error = get_author(&author, repo, worktree);
11239 if (error)
11240 goto done;
11242 if (continue_merge) {
11243 if (!merge_in_progress) {
11244 error = got_error(GOT_ERR_NOT_MERGING);
11245 goto done;
11247 error = got_worktree_merge_continue(&branch_name,
11248 &branch_tip, &fileindex, worktree, repo);
11249 if (error)
11250 goto done;
11251 } else {
11252 error = got_ref_open(&branch, repo, argv[0], 0);
11253 if (error != NULL)
11254 goto done;
11255 branch_name = strdup(got_ref_get_name(branch));
11256 if (branch_name == NULL) {
11257 error = got_error_from_errno("strdup");
11258 goto done;
11260 error = got_ref_resolve(&branch_tip, repo, branch);
11261 if (error)
11262 goto done;
11265 error = got_ref_open(&wt_branch, repo,
11266 got_worktree_get_head_ref_name(worktree), 0);
11267 if (error)
11268 goto done;
11269 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11270 if (error)
11271 goto done;
11272 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11273 wt_branch_tip, branch_tip, 0, repo,
11274 check_cancelled, NULL);
11275 if (error && error->code != GOT_ERR_ANCESTRY)
11276 goto done;
11278 if (!continue_merge) {
11279 error = check_path_prefix(wt_branch_tip, branch_tip,
11280 got_worktree_get_path_prefix(worktree),
11281 GOT_ERR_MERGE_PATH, repo);
11282 if (error)
11283 goto done;
11284 if (yca_id) {
11285 error = check_same_branch(wt_branch_tip, branch,
11286 yca_id, repo);
11287 if (error) {
11288 if (error->code != GOT_ERR_ANCESTRY)
11289 goto done;
11290 error = NULL;
11291 } else {
11292 static char msg[512];
11293 snprintf(msg, sizeof(msg),
11294 "cannot create a merge commit because "
11295 "%s is based on %s; %s can be integrated "
11296 "with 'got integrate' instead", branch_name,
11297 got_worktree_get_head_ref_name(worktree),
11298 branch_name);
11299 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11300 goto done;
11303 error = got_worktree_merge_prepare(&fileindex, worktree,
11304 branch, repo);
11305 if (error)
11306 goto done;
11308 error = got_worktree_merge_branch(worktree, fileindex,
11309 yca_id, branch_tip, repo, update_progress, &upa,
11310 check_cancelled, NULL);
11311 if (error)
11312 goto done;
11313 print_merge_progress_stats(&upa);
11314 if (!upa.did_something) {
11315 error = got_worktree_merge_abort(worktree, fileindex,
11316 repo, abort_progress, &upa);
11317 if (error)
11318 goto done;
11319 printf("Already up-to-date\n");
11320 goto done;
11324 if (interrupt_merge) {
11325 error = got_worktree_merge_postpone(worktree, fileindex);
11326 if (error)
11327 goto done;
11328 printf("Merge of %s interrupted on request\n", branch_name);
11329 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11330 upa.not_deleted > 0 || upa.unversioned > 0) {
11331 error = got_worktree_merge_postpone(worktree, fileindex);
11332 if (error)
11333 goto done;
11334 if (upa.conflicts > 0 && upa.missing == 0 &&
11335 upa.not_deleted == 0 && upa.unversioned == 0) {
11336 error = got_error_msg(GOT_ERR_CONFLICTS,
11337 "conflicts must be resolved before merging "
11338 "can continue");
11339 } else if (upa.conflicts > 0) {
11340 error = got_error_msg(GOT_ERR_CONFLICTS,
11341 "conflicts must be resolved before merging "
11342 "can continue; changes destined for some "
11343 "files were not yet merged and "
11344 "should be merged manually if required before the "
11345 "merge operation is continued");
11346 } else {
11347 error = got_error_msg(GOT_ERR_CONFLICTS,
11348 "changes destined for some "
11349 "files were not yet merged and should be "
11350 "merged manually if required before the "
11351 "merge operation is continued");
11353 goto done;
11354 } else {
11355 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11356 fileindex, author, NULL, 1, branch_tip, branch_name,
11357 repo, continue_merge ? print_status : NULL, NULL);
11358 if (error)
11359 goto done;
11360 error = got_worktree_merge_complete(worktree, fileindex, repo);
11361 if (error)
11362 goto done;
11363 error = got_object_id_str(&id_str, merge_commit_id);
11364 if (error)
11365 goto done;
11366 printf("Merged %s into %s: %s\n", branch_name,
11367 got_worktree_get_head_ref_name(worktree),
11368 id_str);
11371 done:
11372 free(id_str);
11373 free(merge_commit_id);
11374 free(author);
11375 free(branch_tip);
11376 free(branch_name);
11377 free(yca_id);
11378 if (branch)
11379 got_ref_close(branch);
11380 if (wt_branch)
11381 got_ref_close(wt_branch);
11382 if (worktree)
11383 got_worktree_close(worktree);
11384 if (repo) {
11385 const struct got_error *close_err = got_repo_close(repo);
11386 if (error == NULL)
11387 error = close_err;
11389 return error;
11392 __dead static void
11393 usage_stage(void)
11395 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11396 "[-S] [file-path ...]\n",
11397 getprogname());
11398 exit(1);
11401 static const struct got_error *
11402 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11403 const char *path, struct got_object_id *blob_id,
11404 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11405 int dirfd, const char *de_name)
11407 const struct got_error *err = NULL;
11408 char *id_str = NULL;
11410 if (staged_status != GOT_STATUS_ADD &&
11411 staged_status != GOT_STATUS_MODIFY &&
11412 staged_status != GOT_STATUS_DELETE)
11413 return NULL;
11415 if (staged_status == GOT_STATUS_ADD ||
11416 staged_status == GOT_STATUS_MODIFY)
11417 err = got_object_id_str(&id_str, staged_blob_id);
11418 else
11419 err = got_object_id_str(&id_str, blob_id);
11420 if (err)
11421 return err;
11423 printf("%s %c %s\n", id_str, staged_status, path);
11424 free(id_str);
11425 return NULL;
11428 static const struct got_error *
11429 cmd_stage(int argc, char *argv[])
11431 const struct got_error *error = NULL;
11432 struct got_repository *repo = NULL;
11433 struct got_worktree *worktree = NULL;
11434 char *cwd = NULL;
11435 struct got_pathlist_head paths;
11436 struct got_pathlist_entry *pe;
11437 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11438 FILE *patch_script_file = NULL;
11439 const char *patch_script_path = NULL;
11440 struct choose_patch_arg cpa;
11442 TAILQ_INIT(&paths);
11444 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11445 switch (ch) {
11446 case 'l':
11447 list_stage = 1;
11448 break;
11449 case 'p':
11450 pflag = 1;
11451 break;
11452 case 'F':
11453 patch_script_path = optarg;
11454 break;
11455 case 'S':
11456 allow_bad_symlinks = 1;
11457 break;
11458 default:
11459 usage_stage();
11460 /* NOTREACHED */
11464 argc -= optind;
11465 argv += optind;
11467 #ifndef PROFILE
11468 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11469 "unveil", NULL) == -1)
11470 err(1, "pledge");
11471 #endif
11472 if (list_stage && (pflag || patch_script_path))
11473 errx(1, "-l option cannot be used with other options");
11474 if (patch_script_path && !pflag)
11475 errx(1, "-F option can only be used together with -p option");
11477 cwd = getcwd(NULL, 0);
11478 if (cwd == NULL) {
11479 error = got_error_from_errno("getcwd");
11480 goto done;
11483 error = got_worktree_open(&worktree, cwd);
11484 if (error) {
11485 if (error->code == GOT_ERR_NOT_WORKTREE)
11486 error = wrap_not_worktree_error(error, "stage", cwd);
11487 goto done;
11490 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11491 NULL);
11492 if (error != NULL)
11493 goto done;
11495 if (patch_script_path) {
11496 patch_script_file = fopen(patch_script_path, "re");
11497 if (patch_script_file == NULL) {
11498 error = got_error_from_errno2("fopen",
11499 patch_script_path);
11500 goto done;
11503 error = apply_unveil(got_repo_get_path(repo), 0,
11504 got_worktree_get_root_path(worktree));
11505 if (error)
11506 goto done;
11508 error = check_merge_in_progress(worktree, repo);
11509 if (error)
11510 goto done;
11512 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11513 if (error)
11514 goto done;
11516 if (list_stage)
11517 error = got_worktree_status(worktree, &paths, repo, 0,
11518 print_stage, NULL, check_cancelled, NULL);
11519 else {
11520 cpa.patch_script_file = patch_script_file;
11521 cpa.action = "stage";
11522 error = got_worktree_stage(worktree, &paths,
11523 pflag ? NULL : print_status, NULL,
11524 pflag ? choose_patch : NULL, &cpa,
11525 allow_bad_symlinks, repo);
11527 done:
11528 if (patch_script_file && fclose(patch_script_file) == EOF &&
11529 error == NULL)
11530 error = got_error_from_errno2("fclose", patch_script_path);
11531 if (repo) {
11532 const struct got_error *close_err = got_repo_close(repo);
11533 if (error == NULL)
11534 error = close_err;
11536 if (worktree)
11537 got_worktree_close(worktree);
11538 TAILQ_FOREACH(pe, &paths, entry)
11539 free((char *)pe->path);
11540 got_pathlist_free(&paths);
11541 free(cwd);
11542 return error;
11545 __dead static void
11546 usage_unstage(void)
11548 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11549 "[file-path ...]\n",
11550 getprogname());
11551 exit(1);
11555 static const struct got_error *
11556 cmd_unstage(int argc, char *argv[])
11558 const struct got_error *error = NULL;
11559 struct got_repository *repo = NULL;
11560 struct got_worktree *worktree = NULL;
11561 char *cwd = NULL;
11562 struct got_pathlist_head paths;
11563 struct got_pathlist_entry *pe;
11564 int ch, pflag = 0;
11565 struct got_update_progress_arg upa;
11566 FILE *patch_script_file = NULL;
11567 const char *patch_script_path = NULL;
11568 struct choose_patch_arg cpa;
11570 TAILQ_INIT(&paths);
11572 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11573 switch (ch) {
11574 case 'p':
11575 pflag = 1;
11576 break;
11577 case 'F':
11578 patch_script_path = optarg;
11579 break;
11580 default:
11581 usage_unstage();
11582 /* NOTREACHED */
11586 argc -= optind;
11587 argv += optind;
11589 #ifndef PROFILE
11590 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11591 "unveil", NULL) == -1)
11592 err(1, "pledge");
11593 #endif
11594 if (patch_script_path && !pflag)
11595 errx(1, "-F option can only be used together with -p option");
11597 cwd = getcwd(NULL, 0);
11598 if (cwd == NULL) {
11599 error = got_error_from_errno("getcwd");
11600 goto done;
11603 error = got_worktree_open(&worktree, cwd);
11604 if (error) {
11605 if (error->code == GOT_ERR_NOT_WORKTREE)
11606 error = wrap_not_worktree_error(error, "unstage", cwd);
11607 goto done;
11610 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11611 NULL);
11612 if (error != NULL)
11613 goto done;
11615 if (patch_script_path) {
11616 patch_script_file = fopen(patch_script_path, "re");
11617 if (patch_script_file == NULL) {
11618 error = got_error_from_errno2("fopen",
11619 patch_script_path);
11620 goto done;
11624 error = apply_unveil(got_repo_get_path(repo), 0,
11625 got_worktree_get_root_path(worktree));
11626 if (error)
11627 goto done;
11629 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11630 if (error)
11631 goto done;
11633 cpa.patch_script_file = patch_script_file;
11634 cpa.action = "unstage";
11635 memset(&upa, 0, sizeof(upa));
11636 error = got_worktree_unstage(worktree, &paths, update_progress,
11637 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11638 if (!error)
11639 print_merge_progress_stats(&upa);
11640 done:
11641 if (patch_script_file && fclose(patch_script_file) == EOF &&
11642 error == NULL)
11643 error = got_error_from_errno2("fclose", patch_script_path);
11644 if (repo) {
11645 const struct got_error *close_err = got_repo_close(repo);
11646 if (error == NULL)
11647 error = close_err;
11649 if (worktree)
11650 got_worktree_close(worktree);
11651 TAILQ_FOREACH(pe, &paths, entry)
11652 free((char *)pe->path);
11653 got_pathlist_free(&paths);
11654 free(cwd);
11655 return error;
11658 __dead static void
11659 usage_cat(void)
11661 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11662 "arg1 [arg2 ...]\n", getprogname());
11663 exit(1);
11666 static const struct got_error *
11667 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11669 const struct got_error *err;
11670 struct got_blob_object *blob;
11672 err = got_object_open_as_blob(&blob, repo, id, 8192);
11673 if (err)
11674 return err;
11676 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11677 got_object_blob_close(blob);
11678 return err;
11681 static const struct got_error *
11682 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11684 const struct got_error *err;
11685 struct got_tree_object *tree;
11686 int nentries, i;
11688 err = got_object_open_as_tree(&tree, repo, id);
11689 if (err)
11690 return err;
11692 nentries = got_object_tree_get_nentries(tree);
11693 for (i = 0; i < nentries; i++) {
11694 struct got_tree_entry *te;
11695 char *id_str;
11696 if (sigint_received || sigpipe_received)
11697 break;
11698 te = got_object_tree_get_entry(tree, i);
11699 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11700 if (err)
11701 break;
11702 fprintf(outfile, "%s %.7o %s\n", id_str,
11703 got_tree_entry_get_mode(te),
11704 got_tree_entry_get_name(te));
11705 free(id_str);
11708 got_object_tree_close(tree);
11709 return err;
11712 static void
11713 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11715 long long h, m;
11716 char sign = '+';
11718 if (gmtoff < 0) {
11719 sign = '-';
11720 gmtoff = -gmtoff;
11723 h = (long long)gmtoff / 3600;
11724 m = ((long long)gmtoff - h*3600) / 60;
11725 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11728 static const struct got_error *
11729 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11731 const struct got_error *err;
11732 struct got_commit_object *commit;
11733 const struct got_object_id_queue *parent_ids;
11734 struct got_object_qid *pid;
11735 char *id_str = NULL;
11736 const char *logmsg = NULL;
11737 char gmtoff[6];
11739 err = got_object_open_as_commit(&commit, repo, id);
11740 if (err)
11741 return err;
11743 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11744 if (err)
11745 goto done;
11747 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11748 parent_ids = got_object_commit_get_parent_ids(commit);
11749 fprintf(outfile, "numparents %d\n",
11750 got_object_commit_get_nparents(commit));
11751 STAILQ_FOREACH(pid, parent_ids, entry) {
11752 char *pid_str;
11753 err = got_object_id_str(&pid_str, pid->id);
11754 if (err)
11755 goto done;
11756 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11757 free(pid_str);
11759 format_gmtoff(gmtoff, sizeof(gmtoff),
11760 got_object_commit_get_author_gmtoff(commit));
11761 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11762 got_object_commit_get_author(commit),
11763 (long long)got_object_commit_get_author_time(commit),
11764 gmtoff);
11766 format_gmtoff(gmtoff, sizeof(gmtoff),
11767 got_object_commit_get_committer_gmtoff(commit));
11768 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11769 got_object_commit_get_author(commit),
11770 (long long)got_object_commit_get_committer_time(commit),
11771 gmtoff);
11773 logmsg = got_object_commit_get_logmsg_raw(commit);
11774 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11775 fprintf(outfile, "%s", logmsg);
11776 done:
11777 free(id_str);
11778 got_object_commit_close(commit);
11779 return err;
11782 static const struct got_error *
11783 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11785 const struct got_error *err;
11786 struct got_tag_object *tag;
11787 char *id_str = NULL;
11788 const char *tagmsg = NULL;
11789 char gmtoff[6];
11791 err = got_object_open_as_tag(&tag, repo, id);
11792 if (err)
11793 return err;
11795 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11796 if (err)
11797 goto done;
11799 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11801 switch (got_object_tag_get_object_type(tag)) {
11802 case GOT_OBJ_TYPE_BLOB:
11803 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11804 GOT_OBJ_LABEL_BLOB);
11805 break;
11806 case GOT_OBJ_TYPE_TREE:
11807 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11808 GOT_OBJ_LABEL_TREE);
11809 break;
11810 case GOT_OBJ_TYPE_COMMIT:
11811 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11812 GOT_OBJ_LABEL_COMMIT);
11813 break;
11814 case GOT_OBJ_TYPE_TAG:
11815 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11816 GOT_OBJ_LABEL_TAG);
11817 break;
11818 default:
11819 break;
11822 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11823 got_object_tag_get_name(tag));
11825 format_gmtoff(gmtoff, sizeof(gmtoff),
11826 got_object_tag_get_tagger_gmtoff(tag));
11827 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11828 got_object_tag_get_tagger(tag),
11829 (long long)got_object_tag_get_tagger_time(tag),
11830 gmtoff);
11832 tagmsg = got_object_tag_get_message(tag);
11833 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11834 fprintf(outfile, "%s", tagmsg);
11835 done:
11836 free(id_str);
11837 got_object_tag_close(tag);
11838 return err;
11841 static const struct got_error *
11842 cmd_cat(int argc, char *argv[])
11844 const struct got_error *error;
11845 struct got_repository *repo = NULL;
11846 struct got_worktree *worktree = NULL;
11847 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11848 const char *commit_id_str = NULL;
11849 struct got_object_id *id = NULL, *commit_id = NULL;
11850 struct got_commit_object *commit = NULL;
11851 int ch, obj_type, i, force_path = 0;
11852 struct got_reflist_head refs;
11854 TAILQ_INIT(&refs);
11856 #ifndef PROFILE
11857 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11858 NULL) == -1)
11859 err(1, "pledge");
11860 #endif
11862 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11863 switch (ch) {
11864 case 'c':
11865 commit_id_str = optarg;
11866 break;
11867 case 'r':
11868 repo_path = realpath(optarg, NULL);
11869 if (repo_path == NULL)
11870 return got_error_from_errno2("realpath",
11871 optarg);
11872 got_path_strip_trailing_slashes(repo_path);
11873 break;
11874 case 'P':
11875 force_path = 1;
11876 break;
11877 default:
11878 usage_cat();
11879 /* NOTREACHED */
11883 argc -= optind;
11884 argv += optind;
11886 cwd = getcwd(NULL, 0);
11887 if (cwd == NULL) {
11888 error = got_error_from_errno("getcwd");
11889 goto done;
11892 if (repo_path == NULL) {
11893 error = got_worktree_open(&worktree, cwd);
11894 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11895 goto done;
11896 if (worktree) {
11897 repo_path = strdup(
11898 got_worktree_get_repo_path(worktree));
11899 if (repo_path == NULL) {
11900 error = got_error_from_errno("strdup");
11901 goto done;
11904 /* Release work tree lock. */
11905 got_worktree_close(worktree);
11906 worktree = NULL;
11910 if (repo_path == NULL) {
11911 repo_path = strdup(cwd);
11912 if (repo_path == NULL)
11913 return got_error_from_errno("strdup");
11916 error = got_repo_open(&repo, repo_path, NULL);
11917 free(repo_path);
11918 if (error != NULL)
11919 goto done;
11921 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11922 if (error)
11923 goto done;
11925 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11926 if (error)
11927 goto done;
11929 if (commit_id_str == NULL)
11930 commit_id_str = GOT_REF_HEAD;
11931 error = got_repo_match_object_id(&commit_id, NULL,
11932 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11933 if (error)
11934 goto done;
11936 error = got_object_open_as_commit(&commit, repo, commit_id);
11937 if (error)
11938 goto done;
11940 for (i = 0; i < argc; i++) {
11941 if (force_path) {
11942 error = got_object_id_by_path(&id, repo, commit,
11943 argv[i]);
11944 if (error)
11945 break;
11946 } else {
11947 error = got_repo_match_object_id(&id, &label, argv[i],
11948 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11949 repo);
11950 if (error) {
11951 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11952 error->code != GOT_ERR_NOT_REF)
11953 break;
11954 error = got_object_id_by_path(&id, repo,
11955 commit, argv[i]);
11956 if (error)
11957 break;
11961 error = got_object_get_type(&obj_type, repo, id);
11962 if (error)
11963 break;
11965 switch (obj_type) {
11966 case GOT_OBJ_TYPE_BLOB:
11967 error = cat_blob(id, repo, stdout);
11968 break;
11969 case GOT_OBJ_TYPE_TREE:
11970 error = cat_tree(id, repo, stdout);
11971 break;
11972 case GOT_OBJ_TYPE_COMMIT:
11973 error = cat_commit(id, repo, stdout);
11974 break;
11975 case GOT_OBJ_TYPE_TAG:
11976 error = cat_tag(id, repo, stdout);
11977 break;
11978 default:
11979 error = got_error(GOT_ERR_OBJ_TYPE);
11980 break;
11982 if (error)
11983 break;
11984 free(label);
11985 label = NULL;
11986 free(id);
11987 id = NULL;
11989 done:
11990 free(label);
11991 free(id);
11992 free(commit_id);
11993 if (commit)
11994 got_object_commit_close(commit);
11995 if (worktree)
11996 got_worktree_close(worktree);
11997 if (repo) {
11998 const struct got_error *close_err = got_repo_close(repo);
11999 if (error == NULL)
12000 error = close_err;
12002 got_ref_list_free(&refs);
12003 return error;
12006 __dead static void
12007 usage_info(void)
12009 fprintf(stderr, "usage: %s info [path ...]\n",
12010 getprogname());
12011 exit(1);
12014 static const struct got_error *
12015 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12016 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12017 struct got_object_id *commit_id)
12019 const struct got_error *err = NULL;
12020 char *id_str = NULL;
12021 char datebuf[128];
12022 struct tm mytm, *tm;
12023 struct got_pathlist_head *paths = arg;
12024 struct got_pathlist_entry *pe;
12027 * Clear error indication from any of the path arguments which
12028 * would cause this file index entry to be displayed.
12030 TAILQ_FOREACH(pe, paths, entry) {
12031 if (got_path_cmp(path, pe->path, strlen(path),
12032 pe->path_len) == 0 ||
12033 got_path_is_child(path, pe->path, pe->path_len))
12034 pe->data = NULL; /* no error */
12037 printf(GOT_COMMIT_SEP_STR);
12038 if (S_ISLNK(mode))
12039 printf("symlink: %s\n", path);
12040 else if (S_ISREG(mode)) {
12041 printf("file: %s\n", path);
12042 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12043 } else if (S_ISDIR(mode))
12044 printf("directory: %s\n", path);
12045 else
12046 printf("something: %s\n", path);
12048 tm = localtime_r(&mtime, &mytm);
12049 if (tm == NULL)
12050 return NULL;
12051 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12052 return got_error(GOT_ERR_NO_SPACE);
12053 printf("timestamp: %s\n", datebuf);
12055 if (blob_id) {
12056 err = got_object_id_str(&id_str, blob_id);
12057 if (err)
12058 return err;
12059 printf("based on blob: %s\n", id_str);
12060 free(id_str);
12063 if (staged_blob_id) {
12064 err = got_object_id_str(&id_str, staged_blob_id);
12065 if (err)
12066 return err;
12067 printf("based on staged blob: %s\n", id_str);
12068 free(id_str);
12071 if (commit_id) {
12072 err = got_object_id_str(&id_str, commit_id);
12073 if (err)
12074 return err;
12075 printf("based on commit: %s\n", id_str);
12076 free(id_str);
12079 return NULL;
12082 static const struct got_error *
12083 cmd_info(int argc, char *argv[])
12085 const struct got_error *error = NULL;
12086 struct got_worktree *worktree = NULL;
12087 char *cwd = NULL, *id_str = NULL;
12088 struct got_pathlist_head paths;
12089 struct got_pathlist_entry *pe;
12090 char *uuidstr = NULL;
12091 int ch, show_files = 0;
12093 TAILQ_INIT(&paths);
12095 while ((ch = getopt(argc, argv, "")) != -1) {
12096 switch (ch) {
12097 default:
12098 usage_info();
12099 /* NOTREACHED */
12103 argc -= optind;
12104 argv += optind;
12106 #ifndef PROFILE
12107 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12108 NULL) == -1)
12109 err(1, "pledge");
12110 #endif
12111 cwd = getcwd(NULL, 0);
12112 if (cwd == NULL) {
12113 error = got_error_from_errno("getcwd");
12114 goto done;
12117 error = got_worktree_open(&worktree, cwd);
12118 if (error) {
12119 if (error->code == GOT_ERR_NOT_WORKTREE)
12120 error = wrap_not_worktree_error(error, "info", cwd);
12121 goto done;
12124 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12125 if (error)
12126 goto done;
12128 if (argc >= 1) {
12129 error = get_worktree_paths_from_argv(&paths, argc, argv,
12130 worktree);
12131 if (error)
12132 goto done;
12133 show_files = 1;
12136 error = got_object_id_str(&id_str,
12137 got_worktree_get_base_commit_id(worktree));
12138 if (error)
12139 goto done;
12141 error = got_worktree_get_uuid(&uuidstr, worktree);
12142 if (error)
12143 goto done;
12145 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12146 printf("work tree base commit: %s\n", id_str);
12147 printf("work tree path prefix: %s\n",
12148 got_worktree_get_path_prefix(worktree));
12149 printf("work tree branch reference: %s\n",
12150 got_worktree_get_head_ref_name(worktree));
12151 printf("work tree UUID: %s\n", uuidstr);
12152 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12154 if (show_files) {
12155 struct got_pathlist_entry *pe;
12156 TAILQ_FOREACH(pe, &paths, entry) {
12157 if (pe->path_len == 0)
12158 continue;
12160 * Assume this path will fail. This will be corrected
12161 * in print_path_info() in case the path does suceeed.
12163 pe->data = (void *)got_error_path(pe->path,
12164 GOT_ERR_BAD_PATH);
12166 error = got_worktree_path_info(worktree, &paths,
12167 print_path_info, &paths, check_cancelled, NULL);
12168 if (error)
12169 goto done;
12170 TAILQ_FOREACH(pe, &paths, entry) {
12171 if (pe->data != NULL) {
12172 error = pe->data; /* bad path */
12173 break;
12177 done:
12178 TAILQ_FOREACH(pe, &paths, entry)
12179 free((char *)pe->path);
12180 got_pathlist_free(&paths);
12181 free(cwd);
12182 free(id_str);
12183 free(uuidstr);
12184 return error;