Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libgen.h>
36 #include <time.h>
37 #include <paths.h>
38 #include <regex.h>
39 #include <getopt.h>
40 #include <util.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 free(commit_id);
2997 if (error->code == GOT_ERR_ANCESTRY) {
2998 error = checkout_ancestry_error(
2999 head_ref, commit_id_str);
3001 goto done;
3003 error = check_same_branch(commit_id, head_ref, NULL, repo);
3004 if (error) {
3005 if (error->code == GOT_ERR_ANCESTRY) {
3006 error = checkout_ancestry_error(
3007 head_ref, commit_id_str);
3009 goto done;
3011 error = got_worktree_set_base_commit_id(worktree, repo,
3012 commit_id);
3013 if (error)
3014 goto done;
3015 /* Expand potentially abbreviated commit ID string. */
3016 free(commit_id_str);
3017 error = got_object_id_str(&commit_id_str, commit_id);
3018 if (error)
3019 goto done;
3020 } else {
3021 commit_id = got_object_id_dup(
3022 got_worktree_get_base_commit_id(worktree));
3023 if (commit_id == NULL) {
3024 error = got_error_from_errno("got_object_id_dup");
3025 goto done;
3027 error = got_object_id_str(&commit_id_str, commit_id);
3028 if (error)
3029 goto done;
3032 error = got_pathlist_append(&paths, "", NULL);
3033 if (error)
3034 goto done;
3035 cpa.worktree_path = worktree_path;
3036 cpa.had_base_commit_ref_error = 0;
3037 cpa.verbosity = verbosity;
3038 error = got_worktree_checkout_files(worktree, &paths, repo,
3039 checkout_progress, &cpa, check_cancelled, NULL);
3040 if (error != NULL)
3041 goto done;
3043 if (got_ref_is_symbolic(head_ref)) {
3044 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3045 if (error)
3046 goto done;
3047 refname = got_ref_get_name(ref);
3048 } else
3049 refname = got_ref_get_name(head_ref);
3050 printf("Checked out %s: %s\n", refname, commit_id_str);
3051 printf("Now shut up and hack\n");
3052 if (cpa.had_base_commit_ref_error)
3053 show_worktree_base_ref_warning();
3054 done:
3055 if (head_ref)
3056 got_ref_close(head_ref);
3057 if (ref)
3058 got_ref_close(ref);
3059 got_pathlist_free(&paths);
3060 free(commit_id_str);
3061 free(commit_id);
3062 free(repo_path);
3063 free(worktree_path);
3064 free(cwd);
3065 return error;
3068 struct got_update_progress_arg {
3069 int did_something;
3070 int conflicts;
3071 int obstructed;
3072 int not_updated;
3073 int missing;
3074 int not_deleted;
3075 int unversioned;
3076 int verbosity;
3079 void
3080 print_update_progress_stats(struct got_update_progress_arg *upa)
3082 if (!upa->did_something)
3083 return;
3085 if (upa->conflicts > 0)
3086 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3087 if (upa->obstructed > 0)
3088 printf("File paths obstructed by a non-regular file: %d\n",
3089 upa->obstructed);
3090 if (upa->not_updated > 0)
3091 printf("Files not updated because of existing merge "
3092 "conflicts: %d\n", upa->not_updated);
3096 * The meaning of some status codes differs between merge-style operations and
3097 * update operations. For example, the ! status code means "file was missing"
3098 * if changes were merged into the work tree, and "missing file was restored"
3099 * if the work tree was updated. This function should be used by any operation
3100 * which merges changes into the work tree without updating the work tree.
3102 void
3103 print_merge_progress_stats(struct got_update_progress_arg *upa)
3105 if (!upa->did_something)
3106 return;
3108 if (upa->conflicts > 0)
3109 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3110 if (upa->obstructed > 0)
3111 printf("File paths obstructed by a non-regular file: %d\n",
3112 upa->obstructed);
3113 if (upa->missing > 0)
3114 printf("Files which had incoming changes but could not be "
3115 "found in the work tree: %d\n", upa->missing);
3116 if (upa->not_deleted > 0)
3117 printf("Files not deleted due to differences in deleted "
3118 "content: %d\n", upa->not_deleted);
3119 if (upa->unversioned > 0)
3120 printf("Files not merged because an unversioned file was "
3121 "found in the work tree: %d\n", upa->unversioned);
3124 __dead static void
3125 usage_update(void)
3127 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3128 "[path ...]\n",
3129 getprogname());
3130 exit(1);
3133 static const struct got_error *
3134 update_progress(void *arg, unsigned char status, const char *path)
3136 struct got_update_progress_arg *upa = arg;
3138 if (status == GOT_STATUS_EXISTS ||
3139 status == GOT_STATUS_BASE_REF_ERR)
3140 return NULL;
3142 upa->did_something = 1;
3144 /* Base commit bump happens silently. */
3145 if (status == GOT_STATUS_BUMP_BASE)
3146 return NULL;
3148 if (status == GOT_STATUS_CONFLICT)
3149 upa->conflicts++;
3150 if (status == GOT_STATUS_OBSTRUCTED)
3151 upa->obstructed++;
3152 if (status == GOT_STATUS_CANNOT_UPDATE)
3153 upa->not_updated++;
3154 if (status == GOT_STATUS_MISSING)
3155 upa->missing++;
3156 if (status == GOT_STATUS_CANNOT_DELETE)
3157 upa->not_deleted++;
3158 if (status == GOT_STATUS_UNVERSIONED)
3159 upa->unversioned++;
3161 while (path[0] == '/')
3162 path++;
3163 if (upa->verbosity >= 0)
3164 printf("%c %s\n", status, path);
3166 return NULL;
3169 static const struct got_error *
3170 switch_head_ref(struct got_reference *head_ref,
3171 struct got_object_id *commit_id, struct got_worktree *worktree,
3172 struct got_repository *repo)
3174 const struct got_error *err = NULL;
3175 char *base_id_str;
3176 int ref_has_moved = 0;
3178 /* Trivial case: switching between two different references. */
3179 if (strcmp(got_ref_get_name(head_ref),
3180 got_worktree_get_head_ref_name(worktree)) != 0) {
3181 printf("Switching work tree from %s to %s\n",
3182 got_worktree_get_head_ref_name(worktree),
3183 got_ref_get_name(head_ref));
3184 return got_worktree_set_head_ref(worktree, head_ref);
3187 err = check_linear_ancestry(commit_id,
3188 got_worktree_get_base_commit_id(worktree), 0, repo);
3189 if (err) {
3190 if (err->code != GOT_ERR_ANCESTRY)
3191 return err;
3192 ref_has_moved = 1;
3194 if (!ref_has_moved)
3195 return NULL;
3197 /* Switching to a rebased branch with the same reference name. */
3198 err = got_object_id_str(&base_id_str,
3199 got_worktree_get_base_commit_id(worktree));
3200 if (err)
3201 return err;
3202 printf("Reference %s now points at a different branch\n",
3203 got_worktree_get_head_ref_name(worktree));
3204 printf("Switching work tree from %s to %s\n", base_id_str,
3205 got_worktree_get_head_ref_name(worktree));
3206 return NULL;
3209 static const struct got_error *
3210 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3212 const struct got_error *err;
3213 int in_progress;
3215 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3216 if (err)
3217 return err;
3218 if (in_progress)
3219 return got_error(GOT_ERR_REBASING);
3221 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3222 if (err)
3223 return err;
3224 if (in_progress)
3225 return got_error(GOT_ERR_HISTEDIT_BUSY);
3227 return NULL;
3230 static const struct got_error *
3231 check_merge_in_progress(struct got_worktree *worktree,
3232 struct got_repository *repo)
3234 const struct got_error *err;
3235 int in_progress;
3237 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3238 if (err)
3239 return err;
3240 if (in_progress)
3241 return got_error(GOT_ERR_MERGE_BUSY);
3243 return NULL;
3246 static const struct got_error *
3247 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3248 char *argv[], struct got_worktree *worktree)
3250 const struct got_error *err = NULL;
3251 char *path;
3252 struct got_pathlist_entry *new;
3253 int i;
3255 if (argc == 0) {
3256 path = strdup("");
3257 if (path == NULL)
3258 return got_error_from_errno("strdup");
3259 return got_pathlist_append(paths, path, NULL);
3262 for (i = 0; i < argc; i++) {
3263 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3264 if (err)
3265 break;
3266 err = got_pathlist_insert(&new, paths, path, NULL);
3267 if (err || new == NULL /* duplicate */) {
3268 free(path);
3269 if (err)
3270 break;
3274 return err;
3277 static const struct got_error *
3278 wrap_not_worktree_error(const struct got_error *orig_err,
3279 const char *cmdname, const char *path)
3281 const struct got_error *err;
3282 struct got_repository *repo;
3283 static char msg[512];
3285 err = got_repo_open(&repo, path, NULL);
3286 if (err)
3287 return orig_err;
3289 snprintf(msg, sizeof(msg),
3290 "'got %s' needs a work tree in addition to a git repository\n"
3291 "Work trees can be checked out from this Git repository with "
3292 "'got checkout'.\n"
3293 "The got(1) manual page contains more information.", cmdname);
3294 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3295 got_repo_close(repo);
3296 return err;
3299 static const struct got_error *
3300 cmd_update(int argc, char *argv[])
3302 const struct got_error *error = NULL;
3303 struct got_repository *repo = NULL;
3304 struct got_worktree *worktree = NULL;
3305 char *worktree_path = NULL;
3306 struct got_object_id *commit_id = NULL;
3307 char *commit_id_str = NULL;
3308 const char *branch_name = NULL;
3309 struct got_reference *head_ref = NULL;
3310 struct got_pathlist_head paths;
3311 struct got_pathlist_entry *pe;
3312 int ch, verbosity = 0;
3313 struct got_update_progress_arg upa;
3315 TAILQ_INIT(&paths);
3317 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3318 switch (ch) {
3319 case 'b':
3320 branch_name = optarg;
3321 break;
3322 case 'c':
3323 commit_id_str = strdup(optarg);
3324 if (commit_id_str == NULL)
3325 return got_error_from_errno("strdup");
3326 break;
3327 case 'q':
3328 verbosity = -1;
3329 break;
3330 default:
3331 usage_update();
3332 /* NOTREACHED */
3336 argc -= optind;
3337 argv += optind;
3339 #ifndef PROFILE
3340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3341 "unveil", NULL) == -1)
3342 err(1, "pledge");
3343 #endif
3344 worktree_path = getcwd(NULL, 0);
3345 if (worktree_path == NULL) {
3346 error = got_error_from_errno("getcwd");
3347 goto done;
3349 error = got_worktree_open(&worktree, worktree_path);
3350 if (error) {
3351 if (error->code == GOT_ERR_NOT_WORKTREE)
3352 error = wrap_not_worktree_error(error, "update",
3353 worktree_path);
3354 goto done;
3357 error = check_rebase_or_histedit_in_progress(worktree);
3358 if (error)
3359 goto done;
3361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3362 NULL);
3363 if (error != NULL)
3364 goto done;
3366 error = apply_unveil(got_repo_get_path(repo), 0,
3367 got_worktree_get_root_path(worktree));
3368 if (error)
3369 goto done;
3371 error = check_merge_in_progress(worktree, repo);
3372 if (error)
3373 goto done;
3375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3376 if (error)
3377 goto done;
3379 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3380 got_worktree_get_head_ref_name(worktree), 0);
3381 if (error != NULL)
3382 goto done;
3383 if (commit_id_str == NULL) {
3384 error = got_ref_resolve(&commit_id, repo, head_ref);
3385 if (error != NULL)
3386 goto done;
3387 error = got_object_id_str(&commit_id_str, commit_id);
3388 if (error != NULL)
3389 goto done;
3390 } else {
3391 struct got_reflist_head refs;
3392 TAILQ_INIT(&refs);
3393 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3394 NULL);
3395 if (error)
3396 goto done;
3397 error = got_repo_match_object_id(&commit_id, NULL,
3398 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3399 got_ref_list_free(&refs);
3400 free(commit_id_str);
3401 commit_id_str = NULL;
3402 if (error)
3403 goto done;
3404 error = got_object_id_str(&commit_id_str, commit_id);
3405 if (error)
3406 goto done;
3409 if (branch_name) {
3410 struct got_object_id *head_commit_id;
3411 TAILQ_FOREACH(pe, &paths, entry) {
3412 if (pe->path_len == 0)
3413 continue;
3414 error = got_error_msg(GOT_ERR_BAD_PATH,
3415 "switching between branches requires that "
3416 "the entire work tree gets updated");
3417 goto done;
3419 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3420 if (error)
3421 goto done;
3422 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3423 repo);
3424 free(head_commit_id);
3425 if (error != NULL)
3426 goto done;
3427 error = check_same_branch(commit_id, head_ref, NULL, repo);
3428 if (error)
3429 goto done;
3430 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3431 if (error)
3432 goto done;
3433 } else {
3434 error = check_linear_ancestry(commit_id,
3435 got_worktree_get_base_commit_id(worktree), 0, repo);
3436 if (error != NULL) {
3437 if (error->code == GOT_ERR_ANCESTRY)
3438 error = got_error(GOT_ERR_BRANCH_MOVED);
3439 goto done;
3441 error = check_same_branch(commit_id, head_ref, NULL, repo);
3442 if (error)
3443 goto done;
3446 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3447 commit_id) != 0) {
3448 error = got_worktree_set_base_commit_id(worktree, repo,
3449 commit_id);
3450 if (error)
3451 goto done;
3454 memset(&upa, 0, sizeof(upa));
3455 upa.verbosity = verbosity;
3456 error = got_worktree_checkout_files(worktree, &paths, repo,
3457 update_progress, &upa, check_cancelled, NULL);
3458 if (error != NULL)
3459 goto done;
3461 if (upa.did_something) {
3462 printf("Updated to %s: %s\n",
3463 got_worktree_get_head_ref_name(worktree), commit_id_str);
3464 } else
3465 printf("Already up-to-date\n");
3466 print_update_progress_stats(&upa);
3467 done:
3468 free(worktree_path);
3469 TAILQ_FOREACH(pe, &paths, entry)
3470 free((char *)pe->path);
3471 got_pathlist_free(&paths);
3472 free(commit_id);
3473 free(commit_id_str);
3474 return error;
3477 static const struct got_error *
3478 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3479 const char *path, int diff_context, int ignore_whitespace,
3480 int force_text_diff, struct got_repository *repo)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3485 if (blob_id1) {
3486 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3487 if (err)
3488 goto done;
3491 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3492 if (err)
3493 goto done;
3495 while (path[0] == '/')
3496 path++;
3497 err = got_diff_blob(NULL, NULL, blob1, blob2, path, path,
3498 diff_context, ignore_whitespace, force_text_diff, stdout);
3499 done:
3500 if (blob1)
3501 got_object_blob_close(blob1);
3502 got_object_blob_close(blob2);
3503 return err;
3506 static const struct got_error *
3507 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3508 const char *path, int diff_context, int ignore_whitespace,
3509 int force_text_diff, struct got_repository *repo)
3511 const struct got_error *err = NULL;
3512 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3513 struct got_diff_blob_output_unidiff_arg arg;
3515 if (tree_id1) {
3516 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3517 if (err)
3518 goto done;
3521 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3522 if (err)
3523 goto done;
3525 arg.diff_context = diff_context;
3526 arg.ignore_whitespace = ignore_whitespace;
3527 arg.force_text_diff = force_text_diff;
3528 arg.outfile = stdout;
3529 arg.line_offsets = NULL;
3530 arg.nlines = 0;
3531 while (path[0] == '/')
3532 path++;
3533 err = got_diff_tree(tree1, tree2, path, path, repo,
3534 got_diff_blob_output_unidiff, &arg, 1);
3535 done:
3536 if (tree1)
3537 got_object_tree_close(tree1);
3538 if (tree2)
3539 got_object_tree_close(tree2);
3540 return err;
3543 static const struct got_error *
3544 get_changed_paths(struct got_pathlist_head *paths,
3545 struct got_commit_object *commit, struct got_repository *repo)
3547 const struct got_error *err = NULL;
3548 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3549 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3550 struct got_object_qid *qid;
3552 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3553 if (qid != NULL) {
3554 struct got_commit_object *pcommit;
3555 err = got_object_open_as_commit(&pcommit, repo,
3556 qid->id);
3557 if (err)
3558 return err;
3560 tree_id1 = got_object_id_dup(
3561 got_object_commit_get_tree_id(pcommit));
3562 if (tree_id1 == NULL) {
3563 got_object_commit_close(pcommit);
3564 return got_error_from_errno("got_object_id_dup");
3566 got_object_commit_close(pcommit);
3570 if (tree_id1) {
3571 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3572 if (err)
3573 goto done;
3576 tree_id2 = got_object_commit_get_tree_id(commit);
3577 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3578 if (err)
3579 goto done;
3581 err = got_diff_tree(tree1, tree2, "", "", repo,
3582 got_diff_tree_collect_changed_paths, paths, 0);
3583 done:
3584 if (tree1)
3585 got_object_tree_close(tree1);
3586 if (tree2)
3587 got_object_tree_close(tree2);
3588 free(tree_id1);
3589 return err;
3592 static const struct got_error *
3593 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3594 const char *path, int diff_context, struct got_repository *repo)
3596 const struct got_error *err = NULL;
3597 struct got_commit_object *pcommit = NULL;
3598 char *id_str1 = NULL, *id_str2 = NULL;
3599 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3600 struct got_object_qid *qid;
3602 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3603 if (qid != NULL) {
3604 err = got_object_open_as_commit(&pcommit, repo,
3605 qid->id);
3606 if (err)
3607 return err;
3610 if (path && path[0] != '\0') {
3611 int obj_type;
3612 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3613 if (err)
3614 goto done;
3615 err = got_object_id_str(&id_str2, obj_id2);
3616 if (err) {
3617 free(obj_id2);
3618 goto done;
3620 if (pcommit) {
3621 err = got_object_id_by_path(&obj_id1, repo,
3622 pcommit, path);
3623 if (err) {
3624 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3625 free(obj_id2);
3626 goto done;
3628 } else {
3629 err = got_object_id_str(&id_str1, obj_id1);
3630 if (err) {
3631 free(obj_id2);
3632 goto done;
3636 err = got_object_get_type(&obj_type, repo, obj_id2);
3637 if (err) {
3638 free(obj_id2);
3639 goto done;
3641 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3642 switch (obj_type) {
3643 case GOT_OBJ_TYPE_BLOB:
3644 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3645 0, 0, repo);
3646 break;
3647 case GOT_OBJ_TYPE_TREE:
3648 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3649 0, 0, repo);
3650 break;
3651 default:
3652 err = got_error(GOT_ERR_OBJ_TYPE);
3653 break;
3655 free(obj_id1);
3656 free(obj_id2);
3657 } else {
3658 obj_id2 = got_object_commit_get_tree_id(commit);
3659 err = got_object_id_str(&id_str2, obj_id2);
3660 if (err)
3661 goto done;
3662 if (pcommit) {
3663 obj_id1 = got_object_commit_get_tree_id(pcommit);
3664 err = got_object_id_str(&id_str1, obj_id1);
3665 if (err)
3666 goto done;
3668 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3669 id_str2);
3670 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3671 repo);
3673 done:
3674 free(id_str1);
3675 free(id_str2);
3676 if (pcommit)
3677 got_object_commit_close(pcommit);
3678 return err;
3681 static char *
3682 get_datestr(time_t *time, char *datebuf)
3684 struct tm mytm, *tm;
3685 char *p, *s;
3687 tm = gmtime_r(time, &mytm);
3688 if (tm == NULL)
3689 return NULL;
3690 s = asctime_r(tm, datebuf);
3691 if (s == NULL)
3692 return NULL;
3693 p = strchr(s, '\n');
3694 if (p)
3695 *p = '\0';
3696 return s;
3699 static const struct got_error *
3700 match_logmsg(int *have_match, struct got_object_id *id,
3701 struct got_commit_object *commit, regex_t *regex)
3703 const struct got_error *err = NULL;
3704 regmatch_t regmatch;
3705 char *id_str = NULL, *logmsg = NULL;
3707 *have_match = 0;
3709 err = got_object_id_str(&id_str, id);
3710 if (err)
3711 return err;
3713 err = got_object_commit_get_logmsg(&logmsg, commit);
3714 if (err)
3715 goto done;
3717 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3718 *have_match = 1;
3719 done:
3720 free(id_str);
3721 free(logmsg);
3722 return err;
3725 static void
3726 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3727 regex_t *regex)
3729 regmatch_t regmatch;
3730 struct got_pathlist_entry *pe;
3732 *have_match = 0;
3734 TAILQ_FOREACH(pe, changed_paths, entry) {
3735 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3736 *have_match = 1;
3737 break;
3742 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3744 static const struct got_error*
3745 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3746 struct got_object_id *id, struct got_repository *repo)
3748 static const struct got_error *err = NULL;
3749 struct got_reflist_entry *re;
3750 char *s;
3751 const char *name;
3753 *refs_str = NULL;
3755 TAILQ_FOREACH(re, refs, entry) {
3756 struct got_tag_object *tag = NULL;
3757 struct got_object_id *ref_id;
3758 int cmp;
3760 name = got_ref_get_name(re->ref);
3761 if (strcmp(name, GOT_REF_HEAD) == 0)
3762 continue;
3763 if (strncmp(name, "refs/", 5) == 0)
3764 name += 5;
3765 if (strncmp(name, "got/", 4) == 0)
3766 continue;
3767 if (strncmp(name, "heads/", 6) == 0)
3768 name += 6;
3769 if (strncmp(name, "remotes/", 8) == 0) {
3770 name += 8;
3771 s = strstr(name, "/" GOT_REF_HEAD);
3772 if (s != NULL && s[strlen(s)] == '\0')
3773 continue;
3775 err = got_ref_resolve(&ref_id, repo, re->ref);
3776 if (err)
3777 break;
3778 if (strncmp(name, "tags/", 5) == 0) {
3779 err = got_object_open_as_tag(&tag, repo, ref_id);
3780 if (err) {
3781 if (err->code != GOT_ERR_OBJ_TYPE) {
3782 free(ref_id);
3783 break;
3785 /* Ref points at something other than a tag. */
3786 err = NULL;
3787 tag = NULL;
3790 cmp = got_object_id_cmp(tag ?
3791 got_object_tag_get_object_id(tag) : ref_id, id);
3792 free(ref_id);
3793 if (tag)
3794 got_object_tag_close(tag);
3795 if (cmp != 0)
3796 continue;
3797 s = *refs_str;
3798 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3799 s ? ", " : "", name) == -1) {
3800 err = got_error_from_errno("asprintf");
3801 free(s);
3802 *refs_str = NULL;
3803 break;
3805 free(s);
3808 return err;
3811 static const struct got_error *
3812 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3813 struct got_repository *repo, const char *path,
3814 struct got_pathlist_head *changed_paths, int show_patch,
3815 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3816 const char *custom_refs_str)
3818 const struct got_error *err = NULL;
3819 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3820 char datebuf[26];
3821 time_t committer_time;
3822 const char *author, *committer;
3823 char *refs_str = NULL;
3825 err = got_object_id_str(&id_str, id);
3826 if (err)
3827 return err;
3829 if (custom_refs_str == NULL) {
3830 struct got_reflist_head *refs;
3831 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3832 if (refs) {
3833 err = build_refs_str(&refs_str, refs, id, repo);
3834 if (err)
3835 goto done;
3839 printf(GOT_COMMIT_SEP_STR);
3840 if (custom_refs_str)
3841 printf("commit %s (%s)\n", id_str, custom_refs_str);
3842 else
3843 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3844 refs_str ? refs_str : "", refs_str ? ")" : "");
3845 free(id_str);
3846 id_str = NULL;
3847 free(refs_str);
3848 refs_str = NULL;
3849 printf("from: %s\n", got_object_commit_get_author(commit));
3850 committer_time = got_object_commit_get_committer_time(commit);
3851 datestr = get_datestr(&committer_time, datebuf);
3852 if (datestr)
3853 printf("date: %s UTC\n", datestr);
3854 author = got_object_commit_get_author(commit);
3855 committer = got_object_commit_get_committer(commit);
3856 if (strcmp(author, committer) != 0)
3857 printf("via: %s\n", committer);
3858 if (got_object_commit_get_nparents(commit) > 1) {
3859 const struct got_object_id_queue *parent_ids;
3860 struct got_object_qid *qid;
3861 int n = 1;
3862 parent_ids = got_object_commit_get_parent_ids(commit);
3863 STAILQ_FOREACH(qid, parent_ids, entry) {
3864 err = got_object_id_str(&id_str, qid->id);
3865 if (err)
3866 goto done;
3867 printf("parent %d: %s\n", n++, id_str);
3868 free(id_str);
3869 id_str = NULL;
3873 err = got_object_commit_get_logmsg(&logmsg0, commit);
3874 if (err)
3875 goto done;
3877 logmsg = logmsg0;
3878 do {
3879 line = strsep(&logmsg, "\n");
3880 if (line)
3881 printf(" %s\n", line);
3882 } while (line);
3883 free(logmsg0);
3885 if (changed_paths) {
3886 struct got_pathlist_entry *pe;
3887 TAILQ_FOREACH(pe, changed_paths, entry) {
3888 struct got_diff_changed_path *cp = pe->data;
3889 printf(" %c %s\n", cp->status, pe->path);
3891 printf("\n");
3893 if (show_patch) {
3894 err = print_patch(commit, id, path, diff_context, repo);
3895 if (err == 0)
3896 printf("\n");
3899 if (fflush(stdout) != 0 && err == NULL)
3900 err = got_error_from_errno("fflush");
3901 done:
3902 free(id_str);
3903 free(refs_str);
3904 return err;
3907 static const struct got_error *
3908 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3909 struct got_repository *repo, const char *path, int show_changed_paths,
3910 int show_patch, const char *search_pattern, int diff_context, int limit,
3911 int log_branches, int reverse_display_order,
3912 struct got_reflist_object_id_map *refs_idmap)
3914 const struct got_error *err;
3915 struct got_commit_graph *graph;
3916 regex_t regex;
3917 int have_match;
3918 struct got_object_id_queue reversed_commits;
3919 struct got_object_qid *qid;
3920 struct got_commit_object *commit;
3921 struct got_pathlist_head changed_paths;
3922 struct got_pathlist_entry *pe;
3924 STAILQ_INIT(&reversed_commits);
3925 TAILQ_INIT(&changed_paths);
3927 if (search_pattern && regcomp(&regex, search_pattern,
3928 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3929 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3931 err = got_commit_graph_open(&graph, path, !log_branches);
3932 if (err)
3933 return err;
3934 err = got_commit_graph_iter_start(graph, root_id, repo,
3935 check_cancelled, NULL);
3936 if (err)
3937 goto done;
3938 for (;;) {
3939 struct got_object_id *id;
3941 if (sigint_received || sigpipe_received)
3942 break;
3944 err = got_commit_graph_iter_next(&id, graph, repo,
3945 check_cancelled, NULL);
3946 if (err) {
3947 if (err->code == GOT_ERR_ITER_COMPLETED)
3948 err = NULL;
3949 break;
3951 if (id == NULL)
3952 break;
3954 err = got_object_open_as_commit(&commit, repo, id);
3955 if (err)
3956 break;
3958 if (show_changed_paths && !reverse_display_order) {
3959 err = get_changed_paths(&changed_paths, commit, repo);
3960 if (err)
3961 break;
3964 if (search_pattern) {
3965 err = match_logmsg(&have_match, id, commit, &regex);
3966 if (err) {
3967 got_object_commit_close(commit);
3968 break;
3970 if (have_match == 0 && show_changed_paths)
3971 match_changed_paths(&have_match,
3972 &changed_paths, &regex);
3973 if (have_match == 0) {
3974 got_object_commit_close(commit);
3975 TAILQ_FOREACH(pe, &changed_paths, entry) {
3976 free((char *)pe->path);
3977 free(pe->data);
3979 got_pathlist_free(&changed_paths);
3980 continue;
3984 if (reverse_display_order) {
3985 err = got_object_qid_alloc(&qid, id);
3986 if (err)
3987 break;
3988 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3989 got_object_commit_close(commit);
3990 } else {
3991 err = print_commit(commit, id, repo, path,
3992 show_changed_paths ? &changed_paths : NULL,
3993 show_patch, diff_context, refs_idmap, NULL);
3994 got_object_commit_close(commit);
3995 if (err)
3996 break;
3998 if ((limit && --limit == 0) ||
3999 (end_id && got_object_id_cmp(id, end_id) == 0))
4000 break;
4002 TAILQ_FOREACH(pe, &changed_paths, entry) {
4003 free((char *)pe->path);
4004 free(pe->data);
4006 got_pathlist_free(&changed_paths);
4008 if (reverse_display_order) {
4009 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4010 err = got_object_open_as_commit(&commit, repo, qid->id);
4011 if (err)
4012 break;
4013 if (show_changed_paths) {
4014 err = get_changed_paths(&changed_paths,
4015 commit, repo);
4016 if (err)
4017 break;
4019 err = print_commit(commit, qid->id, repo, path,
4020 show_changed_paths ? &changed_paths : NULL,
4021 show_patch, diff_context, refs_idmap, NULL);
4022 got_object_commit_close(commit);
4023 if (err)
4024 break;
4025 TAILQ_FOREACH(pe, &changed_paths, entry) {
4026 free((char *)pe->path);
4027 free(pe->data);
4029 got_pathlist_free(&changed_paths);
4032 done:
4033 while (!STAILQ_EMPTY(&reversed_commits)) {
4034 qid = STAILQ_FIRST(&reversed_commits);
4035 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4036 got_object_qid_free(qid);
4038 TAILQ_FOREACH(pe, &changed_paths, entry) {
4039 free((char *)pe->path);
4040 free(pe->data);
4042 got_pathlist_free(&changed_paths);
4043 if (search_pattern)
4044 regfree(&regex);
4045 got_commit_graph_close(graph);
4046 return err;
4049 __dead static void
4050 usage_log(void)
4052 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4053 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4054 "[-R] [path]\n", getprogname());
4055 exit(1);
4058 static int
4059 get_default_log_limit(void)
4061 const char *got_default_log_limit;
4062 long long n;
4063 const char *errstr;
4065 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4066 if (got_default_log_limit == NULL)
4067 return 0;
4068 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4069 if (errstr != NULL)
4070 return 0;
4071 return n;
4074 static const struct got_error *
4075 cmd_log(int argc, char *argv[])
4077 const struct got_error *error;
4078 struct got_repository *repo = NULL;
4079 struct got_worktree *worktree = NULL;
4080 struct got_object_id *start_id = NULL, *end_id = NULL;
4081 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4082 const char *start_commit = NULL, *end_commit = NULL;
4083 const char *search_pattern = NULL;
4084 int diff_context = -1, ch;
4085 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4086 int reverse_display_order = 0;
4087 const char *errstr;
4088 struct got_reflist_head refs;
4089 struct got_reflist_object_id_map *refs_idmap = NULL;
4091 TAILQ_INIT(&refs);
4093 #ifndef PROFILE
4094 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4095 NULL)
4096 == -1)
4097 err(1, "pledge");
4098 #endif
4100 limit = get_default_log_limit();
4102 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4103 switch (ch) {
4104 case 'p':
4105 show_patch = 1;
4106 break;
4107 case 'P':
4108 show_changed_paths = 1;
4109 break;
4110 case 'c':
4111 start_commit = optarg;
4112 break;
4113 case 'C':
4114 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4115 &errstr);
4116 if (errstr != NULL)
4117 errx(1, "number of context lines is %s: %s",
4118 errstr, optarg);
4119 break;
4120 case 'l':
4121 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4122 if (errstr != NULL)
4123 errx(1, "number of commits is %s: %s",
4124 errstr, optarg);
4125 break;
4126 case 'b':
4127 log_branches = 1;
4128 break;
4129 case 'r':
4130 repo_path = realpath(optarg, NULL);
4131 if (repo_path == NULL)
4132 return got_error_from_errno2("realpath",
4133 optarg);
4134 got_path_strip_trailing_slashes(repo_path);
4135 break;
4136 case 'R':
4137 reverse_display_order = 1;
4138 break;
4139 case 's':
4140 search_pattern = optarg;
4141 break;
4142 case 'x':
4143 end_commit = optarg;
4144 break;
4145 default:
4146 usage_log();
4147 /* NOTREACHED */
4151 argc -= optind;
4152 argv += optind;
4154 if (diff_context == -1)
4155 diff_context = 3;
4156 else if (!show_patch)
4157 errx(1, "-C requires -p");
4159 cwd = getcwd(NULL, 0);
4160 if (cwd == NULL) {
4161 error = got_error_from_errno("getcwd");
4162 goto done;
4165 if (repo_path == NULL) {
4166 error = got_worktree_open(&worktree, cwd);
4167 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4168 goto done;
4169 error = NULL;
4172 if (argc == 1) {
4173 if (worktree) {
4174 error = got_worktree_resolve_path(&path, worktree,
4175 argv[0]);
4176 if (error)
4177 goto done;
4178 } else {
4179 path = strdup(argv[0]);
4180 if (path == NULL) {
4181 error = got_error_from_errno("strdup");
4182 goto done;
4185 } else if (argc != 0)
4186 usage_log();
4188 if (repo_path == NULL) {
4189 repo_path = worktree ?
4190 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4192 if (repo_path == NULL) {
4193 error = got_error_from_errno("strdup");
4194 goto done;
4197 error = got_repo_open(&repo, repo_path, NULL);
4198 if (error != NULL)
4199 goto done;
4201 error = apply_unveil(got_repo_get_path(repo), 1,
4202 worktree ? got_worktree_get_root_path(worktree) : NULL);
4203 if (error)
4204 goto done;
4206 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4207 if (error)
4208 goto done;
4210 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4211 if (error)
4212 goto done;
4214 if (start_commit == NULL) {
4215 struct got_reference *head_ref;
4216 struct got_commit_object *commit = NULL;
4217 error = got_ref_open(&head_ref, repo,
4218 worktree ? got_worktree_get_head_ref_name(worktree)
4219 : GOT_REF_HEAD, 0);
4220 if (error != NULL)
4221 goto done;
4222 error = got_ref_resolve(&start_id, repo, head_ref);
4223 got_ref_close(head_ref);
4224 if (error != NULL)
4225 goto done;
4226 error = got_object_open_as_commit(&commit, repo,
4227 start_id);
4228 if (error != NULL)
4229 goto done;
4230 got_object_commit_close(commit);
4231 } else {
4232 error = got_repo_match_object_id(&start_id, NULL,
4233 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4234 if (error != NULL)
4235 goto done;
4237 if (end_commit != NULL) {
4238 error = got_repo_match_object_id(&end_id, NULL,
4239 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4240 if (error != NULL)
4241 goto done;
4244 if (worktree) {
4246 * If a path was specified on the command line it was resolved
4247 * to a path in the work tree above. Prepend the work tree's
4248 * path prefix to obtain the corresponding in-repository path.
4250 if (path) {
4251 const char *prefix;
4252 prefix = got_worktree_get_path_prefix(worktree);
4253 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4254 (path[0] != '\0') ? "/" : "", path) == -1) {
4255 error = got_error_from_errno("asprintf");
4256 goto done;
4259 } else
4260 error = got_repo_map_path(&in_repo_path, repo,
4261 path ? path : "");
4262 if (error != NULL)
4263 goto done;
4264 if (in_repo_path) {
4265 free(path);
4266 path = in_repo_path;
4269 if (worktree) {
4270 /* Release work tree lock. */
4271 got_worktree_close(worktree);
4272 worktree = NULL;
4275 error = print_commits(start_id, end_id, repo, path ? path : "",
4276 show_changed_paths, show_patch, search_pattern, diff_context,
4277 limit, log_branches, reverse_display_order, refs_idmap);
4278 done:
4279 free(path);
4280 free(repo_path);
4281 free(cwd);
4282 if (worktree)
4283 got_worktree_close(worktree);
4284 if (repo) {
4285 const struct got_error *close_err = got_repo_close(repo);
4286 if (error == NULL)
4287 error = close_err;
4289 if (refs_idmap)
4290 got_reflist_object_id_map_free(refs_idmap);
4291 got_ref_list_free(&refs);
4292 return error;
4295 __dead static void
4296 usage_diff(void)
4298 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4299 "[-r repository-path] [-s] [-w] [-P] "
4300 "[object1 object2 | path ...]\n", getprogname());
4301 exit(1);
4304 struct print_diff_arg {
4305 struct got_repository *repo;
4306 struct got_worktree *worktree;
4307 int diff_context;
4308 const char *id_str;
4309 int header_shown;
4310 int diff_staged;
4311 int ignore_whitespace;
4312 int force_text_diff;
4316 * Create a file which contains the target path of a symlink so we can feed
4317 * it as content to the diff engine.
4319 static const struct got_error *
4320 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4321 const char *abspath)
4323 const struct got_error *err = NULL;
4324 char target_path[PATH_MAX];
4325 ssize_t target_len, outlen;
4327 *fd = -1;
4329 if (dirfd != -1) {
4330 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4331 if (target_len == -1)
4332 return got_error_from_errno2("readlinkat", abspath);
4333 } else {
4334 target_len = readlink(abspath, target_path, PATH_MAX);
4335 if (target_len == -1)
4336 return got_error_from_errno2("readlink", abspath);
4339 *fd = got_opentempfd();
4340 if (*fd == -1)
4341 return got_error_from_errno("got_opentempfd");
4343 outlen = write(*fd, target_path, target_len);
4344 if (outlen == -1) {
4345 err = got_error_from_errno("got_opentempfd");
4346 goto done;
4349 if (lseek(*fd, 0, SEEK_SET) == -1) {
4350 err = got_error_from_errno2("lseek", abspath);
4351 goto done;
4353 done:
4354 if (err) {
4355 close(*fd);
4356 *fd = -1;
4358 return err;
4361 static const struct got_error *
4362 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4363 const char *path, struct got_object_id *blob_id,
4364 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4365 int dirfd, const char *de_name)
4367 struct print_diff_arg *a = arg;
4368 const struct got_error *err = NULL;
4369 struct got_blob_object *blob1 = NULL;
4370 int fd = -1;
4371 FILE *f2 = NULL;
4372 char *abspath = NULL, *label1 = NULL;
4373 struct stat sb;
4375 if (a->diff_staged) {
4376 if (staged_status != GOT_STATUS_MODIFY &&
4377 staged_status != GOT_STATUS_ADD &&
4378 staged_status != GOT_STATUS_DELETE)
4379 return NULL;
4380 } else {
4381 if (staged_status == GOT_STATUS_DELETE)
4382 return NULL;
4383 if (status == GOT_STATUS_NONEXISTENT)
4384 return got_error_set_errno(ENOENT, path);
4385 if (status != GOT_STATUS_MODIFY &&
4386 status != GOT_STATUS_ADD &&
4387 status != GOT_STATUS_DELETE &&
4388 status != GOT_STATUS_CONFLICT)
4389 return NULL;
4392 if (!a->header_shown) {
4393 printf("diff %s %s%s\n", a->id_str,
4394 got_worktree_get_root_path(a->worktree),
4395 a->diff_staged ? " (staged changes)" : "");
4396 a->header_shown = 1;
4399 if (a->diff_staged) {
4400 const char *label1 = NULL, *label2 = NULL;
4401 switch (staged_status) {
4402 case GOT_STATUS_MODIFY:
4403 label1 = path;
4404 label2 = path;
4405 break;
4406 case GOT_STATUS_ADD:
4407 label2 = path;
4408 break;
4409 case GOT_STATUS_DELETE:
4410 label1 = path;
4411 break;
4412 default:
4413 return got_error(GOT_ERR_FILE_STATUS);
4415 return got_diff_objects_as_blobs(NULL, NULL, blob_id,
4416 staged_blob_id, label1, label2, a->diff_context,
4417 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4420 if (staged_status == GOT_STATUS_ADD ||
4421 staged_status == GOT_STATUS_MODIFY) {
4422 char *id_str;
4423 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4424 8192);
4425 if (err)
4426 goto done;
4427 err = got_object_id_str(&id_str, staged_blob_id);
4428 if (err)
4429 goto done;
4430 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4431 err = got_error_from_errno("asprintf");
4432 free(id_str);
4433 goto done;
4435 free(id_str);
4436 } else if (status != GOT_STATUS_ADD) {
4437 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4438 if (err)
4439 goto done;
4442 if (status != GOT_STATUS_DELETE) {
4443 if (asprintf(&abspath, "%s/%s",
4444 got_worktree_get_root_path(a->worktree), path) == -1) {
4445 err = got_error_from_errno("asprintf");
4446 goto done;
4449 if (dirfd != -1) {
4450 fd = openat(dirfd, de_name,
4451 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4452 if (fd == -1) {
4453 if (!got_err_open_nofollow_on_symlink()) {
4454 err = got_error_from_errno2("openat",
4455 abspath);
4456 goto done;
4458 err = get_symlink_target_file(&fd, dirfd,
4459 de_name, abspath);
4460 if (err)
4461 goto done;
4463 } else {
4464 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4465 if (fd == -1) {
4466 if (!got_err_open_nofollow_on_symlink()) {
4467 err = got_error_from_errno2("open",
4468 abspath);
4469 goto done;
4471 err = get_symlink_target_file(&fd, dirfd,
4472 de_name, abspath);
4473 if (err)
4474 goto done;
4477 if (fstat(fd, &sb) == -1) {
4478 err = got_error_from_errno2("fstat", abspath);
4479 goto done;
4481 f2 = fdopen(fd, "r");
4482 if (f2 == NULL) {
4483 err = got_error_from_errno2("fdopen", abspath);
4484 goto done;
4486 fd = -1;
4487 } else
4488 sb.st_size = 0;
4490 err = got_diff_blob_file(blob1, label1, f2, sb.st_size, path,
4491 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4492 done:
4493 if (blob1)
4494 got_object_blob_close(blob1);
4495 if (f2 && fclose(f2) == EOF && err == NULL)
4496 err = got_error_from_errno("fclose");
4497 if (fd != -1 && close(fd) == -1 && err == NULL)
4498 err = got_error_from_errno("close");
4499 free(abspath);
4500 return err;
4503 static const struct got_error *
4504 cmd_diff(int argc, char *argv[])
4506 const struct got_error *error;
4507 struct got_repository *repo = NULL;
4508 struct got_worktree *worktree = NULL;
4509 char *cwd = NULL, *repo_path = NULL;
4510 const char *commit_args[2] = { NULL, NULL };
4511 int ncommit_args = 0;
4512 struct got_object_id *ids[2] = { NULL, NULL };
4513 char *labels[2] = { NULL, NULL };
4514 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4515 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4516 int force_text_diff = 0, force_path = 0, rflag = 0;
4517 const char *errstr;
4518 struct got_reflist_head refs;
4519 struct got_pathlist_head paths;
4520 struct got_pathlist_entry *pe;
4522 TAILQ_INIT(&refs);
4523 TAILQ_INIT(&paths);
4525 #ifndef PROFILE
4526 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4527 NULL) == -1)
4528 err(1, "pledge");
4529 #endif
4531 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4532 switch (ch) {
4533 case 'a':
4534 force_text_diff = 1;
4535 break;
4536 case 'c':
4537 if (ncommit_args >= 2)
4538 errx(1, "too many -c options used");
4539 commit_args[ncommit_args++] = optarg;
4540 break;
4541 case 'C':
4542 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4543 &errstr);
4544 if (errstr != NULL)
4545 errx(1, "number of context lines is %s: %s",
4546 errstr, optarg);
4547 break;
4548 case 'r':
4549 repo_path = realpath(optarg, NULL);
4550 if (repo_path == NULL)
4551 return got_error_from_errno2("realpath",
4552 optarg);
4553 got_path_strip_trailing_slashes(repo_path);
4554 rflag = 1;
4555 break;
4556 case 's':
4557 diff_staged = 1;
4558 break;
4559 case 'w':
4560 ignore_whitespace = 1;
4561 break;
4562 case 'P':
4563 force_path = 1;
4564 break;
4565 default:
4566 usage_diff();
4567 /* NOTREACHED */
4571 argc -= optind;
4572 argv += optind;
4574 cwd = getcwd(NULL, 0);
4575 if (cwd == NULL) {
4576 error = got_error_from_errno("getcwd");
4577 goto done;
4580 if (repo_path == NULL) {
4581 error = got_worktree_open(&worktree, cwd);
4582 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4583 goto done;
4584 else
4585 error = NULL;
4586 if (worktree) {
4587 repo_path =
4588 strdup(got_worktree_get_repo_path(worktree));
4589 if (repo_path == NULL) {
4590 error = got_error_from_errno("strdup");
4591 goto done;
4593 } else {
4594 repo_path = strdup(cwd);
4595 if (repo_path == NULL) {
4596 error = got_error_from_errno("strdup");
4597 goto done;
4602 error = got_repo_open(&repo, repo_path, NULL);
4603 free(repo_path);
4604 if (error != NULL)
4605 goto done;
4607 if (rflag || worktree == NULL || ncommit_args > 0) {
4608 if (force_path) {
4609 error = got_error_msg(GOT_ERR_NOT_IMPL,
4610 "-P option can only be used when diffing "
4611 "a work tree");
4612 goto done;
4614 if (diff_staged) {
4615 error = got_error_msg(GOT_ERR_NOT_IMPL,
4616 "-s option can only be used when diffing "
4617 "a work tree");
4618 goto done;
4622 error = apply_unveil(got_repo_get_path(repo), 1,
4623 worktree ? got_worktree_get_root_path(worktree) : NULL);
4624 if (error)
4625 goto done;
4627 if ((!force_path && argc == 2) || ncommit_args > 0) {
4628 int obj_type = (ncommit_args > 0 ?
4629 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4630 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4631 NULL);
4632 if (error)
4633 goto done;
4634 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4635 const char *arg;
4636 if (ncommit_args > 0)
4637 arg = commit_args[i];
4638 else
4639 arg = argv[i];
4640 error = got_repo_match_object_id(&ids[i], &labels[i],
4641 arg, obj_type, &refs, repo);
4642 if (error) {
4643 if (error->code != GOT_ERR_NOT_REF &&
4644 error->code != GOT_ERR_NO_OBJ)
4645 goto done;
4646 if (ncommit_args > 0)
4647 goto done;
4648 error = NULL;
4649 break;
4654 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4655 struct print_diff_arg arg;
4656 char *id_str;
4658 if (worktree == NULL) {
4659 if (argc == 2 && ids[0] == NULL) {
4660 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4661 goto done;
4662 } else if (argc == 2 && ids[1] == NULL) {
4663 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4664 goto done;
4665 } else if (argc > 0) {
4666 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4667 "%s", "specified paths cannot be resolved");
4668 goto done;
4669 } else {
4670 error = got_error(GOT_ERR_NOT_WORKTREE);
4671 goto done;
4675 error = get_worktree_paths_from_argv(&paths, argc, argv,
4676 worktree);
4677 if (error)
4678 goto done;
4680 error = got_object_id_str(&id_str,
4681 got_worktree_get_base_commit_id(worktree));
4682 if (error)
4683 goto done;
4684 arg.repo = repo;
4685 arg.worktree = worktree;
4686 arg.diff_context = diff_context;
4687 arg.id_str = id_str;
4688 arg.header_shown = 0;
4689 arg.diff_staged = diff_staged;
4690 arg.ignore_whitespace = ignore_whitespace;
4691 arg.force_text_diff = force_text_diff;
4693 error = got_worktree_status(worktree, &paths, repo, 0,
4694 print_diff, &arg, check_cancelled, NULL);
4695 free(id_str);
4696 goto done;
4699 if (ncommit_args == 1) {
4700 struct got_commit_object *commit;
4701 error = got_object_open_as_commit(&commit, repo, ids[0]);
4702 if (error)
4703 goto done;
4705 labels[1] = labels[0];
4706 ids[1] = ids[0];
4707 if (got_object_commit_get_nparents(commit) > 0) {
4708 const struct got_object_id_queue *pids;
4709 struct got_object_qid *pid;
4710 pids = got_object_commit_get_parent_ids(commit);
4711 pid = STAILQ_FIRST(pids);
4712 ids[0] = got_object_id_dup(pid->id);
4713 if (ids[0] == NULL) {
4714 error = got_error_from_errno(
4715 "got_object_id_dup");
4716 got_object_commit_close(commit);
4717 goto done;
4719 error = got_object_id_str(&labels[0], ids[0]);
4720 if (error) {
4721 got_object_commit_close(commit);
4722 goto done;
4724 } else {
4725 ids[0] = NULL;
4726 labels[0] = strdup("/dev/null");
4727 if (labels[0] == NULL) {
4728 error = got_error_from_errno("strdup");
4729 got_object_commit_close(commit);
4730 goto done;
4734 got_object_commit_close(commit);
4737 if (ncommit_args == 0 && argc > 2) {
4738 error = got_error_msg(GOT_ERR_BAD_PATH,
4739 "path arguments cannot be used when diffing two objects");
4740 goto done;
4743 if (ids[0]) {
4744 error = got_object_get_type(&type1, repo, ids[0]);
4745 if (error)
4746 goto done;
4749 error = got_object_get_type(&type2, repo, ids[1]);
4750 if (error)
4751 goto done;
4752 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4753 error = got_error(GOT_ERR_OBJ_TYPE);
4754 goto done;
4756 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4757 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4758 "path arguments cannot be used when diffing blobs");
4759 goto done;
4762 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4763 char *in_repo_path;
4764 struct got_pathlist_entry *new;
4765 if (worktree) {
4766 const char *prefix;
4767 char *p;
4768 error = got_worktree_resolve_path(&p, worktree,
4769 argv[i]);
4770 if (error)
4771 goto done;
4772 prefix = got_worktree_get_path_prefix(worktree);
4773 while (prefix[0] == '/')
4774 prefix++;
4775 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4776 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4777 p) == -1) {
4778 error = got_error_from_errno("asprintf");
4779 free(p);
4780 goto done;
4782 free(p);
4783 } else {
4784 char *mapped_path, *s;
4785 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4786 if (error)
4787 goto done;
4788 s = mapped_path;
4789 while (s[0] == '/')
4790 s++;
4791 in_repo_path = strdup(s);
4792 if (in_repo_path == NULL) {
4793 error = got_error_from_errno("asprintf");
4794 free(mapped_path);
4795 goto done;
4797 free(mapped_path);
4800 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4801 if (error || new == NULL /* duplicate */)
4802 free(in_repo_path);
4803 if (error)
4804 goto done;
4807 if (worktree) {
4808 /* Release work tree lock. */
4809 got_worktree_close(worktree);
4810 worktree = NULL;
4813 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4814 case GOT_OBJ_TYPE_BLOB:
4815 error = got_diff_objects_as_blobs(NULL, NULL, ids[0], ids[1],
4816 NULL, NULL, diff_context, ignore_whitespace,
4817 force_text_diff, repo, stdout);
4818 break;
4819 case GOT_OBJ_TYPE_TREE:
4820 error = got_diff_objects_as_trees(NULL, NULL, ids[0], ids[1],
4821 &paths, "", "", diff_context, ignore_whitespace,
4822 force_text_diff, repo, stdout);
4823 break;
4824 case GOT_OBJ_TYPE_COMMIT:
4825 printf("diff %s %s\n", labels[0], labels[1]);
4826 error = got_diff_objects_as_commits(NULL, NULL, ids[0], ids[1],
4827 &paths, diff_context, ignore_whitespace, force_text_diff,
4828 repo, stdout);
4829 break;
4830 default:
4831 error = got_error(GOT_ERR_OBJ_TYPE);
4833 done:
4834 free(labels[0]);
4835 free(labels[1]);
4836 free(ids[0]);
4837 free(ids[1]);
4838 if (worktree)
4839 got_worktree_close(worktree);
4840 if (repo) {
4841 const struct got_error *close_err = got_repo_close(repo);
4842 if (error == NULL)
4843 error = close_err;
4845 TAILQ_FOREACH(pe, &paths, entry)
4846 free((char *)pe->path);
4847 got_pathlist_free(&paths);
4848 got_ref_list_free(&refs);
4849 return error;
4852 __dead static void
4853 usage_blame(void)
4855 fprintf(stderr,
4856 "usage: %s blame [-c commit] [-r repository-path] path\n",
4857 getprogname());
4858 exit(1);
4861 struct blame_line {
4862 int annotated;
4863 char *id_str;
4864 char *committer;
4865 char datebuf[11]; /* YYYY-MM-DD + NUL */
4868 struct blame_cb_args {
4869 struct blame_line *lines;
4870 int nlines;
4871 int nlines_prec;
4872 int lineno_cur;
4873 off_t *line_offsets;
4874 FILE *f;
4875 struct got_repository *repo;
4878 static const struct got_error *
4879 blame_cb(void *arg, int nlines, int lineno,
4880 struct got_commit_object *commit, struct got_object_id *id)
4882 const struct got_error *err = NULL;
4883 struct blame_cb_args *a = arg;
4884 struct blame_line *bline;
4885 char *line = NULL;
4886 size_t linesize = 0;
4887 off_t offset;
4888 struct tm tm;
4889 time_t committer_time;
4891 if (nlines != a->nlines ||
4892 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4893 return got_error(GOT_ERR_RANGE);
4895 if (sigint_received)
4896 return got_error(GOT_ERR_ITER_COMPLETED);
4898 if (lineno == -1)
4899 return NULL; /* no change in this commit */
4901 /* Annotate this line. */
4902 bline = &a->lines[lineno - 1];
4903 if (bline->annotated)
4904 return NULL;
4905 err = got_object_id_str(&bline->id_str, id);
4906 if (err)
4907 return err;
4909 bline->committer = strdup(got_object_commit_get_committer(commit));
4910 if (bline->committer == NULL) {
4911 err = got_error_from_errno("strdup");
4912 goto done;
4915 committer_time = got_object_commit_get_committer_time(commit);
4916 if (gmtime_r(&committer_time, &tm) == NULL)
4917 return got_error_from_errno("gmtime_r");
4918 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4919 &tm) == 0) {
4920 err = got_error(GOT_ERR_NO_SPACE);
4921 goto done;
4923 bline->annotated = 1;
4925 /* Print lines annotated so far. */
4926 bline = &a->lines[a->lineno_cur - 1];
4927 if (!bline->annotated)
4928 goto done;
4930 offset = a->line_offsets[a->lineno_cur - 1];
4931 if (fseeko(a->f, offset, SEEK_SET) == -1) {
4932 err = got_error_from_errno("fseeko");
4933 goto done;
4936 while (bline->annotated) {
4937 char *smallerthan, *at, *nl, *committer;
4938 size_t len;
4940 if (getline(&line, &linesize, a->f) == -1) {
4941 if (ferror(a->f))
4942 err = got_error_from_errno("getline");
4943 break;
4946 committer = bline->committer;
4947 smallerthan = strchr(committer, '<');
4948 if (smallerthan && smallerthan[1] != '\0')
4949 committer = smallerthan + 1;
4950 at = strchr(committer, '@');
4951 if (at)
4952 *at = '\0';
4953 len = strlen(committer);
4954 if (len >= 9)
4955 committer[8] = '\0';
4957 nl = strchr(line, '\n');
4958 if (nl)
4959 *nl = '\0';
4960 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
4961 bline->id_str, bline->datebuf, committer, line);
4963 a->lineno_cur++;
4964 bline = &a->lines[a->lineno_cur - 1];
4966 done:
4967 free(line);
4968 return err;
4971 static const struct got_error *
4972 cmd_blame(int argc, char *argv[])
4974 const struct got_error *error;
4975 struct got_repository *repo = NULL;
4976 struct got_worktree *worktree = NULL;
4977 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
4978 char *link_target = NULL;
4979 struct got_object_id *obj_id = NULL;
4980 struct got_object_id *commit_id = NULL;
4981 struct got_commit_object *commit = NULL;
4982 struct got_blob_object *blob = NULL;
4983 char *commit_id_str = NULL;
4984 struct blame_cb_args bca;
4985 int ch, obj_type, i;
4986 off_t filesize;
4988 memset(&bca, 0, sizeof(bca));
4990 #ifndef PROFILE
4991 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4992 NULL) == -1)
4993 err(1, "pledge");
4994 #endif
4996 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
4997 switch (ch) {
4998 case 'c':
4999 commit_id_str = optarg;
5000 break;
5001 case 'r':
5002 repo_path = realpath(optarg, NULL);
5003 if (repo_path == NULL)
5004 return got_error_from_errno2("realpath",
5005 optarg);
5006 got_path_strip_trailing_slashes(repo_path);
5007 break;
5008 default:
5009 usage_blame();
5010 /* NOTREACHED */
5014 argc -= optind;
5015 argv += optind;
5017 if (argc == 1)
5018 path = argv[0];
5019 else
5020 usage_blame();
5022 cwd = getcwd(NULL, 0);
5023 if (cwd == NULL) {
5024 error = got_error_from_errno("getcwd");
5025 goto done;
5027 if (repo_path == NULL) {
5028 error = got_worktree_open(&worktree, cwd);
5029 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5030 goto done;
5031 else
5032 error = NULL;
5033 if (worktree) {
5034 repo_path =
5035 strdup(got_worktree_get_repo_path(worktree));
5036 if (repo_path == NULL) {
5037 error = got_error_from_errno("strdup");
5038 if (error)
5039 goto done;
5041 } else {
5042 repo_path = strdup(cwd);
5043 if (repo_path == NULL) {
5044 error = got_error_from_errno("strdup");
5045 goto done;
5050 error = got_repo_open(&repo, repo_path, NULL);
5051 if (error != NULL)
5052 goto done;
5054 if (worktree) {
5055 const char *prefix = got_worktree_get_path_prefix(worktree);
5056 char *p;
5058 error = got_worktree_resolve_path(&p, worktree, path);
5059 if (error)
5060 goto done;
5061 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5062 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5063 p) == -1) {
5064 error = got_error_from_errno("asprintf");
5065 free(p);
5066 goto done;
5068 free(p);
5069 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5070 } else {
5071 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5072 if (error)
5073 goto done;
5074 error = got_repo_map_path(&in_repo_path, repo, path);
5076 if (error)
5077 goto done;
5079 if (commit_id_str == NULL) {
5080 struct got_reference *head_ref;
5081 error = got_ref_open(&head_ref, repo, worktree ?
5082 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5083 if (error != NULL)
5084 goto done;
5085 error = got_ref_resolve(&commit_id, repo, head_ref);
5086 got_ref_close(head_ref);
5087 if (error != NULL)
5088 goto done;
5089 } else {
5090 struct got_reflist_head refs;
5091 TAILQ_INIT(&refs);
5092 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5093 NULL);
5094 if (error)
5095 goto done;
5096 error = got_repo_match_object_id(&commit_id, NULL,
5097 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5098 got_ref_list_free(&refs);
5099 if (error)
5100 goto done;
5103 if (worktree) {
5104 /* Release work tree lock. */
5105 got_worktree_close(worktree);
5106 worktree = NULL;
5109 error = got_object_open_as_commit(&commit, repo, commit_id);
5110 if (error)
5111 goto done;
5113 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5114 commit, repo);
5115 if (error)
5116 goto done;
5118 error = got_object_id_by_path(&obj_id, repo, commit,
5119 link_target ? link_target : in_repo_path);
5120 if (error)
5121 goto done;
5123 error = got_object_get_type(&obj_type, repo, obj_id);
5124 if (error)
5125 goto done;
5127 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5128 error = got_error_path(link_target ? link_target : in_repo_path,
5129 GOT_ERR_OBJ_TYPE);
5130 goto done;
5133 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5134 if (error)
5135 goto done;
5136 bca.f = got_opentemp();
5137 if (bca.f == NULL) {
5138 error = got_error_from_errno("got_opentemp");
5139 goto done;
5141 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5142 &bca.line_offsets, bca.f, blob);
5143 if (error || bca.nlines == 0)
5144 goto done;
5146 /* Don't include \n at EOF in the blame line count. */
5147 if (bca.line_offsets[bca.nlines - 1] == filesize)
5148 bca.nlines--;
5150 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5151 if (bca.lines == NULL) {
5152 error = got_error_from_errno("calloc");
5153 goto done;
5155 bca.lineno_cur = 1;
5156 bca.nlines_prec = 0;
5157 i = bca.nlines;
5158 while (i > 0) {
5159 i /= 10;
5160 bca.nlines_prec++;
5162 bca.repo = repo;
5164 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5165 repo, blame_cb, &bca, check_cancelled, NULL);
5166 done:
5167 free(in_repo_path);
5168 free(link_target);
5169 free(repo_path);
5170 free(cwd);
5171 free(commit_id);
5172 free(obj_id);
5173 if (commit)
5174 got_object_commit_close(commit);
5175 if (blob)
5176 got_object_blob_close(blob);
5177 if (worktree)
5178 got_worktree_close(worktree);
5179 if (repo) {
5180 const struct got_error *close_err = got_repo_close(repo);
5181 if (error == NULL)
5182 error = close_err;
5184 if (bca.lines) {
5185 for (i = 0; i < bca.nlines; i++) {
5186 struct blame_line *bline = &bca.lines[i];
5187 free(bline->id_str);
5188 free(bline->committer);
5190 free(bca.lines);
5192 free(bca.line_offsets);
5193 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5194 error = got_error_from_errno("fclose");
5195 return error;
5198 __dead static void
5199 usage_tree(void)
5201 fprintf(stderr,
5202 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5203 getprogname());
5204 exit(1);
5207 static const struct got_error *
5208 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5209 const char *root_path, struct got_repository *repo)
5211 const struct got_error *err = NULL;
5212 int is_root_path = (strcmp(path, root_path) == 0);
5213 const char *modestr = "";
5214 mode_t mode = got_tree_entry_get_mode(te);
5215 char *link_target = NULL;
5217 path += strlen(root_path);
5218 while (path[0] == '/')
5219 path++;
5221 if (got_object_tree_entry_is_submodule(te))
5222 modestr = "$";
5223 else if (S_ISLNK(mode)) {
5224 int i;
5226 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5227 if (err)
5228 return err;
5229 for (i = 0; i < strlen(link_target); i++) {
5230 if (!isprint((unsigned char)link_target[i]))
5231 link_target[i] = '?';
5234 modestr = "@";
5236 else if (S_ISDIR(mode))
5237 modestr = "/";
5238 else if (mode & S_IXUSR)
5239 modestr = "*";
5241 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5242 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5243 link_target ? " -> ": "", link_target ? link_target : "");
5245 free(link_target);
5246 return NULL;
5249 static const struct got_error *
5250 print_tree(const char *path, struct got_commit_object *commit,
5251 int show_ids, int recurse, const char *root_path,
5252 struct got_repository *repo)
5254 const struct got_error *err = NULL;
5255 struct got_object_id *tree_id = NULL;
5256 struct got_tree_object *tree = NULL;
5257 int nentries, i;
5259 err = got_object_id_by_path(&tree_id, repo, commit, path);
5260 if (err)
5261 goto done;
5263 err = got_object_open_as_tree(&tree, repo, tree_id);
5264 if (err)
5265 goto done;
5266 nentries = got_object_tree_get_nentries(tree);
5267 for (i = 0; i < nentries; i++) {
5268 struct got_tree_entry *te;
5269 char *id = NULL;
5271 if (sigint_received || sigpipe_received)
5272 break;
5274 te = got_object_tree_get_entry(tree, i);
5275 if (show_ids) {
5276 char *id_str;
5277 err = got_object_id_str(&id_str,
5278 got_tree_entry_get_id(te));
5279 if (err)
5280 goto done;
5281 if (asprintf(&id, "%s ", id_str) == -1) {
5282 err = got_error_from_errno("asprintf");
5283 free(id_str);
5284 goto done;
5286 free(id_str);
5288 err = print_entry(te, id, path, root_path, repo);
5289 free(id);
5290 if (err)
5291 goto done;
5293 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5294 char *child_path;
5295 if (asprintf(&child_path, "%s%s%s", path,
5296 path[0] == '/' && path[1] == '\0' ? "" : "/",
5297 got_tree_entry_get_name(te)) == -1) {
5298 err = got_error_from_errno("asprintf");
5299 goto done;
5301 err = print_tree(child_path, commit, show_ids, 1,
5302 root_path, repo);
5303 free(child_path);
5304 if (err)
5305 goto done;
5308 done:
5309 if (tree)
5310 got_object_tree_close(tree);
5311 free(tree_id);
5312 return err;
5315 static const struct got_error *
5316 cmd_tree(int argc, char *argv[])
5318 const struct got_error *error;
5319 struct got_repository *repo = NULL;
5320 struct got_worktree *worktree = NULL;
5321 const char *path, *refname = NULL;
5322 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5323 struct got_object_id *commit_id = NULL;
5324 struct got_commit_object *commit = NULL;
5325 char *commit_id_str = NULL;
5326 int show_ids = 0, recurse = 0;
5327 int ch;
5329 #ifndef PROFILE
5330 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5331 NULL) == -1)
5332 err(1, "pledge");
5333 #endif
5335 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5336 switch (ch) {
5337 case 'c':
5338 commit_id_str = optarg;
5339 break;
5340 case 'r':
5341 repo_path = realpath(optarg, NULL);
5342 if (repo_path == NULL)
5343 return got_error_from_errno2("realpath",
5344 optarg);
5345 got_path_strip_trailing_slashes(repo_path);
5346 break;
5347 case 'i':
5348 show_ids = 1;
5349 break;
5350 case 'R':
5351 recurse = 1;
5352 break;
5353 default:
5354 usage_tree();
5355 /* NOTREACHED */
5359 argc -= optind;
5360 argv += optind;
5362 if (argc == 1)
5363 path = argv[0];
5364 else if (argc > 1)
5365 usage_tree();
5366 else
5367 path = NULL;
5369 cwd = getcwd(NULL, 0);
5370 if (cwd == NULL) {
5371 error = got_error_from_errno("getcwd");
5372 goto done;
5374 if (repo_path == NULL) {
5375 error = got_worktree_open(&worktree, cwd);
5376 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5377 goto done;
5378 else
5379 error = NULL;
5380 if (worktree) {
5381 repo_path =
5382 strdup(got_worktree_get_repo_path(worktree));
5383 if (repo_path == NULL)
5384 error = got_error_from_errno("strdup");
5385 if (error)
5386 goto done;
5387 } else {
5388 repo_path = strdup(cwd);
5389 if (repo_path == NULL) {
5390 error = got_error_from_errno("strdup");
5391 goto done;
5396 error = got_repo_open(&repo, repo_path, NULL);
5397 if (error != NULL)
5398 goto done;
5400 if (worktree) {
5401 const char *prefix = got_worktree_get_path_prefix(worktree);
5402 char *p;
5404 if (path == NULL)
5405 path = "";
5406 error = got_worktree_resolve_path(&p, worktree, path);
5407 if (error)
5408 goto done;
5409 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5410 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5411 p) == -1) {
5412 error = got_error_from_errno("asprintf");
5413 free(p);
5414 goto done;
5416 free(p);
5417 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5418 if (error)
5419 goto done;
5420 } else {
5421 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5422 if (error)
5423 goto done;
5424 if (path == NULL)
5425 path = "/";
5426 error = got_repo_map_path(&in_repo_path, repo, path);
5427 if (error != NULL)
5428 goto done;
5431 if (commit_id_str == NULL) {
5432 struct got_reference *head_ref;
5433 if (worktree)
5434 refname = got_worktree_get_head_ref_name(worktree);
5435 else
5436 refname = GOT_REF_HEAD;
5437 error = got_ref_open(&head_ref, repo, refname, 0);
5438 if (error != NULL)
5439 goto done;
5440 error = got_ref_resolve(&commit_id, repo, head_ref);
5441 got_ref_close(head_ref);
5442 if (error != NULL)
5443 goto done;
5444 } else {
5445 struct got_reflist_head refs;
5446 TAILQ_INIT(&refs);
5447 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5448 NULL);
5449 if (error)
5450 goto done;
5451 error = got_repo_match_object_id(&commit_id, NULL,
5452 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5453 got_ref_list_free(&refs);
5454 if (error)
5455 goto done;
5458 if (worktree) {
5459 /* Release work tree lock. */
5460 got_worktree_close(worktree);
5461 worktree = NULL;
5464 error = got_object_open_as_commit(&commit, repo, commit_id);
5465 if (error)
5466 goto done;
5468 error = print_tree(in_repo_path, commit, show_ids, recurse,
5469 in_repo_path, repo);
5470 done:
5471 free(in_repo_path);
5472 free(repo_path);
5473 free(cwd);
5474 free(commit_id);
5475 if (commit)
5476 got_object_commit_close(commit);
5477 if (worktree)
5478 got_worktree_close(worktree);
5479 if (repo) {
5480 const struct got_error *close_err = got_repo_close(repo);
5481 if (error == NULL)
5482 error = close_err;
5484 return error;
5487 __dead static void
5488 usage_status(void)
5490 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5491 "[-S status-codes] [path ...]\n", getprogname());
5492 exit(1);
5495 struct got_status_arg {
5496 char *status_codes;
5497 int suppress;
5500 static const struct got_error *
5501 print_status(void *arg, unsigned char status, unsigned char staged_status,
5502 const char *path, struct got_object_id *blob_id,
5503 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5504 int dirfd, const char *de_name)
5506 struct got_status_arg *st = arg;
5508 if (status == staged_status && (status == GOT_STATUS_DELETE))
5509 status = GOT_STATUS_NO_CHANGE;
5510 if (st != NULL && st->status_codes) {
5511 size_t ncodes = strlen(st->status_codes);
5512 int i, j = 0;
5514 for (i = 0; i < ncodes ; i++) {
5515 if (st->suppress) {
5516 if (status == st->status_codes[i] ||
5517 staged_status == st->status_codes[i]) {
5518 j++;
5519 continue;
5521 } else {
5522 if (status == st->status_codes[i] ||
5523 staged_status == st->status_codes[i])
5524 break;
5528 if (st->suppress && j == 0)
5529 goto print;
5531 if (i == ncodes)
5532 return NULL;
5534 print:
5535 printf("%c%c %s\n", status, staged_status, path);
5536 return NULL;
5539 static const struct got_error *
5540 cmd_status(int argc, char *argv[])
5542 const struct got_error *error = NULL;
5543 struct got_repository *repo = NULL;
5544 struct got_worktree *worktree = NULL;
5545 struct got_status_arg st;
5546 char *cwd = NULL;
5547 struct got_pathlist_head paths;
5548 struct got_pathlist_entry *pe;
5549 int ch, i, no_ignores = 0;
5551 TAILQ_INIT(&paths);
5553 memset(&st, 0, sizeof(st));
5554 st.status_codes = NULL;
5555 st.suppress = 0;
5557 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5558 switch (ch) {
5559 case 'I':
5560 no_ignores = 1;
5561 break;
5562 case 'S':
5563 if (st.status_codes != NULL && st.suppress == 0)
5564 option_conflict('S', 's');
5565 st.suppress = 1;
5566 /* fallthrough */
5567 case 's':
5568 for (i = 0; i < strlen(optarg); i++) {
5569 switch (optarg[i]) {
5570 case GOT_STATUS_MODIFY:
5571 case GOT_STATUS_ADD:
5572 case GOT_STATUS_DELETE:
5573 case GOT_STATUS_CONFLICT:
5574 case GOT_STATUS_MISSING:
5575 case GOT_STATUS_OBSTRUCTED:
5576 case GOT_STATUS_UNVERSIONED:
5577 case GOT_STATUS_MODE_CHANGE:
5578 case GOT_STATUS_NONEXISTENT:
5579 break;
5580 default:
5581 errx(1, "invalid status code '%c'",
5582 optarg[i]);
5585 if (ch == 's' && st.suppress)
5586 option_conflict('s', 'S');
5587 st.status_codes = optarg;
5588 break;
5589 default:
5590 usage_status();
5591 /* NOTREACHED */
5595 argc -= optind;
5596 argv += optind;
5598 #ifndef PROFILE
5599 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5600 NULL) == -1)
5601 err(1, "pledge");
5602 #endif
5603 cwd = getcwd(NULL, 0);
5604 if (cwd == NULL) {
5605 error = got_error_from_errno("getcwd");
5606 goto done;
5609 error = got_worktree_open(&worktree, cwd);
5610 if (error) {
5611 if (error->code == GOT_ERR_NOT_WORKTREE)
5612 error = wrap_not_worktree_error(error, "status", cwd);
5613 goto done;
5616 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5617 NULL);
5618 if (error != NULL)
5619 goto done;
5621 error = apply_unveil(got_repo_get_path(repo), 1,
5622 got_worktree_get_root_path(worktree));
5623 if (error)
5624 goto done;
5626 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5627 if (error)
5628 goto done;
5630 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5631 print_status, &st, check_cancelled, NULL);
5632 done:
5633 TAILQ_FOREACH(pe, &paths, entry)
5634 free((char *)pe->path);
5635 got_pathlist_free(&paths);
5636 free(cwd);
5637 return error;
5640 __dead static void
5641 usage_ref(void)
5643 fprintf(stderr,
5644 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5645 "[-s reference] [-d] [name]\n",
5646 getprogname());
5647 exit(1);
5650 static const struct got_error *
5651 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5653 static const struct got_error *err = NULL;
5654 struct got_reflist_head refs;
5655 struct got_reflist_entry *re;
5657 TAILQ_INIT(&refs);
5658 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5659 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5660 repo);
5661 if (err)
5662 return err;
5664 TAILQ_FOREACH(re, &refs, entry) {
5665 char *refstr;
5666 refstr = got_ref_to_str(re->ref);
5667 if (refstr == NULL) {
5668 err = got_error_from_errno("got_ref_to_str");
5669 break;
5671 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5672 free(refstr);
5675 got_ref_list_free(&refs);
5676 return err;
5679 static const struct got_error *
5680 delete_ref_by_name(struct got_repository *repo, const char *refname)
5682 const struct got_error *err;
5683 struct got_reference *ref;
5685 err = got_ref_open(&ref, repo, refname, 0);
5686 if (err)
5687 return err;
5689 err = delete_ref(repo, ref);
5690 got_ref_close(ref);
5691 return err;
5694 static const struct got_error *
5695 add_ref(struct got_repository *repo, const char *refname, const char *target)
5697 const struct got_error *err = NULL;
5698 struct got_object_id *id = NULL;
5699 struct got_reference *ref = NULL;
5700 struct got_reflist_head refs;
5703 * Don't let the user create a reference name with a leading '-'.
5704 * While technically a valid reference name, this case is usually
5705 * an unintended typo.
5707 if (refname[0] == '-')
5708 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5710 TAILQ_INIT(&refs);
5711 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5712 if (err)
5713 goto done;
5714 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5715 &refs, repo);
5716 got_ref_list_free(&refs);
5717 if (err)
5718 goto done;
5720 err = got_ref_alloc(&ref, refname, id);
5721 if (err)
5722 goto done;
5724 err = got_ref_write(ref, repo);
5725 done:
5726 if (ref)
5727 got_ref_close(ref);
5728 free(id);
5729 return err;
5732 static const struct got_error *
5733 add_symref(struct got_repository *repo, const char *refname, const char *target)
5735 const struct got_error *err = NULL;
5736 struct got_reference *ref = NULL;
5737 struct got_reference *target_ref = NULL;
5740 * Don't let the user create a reference name with a leading '-'.
5741 * While technically a valid reference name, this case is usually
5742 * an unintended typo.
5744 if (refname[0] == '-')
5745 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5747 err = got_ref_open(&target_ref, repo, target, 0);
5748 if (err)
5749 return err;
5751 err = got_ref_alloc_symref(&ref, refname, target_ref);
5752 if (err)
5753 goto done;
5755 err = got_ref_write(ref, repo);
5756 done:
5757 if (target_ref)
5758 got_ref_close(target_ref);
5759 if (ref)
5760 got_ref_close(ref);
5761 return err;
5764 static const struct got_error *
5765 cmd_ref(int argc, char *argv[])
5767 const struct got_error *error = NULL;
5768 struct got_repository *repo = NULL;
5769 struct got_worktree *worktree = NULL;
5770 char *cwd = NULL, *repo_path = NULL;
5771 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5772 const char *obj_arg = NULL, *symref_target= NULL;
5773 char *refname = NULL;
5775 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5776 switch (ch) {
5777 case 'c':
5778 obj_arg = optarg;
5779 break;
5780 case 'd':
5781 do_delete = 1;
5782 break;
5783 case 'r':
5784 repo_path = realpath(optarg, NULL);
5785 if (repo_path == NULL)
5786 return got_error_from_errno2("realpath",
5787 optarg);
5788 got_path_strip_trailing_slashes(repo_path);
5789 break;
5790 case 'l':
5791 do_list = 1;
5792 break;
5793 case 's':
5794 symref_target = optarg;
5795 break;
5796 case 't':
5797 sort_by_time = 1;
5798 break;
5799 default:
5800 usage_ref();
5801 /* NOTREACHED */
5805 if (obj_arg && do_list)
5806 option_conflict('c', 'l');
5807 if (obj_arg && do_delete)
5808 option_conflict('c', 'd');
5809 if (obj_arg && symref_target)
5810 option_conflict('c', 's');
5811 if (symref_target && do_delete)
5812 option_conflict('s', 'd');
5813 if (symref_target && do_list)
5814 option_conflict('s', 'l');
5815 if (do_delete && do_list)
5816 option_conflict('d', 'l');
5817 if (sort_by_time && !do_list)
5818 errx(1, "-t option requires -l option");
5820 argc -= optind;
5821 argv += optind;
5823 if (do_list) {
5824 if (argc != 0 && argc != 1)
5825 usage_ref();
5826 if (argc == 1) {
5827 refname = strdup(argv[0]);
5828 if (refname == NULL) {
5829 error = got_error_from_errno("strdup");
5830 goto done;
5833 } else {
5834 if (argc != 1)
5835 usage_ref();
5836 refname = strdup(argv[0]);
5837 if (refname == NULL) {
5838 error = got_error_from_errno("strdup");
5839 goto done;
5843 if (refname)
5844 got_path_strip_trailing_slashes(refname);
5846 #ifndef PROFILE
5847 if (do_list) {
5848 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5849 NULL) == -1)
5850 err(1, "pledge");
5851 } else {
5852 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5853 "sendfd unveil", NULL) == -1)
5854 err(1, "pledge");
5856 #endif
5857 cwd = getcwd(NULL, 0);
5858 if (cwd == NULL) {
5859 error = got_error_from_errno("getcwd");
5860 goto done;
5863 if (repo_path == NULL) {
5864 error = got_worktree_open(&worktree, cwd);
5865 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5866 goto done;
5867 else
5868 error = NULL;
5869 if (worktree) {
5870 repo_path =
5871 strdup(got_worktree_get_repo_path(worktree));
5872 if (repo_path == NULL)
5873 error = got_error_from_errno("strdup");
5874 if (error)
5875 goto done;
5876 } else {
5877 repo_path = strdup(cwd);
5878 if (repo_path == NULL) {
5879 error = got_error_from_errno("strdup");
5880 goto done;
5885 error = got_repo_open(&repo, repo_path, NULL);
5886 if (error != NULL)
5887 goto done;
5889 error = apply_unveil(got_repo_get_path(repo), do_list,
5890 worktree ? got_worktree_get_root_path(worktree) : NULL);
5891 if (error)
5892 goto done;
5894 if (do_list)
5895 error = list_refs(repo, refname, sort_by_time);
5896 else if (do_delete)
5897 error = delete_ref_by_name(repo, refname);
5898 else if (symref_target)
5899 error = add_symref(repo, refname, symref_target);
5900 else {
5901 if (obj_arg == NULL)
5902 usage_ref();
5903 error = add_ref(repo, refname, obj_arg);
5905 done:
5906 free(refname);
5907 if (repo) {
5908 const struct got_error *close_err = got_repo_close(repo);
5909 if (error == NULL)
5910 error = close_err;
5912 if (worktree)
5913 got_worktree_close(worktree);
5914 free(cwd);
5915 free(repo_path);
5916 return error;
5919 __dead static void
5920 usage_branch(void)
5922 fprintf(stderr,
5923 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
5924 "[-n] [name]\n", getprogname());
5925 exit(1);
5928 static const struct got_error *
5929 list_branch(struct got_repository *repo, struct got_worktree *worktree,
5930 struct got_reference *ref)
5932 const struct got_error *err = NULL;
5933 const char *refname, *marker = " ";
5934 char *refstr;
5936 refname = got_ref_get_name(ref);
5937 if (worktree && strcmp(refname,
5938 got_worktree_get_head_ref_name(worktree)) == 0) {
5939 struct got_object_id *id = NULL;
5941 err = got_ref_resolve(&id, repo, ref);
5942 if (err)
5943 return err;
5944 if (got_object_id_cmp(id,
5945 got_worktree_get_base_commit_id(worktree)) == 0)
5946 marker = "* ";
5947 else
5948 marker = "~ ";
5949 free(id);
5952 if (strncmp(refname, "refs/heads/", 11) == 0)
5953 refname += 11;
5954 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5955 refname += 18;
5956 if (strncmp(refname, "refs/remotes/", 13) == 0)
5957 refname += 13;
5959 refstr = got_ref_to_str(ref);
5960 if (refstr == NULL)
5961 return got_error_from_errno("got_ref_to_str");
5963 printf("%s%s: %s\n", marker, refname, refstr);
5964 free(refstr);
5965 return NULL;
5968 static const struct got_error *
5969 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
5971 const char *refname;
5973 if (worktree == NULL)
5974 return got_error(GOT_ERR_NOT_WORKTREE);
5976 refname = got_worktree_get_head_ref_name(worktree);
5978 if (strncmp(refname, "refs/heads/", 11) == 0)
5979 refname += 11;
5980 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
5981 refname += 18;
5983 printf("%s\n", refname);
5985 return NULL;
5988 static const struct got_error *
5989 list_branches(struct got_repository *repo, struct got_worktree *worktree,
5990 int sort_by_time)
5992 static const struct got_error *err = NULL;
5993 struct got_reflist_head refs;
5994 struct got_reflist_entry *re;
5995 struct got_reference *temp_ref = NULL;
5996 int rebase_in_progress, histedit_in_progress;
5998 TAILQ_INIT(&refs);
6000 if (worktree) {
6001 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6002 worktree);
6003 if (err)
6004 return err;
6006 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6007 worktree);
6008 if (err)
6009 return err;
6011 if (rebase_in_progress || histedit_in_progress) {
6012 err = got_ref_open(&temp_ref, repo,
6013 got_worktree_get_head_ref_name(worktree), 0);
6014 if (err)
6015 return err;
6016 list_branch(repo, worktree, temp_ref);
6017 got_ref_close(temp_ref);
6021 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6022 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6023 repo);
6024 if (err)
6025 return err;
6027 TAILQ_FOREACH(re, &refs, entry)
6028 list_branch(repo, worktree, re->ref);
6030 got_ref_list_free(&refs);
6032 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6033 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6034 repo);
6035 if (err)
6036 return err;
6038 TAILQ_FOREACH(re, &refs, entry)
6039 list_branch(repo, worktree, re->ref);
6041 got_ref_list_free(&refs);
6043 return NULL;
6046 static const struct got_error *
6047 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6048 const char *branch_name)
6050 const struct got_error *err = NULL;
6051 struct got_reference *ref = NULL;
6052 char *refname, *remote_refname = NULL;
6054 if (strncmp(branch_name, "refs/", 5) == 0)
6055 branch_name += 5;
6056 if (strncmp(branch_name, "heads/", 6) == 0)
6057 branch_name += 6;
6058 else if (strncmp(branch_name, "remotes/", 8) == 0)
6059 branch_name += 8;
6061 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6062 return got_error_from_errno("asprintf");
6064 if (asprintf(&remote_refname, "refs/remotes/%s",
6065 branch_name) == -1) {
6066 err = got_error_from_errno("asprintf");
6067 goto done;
6070 err = got_ref_open(&ref, repo, refname, 0);
6071 if (err) {
6072 const struct got_error *err2;
6073 if (err->code != GOT_ERR_NOT_REF)
6074 goto done;
6076 * Keep 'err' intact such that if neither branch exists
6077 * we report "refs/heads" rather than "refs/remotes" in
6078 * our error message.
6080 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6081 if (err2)
6082 goto done;
6083 err = NULL;
6086 if (worktree &&
6087 strcmp(got_worktree_get_head_ref_name(worktree),
6088 got_ref_get_name(ref)) == 0) {
6089 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6090 "will not delete this work tree's current branch");
6091 goto done;
6094 err = delete_ref(repo, ref);
6095 done:
6096 if (ref)
6097 got_ref_close(ref);
6098 free(refname);
6099 free(remote_refname);
6100 return err;
6103 static const struct got_error *
6104 add_branch(struct got_repository *repo, const char *branch_name,
6105 struct got_object_id *base_commit_id)
6107 const struct got_error *err = NULL;
6108 struct got_reference *ref = NULL;
6109 char *base_refname = NULL, *refname = NULL;
6112 * Don't let the user create a branch name with a leading '-'.
6113 * While technically a valid reference name, this case is usually
6114 * an unintended typo.
6116 if (branch_name[0] == '-')
6117 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6119 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6120 branch_name += 11;
6122 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6123 err = got_error_from_errno("asprintf");
6124 goto done;
6127 err = got_ref_open(&ref, repo, refname, 0);
6128 if (err == NULL) {
6129 err = got_error(GOT_ERR_BRANCH_EXISTS);
6130 goto done;
6131 } else if (err->code != GOT_ERR_NOT_REF)
6132 goto done;
6134 err = got_ref_alloc(&ref, refname, base_commit_id);
6135 if (err)
6136 goto done;
6138 err = got_ref_write(ref, repo);
6139 done:
6140 if (ref)
6141 got_ref_close(ref);
6142 free(base_refname);
6143 free(refname);
6144 return err;
6147 static const struct got_error *
6148 cmd_branch(int argc, char *argv[])
6150 const struct got_error *error = NULL;
6151 struct got_repository *repo = NULL;
6152 struct got_worktree *worktree = NULL;
6153 char *cwd = NULL, *repo_path = NULL;
6154 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6155 const char *delref = NULL, *commit_id_arg = NULL;
6156 struct got_reference *ref = NULL;
6157 struct got_pathlist_head paths;
6158 struct got_pathlist_entry *pe;
6159 struct got_object_id *commit_id = NULL;
6160 char *commit_id_str = NULL;
6162 TAILQ_INIT(&paths);
6164 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6165 switch (ch) {
6166 case 'c':
6167 commit_id_arg = optarg;
6168 break;
6169 case 'd':
6170 delref = optarg;
6171 break;
6172 case 'r':
6173 repo_path = realpath(optarg, NULL);
6174 if (repo_path == NULL)
6175 return got_error_from_errno2("realpath",
6176 optarg);
6177 got_path_strip_trailing_slashes(repo_path);
6178 break;
6179 case 'l':
6180 do_list = 1;
6181 break;
6182 case 'n':
6183 do_update = 0;
6184 break;
6185 case 't':
6186 sort_by_time = 1;
6187 break;
6188 default:
6189 usage_branch();
6190 /* NOTREACHED */
6194 if (do_list && delref)
6195 option_conflict('l', 'd');
6196 if (sort_by_time && !do_list)
6197 errx(1, "-t option requires -l option");
6199 argc -= optind;
6200 argv += optind;
6202 if (!do_list && !delref && argc == 0)
6203 do_show = 1;
6205 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6206 errx(1, "-c option can only be used when creating a branch");
6208 if (do_list || delref) {
6209 if (argc > 0)
6210 usage_branch();
6211 } else if (!do_show && argc != 1)
6212 usage_branch();
6214 #ifndef PROFILE
6215 if (do_list || do_show) {
6216 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6217 NULL) == -1)
6218 err(1, "pledge");
6219 } else {
6220 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6221 "sendfd unveil", NULL) == -1)
6222 err(1, "pledge");
6224 #endif
6225 cwd = getcwd(NULL, 0);
6226 if (cwd == NULL) {
6227 error = got_error_from_errno("getcwd");
6228 goto done;
6231 if (repo_path == NULL) {
6232 error = got_worktree_open(&worktree, cwd);
6233 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6234 goto done;
6235 else
6236 error = NULL;
6237 if (worktree) {
6238 repo_path =
6239 strdup(got_worktree_get_repo_path(worktree));
6240 if (repo_path == NULL)
6241 error = got_error_from_errno("strdup");
6242 if (error)
6243 goto done;
6244 } else {
6245 repo_path = strdup(cwd);
6246 if (repo_path == NULL) {
6247 error = got_error_from_errno("strdup");
6248 goto done;
6253 error = got_repo_open(&repo, repo_path, NULL);
6254 if (error != NULL)
6255 goto done;
6257 error = apply_unveil(got_repo_get_path(repo), do_list,
6258 worktree ? got_worktree_get_root_path(worktree) : NULL);
6259 if (error)
6260 goto done;
6262 if (do_show)
6263 error = show_current_branch(repo, worktree);
6264 else if (do_list)
6265 error = list_branches(repo, worktree, sort_by_time);
6266 else if (delref)
6267 error = delete_branch(repo, worktree, delref);
6268 else {
6269 struct got_reflist_head refs;
6270 TAILQ_INIT(&refs);
6271 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6272 NULL);
6273 if (error)
6274 goto done;
6275 if (commit_id_arg == NULL)
6276 commit_id_arg = worktree ?
6277 got_worktree_get_head_ref_name(worktree) :
6278 GOT_REF_HEAD;
6279 error = got_repo_match_object_id(&commit_id, NULL,
6280 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6281 got_ref_list_free(&refs);
6282 if (error)
6283 goto done;
6284 error = add_branch(repo, argv[0], commit_id);
6285 if (error)
6286 goto done;
6287 if (worktree && do_update) {
6288 struct got_update_progress_arg upa;
6289 char *branch_refname = NULL;
6291 error = got_object_id_str(&commit_id_str, commit_id);
6292 if (error)
6293 goto done;
6294 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6295 worktree);
6296 if (error)
6297 goto done;
6298 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6299 == -1) {
6300 error = got_error_from_errno("asprintf");
6301 goto done;
6303 error = got_ref_open(&ref, repo, branch_refname, 0);
6304 free(branch_refname);
6305 if (error)
6306 goto done;
6307 error = switch_head_ref(ref, commit_id, worktree,
6308 repo);
6309 if (error)
6310 goto done;
6311 error = got_worktree_set_base_commit_id(worktree, repo,
6312 commit_id);
6313 if (error)
6314 goto done;
6315 memset(&upa, 0, sizeof(upa));
6316 error = got_worktree_checkout_files(worktree, &paths,
6317 repo, update_progress, &upa, check_cancelled,
6318 NULL);
6319 if (error)
6320 goto done;
6321 if (upa.did_something) {
6322 printf("Updated to %s: %s\n",
6323 got_worktree_get_head_ref_name(worktree),
6324 commit_id_str);
6326 print_update_progress_stats(&upa);
6329 done:
6330 if (ref)
6331 got_ref_close(ref);
6332 if (repo) {
6333 const struct got_error *close_err = got_repo_close(repo);
6334 if (error == NULL)
6335 error = close_err;
6337 if (worktree)
6338 got_worktree_close(worktree);
6339 free(cwd);
6340 free(repo_path);
6341 free(commit_id);
6342 free(commit_id_str);
6343 TAILQ_FOREACH(pe, &paths, entry)
6344 free((char *)pe->path);
6345 got_pathlist_free(&paths);
6346 return error;
6350 __dead static void
6351 usage_tag(void)
6353 fprintf(stderr,
6354 "usage: %s tag [-c commit] [-r repository] [-l] "
6355 "[-m message] name\n", getprogname());
6356 exit(1);
6359 #if 0
6360 static const struct got_error *
6361 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6363 const struct got_error *err = NULL;
6364 struct got_reflist_entry *re, *se, *new;
6365 struct got_object_id *re_id, *se_id;
6366 struct got_tag_object *re_tag, *se_tag;
6367 time_t re_time, se_time;
6369 STAILQ_FOREACH(re, tags, entry) {
6370 se = STAILQ_FIRST(sorted);
6371 if (se == NULL) {
6372 err = got_reflist_entry_dup(&new, re);
6373 if (err)
6374 return err;
6375 STAILQ_INSERT_HEAD(sorted, new, entry);
6376 continue;
6377 } else {
6378 err = got_ref_resolve(&re_id, repo, re->ref);
6379 if (err)
6380 break;
6381 err = got_object_open_as_tag(&re_tag, repo, re_id);
6382 free(re_id);
6383 if (err)
6384 break;
6385 re_time = got_object_tag_get_tagger_time(re_tag);
6386 got_object_tag_close(re_tag);
6389 while (se) {
6390 err = got_ref_resolve(&se_id, repo, re->ref);
6391 if (err)
6392 break;
6393 err = got_object_open_as_tag(&se_tag, repo, se_id);
6394 free(se_id);
6395 if (err)
6396 break;
6397 se_time = got_object_tag_get_tagger_time(se_tag);
6398 got_object_tag_close(se_tag);
6400 if (se_time > re_time) {
6401 err = got_reflist_entry_dup(&new, re);
6402 if (err)
6403 return err;
6404 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6405 break;
6407 se = STAILQ_NEXT(se, entry);
6408 continue;
6411 done:
6412 return err;
6414 #endif
6416 static const struct got_error *
6417 list_tags(struct got_repository *repo)
6419 static const struct got_error *err = NULL;
6420 struct got_reflist_head refs;
6421 struct got_reflist_entry *re;
6423 TAILQ_INIT(&refs);
6425 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6426 if (err)
6427 return err;
6429 TAILQ_FOREACH(re, &refs, entry) {
6430 const char *refname;
6431 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6432 char datebuf[26];
6433 const char *tagger;
6434 time_t tagger_time;
6435 struct got_object_id *id;
6436 struct got_tag_object *tag;
6437 struct got_commit_object *commit = NULL;
6439 refname = got_ref_get_name(re->ref);
6440 if (strncmp(refname, "refs/tags/", 10) != 0)
6441 continue;
6442 refname += 10;
6443 refstr = got_ref_to_str(re->ref);
6444 if (refstr == NULL) {
6445 err = got_error_from_errno("got_ref_to_str");
6446 break;
6448 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6449 free(refstr);
6451 err = got_ref_resolve(&id, repo, re->ref);
6452 if (err)
6453 break;
6454 err = got_object_open_as_tag(&tag, repo, id);
6455 if (err) {
6456 if (err->code != GOT_ERR_OBJ_TYPE) {
6457 free(id);
6458 break;
6460 /* "lightweight" tag */
6461 err = got_object_open_as_commit(&commit, repo, id);
6462 if (err) {
6463 free(id);
6464 break;
6466 tagger = got_object_commit_get_committer(commit);
6467 tagger_time =
6468 got_object_commit_get_committer_time(commit);
6469 err = got_object_id_str(&id_str, id);
6470 free(id);
6471 if (err)
6472 break;
6473 } else {
6474 free(id);
6475 tagger = got_object_tag_get_tagger(tag);
6476 tagger_time = got_object_tag_get_tagger_time(tag);
6477 err = got_object_id_str(&id_str,
6478 got_object_tag_get_object_id(tag));
6479 if (err)
6480 break;
6482 printf("from: %s\n", tagger);
6483 datestr = get_datestr(&tagger_time, datebuf);
6484 if (datestr)
6485 printf("date: %s UTC\n", datestr);
6486 if (commit)
6487 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6488 else {
6489 switch (got_object_tag_get_object_type(tag)) {
6490 case GOT_OBJ_TYPE_BLOB:
6491 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6492 id_str);
6493 break;
6494 case GOT_OBJ_TYPE_TREE:
6495 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6496 id_str);
6497 break;
6498 case GOT_OBJ_TYPE_COMMIT:
6499 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6500 id_str);
6501 break;
6502 case GOT_OBJ_TYPE_TAG:
6503 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6504 id_str);
6505 break;
6506 default:
6507 break;
6510 free(id_str);
6511 if (commit) {
6512 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6513 if (err)
6514 break;
6515 got_object_commit_close(commit);
6516 } else {
6517 tagmsg0 = strdup(got_object_tag_get_message(tag));
6518 got_object_tag_close(tag);
6519 if (tagmsg0 == NULL) {
6520 err = got_error_from_errno("strdup");
6521 break;
6525 tagmsg = tagmsg0;
6526 do {
6527 line = strsep(&tagmsg, "\n");
6528 if (line)
6529 printf(" %s\n", line);
6530 } while (line);
6531 free(tagmsg0);
6534 got_ref_list_free(&refs);
6535 return NULL;
6538 static const struct got_error *
6539 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6540 const char *tag_name, const char *repo_path)
6542 const struct got_error *err = NULL;
6543 char *template = NULL, *initial_content = NULL;
6544 char *editor = NULL;
6545 int initial_content_len;
6546 int fd = -1;
6548 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6549 err = got_error_from_errno("asprintf");
6550 goto done;
6553 initial_content_len = asprintf(&initial_content,
6554 "\n# tagging commit %s as %s\n",
6555 commit_id_str, tag_name);
6556 if (initial_content_len == -1) {
6557 err = got_error_from_errno("asprintf");
6558 goto done;
6561 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6562 if (err)
6563 goto done;
6565 if (write(fd, initial_content, initial_content_len) == -1) {
6566 err = got_error_from_errno2("write", *tagmsg_path);
6567 goto done;
6570 err = get_editor(&editor);
6571 if (err)
6572 goto done;
6573 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6574 initial_content_len, 1);
6575 done:
6576 free(initial_content);
6577 free(template);
6578 free(editor);
6580 if (fd != -1 && close(fd) == -1 && err == NULL)
6581 err = got_error_from_errno2("close", *tagmsg_path);
6583 /* Editor is done; we can now apply unveil(2) */
6584 if (err == NULL)
6585 err = apply_unveil(repo_path, 0, NULL);
6586 if (err) {
6587 free(*tagmsg);
6588 *tagmsg = NULL;
6590 return err;
6593 static const struct got_error *
6594 add_tag(struct got_repository *repo, const char *tagger,
6595 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6597 const struct got_error *err = NULL;
6598 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6599 char *label = NULL, *commit_id_str = NULL;
6600 struct got_reference *ref = NULL;
6601 char *refname = NULL, *tagmsg = NULL;
6602 char *tagmsg_path = NULL, *tag_id_str = NULL;
6603 int preserve_tagmsg = 0;
6604 struct got_reflist_head refs;
6606 TAILQ_INIT(&refs);
6609 * Don't let the user create a tag name with a leading '-'.
6610 * While technically a valid reference name, this case is usually
6611 * an unintended typo.
6613 if (tag_name[0] == '-')
6614 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6616 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6617 if (err)
6618 goto done;
6620 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6621 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6622 if (err)
6623 goto done;
6625 err = got_object_id_str(&commit_id_str, commit_id);
6626 if (err)
6627 goto done;
6629 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6630 refname = strdup(tag_name);
6631 if (refname == NULL) {
6632 err = got_error_from_errno("strdup");
6633 goto done;
6635 tag_name += 10;
6636 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6637 err = got_error_from_errno("asprintf");
6638 goto done;
6641 err = got_ref_open(&ref, repo, refname, 0);
6642 if (err == NULL) {
6643 err = got_error(GOT_ERR_TAG_EXISTS);
6644 goto done;
6645 } else if (err->code != GOT_ERR_NOT_REF)
6646 goto done;
6648 if (tagmsg_arg == NULL) {
6649 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6650 tag_name, got_repo_get_path(repo));
6651 if (err) {
6652 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6653 tagmsg_path != NULL)
6654 preserve_tagmsg = 1;
6655 goto done;
6659 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6660 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6661 if (err) {
6662 if (tagmsg_path)
6663 preserve_tagmsg = 1;
6664 goto done;
6667 err = got_ref_alloc(&ref, refname, tag_id);
6668 if (err) {
6669 if (tagmsg_path)
6670 preserve_tagmsg = 1;
6671 goto done;
6674 err = got_ref_write(ref, repo);
6675 if (err) {
6676 if (tagmsg_path)
6677 preserve_tagmsg = 1;
6678 goto done;
6681 err = got_object_id_str(&tag_id_str, tag_id);
6682 if (err) {
6683 if (tagmsg_path)
6684 preserve_tagmsg = 1;
6685 goto done;
6687 printf("Created tag %s\n", tag_id_str);
6688 done:
6689 if (preserve_tagmsg) {
6690 fprintf(stderr, "%s: tag message preserved in %s\n",
6691 getprogname(), tagmsg_path);
6692 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6693 err = got_error_from_errno2("unlink", tagmsg_path);
6694 free(tag_id_str);
6695 if (ref)
6696 got_ref_close(ref);
6697 free(commit_id);
6698 free(commit_id_str);
6699 free(refname);
6700 free(tagmsg);
6701 free(tagmsg_path);
6702 got_ref_list_free(&refs);
6703 return err;
6706 static const struct got_error *
6707 cmd_tag(int argc, char *argv[])
6709 const struct got_error *error = NULL;
6710 struct got_repository *repo = NULL;
6711 struct got_worktree *worktree = NULL;
6712 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6713 char *gitconfig_path = NULL, *tagger = NULL;
6714 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6715 int ch, do_list = 0;
6717 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6718 switch (ch) {
6719 case 'c':
6720 commit_id_arg = optarg;
6721 break;
6722 case 'm':
6723 tagmsg = optarg;
6724 break;
6725 case 'r':
6726 repo_path = realpath(optarg, NULL);
6727 if (repo_path == NULL)
6728 return got_error_from_errno2("realpath",
6729 optarg);
6730 got_path_strip_trailing_slashes(repo_path);
6731 break;
6732 case 'l':
6733 do_list = 1;
6734 break;
6735 default:
6736 usage_tag();
6737 /* NOTREACHED */
6741 argc -= optind;
6742 argv += optind;
6744 if (do_list) {
6745 if (commit_id_arg != NULL)
6746 errx(1,
6747 "-c option can only be used when creating a tag");
6748 if (tagmsg)
6749 option_conflict('l', 'm');
6750 if (argc > 0)
6751 usage_tag();
6752 } else if (argc != 1)
6753 usage_tag();
6755 tag_name = argv[0];
6757 #ifndef PROFILE
6758 if (do_list) {
6759 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6760 NULL) == -1)
6761 err(1, "pledge");
6762 } else {
6763 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6764 "sendfd unveil", NULL) == -1)
6765 err(1, "pledge");
6767 #endif
6768 cwd = getcwd(NULL, 0);
6769 if (cwd == NULL) {
6770 error = got_error_from_errno("getcwd");
6771 goto done;
6774 if (repo_path == NULL) {
6775 error = got_worktree_open(&worktree, cwd);
6776 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6777 goto done;
6778 else
6779 error = NULL;
6780 if (worktree) {
6781 repo_path =
6782 strdup(got_worktree_get_repo_path(worktree));
6783 if (repo_path == NULL)
6784 error = got_error_from_errno("strdup");
6785 if (error)
6786 goto done;
6787 } else {
6788 repo_path = strdup(cwd);
6789 if (repo_path == NULL) {
6790 error = got_error_from_errno("strdup");
6791 goto done;
6796 if (do_list) {
6797 if (worktree) {
6798 /* Release work tree lock. */
6799 got_worktree_close(worktree);
6800 worktree = NULL;
6802 error = got_repo_open(&repo, repo_path, NULL);
6803 if (error != NULL)
6804 goto done;
6805 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6806 if (error)
6807 goto done;
6808 error = list_tags(repo);
6809 } else {
6810 error = get_gitconfig_path(&gitconfig_path);
6811 if (error)
6812 goto done;
6813 error = got_repo_open(&repo, repo_path, gitconfig_path);
6814 if (error != NULL)
6815 goto done;
6817 error = get_author(&tagger, repo, worktree);
6818 if (error)
6819 goto done;
6820 if (worktree) {
6821 /* Release work tree lock. */
6822 got_worktree_close(worktree);
6823 worktree = NULL;
6826 if (tagmsg) {
6827 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6828 if (error)
6829 goto done;
6832 if (commit_id_arg == NULL) {
6833 struct got_reference *head_ref;
6834 struct got_object_id *commit_id;
6835 error = got_ref_open(&head_ref, repo,
6836 worktree ? got_worktree_get_head_ref_name(worktree)
6837 : GOT_REF_HEAD, 0);
6838 if (error)
6839 goto done;
6840 error = got_ref_resolve(&commit_id, repo, head_ref);
6841 got_ref_close(head_ref);
6842 if (error)
6843 goto done;
6844 error = got_object_id_str(&commit_id_str, commit_id);
6845 free(commit_id);
6846 if (error)
6847 goto done;
6850 error = add_tag(repo, tagger, tag_name,
6851 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6853 done:
6854 if (repo) {
6855 const struct got_error *close_err = got_repo_close(repo);
6856 if (error == NULL)
6857 error = close_err;
6859 if (worktree)
6860 got_worktree_close(worktree);
6861 free(cwd);
6862 free(repo_path);
6863 free(gitconfig_path);
6864 free(commit_id_str);
6865 free(tagger);
6866 return error;
6869 __dead static void
6870 usage_add(void)
6872 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6873 getprogname());
6874 exit(1);
6877 static const struct got_error *
6878 add_progress(void *arg, unsigned char status, const char *path)
6880 while (path[0] == '/')
6881 path++;
6882 printf("%c %s\n", status, path);
6883 return NULL;
6886 static const struct got_error *
6887 cmd_add(int argc, char *argv[])
6889 const struct got_error *error = NULL;
6890 struct got_repository *repo = NULL;
6891 struct got_worktree *worktree = NULL;
6892 char *cwd = NULL;
6893 struct got_pathlist_head paths;
6894 struct got_pathlist_entry *pe;
6895 int ch, can_recurse = 0, no_ignores = 0;
6897 TAILQ_INIT(&paths);
6899 while ((ch = getopt(argc, argv, "IR")) != -1) {
6900 switch (ch) {
6901 case 'I':
6902 no_ignores = 1;
6903 break;
6904 case 'R':
6905 can_recurse = 1;
6906 break;
6907 default:
6908 usage_add();
6909 /* NOTREACHED */
6913 argc -= optind;
6914 argv += optind;
6916 #ifndef PROFILE
6917 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6918 NULL) == -1)
6919 err(1, "pledge");
6920 #endif
6921 if (argc < 1)
6922 usage_add();
6924 cwd = getcwd(NULL, 0);
6925 if (cwd == NULL) {
6926 error = got_error_from_errno("getcwd");
6927 goto done;
6930 error = got_worktree_open(&worktree, cwd);
6931 if (error) {
6932 if (error->code == GOT_ERR_NOT_WORKTREE)
6933 error = wrap_not_worktree_error(error, "add", cwd);
6934 goto done;
6937 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6938 NULL);
6939 if (error != NULL)
6940 goto done;
6942 error = apply_unveil(got_repo_get_path(repo), 1,
6943 got_worktree_get_root_path(worktree));
6944 if (error)
6945 goto done;
6947 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6948 if (error)
6949 goto done;
6951 if (!can_recurse) {
6952 char *ondisk_path;
6953 struct stat sb;
6954 TAILQ_FOREACH(pe, &paths, entry) {
6955 if (asprintf(&ondisk_path, "%s/%s",
6956 got_worktree_get_root_path(worktree),
6957 pe->path) == -1) {
6958 error = got_error_from_errno("asprintf");
6959 goto done;
6961 if (lstat(ondisk_path, &sb) == -1) {
6962 if (errno == ENOENT) {
6963 free(ondisk_path);
6964 continue;
6966 error = got_error_from_errno2("lstat",
6967 ondisk_path);
6968 free(ondisk_path);
6969 goto done;
6971 free(ondisk_path);
6972 if (S_ISDIR(sb.st_mode)) {
6973 error = got_error_msg(GOT_ERR_BAD_PATH,
6974 "adding directories requires -R option");
6975 goto done;
6980 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6981 NULL, repo, no_ignores);
6982 done:
6983 if (repo) {
6984 const struct got_error *close_err = got_repo_close(repo);
6985 if (error == NULL)
6986 error = close_err;
6988 if (worktree)
6989 got_worktree_close(worktree);
6990 TAILQ_FOREACH(pe, &paths, entry)
6991 free((char *)pe->path);
6992 got_pathlist_free(&paths);
6993 free(cwd);
6994 return error;
6997 __dead static void
6998 usage_remove(void)
7000 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7001 "path ...\n", getprogname());
7002 exit(1);
7005 static const struct got_error *
7006 print_remove_status(void *arg, unsigned char status,
7007 unsigned char staged_status, const char *path)
7009 while (path[0] == '/')
7010 path++;
7011 if (status == GOT_STATUS_NONEXISTENT)
7012 return NULL;
7013 if (status == staged_status && (status == GOT_STATUS_DELETE))
7014 status = GOT_STATUS_NO_CHANGE;
7015 printf("%c%c %s\n", status, staged_status, path);
7016 return NULL;
7019 static const struct got_error *
7020 cmd_remove(int argc, char *argv[])
7022 const struct got_error *error = NULL;
7023 struct got_worktree *worktree = NULL;
7024 struct got_repository *repo = NULL;
7025 const char *status_codes = NULL;
7026 char *cwd = NULL;
7027 struct got_pathlist_head paths;
7028 struct got_pathlist_entry *pe;
7029 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7030 int ignore_missing_paths = 0;
7032 TAILQ_INIT(&paths);
7034 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7035 switch (ch) {
7036 case 'f':
7037 delete_local_mods = 1;
7038 ignore_missing_paths = 1;
7039 break;
7040 case 'k':
7041 keep_on_disk = 1;
7042 break;
7043 case 'R':
7044 can_recurse = 1;
7045 break;
7046 case 's':
7047 for (i = 0; i < strlen(optarg); i++) {
7048 switch (optarg[i]) {
7049 case GOT_STATUS_MODIFY:
7050 delete_local_mods = 1;
7051 break;
7052 case GOT_STATUS_MISSING:
7053 ignore_missing_paths = 1;
7054 break;
7055 default:
7056 errx(1, "invalid status code '%c'",
7057 optarg[i]);
7060 status_codes = optarg;
7061 break;
7062 default:
7063 usage_remove();
7064 /* NOTREACHED */
7068 argc -= optind;
7069 argv += optind;
7071 #ifndef PROFILE
7072 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7073 NULL) == -1)
7074 err(1, "pledge");
7075 #endif
7076 if (argc < 1)
7077 usage_remove();
7079 cwd = getcwd(NULL, 0);
7080 if (cwd == NULL) {
7081 error = got_error_from_errno("getcwd");
7082 goto done;
7084 error = got_worktree_open(&worktree, cwd);
7085 if (error) {
7086 if (error->code == GOT_ERR_NOT_WORKTREE)
7087 error = wrap_not_worktree_error(error, "remove", cwd);
7088 goto done;
7091 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7092 NULL);
7093 if (error)
7094 goto done;
7096 error = apply_unveil(got_repo_get_path(repo), 1,
7097 got_worktree_get_root_path(worktree));
7098 if (error)
7099 goto done;
7101 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7102 if (error)
7103 goto done;
7105 if (!can_recurse) {
7106 char *ondisk_path;
7107 struct stat sb;
7108 TAILQ_FOREACH(pe, &paths, entry) {
7109 if (asprintf(&ondisk_path, "%s/%s",
7110 got_worktree_get_root_path(worktree),
7111 pe->path) == -1) {
7112 error = got_error_from_errno("asprintf");
7113 goto done;
7115 if (lstat(ondisk_path, &sb) == -1) {
7116 if (errno == ENOENT) {
7117 free(ondisk_path);
7118 continue;
7120 error = got_error_from_errno2("lstat",
7121 ondisk_path);
7122 free(ondisk_path);
7123 goto done;
7125 free(ondisk_path);
7126 if (S_ISDIR(sb.st_mode)) {
7127 error = got_error_msg(GOT_ERR_BAD_PATH,
7128 "removing directories requires -R option");
7129 goto done;
7134 error = got_worktree_schedule_delete(worktree, &paths,
7135 delete_local_mods, status_codes, print_remove_status, NULL,
7136 repo, keep_on_disk, ignore_missing_paths);
7137 done:
7138 if (repo) {
7139 const struct got_error *close_err = got_repo_close(repo);
7140 if (error == NULL)
7141 error = close_err;
7143 if (worktree)
7144 got_worktree_close(worktree);
7145 TAILQ_FOREACH(pe, &paths, entry)
7146 free((char *)pe->path);
7147 got_pathlist_free(&paths);
7148 free(cwd);
7149 return error;
7152 __dead static void
7153 usage_patch(void)
7155 fprintf(stderr, "usage: %s patch [-n] [patchfile]\n",
7156 getprogname());
7157 exit(1);
7160 static const struct got_error *
7161 patch_from_stdin(int *patchfd)
7163 const struct got_error *err = NULL;
7164 ssize_t r;
7165 char *path, buf[BUFSIZ];
7166 sig_t sighup, sigint, sigquit;
7168 err = got_opentemp_named_fd(&path, patchfd,
7169 GOT_TMPDIR_STR "/got-patch");
7170 if (err)
7171 return err;
7172 unlink(path);
7173 free(path);
7175 sighup = signal(SIGHUP, SIG_DFL);
7176 sigint = signal(SIGINT, SIG_DFL);
7177 sigquit = signal(SIGQUIT, SIG_DFL);
7179 for (;;) {
7180 r = read(0, buf, sizeof(buf));
7181 if (r == -1) {
7182 err = got_error_from_errno("read");
7183 break;
7185 if (r == 0)
7186 break;
7187 if (write(*patchfd, buf, r) == -1) {
7188 err = got_error_from_errno("write");
7189 break;
7193 signal(SIGHUP, sighup);
7194 signal(SIGINT, sigint);
7195 signal(SIGQUIT, sigquit);
7197 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7198 err = got_error_from_errno("lseek");
7200 if (err != NULL) {
7201 close(*patchfd);
7202 *patchfd = -1;
7205 return err;
7208 static const struct got_error *
7209 patch_progress(void *arg, const char *old, const char *new,
7210 unsigned char status, const struct got_error *error, long old_from,
7211 long old_lines, long new_from, long new_lines, long offset,
7212 const struct got_error *hunk_err)
7214 const char *path = new == NULL ? old : new;
7216 while (*path == '/')
7217 path++;
7219 if (status != 0)
7220 printf("%c %s\n", status, path);
7222 if (error != NULL)
7223 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7225 if (offset != 0 || hunk_err != NULL) {
7226 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7227 old_lines, new_from, new_lines);
7228 if (hunk_err != NULL)
7229 printf("%s\n", hunk_err->msg);
7230 else
7231 printf("applied with offset %ld\n", offset);
7234 return NULL;
7237 static const struct got_error *
7238 cmd_patch(int argc, char *argv[])
7240 const struct got_error *error = NULL, *close_error = NULL;
7241 struct got_worktree *worktree = NULL;
7242 struct got_repository *repo = NULL;
7243 const char *errstr;
7244 char *cwd = NULL;
7245 int ch, nop = 0, strip = -1;
7246 int patchfd;
7248 while ((ch = getopt(argc, argv, "np:")) != -1) {
7249 switch (ch) {
7250 case 'n':
7251 nop = 1;
7252 break;
7253 case 'p':
7254 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7255 if (errstr != NULL)
7256 errx(1, "pathname strip count is %s: %s",
7257 errstr, optarg);
7258 break;
7259 default:
7260 usage_patch();
7261 /* NOTREACHED */
7265 argc -= optind;
7266 argv += optind;
7268 if (argc == 0) {
7269 error = patch_from_stdin(&patchfd);
7270 if (error)
7271 return error;
7272 } else if (argc == 1) {
7273 patchfd = open(argv[0], O_RDONLY);
7274 if (patchfd == -1) {
7275 error = got_error_from_errno2("open", argv[0]);
7276 return error;
7278 } else
7279 usage_patch();
7281 if ((cwd = getcwd(NULL, 0)) == NULL) {
7282 error = got_error_from_errno("getcwd");
7283 goto done;
7286 error = got_worktree_open(&worktree, cwd);
7287 if (error != NULL)
7288 goto done;
7290 const char *repo_path = got_worktree_get_repo_path(worktree);
7291 error = got_repo_open(&repo, repo_path, NULL);
7292 if (error != NULL)
7293 goto done;
7295 error = apply_unveil(got_repo_get_path(repo), 0,
7296 worktree ? got_worktree_get_root_path(worktree) : NULL);
7297 if (error != NULL)
7298 goto done;
7300 #ifndef PROFILE
7301 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7302 NULL) == -1)
7303 err(1, "pledge");
7304 #endif
7306 error = got_patch(patchfd, worktree, repo, nop, strip,
7307 &patch_progress, NULL, check_cancelled, NULL);
7309 done:
7310 if (repo) {
7311 close_error = got_repo_close(repo);
7312 if (error == NULL)
7313 error = close_error;
7315 if (worktree != NULL) {
7316 close_error = got_worktree_close(worktree);
7317 if (error == NULL)
7318 error = close_error;
7320 free(cwd);
7321 return error;
7324 __dead static void
7325 usage_revert(void)
7327 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7328 "path ...\n", getprogname());
7329 exit(1);
7332 static const struct got_error *
7333 revert_progress(void *arg, unsigned char status, const char *path)
7335 if (status == GOT_STATUS_UNVERSIONED)
7336 return NULL;
7338 while (path[0] == '/')
7339 path++;
7340 printf("%c %s\n", status, path);
7341 return NULL;
7344 struct choose_patch_arg {
7345 FILE *patch_script_file;
7346 const char *action;
7349 static const struct got_error *
7350 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7351 int nchanges, const char *action)
7353 char *line = NULL;
7354 size_t linesize = 0;
7355 ssize_t linelen;
7357 switch (status) {
7358 case GOT_STATUS_ADD:
7359 printf("A %s\n%s this addition? [y/n] ", path, action);
7360 break;
7361 case GOT_STATUS_DELETE:
7362 printf("D %s\n%s this deletion? [y/n] ", path, action);
7363 break;
7364 case GOT_STATUS_MODIFY:
7365 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7366 return got_error_from_errno("fseek");
7367 printf(GOT_COMMIT_SEP_STR);
7368 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7369 printf("%s", line);
7370 if (ferror(patch_file))
7371 return got_error_from_errno("getline");
7372 printf(GOT_COMMIT_SEP_STR);
7373 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7374 path, n, nchanges, action);
7375 break;
7376 default:
7377 return got_error_path(path, GOT_ERR_FILE_STATUS);
7380 return NULL;
7383 static const struct got_error *
7384 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7385 FILE *patch_file, int n, int nchanges)
7387 const struct got_error *err = NULL;
7388 char *line = NULL;
7389 size_t linesize = 0;
7390 ssize_t linelen;
7391 int resp = ' ';
7392 struct choose_patch_arg *a = arg;
7394 *choice = GOT_PATCH_CHOICE_NONE;
7396 if (a->patch_script_file) {
7397 char *nl;
7398 err = show_change(status, path, patch_file, n, nchanges,
7399 a->action);
7400 if (err)
7401 return err;
7402 linelen = getline(&line, &linesize, a->patch_script_file);
7403 if (linelen == -1) {
7404 if (ferror(a->patch_script_file))
7405 return got_error_from_errno("getline");
7406 return NULL;
7408 nl = strchr(line, '\n');
7409 if (nl)
7410 *nl = '\0';
7411 if (strcmp(line, "y") == 0) {
7412 *choice = GOT_PATCH_CHOICE_YES;
7413 printf("y\n");
7414 } else if (strcmp(line, "n") == 0) {
7415 *choice = GOT_PATCH_CHOICE_NO;
7416 printf("n\n");
7417 } else if (strcmp(line, "q") == 0 &&
7418 status == GOT_STATUS_MODIFY) {
7419 *choice = GOT_PATCH_CHOICE_QUIT;
7420 printf("q\n");
7421 } else
7422 printf("invalid response '%s'\n", line);
7423 free(line);
7424 return NULL;
7427 while (resp != 'y' && resp != 'n' && resp != 'q') {
7428 err = show_change(status, path, patch_file, n, nchanges,
7429 a->action);
7430 if (err)
7431 return err;
7432 resp = getchar();
7433 if (resp == '\n')
7434 resp = getchar();
7435 if (status == GOT_STATUS_MODIFY) {
7436 if (resp != 'y' && resp != 'n' && resp != 'q') {
7437 printf("invalid response '%c'\n", resp);
7438 resp = ' ';
7440 } else if (resp != 'y' && resp != 'n') {
7441 printf("invalid response '%c'\n", resp);
7442 resp = ' ';
7446 if (resp == 'y')
7447 *choice = GOT_PATCH_CHOICE_YES;
7448 else if (resp == 'n')
7449 *choice = GOT_PATCH_CHOICE_NO;
7450 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7451 *choice = GOT_PATCH_CHOICE_QUIT;
7453 return NULL;
7456 static const struct got_error *
7457 cmd_revert(int argc, char *argv[])
7459 const struct got_error *error = NULL;
7460 struct got_worktree *worktree = NULL;
7461 struct got_repository *repo = NULL;
7462 char *cwd = NULL, *path = NULL;
7463 struct got_pathlist_head paths;
7464 struct got_pathlist_entry *pe;
7465 int ch, can_recurse = 0, pflag = 0;
7466 FILE *patch_script_file = NULL;
7467 const char *patch_script_path = NULL;
7468 struct choose_patch_arg cpa;
7470 TAILQ_INIT(&paths);
7472 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7473 switch (ch) {
7474 case 'p':
7475 pflag = 1;
7476 break;
7477 case 'F':
7478 patch_script_path = optarg;
7479 break;
7480 case 'R':
7481 can_recurse = 1;
7482 break;
7483 default:
7484 usage_revert();
7485 /* NOTREACHED */
7489 argc -= optind;
7490 argv += optind;
7492 #ifndef PROFILE
7493 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7494 "unveil", NULL) == -1)
7495 err(1, "pledge");
7496 #endif
7497 if (argc < 1)
7498 usage_revert();
7499 if (patch_script_path && !pflag)
7500 errx(1, "-F option can only be used together with -p option");
7502 cwd = getcwd(NULL, 0);
7503 if (cwd == NULL) {
7504 error = got_error_from_errno("getcwd");
7505 goto done;
7507 error = got_worktree_open(&worktree, cwd);
7508 if (error) {
7509 if (error->code == GOT_ERR_NOT_WORKTREE)
7510 error = wrap_not_worktree_error(error, "revert", cwd);
7511 goto done;
7514 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7515 NULL);
7516 if (error != NULL)
7517 goto done;
7519 if (patch_script_path) {
7520 patch_script_file = fopen(patch_script_path, "re");
7521 if (patch_script_file == NULL) {
7522 error = got_error_from_errno2("fopen",
7523 patch_script_path);
7524 goto done;
7527 error = apply_unveil(got_repo_get_path(repo), 1,
7528 got_worktree_get_root_path(worktree));
7529 if (error)
7530 goto done;
7532 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7533 if (error)
7534 goto done;
7536 if (!can_recurse) {
7537 char *ondisk_path;
7538 struct stat sb;
7539 TAILQ_FOREACH(pe, &paths, entry) {
7540 if (asprintf(&ondisk_path, "%s/%s",
7541 got_worktree_get_root_path(worktree),
7542 pe->path) == -1) {
7543 error = got_error_from_errno("asprintf");
7544 goto done;
7546 if (lstat(ondisk_path, &sb) == -1) {
7547 if (errno == ENOENT) {
7548 free(ondisk_path);
7549 continue;
7551 error = got_error_from_errno2("lstat",
7552 ondisk_path);
7553 free(ondisk_path);
7554 goto done;
7556 free(ondisk_path);
7557 if (S_ISDIR(sb.st_mode)) {
7558 error = got_error_msg(GOT_ERR_BAD_PATH,
7559 "reverting directories requires -R option");
7560 goto done;
7565 cpa.patch_script_file = patch_script_file;
7566 cpa.action = "revert";
7567 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7568 pflag ? choose_patch : NULL, &cpa, repo);
7569 done:
7570 if (patch_script_file && fclose(patch_script_file) == EOF &&
7571 error == NULL)
7572 error = got_error_from_errno2("fclose", patch_script_path);
7573 if (repo) {
7574 const struct got_error *close_err = got_repo_close(repo);
7575 if (error == NULL)
7576 error = close_err;
7578 if (worktree)
7579 got_worktree_close(worktree);
7580 free(path);
7581 free(cwd);
7582 return error;
7585 __dead static void
7586 usage_commit(void)
7588 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7589 "[path ...]\n", getprogname());
7590 exit(1);
7593 struct collect_commit_logmsg_arg {
7594 const char *cmdline_log;
7595 const char *prepared_log;
7596 int non_interactive;
7597 const char *editor;
7598 const char *worktree_path;
7599 const char *branch_name;
7600 const char *repo_path;
7601 char *logmsg_path;
7605 static const struct got_error *
7606 read_prepared_logmsg(char **logmsg, const char *path)
7608 const struct got_error *err = NULL;
7609 FILE *f = NULL;
7610 struct stat sb;
7611 size_t r;
7613 *logmsg = NULL;
7614 memset(&sb, 0, sizeof(sb));
7616 f = fopen(path, "re");
7617 if (f == NULL)
7618 return got_error_from_errno2("fopen", path);
7620 if (fstat(fileno(f), &sb) == -1) {
7621 err = got_error_from_errno2("fstat", path);
7622 goto done;
7624 if (sb.st_size == 0) {
7625 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7626 goto done;
7629 *logmsg = malloc(sb.st_size + 1);
7630 if (*logmsg == NULL) {
7631 err = got_error_from_errno("malloc");
7632 goto done;
7635 r = fread(*logmsg, 1, sb.st_size, f);
7636 if (r != sb.st_size) {
7637 if (ferror(f))
7638 err = got_error_from_errno2("fread", path);
7639 else
7640 err = got_error(GOT_ERR_IO);
7641 goto done;
7643 (*logmsg)[sb.st_size] = '\0';
7644 done:
7645 if (fclose(f) == EOF && err == NULL)
7646 err = got_error_from_errno2("fclose", path);
7647 if (err) {
7648 free(*logmsg);
7649 *logmsg = NULL;
7651 return err;
7655 static const struct got_error *
7656 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7657 void *arg)
7659 char *initial_content = NULL;
7660 struct got_pathlist_entry *pe;
7661 const struct got_error *err = NULL;
7662 char *template = NULL;
7663 struct collect_commit_logmsg_arg *a = arg;
7664 int initial_content_len;
7665 int fd = -1;
7666 size_t len;
7668 /* if a message was specified on the command line, just use it */
7669 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7670 len = strlen(a->cmdline_log) + 1;
7671 *logmsg = malloc(len + 1);
7672 if (*logmsg == NULL)
7673 return got_error_from_errno("malloc");
7674 strlcpy(*logmsg, a->cmdline_log, len);
7675 return NULL;
7676 } else if (a->prepared_log != NULL && a->non_interactive)
7677 return read_prepared_logmsg(logmsg, a->prepared_log);
7679 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7680 return got_error_from_errno("asprintf");
7682 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7683 if (err)
7684 goto done;
7686 if (a->prepared_log) {
7687 char *msg;
7688 err = read_prepared_logmsg(&msg, a->prepared_log);
7689 if (err)
7690 goto done;
7691 if (write(fd, msg, strlen(msg)) == -1) {
7692 err = got_error_from_errno2("write", a->logmsg_path);
7693 free(msg);
7694 goto done;
7696 free(msg);
7699 initial_content_len = asprintf(&initial_content,
7700 "\n# changes to be committed on branch %s:\n",
7701 a->branch_name);
7702 if (initial_content_len == -1) {
7703 err = got_error_from_errno("asprintf");
7704 goto done;
7707 if (write(fd, initial_content, initial_content_len) == -1) {
7708 err = got_error_from_errno2("write", a->logmsg_path);
7709 goto done;
7712 TAILQ_FOREACH(pe, commitable_paths, entry) {
7713 struct got_commitable *ct = pe->data;
7714 dprintf(fd, "# %c %s\n",
7715 got_commitable_get_status(ct),
7716 got_commitable_get_path(ct));
7719 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7720 initial_content_len, a->prepared_log ? 0 : 1);
7721 done:
7722 free(initial_content);
7723 free(template);
7725 if (fd != -1 && close(fd) == -1 && err == NULL)
7726 err = got_error_from_errno2("close", a->logmsg_path);
7728 /* Editor is done; we can now apply unveil(2) */
7729 if (err == NULL)
7730 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7731 if (err) {
7732 free(*logmsg);
7733 *logmsg = NULL;
7735 return err;
7738 static const struct got_error *
7739 cmd_commit(int argc, char *argv[])
7741 const struct got_error *error = NULL;
7742 struct got_worktree *worktree = NULL;
7743 struct got_repository *repo = NULL;
7744 char *cwd = NULL, *id_str = NULL;
7745 struct got_object_id *id = NULL;
7746 const char *logmsg = NULL;
7747 char *prepared_logmsg = NULL;
7748 struct collect_commit_logmsg_arg cl_arg;
7749 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7750 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7751 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7752 struct got_pathlist_head paths;
7754 TAILQ_INIT(&paths);
7755 cl_arg.logmsg_path = NULL;
7757 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7758 switch (ch) {
7759 case 'F':
7760 if (logmsg != NULL)
7761 option_conflict('F', 'm');
7762 prepared_logmsg = realpath(optarg, NULL);
7763 if (prepared_logmsg == NULL)
7764 return got_error_from_errno2("realpath",
7765 optarg);
7766 break;
7767 case 'm':
7768 if (prepared_logmsg)
7769 option_conflict('m', 'F');
7770 logmsg = optarg;
7771 break;
7772 case 'N':
7773 non_interactive = 1;
7774 break;
7775 case 'S':
7776 allow_bad_symlinks = 1;
7777 break;
7778 default:
7779 usage_commit();
7780 /* NOTREACHED */
7784 argc -= optind;
7785 argv += optind;
7787 #ifndef PROFILE
7788 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7789 "unveil", NULL) == -1)
7790 err(1, "pledge");
7791 #endif
7792 cwd = getcwd(NULL, 0);
7793 if (cwd == NULL) {
7794 error = got_error_from_errno("getcwd");
7795 goto done;
7797 error = got_worktree_open(&worktree, cwd);
7798 if (error) {
7799 if (error->code == GOT_ERR_NOT_WORKTREE)
7800 error = wrap_not_worktree_error(error, "commit", cwd);
7801 goto done;
7804 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7805 if (error)
7806 goto done;
7807 if (rebase_in_progress) {
7808 error = got_error(GOT_ERR_REBASING);
7809 goto done;
7812 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7813 worktree);
7814 if (error)
7815 goto done;
7817 error = get_gitconfig_path(&gitconfig_path);
7818 if (error)
7819 goto done;
7820 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7821 gitconfig_path);
7822 if (error != NULL)
7823 goto done;
7825 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7826 if (error)
7827 goto done;
7828 if (merge_in_progress) {
7829 error = got_error(GOT_ERR_MERGE_BUSY);
7830 goto done;
7833 error = get_author(&author, repo, worktree);
7834 if (error)
7835 return error;
7838 * unveil(2) traverses exec(2); if an editor is used we have
7839 * to apply unveil after the log message has been written.
7841 if (logmsg == NULL || strlen(logmsg) == 0)
7842 error = get_editor(&editor);
7843 else
7844 error = apply_unveil(got_repo_get_path(repo), 0,
7845 got_worktree_get_root_path(worktree));
7846 if (error)
7847 goto done;
7849 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7850 if (error)
7851 goto done;
7853 cl_arg.editor = editor;
7854 cl_arg.cmdline_log = logmsg;
7855 cl_arg.prepared_log = prepared_logmsg;
7856 cl_arg.non_interactive = non_interactive;
7857 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7858 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7859 if (!histedit_in_progress) {
7860 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7861 error = got_error(GOT_ERR_COMMIT_BRANCH);
7862 goto done;
7864 cl_arg.branch_name += 11;
7866 cl_arg.repo_path = got_repo_get_path(repo);
7867 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7868 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7869 print_status, NULL, repo);
7870 if (error) {
7871 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7872 cl_arg.logmsg_path != NULL)
7873 preserve_logmsg = 1;
7874 goto done;
7877 error = got_object_id_str(&id_str, id);
7878 if (error)
7879 goto done;
7880 printf("Created commit %s\n", id_str);
7881 done:
7882 if (preserve_logmsg) {
7883 fprintf(stderr, "%s: log message preserved in %s\n",
7884 getprogname(), cl_arg.logmsg_path);
7885 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7886 error == NULL)
7887 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7888 free(cl_arg.logmsg_path);
7889 if (repo) {
7890 const struct got_error *close_err = got_repo_close(repo);
7891 if (error == NULL)
7892 error = close_err;
7894 if (worktree)
7895 got_worktree_close(worktree);
7896 free(cwd);
7897 free(id_str);
7898 free(gitconfig_path);
7899 free(editor);
7900 free(author);
7901 free(prepared_logmsg);
7902 return error;
7905 __dead static void
7906 usage_send(void)
7908 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7909 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7910 "[remote-repository]\n", getprogname());
7911 exit(1);
7914 static void
7915 print_load_info(int print_colored, int print_found, int print_trees,
7916 int ncolored, int nfound, int ntrees)
7918 if (print_colored) {
7919 printf("%d commit%s colored", ncolored,
7920 ncolored == 1 ? "" : "s");
7922 if (print_found) {
7923 printf("%s%d object%s found",
7924 ncolored > 0 ? "; " : "",
7925 nfound, nfound == 1 ? "" : "s");
7927 if (print_trees) {
7928 printf("; %d tree%s scanned", ntrees,
7929 ntrees == 1 ? "" : "s");
7933 struct got_send_progress_arg {
7934 char last_scaled_packsize[FMT_SCALED_STRSIZE];
7935 int verbosity;
7936 int last_ncolored;
7937 int last_nfound;
7938 int last_ntrees;
7939 int loading_done;
7940 int last_ncommits;
7941 int last_nobj_total;
7942 int last_p_deltify;
7943 int last_p_written;
7944 int last_p_sent;
7945 int printed_something;
7946 int sent_something;
7947 struct got_pathlist_head *delete_branches;
7950 static const struct got_error *
7951 send_progress(void *arg, int ncolored, int nfound, int ntrees,
7952 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
7953 int nobj_written, off_t bytes_sent, const char *refname, int success)
7955 struct got_send_progress_arg *a = arg;
7956 char scaled_packsize[FMT_SCALED_STRSIZE];
7957 char scaled_sent[FMT_SCALED_STRSIZE];
7958 int p_deltify = 0, p_written = 0, p_sent = 0;
7959 int print_colored = 0, print_found = 0, print_trees = 0;
7960 int print_searching = 0, print_total = 0;
7961 int print_deltify = 0, print_written = 0, print_sent = 0;
7963 if (a->verbosity < 0)
7964 return NULL;
7966 if (refname) {
7967 const char *status = success ? "accepted" : "rejected";
7969 if (success) {
7970 struct got_pathlist_entry *pe;
7971 TAILQ_FOREACH(pe, a->delete_branches, entry) {
7972 const char *branchname = pe->path;
7973 if (got_path_cmp(branchname, refname,
7974 strlen(branchname), strlen(refname)) == 0) {
7975 status = "deleted";
7976 a->sent_something = 1;
7977 break;
7982 if (a->printed_something)
7983 putchar('\n');
7984 printf("Server has %s %s", status, refname);
7985 a->printed_something = 1;
7986 return NULL;
7989 if (a->last_ncolored != ncolored) {
7990 print_colored = 1;
7991 a->last_ncolored = ncolored;
7994 if (a->last_nfound != nfound) {
7995 print_colored = 1;
7996 print_found = 1;
7997 a->last_nfound = nfound;
8000 if (a->last_ntrees != ntrees) {
8001 print_colored = 1;
8002 print_found = 1;
8003 print_trees = 1;
8004 a->last_ntrees = ntrees;
8007 if ((print_colored || print_found || print_trees) &&
8008 !a->loading_done) {
8009 printf("\r");
8010 print_load_info(print_colored, print_found, print_trees,
8011 ncolored, nfound, ntrees);
8012 a->printed_something = 1;
8013 fflush(stdout);
8014 return NULL;
8015 } else if (!a->loading_done) {
8016 printf("\r");
8017 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8018 printf("\n");
8019 a->loading_done = 1;
8022 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8023 return got_error_from_errno("fmt_scaled");
8024 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8025 return got_error_from_errno("fmt_scaled");
8027 if (a->last_ncommits != ncommits) {
8028 print_searching = 1;
8029 a->last_ncommits = ncommits;
8032 if (a->last_nobj_total != nobj_total) {
8033 print_searching = 1;
8034 print_total = 1;
8035 a->last_nobj_total = nobj_total;
8038 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8039 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8040 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8041 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8042 return got_error(GOT_ERR_NO_SPACE);
8045 if (nobj_deltify > 0 || nobj_written > 0) {
8046 if (nobj_deltify > 0) {
8047 p_deltify = (nobj_deltify * 100) / nobj_total;
8048 if (p_deltify != a->last_p_deltify) {
8049 a->last_p_deltify = p_deltify;
8050 print_searching = 1;
8051 print_total = 1;
8052 print_deltify = 1;
8055 if (nobj_written > 0) {
8056 p_written = (nobj_written * 100) / nobj_total;
8057 if (p_written != a->last_p_written) {
8058 a->last_p_written = p_written;
8059 print_searching = 1;
8060 print_total = 1;
8061 print_deltify = 1;
8062 print_written = 1;
8067 if (bytes_sent > 0) {
8068 p_sent = (bytes_sent * 100) / packfile_size;
8069 if (p_sent != a->last_p_sent) {
8070 a->last_p_sent = p_sent;
8071 print_searching = 1;
8072 print_total = 1;
8073 print_deltify = 1;
8074 print_written = 1;
8075 print_sent = 1;
8077 a->sent_something = 1;
8080 if (print_searching || print_total || print_deltify || print_written ||
8081 print_sent)
8082 printf("\r");
8083 if (print_searching)
8084 printf("packing %d reference%s", ncommits,
8085 ncommits == 1 ? "" : "s");
8086 if (print_total)
8087 printf("; %d object%s", nobj_total,
8088 nobj_total == 1 ? "" : "s");
8089 if (print_deltify)
8090 printf("; deltify: %d%%", p_deltify);
8091 if (print_sent)
8092 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8093 scaled_packsize, p_sent);
8094 else if (print_written)
8095 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8096 scaled_packsize, p_written);
8097 if (print_searching || print_total || print_deltify ||
8098 print_written || print_sent) {
8099 a->printed_something = 1;
8100 fflush(stdout);
8102 return NULL;
8105 static const struct got_error *
8106 cmd_send(int argc, char *argv[])
8108 const struct got_error *error = NULL;
8109 char *cwd = NULL, *repo_path = NULL;
8110 const char *remote_name;
8111 char *proto = NULL, *host = NULL, *port = NULL;
8112 char *repo_name = NULL, *server_path = NULL;
8113 const struct got_remote_repo *remotes, *remote = NULL;
8114 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8115 struct got_repository *repo = NULL;
8116 struct got_worktree *worktree = NULL;
8117 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8118 struct got_pathlist_head branches;
8119 struct got_pathlist_head tags;
8120 struct got_reflist_head all_branches;
8121 struct got_reflist_head all_tags;
8122 struct got_pathlist_head delete_args;
8123 struct got_pathlist_head delete_branches;
8124 struct got_reflist_entry *re;
8125 struct got_pathlist_entry *pe;
8126 int i, ch, sendfd = -1, sendstatus;
8127 pid_t sendpid = -1;
8128 struct got_send_progress_arg spa;
8129 int verbosity = 0, overwrite_refs = 0;
8130 int send_all_branches = 0, send_all_tags = 0;
8131 struct got_reference *ref = NULL;
8133 TAILQ_INIT(&branches);
8134 TAILQ_INIT(&tags);
8135 TAILQ_INIT(&all_branches);
8136 TAILQ_INIT(&all_tags);
8137 TAILQ_INIT(&delete_args);
8138 TAILQ_INIT(&delete_branches);
8140 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8141 switch (ch) {
8142 case 'a':
8143 send_all_branches = 1;
8144 break;
8145 case 'b':
8146 error = got_pathlist_append(&branches, optarg, NULL);
8147 if (error)
8148 return error;
8149 nbranches++;
8150 break;
8151 case 'd':
8152 error = got_pathlist_append(&delete_args, optarg, NULL);
8153 if (error)
8154 return error;
8155 break;
8156 case 'f':
8157 overwrite_refs = 1;
8158 break;
8159 case 'r':
8160 repo_path = realpath(optarg, NULL);
8161 if (repo_path == NULL)
8162 return got_error_from_errno2("realpath",
8163 optarg);
8164 got_path_strip_trailing_slashes(repo_path);
8165 break;
8166 case 't':
8167 error = got_pathlist_append(&tags, optarg, NULL);
8168 if (error)
8169 return error;
8170 ntags++;
8171 break;
8172 case 'T':
8173 send_all_tags = 1;
8174 break;
8175 case 'v':
8176 if (verbosity < 0)
8177 verbosity = 0;
8178 else if (verbosity < 3)
8179 verbosity++;
8180 break;
8181 case 'q':
8182 verbosity = -1;
8183 break;
8184 default:
8185 usage_send();
8186 /* NOTREACHED */
8189 argc -= optind;
8190 argv += optind;
8192 if (send_all_branches && !TAILQ_EMPTY(&branches))
8193 option_conflict('a', 'b');
8194 if (send_all_tags && !TAILQ_EMPTY(&tags))
8195 option_conflict('T', 't');
8198 if (argc == 0)
8199 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8200 else if (argc == 1)
8201 remote_name = argv[0];
8202 else
8203 usage_send();
8205 cwd = getcwd(NULL, 0);
8206 if (cwd == NULL) {
8207 error = got_error_from_errno("getcwd");
8208 goto done;
8211 if (repo_path == NULL) {
8212 error = got_worktree_open(&worktree, cwd);
8213 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8214 goto done;
8215 else
8216 error = NULL;
8217 if (worktree) {
8218 repo_path =
8219 strdup(got_worktree_get_repo_path(worktree));
8220 if (repo_path == NULL)
8221 error = got_error_from_errno("strdup");
8222 if (error)
8223 goto done;
8224 } else {
8225 repo_path = strdup(cwd);
8226 if (repo_path == NULL) {
8227 error = got_error_from_errno("strdup");
8228 goto done;
8233 error = got_repo_open(&repo, repo_path, NULL);
8234 if (error)
8235 goto done;
8237 if (worktree) {
8238 worktree_conf = got_worktree_get_gotconfig(worktree);
8239 if (worktree_conf) {
8240 got_gotconfig_get_remotes(&nremotes, &remotes,
8241 worktree_conf);
8242 for (i = 0; i < nremotes; i++) {
8243 if (strcmp(remotes[i].name, remote_name) == 0) {
8244 remote = &remotes[i];
8245 break;
8250 if (remote == NULL) {
8251 repo_conf = got_repo_get_gotconfig(repo);
8252 if (repo_conf) {
8253 got_gotconfig_get_remotes(&nremotes, &remotes,
8254 repo_conf);
8255 for (i = 0; i < nremotes; i++) {
8256 if (strcmp(remotes[i].name, remote_name) == 0) {
8257 remote = &remotes[i];
8258 break;
8263 if (remote == NULL) {
8264 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8265 for (i = 0; i < nremotes; i++) {
8266 if (strcmp(remotes[i].name, remote_name) == 0) {
8267 remote = &remotes[i];
8268 break;
8272 if (remote == NULL) {
8273 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8274 goto done;
8277 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8278 &repo_name, remote->send_url);
8279 if (error)
8280 goto done;
8282 if (strcmp(proto, "git") == 0) {
8283 #ifndef PROFILE
8284 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8285 "sendfd dns inet unveil", NULL) == -1)
8286 err(1, "pledge");
8287 #endif
8288 } else if (strcmp(proto, "git+ssh") == 0 ||
8289 strcmp(proto, "ssh") == 0) {
8290 #ifndef PROFILE
8291 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8292 "sendfd unveil", NULL) == -1)
8293 err(1, "pledge");
8294 #endif
8295 } else if (strcmp(proto, "http") == 0 ||
8296 strcmp(proto, "git+http") == 0) {
8297 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8298 goto done;
8299 } else {
8300 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8301 goto done;
8304 error = got_dial_apply_unveil(proto);
8305 if (error)
8306 goto done;
8308 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8309 if (error)
8310 goto done;
8312 if (send_all_branches) {
8313 error = got_ref_list(&all_branches, repo, "refs/heads",
8314 got_ref_cmp_by_name, NULL);
8315 if (error)
8316 goto done;
8317 TAILQ_FOREACH(re, &all_branches, entry) {
8318 const char *branchname = got_ref_get_name(re->ref);
8319 error = got_pathlist_append(&branches,
8320 branchname, NULL);
8321 if (error)
8322 goto done;
8323 nbranches++;
8325 } else if (nbranches == 0) {
8326 for (i = 0; i < remote->nsend_branches; i++) {
8327 got_pathlist_append(&branches,
8328 remote->send_branches[i], NULL);
8332 if (send_all_tags) {
8333 error = got_ref_list(&all_tags, repo, "refs/tags",
8334 got_ref_cmp_by_name, NULL);
8335 if (error)
8336 goto done;
8337 TAILQ_FOREACH(re, &all_tags, entry) {
8338 const char *tagname = got_ref_get_name(re->ref);
8339 error = got_pathlist_append(&tags,
8340 tagname, NULL);
8341 if (error)
8342 goto done;
8343 ntags++;
8348 * To prevent accidents only branches in refs/heads/ can be deleted
8349 * with 'got send -d'.
8350 * Deleting anything else requires local repository access or Git.
8352 TAILQ_FOREACH(pe, &delete_args, entry) {
8353 const char *branchname = pe->path;
8354 char *s;
8355 struct got_pathlist_entry *new;
8356 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8357 s = strdup(branchname);
8358 if (s == NULL) {
8359 error = got_error_from_errno("strdup");
8360 goto done;
8362 } else {
8363 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8364 error = got_error_from_errno("asprintf");
8365 goto done;
8368 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8369 if (error || new == NULL /* duplicate */)
8370 free(s);
8371 if (error)
8372 goto done;
8373 ndelete_branches++;
8376 if (nbranches == 0 && ndelete_branches == 0) {
8377 struct got_reference *head_ref;
8378 if (worktree)
8379 error = got_ref_open(&head_ref, repo,
8380 got_worktree_get_head_ref_name(worktree), 0);
8381 else
8382 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8383 if (error)
8384 goto done;
8385 if (got_ref_is_symbolic(head_ref)) {
8386 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8387 got_ref_close(head_ref);
8388 if (error)
8389 goto done;
8390 } else
8391 ref = head_ref;
8392 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8393 NULL);
8394 if (error)
8395 goto done;
8396 nbranches++;
8399 if (verbosity >= 0)
8400 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8401 port ? ":" : "", port ? port : "");
8403 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8404 server_path, verbosity);
8405 if (error)
8406 goto done;
8408 memset(&spa, 0, sizeof(spa));
8409 spa.last_scaled_packsize[0] = '\0';
8410 spa.last_p_deltify = -1;
8411 spa.last_p_written = -1;
8412 spa.verbosity = verbosity;
8413 spa.delete_branches = &delete_branches;
8414 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8415 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8416 check_cancelled, NULL);
8417 if (spa.printed_something)
8418 putchar('\n');
8419 if (error)
8420 goto done;
8421 if (!spa.sent_something && verbosity >= 0)
8422 printf("Already up-to-date\n");
8423 done:
8424 if (sendpid > 0) {
8425 if (kill(sendpid, SIGTERM) == -1)
8426 error = got_error_from_errno("kill");
8427 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8428 error = got_error_from_errno("waitpid");
8430 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8431 error = got_error_from_errno("close");
8432 if (repo) {
8433 const struct got_error *close_err = got_repo_close(repo);
8434 if (error == NULL)
8435 error = close_err;
8437 if (worktree)
8438 got_worktree_close(worktree);
8439 if (ref)
8440 got_ref_close(ref);
8441 got_pathlist_free(&branches);
8442 got_pathlist_free(&tags);
8443 got_ref_list_free(&all_branches);
8444 got_ref_list_free(&all_tags);
8445 got_pathlist_free(&delete_args);
8446 TAILQ_FOREACH(pe, &delete_branches, entry)
8447 free((char *)pe->path);
8448 got_pathlist_free(&delete_branches);
8449 free(cwd);
8450 free(repo_path);
8451 free(proto);
8452 free(host);
8453 free(port);
8454 free(server_path);
8455 free(repo_name);
8456 return error;
8459 __dead static void
8460 usage_cherrypick(void)
8462 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8463 exit(1);
8466 static const struct got_error *
8467 cmd_cherrypick(int argc, char *argv[])
8469 const struct got_error *error = NULL;
8470 struct got_worktree *worktree = NULL;
8471 struct got_repository *repo = NULL;
8472 char *cwd = NULL, *commit_id_str = NULL;
8473 struct got_object_id *commit_id = NULL;
8474 struct got_commit_object *commit = NULL;
8475 struct got_object_qid *pid;
8476 int ch;
8477 struct got_update_progress_arg upa;
8479 while ((ch = getopt(argc, argv, "")) != -1) {
8480 switch (ch) {
8481 default:
8482 usage_cherrypick();
8483 /* NOTREACHED */
8487 argc -= optind;
8488 argv += optind;
8490 #ifndef PROFILE
8491 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8492 "unveil", NULL) == -1)
8493 err(1, "pledge");
8494 #endif
8495 if (argc != 1)
8496 usage_cherrypick();
8498 cwd = getcwd(NULL, 0);
8499 if (cwd == NULL) {
8500 error = got_error_from_errno("getcwd");
8501 goto done;
8503 error = got_worktree_open(&worktree, cwd);
8504 if (error) {
8505 if (error->code == GOT_ERR_NOT_WORKTREE)
8506 error = wrap_not_worktree_error(error, "cherrypick",
8507 cwd);
8508 goto done;
8511 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8512 NULL);
8513 if (error != NULL)
8514 goto done;
8516 error = apply_unveil(got_repo_get_path(repo), 0,
8517 got_worktree_get_root_path(worktree));
8518 if (error)
8519 goto done;
8521 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8522 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8523 if (error)
8524 goto done;
8525 error = got_object_id_str(&commit_id_str, commit_id);
8526 if (error)
8527 goto done;
8529 error = got_object_open_as_commit(&commit, repo, commit_id);
8530 if (error)
8531 goto done;
8532 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8533 memset(&upa, 0, sizeof(upa));
8534 error = got_worktree_merge_files(worktree, pid ? pid->id : NULL,
8535 commit_id, repo, update_progress, &upa, check_cancelled,
8536 NULL);
8537 if (error != NULL)
8538 goto done;
8540 if (upa.did_something)
8541 printf("Merged commit %s\n", commit_id_str);
8542 print_merge_progress_stats(&upa);
8543 done:
8544 if (commit)
8545 got_object_commit_close(commit);
8546 free(commit_id_str);
8547 if (worktree)
8548 got_worktree_close(worktree);
8549 if (repo) {
8550 const struct got_error *close_err = got_repo_close(repo);
8551 if (error == NULL)
8552 error = close_err;
8554 return error;
8557 __dead static void
8558 usage_backout(void)
8560 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8561 exit(1);
8564 static const struct got_error *
8565 cmd_backout(int argc, char *argv[])
8567 const struct got_error *error = NULL;
8568 struct got_worktree *worktree = NULL;
8569 struct got_repository *repo = NULL;
8570 char *cwd = NULL, *commit_id_str = NULL;
8571 struct got_object_id *commit_id = NULL;
8572 struct got_commit_object *commit = NULL;
8573 struct got_object_qid *pid;
8574 int ch;
8575 struct got_update_progress_arg upa;
8577 while ((ch = getopt(argc, argv, "")) != -1) {
8578 switch (ch) {
8579 default:
8580 usage_backout();
8581 /* NOTREACHED */
8585 argc -= optind;
8586 argv += optind;
8588 #ifndef PROFILE
8589 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8590 "unveil", NULL) == -1)
8591 err(1, "pledge");
8592 #endif
8593 if (argc != 1)
8594 usage_backout();
8596 cwd = getcwd(NULL, 0);
8597 if (cwd == NULL) {
8598 error = got_error_from_errno("getcwd");
8599 goto done;
8601 error = got_worktree_open(&worktree, cwd);
8602 if (error) {
8603 if (error->code == GOT_ERR_NOT_WORKTREE)
8604 error = wrap_not_worktree_error(error, "backout", cwd);
8605 goto done;
8608 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8609 NULL);
8610 if (error != NULL)
8611 goto done;
8613 error = apply_unveil(got_repo_get_path(repo), 0,
8614 got_worktree_get_root_path(worktree));
8615 if (error)
8616 goto done;
8618 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8619 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8620 if (error)
8621 goto done;
8622 error = got_object_id_str(&commit_id_str, commit_id);
8623 if (error)
8624 goto done;
8626 error = got_object_open_as_commit(&commit, repo, commit_id);
8627 if (error)
8628 goto done;
8629 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8630 if (pid == NULL) {
8631 error = got_error(GOT_ERR_ROOT_COMMIT);
8632 goto done;
8635 memset(&upa, 0, sizeof(upa));
8636 error = got_worktree_merge_files(worktree, commit_id, pid->id,
8637 repo, update_progress, &upa, check_cancelled, NULL);
8638 if (error != NULL)
8639 goto done;
8641 if (upa.did_something)
8642 printf("Backed out commit %s\n", commit_id_str);
8643 print_merge_progress_stats(&upa);
8644 done:
8645 if (commit)
8646 got_object_commit_close(commit);
8647 free(commit_id_str);
8648 if (worktree)
8649 got_worktree_close(worktree);
8650 if (repo) {
8651 const struct got_error *close_err = got_repo_close(repo);
8652 if (error == NULL)
8653 error = close_err;
8655 return error;
8658 __dead static void
8659 usage_rebase(void)
8661 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8662 getprogname());
8663 exit(1);
8666 void
8667 trim_logmsg(char *logmsg, int limit)
8669 char *nl;
8670 size_t len;
8672 len = strlen(logmsg);
8673 if (len > limit)
8674 len = limit;
8675 logmsg[len] = '\0';
8676 nl = strchr(logmsg, '\n');
8677 if (nl)
8678 *nl = '\0';
8681 static const struct got_error *
8682 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8684 const struct got_error *err;
8685 char *logmsg0 = NULL;
8686 const char *s;
8688 err = got_object_commit_get_logmsg(&logmsg0, commit);
8689 if (err)
8690 return err;
8692 s = logmsg0;
8693 while (isspace((unsigned char)s[0]))
8694 s++;
8696 *logmsg = strdup(s);
8697 if (*logmsg == NULL) {
8698 err = got_error_from_errno("strdup");
8699 goto done;
8702 trim_logmsg(*logmsg, limit);
8703 done:
8704 free(logmsg0);
8705 return err;
8708 static const struct got_error *
8709 show_rebase_merge_conflict(struct got_object_id *id,
8710 struct got_repository *repo)
8712 const struct got_error *err;
8713 struct got_commit_object *commit = NULL;
8714 char *id_str = NULL, *logmsg = NULL;
8716 err = got_object_open_as_commit(&commit, repo, id);
8717 if (err)
8718 return err;
8720 err = got_object_id_str(&id_str, id);
8721 if (err)
8722 goto done;
8724 id_str[12] = '\0';
8726 err = get_short_logmsg(&logmsg, 42, commit);
8727 if (err)
8728 goto done;
8730 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8731 done:
8732 free(id_str);
8733 got_object_commit_close(commit);
8734 free(logmsg);
8735 return err;
8738 static const struct got_error *
8739 show_rebase_progress(struct got_commit_object *commit,
8740 struct got_object_id *old_id, struct got_object_id *new_id)
8742 const struct got_error *err;
8743 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8745 err = got_object_id_str(&old_id_str, old_id);
8746 if (err)
8747 goto done;
8749 if (new_id) {
8750 err = got_object_id_str(&new_id_str, new_id);
8751 if (err)
8752 goto done;
8755 old_id_str[12] = '\0';
8756 if (new_id_str)
8757 new_id_str[12] = '\0';
8759 err = get_short_logmsg(&logmsg, 42, commit);
8760 if (err)
8761 goto done;
8763 printf("%s -> %s: %s\n", old_id_str,
8764 new_id_str ? new_id_str : "no-op change", logmsg);
8765 done:
8766 free(old_id_str);
8767 free(new_id_str);
8768 free(logmsg);
8769 return err;
8772 static const struct got_error *
8773 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8774 struct got_reference *branch, struct got_reference *new_base_branch,
8775 struct got_reference *tmp_branch, struct got_repository *repo,
8776 int create_backup)
8778 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8779 return got_worktree_rebase_complete(worktree, fileindex,
8780 new_base_branch, tmp_branch, branch, repo, create_backup);
8783 static const struct got_error *
8784 rebase_commit(struct got_pathlist_head *merged_paths,
8785 struct got_worktree *worktree, struct got_fileindex *fileindex,
8786 struct got_reference *tmp_branch,
8787 struct got_object_id *commit_id, struct got_repository *repo)
8789 const struct got_error *error;
8790 struct got_commit_object *commit;
8791 struct got_object_id *new_commit_id;
8793 error = got_object_open_as_commit(&commit, repo, commit_id);
8794 if (error)
8795 return error;
8797 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8798 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8799 if (error) {
8800 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8801 goto done;
8802 error = show_rebase_progress(commit, commit_id, NULL);
8803 } else {
8804 error = show_rebase_progress(commit, commit_id, new_commit_id);
8805 free(new_commit_id);
8807 done:
8808 got_object_commit_close(commit);
8809 return error;
8812 struct check_path_prefix_arg {
8813 const char *path_prefix;
8814 size_t len;
8815 int errcode;
8818 static const struct got_error *
8819 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8820 struct got_blob_object *blob2, struct got_object_id *id1,
8821 struct got_object_id *id2, const char *path1, const char *path2,
8822 mode_t mode1, mode_t mode2, struct got_repository *repo)
8824 struct check_path_prefix_arg *a = arg;
8826 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8827 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8828 return got_error(a->errcode);
8830 return NULL;
8833 static const struct got_error *
8834 check_path_prefix(struct got_object_id *parent_id,
8835 struct got_object_id *commit_id, const char *path_prefix,
8836 int errcode, struct got_repository *repo)
8838 const struct got_error *err;
8839 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8840 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8841 struct check_path_prefix_arg cpp_arg;
8843 if (got_path_is_root_dir(path_prefix))
8844 return NULL;
8846 err = got_object_open_as_commit(&commit, repo, commit_id);
8847 if (err)
8848 goto done;
8850 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8851 if (err)
8852 goto done;
8854 err = got_object_open_as_tree(&tree1, repo,
8855 got_object_commit_get_tree_id(parent_commit));
8856 if (err)
8857 goto done;
8859 err = got_object_open_as_tree(&tree2, repo,
8860 got_object_commit_get_tree_id(commit));
8861 if (err)
8862 goto done;
8864 cpp_arg.path_prefix = path_prefix;
8865 while (cpp_arg.path_prefix[0] == '/')
8866 cpp_arg.path_prefix++;
8867 cpp_arg.len = strlen(cpp_arg.path_prefix);
8868 cpp_arg.errcode = errcode;
8869 err = got_diff_tree(tree1, tree2, "", "", repo,
8870 check_path_prefix_in_diff, &cpp_arg, 0);
8871 done:
8872 if (tree1)
8873 got_object_tree_close(tree1);
8874 if (tree2)
8875 got_object_tree_close(tree2);
8876 if (commit)
8877 got_object_commit_close(commit);
8878 if (parent_commit)
8879 got_object_commit_close(parent_commit);
8880 return err;
8883 static const struct got_error *
8884 collect_commits(struct got_object_id_queue *commits,
8885 struct got_object_id *initial_commit_id,
8886 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8887 const char *path_prefix, int path_prefix_errcode,
8888 struct got_repository *repo)
8890 const struct got_error *err = NULL;
8891 struct got_commit_graph *graph = NULL;
8892 struct got_object_id *parent_id = NULL;
8893 struct got_object_qid *qid;
8894 struct got_object_id *commit_id = initial_commit_id;
8896 err = got_commit_graph_open(&graph, "/", 1);
8897 if (err)
8898 return err;
8900 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8901 check_cancelled, NULL);
8902 if (err)
8903 goto done;
8904 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8905 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8906 check_cancelled, NULL);
8907 if (err) {
8908 if (err->code == GOT_ERR_ITER_COMPLETED) {
8909 err = got_error_msg(GOT_ERR_ANCESTRY,
8910 "ran out of commits to rebase before "
8911 "youngest common ancestor commit has "
8912 "been reached?!?");
8914 goto done;
8915 } else {
8916 err = check_path_prefix(parent_id, commit_id,
8917 path_prefix, path_prefix_errcode, repo);
8918 if (err)
8919 goto done;
8921 err = got_object_qid_alloc(&qid, commit_id);
8922 if (err)
8923 goto done;
8924 STAILQ_INSERT_HEAD(commits, qid, entry);
8925 commit_id = parent_id;
8928 done:
8929 got_commit_graph_close(graph);
8930 return err;
8933 static const struct got_error *
8934 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
8936 const struct got_error *err = NULL;
8937 time_t committer_time;
8938 struct tm tm;
8939 char datebuf[11]; /* YYYY-MM-DD + NUL */
8940 char *author0 = NULL, *author, *smallerthan;
8941 char *logmsg0 = NULL, *logmsg, *newline;
8943 committer_time = got_object_commit_get_committer_time(commit);
8944 if (gmtime_r(&committer_time, &tm) == NULL)
8945 return got_error_from_errno("gmtime_r");
8946 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
8947 return got_error(GOT_ERR_NO_SPACE);
8949 author0 = strdup(got_object_commit_get_author(commit));
8950 if (author0 == NULL)
8951 return got_error_from_errno("strdup");
8952 author = author0;
8953 smallerthan = strchr(author, '<');
8954 if (smallerthan && smallerthan[1] != '\0')
8955 author = smallerthan + 1;
8956 author[strcspn(author, "@>")] = '\0';
8958 err = got_object_commit_get_logmsg(&logmsg0, commit);
8959 if (err)
8960 goto done;
8961 logmsg = logmsg0;
8962 while (*logmsg == '\n')
8963 logmsg++;
8964 newline = strchr(logmsg, '\n');
8965 if (newline)
8966 *newline = '\0';
8968 if (asprintf(brief_str, "%s %s %s",
8969 datebuf, author, logmsg) == -1)
8970 err = got_error_from_errno("asprintf");
8971 done:
8972 free(author0);
8973 free(logmsg0);
8974 return err;
8977 static const struct got_error *
8978 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
8979 struct got_repository *repo)
8981 const struct got_error *err;
8982 char *id_str;
8984 err = got_object_id_str(&id_str, id);
8985 if (err)
8986 return err;
8988 err = got_ref_delete(ref, repo);
8989 if (err)
8990 goto done;
8992 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
8993 done:
8994 free(id_str);
8995 return err;
8998 static const struct got_error *
8999 print_backup_ref(const char *branch_name, const char *new_id_str,
9000 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9001 struct got_reflist_object_id_map *refs_idmap,
9002 struct got_repository *repo)
9004 const struct got_error *err = NULL;
9005 struct got_reflist_head *refs;
9006 char *refs_str = NULL;
9007 struct got_object_id *new_commit_id = NULL;
9008 struct got_commit_object *new_commit = NULL;
9009 char *new_commit_brief_str = NULL;
9010 struct got_object_id *yca_id = NULL;
9011 struct got_commit_object *yca_commit = NULL;
9012 char *yca_id_str = NULL, *yca_brief_str = NULL;
9013 char *custom_refs_str;
9015 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9016 return got_error_from_errno("asprintf");
9018 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9019 0, 0, refs_idmap, custom_refs_str);
9020 if (err)
9021 goto done;
9023 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9024 if (err)
9025 goto done;
9027 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9028 if (refs) {
9029 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9030 if (err)
9031 goto done;
9034 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9035 if (err)
9036 goto done;
9038 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9039 if (err)
9040 goto done;
9042 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9043 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9044 if (err)
9045 goto done;
9047 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9048 refs_str ? " (" : "", refs_str ? refs_str : "",
9049 refs_str ? ")" : "", new_commit_brief_str);
9050 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9051 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9052 free(refs_str);
9053 refs_str = NULL;
9055 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9056 if (err)
9057 goto done;
9059 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9060 if (err)
9061 goto done;
9063 err = got_object_id_str(&yca_id_str, yca_id);
9064 if (err)
9065 goto done;
9067 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9068 if (refs) {
9069 err = build_refs_str(&refs_str, refs, yca_id, repo);
9070 if (err)
9071 goto done;
9073 printf("history forked at %s%s%s%s\n %s\n",
9074 yca_id_str,
9075 refs_str ? " (" : "", refs_str ? refs_str : "",
9076 refs_str ? ")" : "", yca_brief_str);
9078 done:
9079 free(custom_refs_str);
9080 free(new_commit_id);
9081 free(refs_str);
9082 free(yca_id);
9083 free(yca_id_str);
9084 free(yca_brief_str);
9085 if (new_commit)
9086 got_object_commit_close(new_commit);
9087 if (yca_commit)
9088 got_object_commit_close(yca_commit);
9090 return NULL;
9093 static const struct got_error *
9094 process_backup_refs(const char *backup_ref_prefix,
9095 const char *wanted_branch_name,
9096 int delete, struct got_repository *repo)
9098 const struct got_error *err;
9099 struct got_reflist_head refs, backup_refs;
9100 struct got_reflist_entry *re;
9101 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9102 struct got_object_id *old_commit_id = NULL;
9103 char *branch_name = NULL;
9104 struct got_commit_object *old_commit = NULL;
9105 struct got_reflist_object_id_map *refs_idmap = NULL;
9106 int wanted_branch_found = 0;
9108 TAILQ_INIT(&refs);
9109 TAILQ_INIT(&backup_refs);
9111 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9112 if (err)
9113 return err;
9115 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9116 if (err)
9117 goto done;
9119 if (wanted_branch_name) {
9120 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9121 wanted_branch_name += 11;
9124 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9125 got_ref_cmp_by_commit_timestamp_descending, repo);
9126 if (err)
9127 goto done;
9129 TAILQ_FOREACH(re, &backup_refs, entry) {
9130 const char *refname = got_ref_get_name(re->ref);
9131 char *slash;
9133 err = check_cancelled(NULL);
9134 if (err)
9135 break;
9137 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9138 if (err)
9139 break;
9141 err = got_object_open_as_commit(&old_commit, repo,
9142 old_commit_id);
9143 if (err)
9144 break;
9146 if (strncmp(backup_ref_prefix, refname,
9147 backup_ref_prefix_len) == 0)
9148 refname += backup_ref_prefix_len;
9150 while (refname[0] == '/')
9151 refname++;
9153 branch_name = strdup(refname);
9154 if (branch_name == NULL) {
9155 err = got_error_from_errno("strdup");
9156 break;
9158 slash = strrchr(branch_name, '/');
9159 if (slash) {
9160 *slash = '\0';
9161 refname += strlen(branch_name) + 1;
9164 if (wanted_branch_name == NULL ||
9165 strcmp(wanted_branch_name, branch_name) == 0) {
9166 wanted_branch_found = 1;
9167 if (delete) {
9168 err = delete_backup_ref(re->ref,
9169 old_commit_id, repo);
9170 } else {
9171 err = print_backup_ref(branch_name, refname,
9172 old_commit_id, old_commit, refs_idmap,
9173 repo);
9175 if (err)
9176 break;
9179 free(old_commit_id);
9180 old_commit_id = NULL;
9181 free(branch_name);
9182 branch_name = NULL;
9183 got_object_commit_close(old_commit);
9184 old_commit = NULL;
9187 if (wanted_branch_name && !wanted_branch_found) {
9188 err = got_error_fmt(GOT_ERR_NOT_REF,
9189 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9191 done:
9192 if (refs_idmap)
9193 got_reflist_object_id_map_free(refs_idmap);
9194 got_ref_list_free(&refs);
9195 got_ref_list_free(&backup_refs);
9196 free(old_commit_id);
9197 free(branch_name);
9198 if (old_commit)
9199 got_object_commit_close(old_commit);
9200 return err;
9203 static const struct got_error *
9204 abort_progress(void *arg, unsigned char status, const char *path)
9207 * Unversioned files should not clutter progress output when
9208 * an operation is aborted.
9210 if (status == GOT_STATUS_UNVERSIONED)
9211 return NULL;
9213 return update_progress(arg, status, path);
9216 static const struct got_error *
9217 cmd_rebase(int argc, char *argv[])
9219 const struct got_error *error = NULL;
9220 struct got_worktree *worktree = NULL;
9221 struct got_repository *repo = NULL;
9222 struct got_fileindex *fileindex = NULL;
9223 char *cwd = NULL;
9224 struct got_reference *branch = NULL;
9225 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9226 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9227 struct got_object_id *resume_commit_id = NULL;
9228 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9229 struct got_commit_object *commit = NULL;
9230 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9231 int histedit_in_progress = 0, merge_in_progress = 0;
9232 int create_backup = 1, list_backups = 0, delete_backups = 0;
9233 struct got_object_id_queue commits;
9234 struct got_pathlist_head merged_paths;
9235 const struct got_object_id_queue *parent_ids;
9236 struct got_object_qid *qid, *pid;
9237 struct got_update_progress_arg upa;
9239 STAILQ_INIT(&commits);
9240 TAILQ_INIT(&merged_paths);
9241 memset(&upa, 0, sizeof(upa));
9243 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9244 switch (ch) {
9245 case 'a':
9246 abort_rebase = 1;
9247 break;
9248 case 'c':
9249 continue_rebase = 1;
9250 break;
9251 case 'l':
9252 list_backups = 1;
9253 break;
9254 case 'X':
9255 delete_backups = 1;
9256 break;
9257 default:
9258 usage_rebase();
9259 /* NOTREACHED */
9263 argc -= optind;
9264 argv += optind;
9266 #ifndef PROFILE
9267 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9268 "unveil", NULL) == -1)
9269 err(1, "pledge");
9270 #endif
9271 if (list_backups) {
9272 if (abort_rebase)
9273 option_conflict('l', 'a');
9274 if (continue_rebase)
9275 option_conflict('l', 'c');
9276 if (delete_backups)
9277 option_conflict('l', 'X');
9278 if (argc != 0 && argc != 1)
9279 usage_rebase();
9280 } else if (delete_backups) {
9281 if (abort_rebase)
9282 option_conflict('X', 'a');
9283 if (continue_rebase)
9284 option_conflict('X', 'c');
9285 if (list_backups)
9286 option_conflict('l', 'X');
9287 if (argc != 0 && argc != 1)
9288 usage_rebase();
9289 } else {
9290 if (abort_rebase && continue_rebase)
9291 usage_rebase();
9292 else if (abort_rebase || continue_rebase) {
9293 if (argc != 0)
9294 usage_rebase();
9295 } else if (argc != 1)
9296 usage_rebase();
9299 cwd = getcwd(NULL, 0);
9300 if (cwd == NULL) {
9301 error = got_error_from_errno("getcwd");
9302 goto done;
9304 error = got_worktree_open(&worktree, cwd);
9305 if (error) {
9306 if (list_backups || delete_backups) {
9307 if (error->code != GOT_ERR_NOT_WORKTREE)
9308 goto done;
9309 } else {
9310 if (error->code == GOT_ERR_NOT_WORKTREE)
9311 error = wrap_not_worktree_error(error,
9312 "rebase", cwd);
9313 goto done;
9317 error = got_repo_open(&repo,
9318 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9319 if (error != NULL)
9320 goto done;
9322 error = apply_unveil(got_repo_get_path(repo), 0,
9323 worktree ? got_worktree_get_root_path(worktree) : NULL);
9324 if (error)
9325 goto done;
9327 if (list_backups || delete_backups) {
9328 error = process_backup_refs(
9329 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9330 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9331 goto done; /* nothing else to do */
9334 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9335 worktree);
9336 if (error)
9337 goto done;
9338 if (histedit_in_progress) {
9339 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9340 goto done;
9343 error = got_worktree_merge_in_progress(&merge_in_progress,
9344 worktree, repo);
9345 if (error)
9346 goto done;
9347 if (merge_in_progress) {
9348 error = got_error(GOT_ERR_MERGE_BUSY);
9349 goto done;
9352 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9353 if (error)
9354 goto done;
9356 if (abort_rebase) {
9357 if (!rebase_in_progress) {
9358 error = got_error(GOT_ERR_NOT_REBASING);
9359 goto done;
9361 error = got_worktree_rebase_continue(&resume_commit_id,
9362 &new_base_branch, &tmp_branch, &branch, &fileindex,
9363 worktree, repo);
9364 if (error)
9365 goto done;
9366 printf("Switching work tree to %s\n",
9367 got_ref_get_symref_target(new_base_branch));
9368 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9369 new_base_branch, abort_progress, &upa);
9370 if (error)
9371 goto done;
9372 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9373 print_merge_progress_stats(&upa);
9374 goto done; /* nothing else to do */
9377 if (continue_rebase) {
9378 if (!rebase_in_progress) {
9379 error = got_error(GOT_ERR_NOT_REBASING);
9380 goto done;
9382 error = got_worktree_rebase_continue(&resume_commit_id,
9383 &new_base_branch, &tmp_branch, &branch, &fileindex,
9384 worktree, repo);
9385 if (error)
9386 goto done;
9388 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9389 resume_commit_id, repo);
9390 if (error)
9391 goto done;
9393 yca_id = got_object_id_dup(resume_commit_id);
9394 if (yca_id == NULL) {
9395 error = got_error_from_errno("got_object_id_dup");
9396 goto done;
9398 } else {
9399 error = got_ref_open(&branch, repo, argv[0], 0);
9400 if (error != NULL)
9401 goto done;
9404 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9405 if (error)
9406 goto done;
9408 if (!continue_rebase) {
9409 struct got_object_id *base_commit_id;
9411 base_commit_id = got_worktree_get_base_commit_id(worktree);
9412 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9413 base_commit_id, branch_head_commit_id, 1, repo,
9414 check_cancelled, NULL);
9415 if (error)
9416 goto done;
9417 if (yca_id == NULL) {
9418 error = got_error_msg(GOT_ERR_ANCESTRY,
9419 "specified branch shares no common ancestry "
9420 "with work tree's branch");
9421 goto done;
9424 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9425 if (error) {
9426 if (error->code != GOT_ERR_ANCESTRY)
9427 goto done;
9428 error = NULL;
9429 } else {
9430 struct got_pathlist_head paths;
9431 printf("%s is already based on %s\n",
9432 got_ref_get_name(branch),
9433 got_worktree_get_head_ref_name(worktree));
9434 error = switch_head_ref(branch, branch_head_commit_id,
9435 worktree, repo);
9436 if (error)
9437 goto done;
9438 error = got_worktree_set_base_commit_id(worktree, repo,
9439 branch_head_commit_id);
9440 if (error)
9441 goto done;
9442 TAILQ_INIT(&paths);
9443 error = got_pathlist_append(&paths, "", NULL);
9444 if (error)
9445 goto done;
9446 error = got_worktree_checkout_files(worktree,
9447 &paths, repo, update_progress, &upa,
9448 check_cancelled, NULL);
9449 got_pathlist_free(&paths);
9450 if (error)
9451 goto done;
9452 if (upa.did_something) {
9453 char *id_str;
9454 error = got_object_id_str(&id_str,
9455 branch_head_commit_id);
9456 if (error)
9457 goto done;
9458 printf("Updated to %s: %s\n",
9459 got_worktree_get_head_ref_name(worktree),
9460 id_str);
9461 free(id_str);
9462 } else
9463 printf("Already up-to-date\n");
9464 print_update_progress_stats(&upa);
9465 goto done;
9469 commit_id = branch_head_commit_id;
9470 error = got_object_open_as_commit(&commit, repo, commit_id);
9471 if (error)
9472 goto done;
9474 parent_ids = got_object_commit_get_parent_ids(commit);
9475 pid = STAILQ_FIRST(parent_ids);
9476 if (pid == NULL) {
9477 error = got_error(GOT_ERR_EMPTY_REBASE);
9478 goto done;
9480 error = collect_commits(&commits, commit_id, pid->id,
9481 yca_id, got_worktree_get_path_prefix(worktree),
9482 GOT_ERR_REBASE_PATH, repo);
9483 got_object_commit_close(commit);
9484 commit = NULL;
9485 if (error)
9486 goto done;
9488 if (!continue_rebase) {
9489 error = got_worktree_rebase_prepare(&new_base_branch,
9490 &tmp_branch, &fileindex, worktree, branch, repo);
9491 if (error)
9492 goto done;
9495 if (STAILQ_EMPTY(&commits)) {
9496 if (continue_rebase) {
9497 error = rebase_complete(worktree, fileindex,
9498 branch, new_base_branch, tmp_branch, repo,
9499 create_backup);
9500 goto done;
9501 } else {
9502 /* Fast-forward the reference of the branch. */
9503 struct got_object_id *new_head_commit_id;
9504 char *id_str;
9505 error = got_ref_resolve(&new_head_commit_id, repo,
9506 new_base_branch);
9507 if (error)
9508 goto done;
9509 error = got_object_id_str(&id_str, new_head_commit_id);
9510 printf("Forwarding %s to commit %s\n",
9511 got_ref_get_name(branch), id_str);
9512 free(id_str);
9513 error = got_ref_change_ref(branch,
9514 new_head_commit_id);
9515 if (error)
9516 goto done;
9517 /* No backup needed since objects did not change. */
9518 create_backup = 0;
9522 pid = NULL;
9523 STAILQ_FOREACH(qid, &commits, entry) {
9525 commit_id = qid->id;
9526 parent_id = pid ? pid->id : yca_id;
9527 pid = qid;
9529 memset(&upa, 0, sizeof(upa));
9530 error = got_worktree_rebase_merge_files(&merged_paths,
9531 worktree, fileindex, parent_id, commit_id, repo,
9532 update_progress, &upa, check_cancelled, NULL);
9533 if (error)
9534 goto done;
9536 print_merge_progress_stats(&upa);
9537 if (upa.conflicts > 0 || upa.missing > 0 ||
9538 upa.not_deleted > 0 || upa.unversioned > 0) {
9539 if (upa.conflicts > 0) {
9540 error = show_rebase_merge_conflict(qid->id,
9541 repo);
9542 if (error)
9543 goto done;
9545 got_worktree_rebase_pathlist_free(&merged_paths);
9546 break;
9549 error = rebase_commit(&merged_paths, worktree, fileindex,
9550 tmp_branch, commit_id, repo);
9551 got_worktree_rebase_pathlist_free(&merged_paths);
9552 if (error)
9553 goto done;
9556 if (upa.conflicts > 0 || upa.missing > 0 ||
9557 upa.not_deleted > 0 || upa.unversioned > 0) {
9558 error = got_worktree_rebase_postpone(worktree, fileindex);
9559 if (error)
9560 goto done;
9561 if (upa.conflicts > 0 && upa.missing == 0 &&
9562 upa.not_deleted == 0 && upa.unversioned == 0) {
9563 error = got_error_msg(GOT_ERR_CONFLICTS,
9564 "conflicts must be resolved before rebasing "
9565 "can continue");
9566 } else if (upa.conflicts > 0) {
9567 error = got_error_msg(GOT_ERR_CONFLICTS,
9568 "conflicts must be resolved before rebasing "
9569 "can continue; changes destined for some "
9570 "files were not yet merged and should be "
9571 "merged manually if required before the "
9572 "rebase operation is continued");
9573 } else {
9574 error = got_error_msg(GOT_ERR_CONFLICTS,
9575 "changes destined for some files were not "
9576 "yet merged and should be merged manually "
9577 "if required before the rebase operation "
9578 "is continued");
9580 } else
9581 error = rebase_complete(worktree, fileindex, branch,
9582 new_base_branch, tmp_branch, repo, create_backup);
9583 done:
9584 got_object_id_queue_free(&commits);
9585 free(branch_head_commit_id);
9586 free(resume_commit_id);
9587 free(yca_id);
9588 if (commit)
9589 got_object_commit_close(commit);
9590 if (branch)
9591 got_ref_close(branch);
9592 if (new_base_branch)
9593 got_ref_close(new_base_branch);
9594 if (tmp_branch)
9595 got_ref_close(tmp_branch);
9596 if (worktree)
9597 got_worktree_close(worktree);
9598 if (repo) {
9599 const struct got_error *close_err = got_repo_close(repo);
9600 if (error == NULL)
9601 error = close_err;
9603 return error;
9606 __dead static void
9607 usage_histedit(void)
9609 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9610 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9611 getprogname());
9612 exit(1);
9615 #define GOT_HISTEDIT_PICK 'p'
9616 #define GOT_HISTEDIT_EDIT 'e'
9617 #define GOT_HISTEDIT_FOLD 'f'
9618 #define GOT_HISTEDIT_DROP 'd'
9619 #define GOT_HISTEDIT_MESG 'm'
9621 static const struct got_histedit_cmd {
9622 unsigned char code;
9623 const char *name;
9624 const char *desc;
9625 } got_histedit_cmds[] = {
9626 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9627 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9628 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9629 "be used" },
9630 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9631 { GOT_HISTEDIT_MESG, "mesg",
9632 "single-line log message for commit above (open editor if empty)" },
9635 struct got_histedit_list_entry {
9636 TAILQ_ENTRY(got_histedit_list_entry) entry;
9637 struct got_object_id *commit_id;
9638 const struct got_histedit_cmd *cmd;
9639 char *logmsg;
9641 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9643 static const struct got_error *
9644 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9645 FILE *f, struct got_repository *repo)
9647 const struct got_error *err = NULL;
9648 char *logmsg = NULL, *id_str = NULL;
9649 struct got_commit_object *commit = NULL;
9650 int n;
9652 err = got_object_open_as_commit(&commit, repo, commit_id);
9653 if (err)
9654 goto done;
9656 err = get_short_logmsg(&logmsg, 34, commit);
9657 if (err)
9658 goto done;
9660 err = got_object_id_str(&id_str, commit_id);
9661 if (err)
9662 goto done;
9664 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9665 if (n < 0)
9666 err = got_ferror(f, GOT_ERR_IO);
9667 done:
9668 if (commit)
9669 got_object_commit_close(commit);
9670 free(id_str);
9671 free(logmsg);
9672 return err;
9675 static const struct got_error *
9676 histedit_write_commit_list(struct got_object_id_queue *commits,
9677 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9678 struct got_repository *repo)
9680 const struct got_error *err = NULL;
9681 struct got_object_qid *qid;
9682 const char *histedit_cmd = NULL;
9684 if (STAILQ_EMPTY(commits))
9685 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9687 STAILQ_FOREACH(qid, commits, entry) {
9688 histedit_cmd = got_histedit_cmds[0].name;
9689 if (edit_only)
9690 histedit_cmd = "edit";
9691 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9692 histedit_cmd = "fold";
9693 err = histedit_write_commit(qid->id, histedit_cmd, f, repo);
9694 if (err)
9695 break;
9696 if (edit_logmsg_only) {
9697 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9698 if (n < 0) {
9699 err = got_ferror(f, GOT_ERR_IO);
9700 break;
9705 return err;
9708 static const struct got_error *
9709 write_cmd_list(FILE *f, const char *branch_name,
9710 struct got_object_id_queue *commits)
9712 const struct got_error *err = NULL;
9713 size_t i;
9714 int n;
9715 char *id_str;
9716 struct got_object_qid *qid;
9718 qid = STAILQ_FIRST(commits);
9719 err = got_object_id_str(&id_str, qid->id);
9720 if (err)
9721 return err;
9723 n = fprintf(f,
9724 "# Editing the history of branch '%s' starting at\n"
9725 "# commit %s\n"
9726 "# Commits will be processed in order from top to "
9727 "bottom of this file.\n", branch_name, id_str);
9728 if (n < 0) {
9729 err = got_ferror(f, GOT_ERR_IO);
9730 goto done;
9733 n = fprintf(f, "# Available histedit commands:\n");
9734 if (n < 0) {
9735 err = got_ferror(f, GOT_ERR_IO);
9736 goto done;
9739 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9740 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9741 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9742 cmd->desc);
9743 if (n < 0) {
9744 err = got_ferror(f, GOT_ERR_IO);
9745 break;
9748 done:
9749 free(id_str);
9750 return err;
9753 static const struct got_error *
9754 histedit_syntax_error(int lineno)
9756 static char msg[42];
9757 int ret;
9759 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9760 lineno);
9761 if (ret == -1 || ret >= sizeof(msg))
9762 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9764 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9767 static const struct got_error *
9768 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9769 char *logmsg, struct got_repository *repo)
9771 const struct got_error *err;
9772 struct got_commit_object *folded_commit = NULL;
9773 char *id_str, *folded_logmsg = NULL;
9775 err = got_object_id_str(&id_str, hle->commit_id);
9776 if (err)
9777 return err;
9779 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9780 if (err)
9781 goto done;
9783 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9784 if (err)
9785 goto done;
9786 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9787 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9788 folded_logmsg) == -1) {
9789 err = got_error_from_errno("asprintf");
9791 done:
9792 if (folded_commit)
9793 got_object_commit_close(folded_commit);
9794 free(id_str);
9795 free(folded_logmsg);
9796 return err;
9799 static struct got_histedit_list_entry *
9800 get_folded_commits(struct got_histedit_list_entry *hle)
9802 struct got_histedit_list_entry *prev, *folded = NULL;
9804 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9805 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9806 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9807 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9808 folded = prev;
9809 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9812 return folded;
9815 static const struct got_error *
9816 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9817 struct got_repository *repo)
9819 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9820 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9821 const struct got_error *err = NULL;
9822 struct got_commit_object *commit = NULL;
9823 int logmsg_len;
9824 int fd;
9825 struct got_histedit_list_entry *folded = NULL;
9827 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9828 if (err)
9829 return err;
9831 folded = get_folded_commits(hle);
9832 if (folded) {
9833 while (folded != hle) {
9834 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9835 folded = TAILQ_NEXT(folded, entry);
9836 continue;
9838 err = append_folded_commit_msg(&new_msg, folded,
9839 logmsg, repo);
9840 if (err)
9841 goto done;
9842 free(logmsg);
9843 logmsg = new_msg;
9844 folded = TAILQ_NEXT(folded, entry);
9848 err = got_object_id_str(&id_str, hle->commit_id);
9849 if (err)
9850 goto done;
9851 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9852 if (err)
9853 goto done;
9854 logmsg_len = asprintf(&new_msg,
9855 "%s\n# original log message of commit %s: %s",
9856 logmsg ? logmsg : "", id_str, orig_logmsg);
9857 if (logmsg_len == -1) {
9858 err = got_error_from_errno("asprintf");
9859 goto done;
9861 free(logmsg);
9862 logmsg = new_msg;
9864 err = got_object_id_str(&id_str, hle->commit_id);
9865 if (err)
9866 goto done;
9868 err = got_opentemp_named_fd(&logmsg_path, &fd,
9869 GOT_TMPDIR_STR "/got-logmsg");
9870 if (err)
9871 goto done;
9873 write(fd, logmsg, logmsg_len);
9874 close(fd);
9876 err = get_editor(&editor);
9877 if (err)
9878 goto done;
9880 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9881 logmsg_len, 0);
9882 if (err) {
9883 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9884 goto done;
9885 err = NULL;
9886 hle->logmsg = strdup(new_msg);
9887 if (hle->logmsg == NULL)
9888 err = got_error_from_errno("strdup");
9890 done:
9891 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9892 err = got_error_from_errno2("unlink", logmsg_path);
9893 free(logmsg_path);
9894 free(logmsg);
9895 free(orig_logmsg);
9896 free(editor);
9897 if (commit)
9898 got_object_commit_close(commit);
9899 return err;
9902 static const struct got_error *
9903 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9904 FILE *f, struct got_repository *repo)
9906 const struct got_error *err = NULL;
9907 char *line = NULL, *p, *end;
9908 size_t i, size;
9909 ssize_t len;
9910 int lineno = 0;
9911 const struct got_histedit_cmd *cmd;
9912 struct got_object_id *commit_id = NULL;
9913 struct got_histedit_list_entry *hle = NULL;
9915 for (;;) {
9916 len = getline(&line, &size, f);
9917 if (len == -1) {
9918 const struct got_error *getline_err;
9919 if (feof(f))
9920 break;
9921 getline_err = got_error_from_errno("getline");
9922 err = got_ferror(f, getline_err->code);
9923 break;
9925 lineno++;
9926 p = line;
9927 while (isspace((unsigned char)p[0]))
9928 p++;
9929 if (p[0] == '#' || p[0] == '\0') {
9930 free(line);
9931 line = NULL;
9932 continue;
9934 cmd = NULL;
9935 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9936 cmd = &got_histedit_cmds[i];
9937 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
9938 isspace((unsigned char)p[strlen(cmd->name)])) {
9939 p += strlen(cmd->name);
9940 break;
9942 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
9943 p++;
9944 break;
9947 if (i == nitems(got_histedit_cmds)) {
9948 err = histedit_syntax_error(lineno);
9949 break;
9951 while (isspace((unsigned char)p[0]))
9952 p++;
9953 if (cmd->code == GOT_HISTEDIT_MESG) {
9954 if (hle == NULL || hle->logmsg != NULL) {
9955 err = got_error(GOT_ERR_HISTEDIT_CMD);
9956 break;
9958 if (p[0] == '\0') {
9959 err = histedit_edit_logmsg(hle, repo);
9960 if (err)
9961 break;
9962 } else {
9963 hle->logmsg = strdup(p);
9964 if (hle->logmsg == NULL) {
9965 err = got_error_from_errno("strdup");
9966 break;
9969 free(line);
9970 line = NULL;
9971 continue;
9972 } else {
9973 end = p;
9974 while (end[0] && !isspace((unsigned char)end[0]))
9975 end++;
9976 *end = '\0';
9978 err = got_object_resolve_id_str(&commit_id, repo, p);
9979 if (err) {
9980 /* override error code */
9981 err = histedit_syntax_error(lineno);
9982 break;
9985 hle = malloc(sizeof(*hle));
9986 if (hle == NULL) {
9987 err = got_error_from_errno("malloc");
9988 break;
9990 hle->cmd = cmd;
9991 hle->commit_id = commit_id;
9992 hle->logmsg = NULL;
9993 commit_id = NULL;
9994 free(line);
9995 line = NULL;
9996 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
9999 free(line);
10000 free(commit_id);
10001 return err;
10004 static const struct got_error *
10005 histedit_check_script(struct got_histedit_list *histedit_cmds,
10006 struct got_object_id_queue *commits, struct got_repository *repo)
10008 const struct got_error *err = NULL;
10009 struct got_object_qid *qid;
10010 struct got_histedit_list_entry *hle;
10011 static char msg[92];
10012 char *id_str;
10014 if (TAILQ_EMPTY(histedit_cmds))
10015 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10016 "histedit script contains no commands");
10017 if (STAILQ_EMPTY(commits))
10018 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10020 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10021 struct got_histedit_list_entry *hle2;
10022 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10023 if (hle == hle2)
10024 continue;
10025 if (got_object_id_cmp(hle->commit_id,
10026 hle2->commit_id) != 0)
10027 continue;
10028 err = got_object_id_str(&id_str, hle->commit_id);
10029 if (err)
10030 return err;
10031 snprintf(msg, sizeof(msg), "commit %s is listed "
10032 "more than once in histedit script", id_str);
10033 free(id_str);
10034 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10038 STAILQ_FOREACH(qid, commits, entry) {
10039 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10040 if (got_object_id_cmp(qid->id, hle->commit_id) == 0)
10041 break;
10043 if (hle == NULL) {
10044 err = got_object_id_str(&id_str, qid->id);
10045 if (err)
10046 return err;
10047 snprintf(msg, sizeof(msg),
10048 "commit %s missing from histedit script", id_str);
10049 free(id_str);
10050 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10054 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10055 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10056 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10057 "last commit in histedit script cannot be folded");
10059 return NULL;
10062 static const struct got_error *
10063 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10064 const char *path, struct got_object_id_queue *commits,
10065 struct got_repository *repo)
10067 const struct got_error *err = NULL;
10068 char *editor;
10069 FILE *f = NULL;
10071 err = get_editor(&editor);
10072 if (err)
10073 return err;
10075 if (spawn_editor(editor, path) == -1) {
10076 err = got_error_from_errno("failed spawning editor");
10077 goto done;
10080 f = fopen(path, "re");
10081 if (f == NULL) {
10082 err = got_error_from_errno("fopen");
10083 goto done;
10085 err = histedit_parse_list(histedit_cmds, f, repo);
10086 if (err)
10087 goto done;
10089 err = histedit_check_script(histedit_cmds, commits, repo);
10090 done:
10091 if (f && fclose(f) == EOF && err == NULL)
10092 err = got_error_from_errno("fclose");
10093 free(editor);
10094 return err;
10097 static const struct got_error *
10098 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10099 struct got_object_id_queue *, const char *, const char *,
10100 struct got_repository *);
10102 static const struct got_error *
10103 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10104 struct got_object_id_queue *commits, const char *branch_name,
10105 int edit_logmsg_only, int fold_only, int edit_only,
10106 struct got_repository *repo)
10108 const struct got_error *err;
10109 FILE *f = NULL;
10110 char *path = NULL;
10112 err = got_opentemp_named(&path, &f, "got-histedit");
10113 if (err)
10114 return err;
10116 err = write_cmd_list(f, branch_name, commits);
10117 if (err)
10118 goto done;
10120 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10121 fold_only, edit_only, repo);
10122 if (err)
10123 goto done;
10125 if (edit_logmsg_only || fold_only || edit_only) {
10126 rewind(f);
10127 err = histedit_parse_list(histedit_cmds, f, repo);
10128 } else {
10129 if (fclose(f) == EOF) {
10130 err = got_error_from_errno("fclose");
10131 goto done;
10133 f = NULL;
10134 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10135 if (err) {
10136 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10137 err->code != GOT_ERR_HISTEDIT_CMD)
10138 goto done;
10139 err = histedit_edit_list_retry(histedit_cmds, err,
10140 commits, path, branch_name, repo);
10143 done:
10144 if (f && fclose(f) == EOF && err == NULL)
10145 err = got_error_from_errno("fclose");
10146 if (path && unlink(path) != 0 && err == NULL)
10147 err = got_error_from_errno2("unlink", path);
10148 free(path);
10149 return err;
10152 static const struct got_error *
10153 histedit_save_list(struct got_histedit_list *histedit_cmds,
10154 struct got_worktree *worktree, struct got_repository *repo)
10156 const struct got_error *err = NULL;
10157 char *path = NULL;
10158 FILE *f = NULL;
10159 struct got_histedit_list_entry *hle;
10160 struct got_commit_object *commit = NULL;
10162 err = got_worktree_get_histedit_script_path(&path, worktree);
10163 if (err)
10164 return err;
10166 f = fopen(path, "we");
10167 if (f == NULL) {
10168 err = got_error_from_errno2("fopen", path);
10169 goto done;
10171 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10172 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10173 repo);
10174 if (err)
10175 break;
10177 if (hle->logmsg) {
10178 int n = fprintf(f, "%c %s\n",
10179 GOT_HISTEDIT_MESG, hle->logmsg);
10180 if (n < 0) {
10181 err = got_ferror(f, GOT_ERR_IO);
10182 break;
10186 done:
10187 if (f && fclose(f) == EOF && err == NULL)
10188 err = got_error_from_errno("fclose");
10189 free(path);
10190 if (commit)
10191 got_object_commit_close(commit);
10192 return err;
10195 void
10196 histedit_free_list(struct got_histedit_list *histedit_cmds)
10198 struct got_histedit_list_entry *hle;
10200 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10201 TAILQ_REMOVE(histedit_cmds, hle, entry);
10202 free(hle);
10206 static const struct got_error *
10207 histedit_load_list(struct got_histedit_list *histedit_cmds,
10208 const char *path, struct got_repository *repo)
10210 const struct got_error *err = NULL;
10211 FILE *f = NULL;
10213 f = fopen(path, "re");
10214 if (f == NULL) {
10215 err = got_error_from_errno2("fopen", path);
10216 goto done;
10219 err = histedit_parse_list(histedit_cmds, f, repo);
10220 done:
10221 if (f && fclose(f) == EOF && err == NULL)
10222 err = got_error_from_errno("fclose");
10223 return err;
10226 static const struct got_error *
10227 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10228 const struct got_error *edit_err, struct got_object_id_queue *commits,
10229 const char *path, const char *branch_name, struct got_repository *repo)
10231 const struct got_error *err = NULL, *prev_err = edit_err;
10232 int resp = ' ';
10234 while (resp != 'c' && resp != 'r' && resp != 'a') {
10235 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10236 "or (a)bort: ", getprogname(), prev_err->msg);
10237 resp = getchar();
10238 if (resp == '\n')
10239 resp = getchar();
10240 if (resp == 'c') {
10241 histedit_free_list(histedit_cmds);
10242 err = histedit_run_editor(histedit_cmds, path, commits,
10243 repo);
10244 if (err) {
10245 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10246 err->code != GOT_ERR_HISTEDIT_CMD)
10247 break;
10248 prev_err = err;
10249 resp = ' ';
10250 continue;
10252 break;
10253 } else if (resp == 'r') {
10254 histedit_free_list(histedit_cmds);
10255 err = histedit_edit_script(histedit_cmds,
10256 commits, branch_name, 0, 0, 0, repo);
10257 if (err) {
10258 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10259 err->code != GOT_ERR_HISTEDIT_CMD)
10260 break;
10261 prev_err = err;
10262 resp = ' ';
10263 continue;
10265 break;
10266 } else if (resp == 'a') {
10267 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10268 break;
10269 } else
10270 printf("invalid response '%c'\n", resp);
10273 return err;
10276 static const struct got_error *
10277 histedit_complete(struct got_worktree *worktree,
10278 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10279 struct got_reference *branch, struct got_repository *repo)
10281 printf("Switching work tree to %s\n",
10282 got_ref_get_symref_target(branch));
10283 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10284 branch, repo);
10287 static const struct got_error *
10288 show_histedit_progress(struct got_commit_object *commit,
10289 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10291 const struct got_error *err;
10292 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10294 err = got_object_id_str(&old_id_str, hle->commit_id);
10295 if (err)
10296 goto done;
10298 if (new_id) {
10299 err = got_object_id_str(&new_id_str, new_id);
10300 if (err)
10301 goto done;
10304 old_id_str[12] = '\0';
10305 if (new_id_str)
10306 new_id_str[12] = '\0';
10308 if (hle->logmsg) {
10309 logmsg = strdup(hle->logmsg);
10310 if (logmsg == NULL) {
10311 err = got_error_from_errno("strdup");
10312 goto done;
10314 trim_logmsg(logmsg, 42);
10315 } else {
10316 err = get_short_logmsg(&logmsg, 42, commit);
10317 if (err)
10318 goto done;
10321 switch (hle->cmd->code) {
10322 case GOT_HISTEDIT_PICK:
10323 case GOT_HISTEDIT_EDIT:
10324 printf("%s -> %s: %s\n", old_id_str,
10325 new_id_str ? new_id_str : "no-op change", logmsg);
10326 break;
10327 case GOT_HISTEDIT_DROP:
10328 case GOT_HISTEDIT_FOLD:
10329 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10330 logmsg);
10331 break;
10332 default:
10333 break;
10335 done:
10336 free(old_id_str);
10337 free(new_id_str);
10338 return err;
10341 static const struct got_error *
10342 histedit_commit(struct got_pathlist_head *merged_paths,
10343 struct got_worktree *worktree, struct got_fileindex *fileindex,
10344 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10345 struct got_repository *repo)
10347 const struct got_error *err;
10348 struct got_commit_object *commit;
10349 struct got_object_id *new_commit_id;
10351 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10352 && hle->logmsg == NULL) {
10353 err = histedit_edit_logmsg(hle, repo);
10354 if (err)
10355 return err;
10358 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10359 if (err)
10360 return err;
10362 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10363 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10364 hle->logmsg, repo);
10365 if (err) {
10366 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10367 goto done;
10368 err = show_histedit_progress(commit, hle, NULL);
10369 } else {
10370 err = show_histedit_progress(commit, hle, new_commit_id);
10371 free(new_commit_id);
10373 done:
10374 got_object_commit_close(commit);
10375 return err;
10378 static const struct got_error *
10379 histedit_skip_commit(struct got_histedit_list_entry *hle,
10380 struct got_worktree *worktree, struct got_repository *repo)
10382 const struct got_error *error;
10383 struct got_commit_object *commit;
10385 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10386 repo);
10387 if (error)
10388 return error;
10390 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10391 if (error)
10392 return error;
10394 error = show_histedit_progress(commit, hle, NULL);
10395 got_object_commit_close(commit);
10396 return error;
10399 static const struct got_error *
10400 check_local_changes(void *arg, unsigned char status,
10401 unsigned char staged_status, const char *path,
10402 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10403 struct got_object_id *commit_id, int dirfd, const char *de_name)
10405 int *have_local_changes = arg;
10407 switch (status) {
10408 case GOT_STATUS_ADD:
10409 case GOT_STATUS_DELETE:
10410 case GOT_STATUS_MODIFY:
10411 case GOT_STATUS_CONFLICT:
10412 *have_local_changes = 1;
10413 return got_error(GOT_ERR_CANCELLED);
10414 default:
10415 break;
10418 switch (staged_status) {
10419 case GOT_STATUS_ADD:
10420 case GOT_STATUS_DELETE:
10421 case GOT_STATUS_MODIFY:
10422 *have_local_changes = 1;
10423 return got_error(GOT_ERR_CANCELLED);
10424 default:
10425 break;
10428 return NULL;
10431 static const struct got_error *
10432 cmd_histedit(int argc, char *argv[])
10434 const struct got_error *error = NULL;
10435 struct got_worktree *worktree = NULL;
10436 struct got_fileindex *fileindex = NULL;
10437 struct got_repository *repo = NULL;
10438 char *cwd = NULL;
10439 struct got_reference *branch = NULL;
10440 struct got_reference *tmp_branch = NULL;
10441 struct got_object_id *resume_commit_id = NULL;
10442 struct got_object_id *base_commit_id = NULL;
10443 struct got_object_id *head_commit_id = NULL;
10444 struct got_commit_object *commit = NULL;
10445 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10446 struct got_update_progress_arg upa;
10447 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10448 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10449 int list_backups = 0, delete_backups = 0;
10450 const char *edit_script_path = NULL;
10451 struct got_object_id_queue commits;
10452 struct got_pathlist_head merged_paths;
10453 const struct got_object_id_queue *parent_ids;
10454 struct got_object_qid *pid;
10455 struct got_histedit_list histedit_cmds;
10456 struct got_histedit_list_entry *hle;
10458 STAILQ_INIT(&commits);
10459 TAILQ_INIT(&histedit_cmds);
10460 TAILQ_INIT(&merged_paths);
10461 memset(&upa, 0, sizeof(upa));
10463 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10464 switch (ch) {
10465 case 'a':
10466 abort_edit = 1;
10467 break;
10468 case 'c':
10469 continue_edit = 1;
10470 break;
10471 case 'e':
10472 edit_only = 1;
10473 break;
10474 case 'f':
10475 fold_only = 1;
10476 break;
10477 case 'F':
10478 edit_script_path = optarg;
10479 break;
10480 case 'm':
10481 edit_logmsg_only = 1;
10482 break;
10483 case 'l':
10484 list_backups = 1;
10485 break;
10486 case 'X':
10487 delete_backups = 1;
10488 break;
10489 default:
10490 usage_histedit();
10491 /* NOTREACHED */
10495 argc -= optind;
10496 argv += optind;
10498 #ifndef PROFILE
10499 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10500 "unveil", NULL) == -1)
10501 err(1, "pledge");
10502 #endif
10503 if (abort_edit && continue_edit)
10504 option_conflict('a', 'c');
10505 if (edit_script_path && edit_logmsg_only)
10506 option_conflict('F', 'm');
10507 if (abort_edit && edit_logmsg_only)
10508 option_conflict('a', 'm');
10509 if (continue_edit && edit_logmsg_only)
10510 option_conflict('c', 'm');
10511 if (abort_edit && fold_only)
10512 option_conflict('a', 'f');
10513 if (continue_edit && fold_only)
10514 option_conflict('c', 'f');
10515 if (fold_only && edit_logmsg_only)
10516 option_conflict('f', 'm');
10517 if (edit_script_path && fold_only)
10518 option_conflict('F', 'f');
10519 if (abort_edit && edit_only)
10520 option_conflict('a', 'e');
10521 if (continue_edit && edit_only)
10522 option_conflict('c', 'e');
10523 if (edit_only && edit_logmsg_only)
10524 option_conflict('e', 'm');
10525 if (edit_script_path && edit_only)
10526 option_conflict('F', 'e');
10527 if (list_backups) {
10528 if (abort_edit)
10529 option_conflict('l', 'a');
10530 if (continue_edit)
10531 option_conflict('l', 'c');
10532 if (edit_script_path)
10533 option_conflict('l', 'F');
10534 if (edit_logmsg_only)
10535 option_conflict('l', 'm');
10536 if (fold_only)
10537 option_conflict('l', 'f');
10538 if (edit_only)
10539 option_conflict('l', 'e');
10540 if (delete_backups)
10541 option_conflict('l', 'X');
10542 if (argc != 0 && argc != 1)
10543 usage_histedit();
10544 } else if (delete_backups) {
10545 if (abort_edit)
10546 option_conflict('X', 'a');
10547 if (continue_edit)
10548 option_conflict('X', 'c');
10549 if (edit_script_path)
10550 option_conflict('X', 'F');
10551 if (edit_logmsg_only)
10552 option_conflict('X', 'm');
10553 if (fold_only)
10554 option_conflict('X', 'f');
10555 if (edit_only)
10556 option_conflict('X', 'e');
10557 if (list_backups)
10558 option_conflict('X', 'l');
10559 if (argc != 0 && argc != 1)
10560 usage_histedit();
10561 } else if (argc != 0)
10562 usage_histedit();
10565 * This command cannot apply unveil(2) in all cases because the
10566 * user may choose to run an editor to edit the histedit script
10567 * and to edit individual commit log messages.
10568 * unveil(2) traverses exec(2); if an editor is used we have to
10569 * apply unveil after edit script and log messages have been written.
10570 * XXX TODO: Make use of unveil(2) where possible.
10573 cwd = getcwd(NULL, 0);
10574 if (cwd == NULL) {
10575 error = got_error_from_errno("getcwd");
10576 goto done;
10578 error = got_worktree_open(&worktree, cwd);
10579 if (error) {
10580 if (list_backups || delete_backups) {
10581 if (error->code != GOT_ERR_NOT_WORKTREE)
10582 goto done;
10583 } else {
10584 if (error->code == GOT_ERR_NOT_WORKTREE)
10585 error = wrap_not_worktree_error(error,
10586 "histedit", cwd);
10587 goto done;
10591 if (list_backups || delete_backups) {
10592 error = got_repo_open(&repo,
10593 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10594 NULL);
10595 if (error != NULL)
10596 goto done;
10597 error = apply_unveil(got_repo_get_path(repo), 0,
10598 worktree ? got_worktree_get_root_path(worktree) : NULL);
10599 if (error)
10600 goto done;
10601 error = process_backup_refs(
10602 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10603 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10604 goto done; /* nothing else to do */
10607 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10608 NULL);
10609 if (error != NULL)
10610 goto done;
10612 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10613 if (error)
10614 goto done;
10615 if (rebase_in_progress) {
10616 error = got_error(GOT_ERR_REBASING);
10617 goto done;
10620 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10621 repo);
10622 if (error)
10623 goto done;
10624 if (merge_in_progress) {
10625 error = got_error(GOT_ERR_MERGE_BUSY);
10626 goto done;
10629 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10630 if (error)
10631 goto done;
10633 if (edit_in_progress && edit_logmsg_only) {
10634 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10635 "histedit operation is in progress in this "
10636 "work tree and must be continued or aborted "
10637 "before the -m option can be used");
10638 goto done;
10640 if (edit_in_progress && fold_only) {
10641 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10642 "histedit operation is in progress in this "
10643 "work tree and must be continued or aborted "
10644 "before the -f option can be used");
10645 goto done;
10647 if (edit_in_progress && edit_only) {
10648 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10649 "histedit operation is in progress in this "
10650 "work tree and must be continued or aborted "
10651 "before the -e option can be used");
10652 goto done;
10655 if (edit_in_progress && abort_edit) {
10656 error = got_worktree_histedit_continue(&resume_commit_id,
10657 &tmp_branch, &branch, &base_commit_id, &fileindex,
10658 worktree, repo);
10659 if (error)
10660 goto done;
10661 printf("Switching work tree to %s\n",
10662 got_ref_get_symref_target(branch));
10663 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10664 branch, base_commit_id, abort_progress, &upa);
10665 if (error)
10666 goto done;
10667 printf("Histedit of %s aborted\n",
10668 got_ref_get_symref_target(branch));
10669 print_merge_progress_stats(&upa);
10670 goto done; /* nothing else to do */
10671 } else if (abort_edit) {
10672 error = got_error(GOT_ERR_NOT_HISTEDIT);
10673 goto done;
10676 if (continue_edit) {
10677 char *path;
10679 if (!edit_in_progress) {
10680 error = got_error(GOT_ERR_NOT_HISTEDIT);
10681 goto done;
10684 error = got_worktree_get_histedit_script_path(&path, worktree);
10685 if (error)
10686 goto done;
10688 error = histedit_load_list(&histedit_cmds, path, repo);
10689 free(path);
10690 if (error)
10691 goto done;
10693 error = got_worktree_histedit_continue(&resume_commit_id,
10694 &tmp_branch, &branch, &base_commit_id, &fileindex,
10695 worktree, repo);
10696 if (error)
10697 goto done;
10699 error = got_ref_resolve(&head_commit_id, repo, branch);
10700 if (error)
10701 goto done;
10703 error = got_object_open_as_commit(&commit, repo,
10704 head_commit_id);
10705 if (error)
10706 goto done;
10707 parent_ids = got_object_commit_get_parent_ids(commit);
10708 pid = STAILQ_FIRST(parent_ids);
10709 if (pid == NULL) {
10710 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10711 goto done;
10713 error = collect_commits(&commits, head_commit_id, pid->id,
10714 base_commit_id, got_worktree_get_path_prefix(worktree),
10715 GOT_ERR_HISTEDIT_PATH, repo);
10716 got_object_commit_close(commit);
10717 commit = NULL;
10718 if (error)
10719 goto done;
10720 } else {
10721 if (edit_in_progress) {
10722 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10723 goto done;
10726 error = got_ref_open(&branch, repo,
10727 got_worktree_get_head_ref_name(worktree), 0);
10728 if (error != NULL)
10729 goto done;
10731 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10732 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10733 "will not edit commit history of a branch outside "
10734 "the \"refs/heads/\" reference namespace");
10735 goto done;
10738 error = got_ref_resolve(&head_commit_id, repo, branch);
10739 got_ref_close(branch);
10740 branch = NULL;
10741 if (error)
10742 goto done;
10744 error = got_object_open_as_commit(&commit, repo,
10745 head_commit_id);
10746 if (error)
10747 goto done;
10748 parent_ids = got_object_commit_get_parent_ids(commit);
10749 pid = STAILQ_FIRST(parent_ids);
10750 if (pid == NULL) {
10751 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10752 goto done;
10754 error = collect_commits(&commits, head_commit_id, pid->id,
10755 got_worktree_get_base_commit_id(worktree),
10756 got_worktree_get_path_prefix(worktree),
10757 GOT_ERR_HISTEDIT_PATH, repo);
10758 got_object_commit_close(commit);
10759 commit = NULL;
10760 if (error)
10761 goto done;
10763 if (STAILQ_EMPTY(&commits)) {
10764 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10765 goto done;
10768 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10769 &base_commit_id, &fileindex, worktree, repo);
10770 if (error)
10771 goto done;
10773 if (edit_script_path) {
10774 error = histedit_load_list(&histedit_cmds,
10775 edit_script_path, repo);
10776 if (error) {
10777 got_worktree_histedit_abort(worktree, fileindex,
10778 repo, branch, base_commit_id,
10779 abort_progress, &upa);
10780 print_merge_progress_stats(&upa);
10781 goto done;
10783 } else {
10784 const char *branch_name;
10785 branch_name = got_ref_get_symref_target(branch);
10786 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10787 branch_name += 11;
10788 error = histedit_edit_script(&histedit_cmds, &commits,
10789 branch_name, edit_logmsg_only, fold_only,
10790 edit_only, repo);
10791 if (error) {
10792 got_worktree_histedit_abort(worktree, fileindex,
10793 repo, branch, base_commit_id,
10794 abort_progress, &upa);
10795 print_merge_progress_stats(&upa);
10796 goto done;
10801 error = histedit_save_list(&histedit_cmds, worktree,
10802 repo);
10803 if (error) {
10804 got_worktree_histedit_abort(worktree, fileindex,
10805 repo, branch, base_commit_id,
10806 abort_progress, &upa);
10807 print_merge_progress_stats(&upa);
10808 goto done;
10813 error = histedit_check_script(&histedit_cmds, &commits, repo);
10814 if (error)
10815 goto done;
10817 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10818 if (resume_commit_id) {
10819 if (got_object_id_cmp(hle->commit_id,
10820 resume_commit_id) != 0)
10821 continue;
10823 resume_commit_id = NULL;
10824 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10825 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10826 error = histedit_skip_commit(hle, worktree,
10827 repo);
10828 if (error)
10829 goto done;
10830 } else {
10831 struct got_pathlist_head paths;
10832 int have_changes = 0;
10834 TAILQ_INIT(&paths);
10835 error = got_pathlist_append(&paths, "", NULL);
10836 if (error)
10837 goto done;
10838 error = got_worktree_status(worktree, &paths,
10839 repo, 0, check_local_changes, &have_changes,
10840 check_cancelled, NULL);
10841 got_pathlist_free(&paths);
10842 if (error) {
10843 if (error->code != GOT_ERR_CANCELLED)
10844 goto done;
10845 if (sigint_received || sigpipe_received)
10846 goto done;
10848 if (have_changes) {
10849 error = histedit_commit(NULL, worktree,
10850 fileindex, tmp_branch, hle, repo);
10851 if (error)
10852 goto done;
10853 } else {
10854 error = got_object_open_as_commit(
10855 &commit, repo, hle->commit_id);
10856 if (error)
10857 goto done;
10858 error = show_histedit_progress(commit,
10859 hle, NULL);
10860 got_object_commit_close(commit);
10861 commit = NULL;
10862 if (error)
10863 goto done;
10866 continue;
10869 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10870 error = histedit_skip_commit(hle, worktree, repo);
10871 if (error)
10872 goto done;
10873 continue;
10876 error = got_object_open_as_commit(&commit, repo,
10877 hle->commit_id);
10878 if (error)
10879 goto done;
10880 parent_ids = got_object_commit_get_parent_ids(commit);
10881 pid = STAILQ_FIRST(parent_ids);
10883 error = got_worktree_histedit_merge_files(&merged_paths,
10884 worktree, fileindex, pid->id, hle->commit_id, repo,
10885 update_progress, &upa, check_cancelled, NULL);
10886 if (error)
10887 goto done;
10888 got_object_commit_close(commit);
10889 commit = NULL;
10891 print_merge_progress_stats(&upa);
10892 if (upa.conflicts > 0 || upa.missing > 0 ||
10893 upa.not_deleted > 0 || upa.unversioned > 0) {
10894 if (upa.conflicts > 0) {
10895 error = show_rebase_merge_conflict(
10896 hle->commit_id, repo);
10897 if (error)
10898 goto done;
10900 got_worktree_rebase_pathlist_free(&merged_paths);
10901 break;
10904 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10905 char *id_str;
10906 error = got_object_id_str(&id_str, hle->commit_id);
10907 if (error)
10908 goto done;
10909 printf("Stopping histedit for amending commit %s\n",
10910 id_str);
10911 free(id_str);
10912 got_worktree_rebase_pathlist_free(&merged_paths);
10913 error = got_worktree_histedit_postpone(worktree,
10914 fileindex);
10915 goto done;
10918 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
10919 error = histedit_skip_commit(hle, worktree, repo);
10920 if (error)
10921 goto done;
10922 continue;
10925 error = histedit_commit(&merged_paths, worktree, fileindex,
10926 tmp_branch, hle, repo);
10927 got_worktree_rebase_pathlist_free(&merged_paths);
10928 if (error)
10929 goto done;
10932 if (upa.conflicts > 0 || upa.missing > 0 ||
10933 upa.not_deleted > 0 || upa.unversioned > 0) {
10934 error = got_worktree_histedit_postpone(worktree, fileindex);
10935 if (error)
10936 goto done;
10937 if (upa.conflicts > 0 && upa.missing == 0 &&
10938 upa.not_deleted == 0 && upa.unversioned == 0) {
10939 error = got_error_msg(GOT_ERR_CONFLICTS,
10940 "conflicts must be resolved before histedit "
10941 "can continue");
10942 } else if (upa.conflicts > 0) {
10943 error = got_error_msg(GOT_ERR_CONFLICTS,
10944 "conflicts must be resolved before histedit "
10945 "can continue; changes destined for some "
10946 "files were not yet merged and should be "
10947 "merged manually if required before the "
10948 "histedit operation is continued");
10949 } else {
10950 error = got_error_msg(GOT_ERR_CONFLICTS,
10951 "changes destined for some files were not "
10952 "yet merged and should be merged manually "
10953 "if required before the histedit operation "
10954 "is continued");
10956 } else
10957 error = histedit_complete(worktree, fileindex, tmp_branch,
10958 branch, repo);
10959 done:
10960 got_object_id_queue_free(&commits);
10961 histedit_free_list(&histedit_cmds);
10962 free(head_commit_id);
10963 free(base_commit_id);
10964 free(resume_commit_id);
10965 if (commit)
10966 got_object_commit_close(commit);
10967 if (branch)
10968 got_ref_close(branch);
10969 if (tmp_branch)
10970 got_ref_close(tmp_branch);
10971 if (worktree)
10972 got_worktree_close(worktree);
10973 if (repo) {
10974 const struct got_error *close_err = got_repo_close(repo);
10975 if (error == NULL)
10976 error = close_err;
10978 return error;
10981 __dead static void
10982 usage_integrate(void)
10984 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
10985 exit(1);
10988 static const struct got_error *
10989 cmd_integrate(int argc, char *argv[])
10991 const struct got_error *error = NULL;
10992 struct got_repository *repo = NULL;
10993 struct got_worktree *worktree = NULL;
10994 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
10995 const char *branch_arg = NULL;
10996 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
10997 struct got_fileindex *fileindex = NULL;
10998 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
10999 int ch;
11000 struct got_update_progress_arg upa;
11002 while ((ch = getopt(argc, argv, "")) != -1) {
11003 switch (ch) {
11004 default:
11005 usage_integrate();
11006 /* NOTREACHED */
11010 argc -= optind;
11011 argv += optind;
11013 if (argc != 1)
11014 usage_integrate();
11015 branch_arg = argv[0];
11016 #ifndef PROFILE
11017 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11018 "unveil", NULL) == -1)
11019 err(1, "pledge");
11020 #endif
11021 cwd = getcwd(NULL, 0);
11022 if (cwd == NULL) {
11023 error = got_error_from_errno("getcwd");
11024 goto done;
11027 error = got_worktree_open(&worktree, cwd);
11028 if (error) {
11029 if (error->code == GOT_ERR_NOT_WORKTREE)
11030 error = wrap_not_worktree_error(error, "integrate",
11031 cwd);
11032 goto done;
11035 error = check_rebase_or_histedit_in_progress(worktree);
11036 if (error)
11037 goto done;
11039 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11040 NULL);
11041 if (error != NULL)
11042 goto done;
11044 error = apply_unveil(got_repo_get_path(repo), 0,
11045 got_worktree_get_root_path(worktree));
11046 if (error)
11047 goto done;
11049 error = check_merge_in_progress(worktree, repo);
11050 if (error)
11051 goto done;
11053 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11054 error = got_error_from_errno("asprintf");
11055 goto done;
11058 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11059 &base_branch_ref, worktree, refname, repo);
11060 if (error)
11061 goto done;
11063 refname = strdup(got_ref_get_name(branch_ref));
11064 if (refname == NULL) {
11065 error = got_error_from_errno("strdup");
11066 got_worktree_integrate_abort(worktree, fileindex, repo,
11067 branch_ref, base_branch_ref);
11068 goto done;
11070 base_refname = strdup(got_ref_get_name(base_branch_ref));
11071 if (base_refname == NULL) {
11072 error = got_error_from_errno("strdup");
11073 got_worktree_integrate_abort(worktree, fileindex, repo,
11074 branch_ref, base_branch_ref);
11075 goto done;
11078 error = got_ref_resolve(&commit_id, repo, branch_ref);
11079 if (error)
11080 goto done;
11082 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11083 if (error)
11084 goto done;
11086 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11087 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11088 "specified branch has already been integrated");
11089 got_worktree_integrate_abort(worktree, fileindex, repo,
11090 branch_ref, base_branch_ref);
11091 goto done;
11094 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11095 if (error) {
11096 if (error->code == GOT_ERR_ANCESTRY)
11097 error = got_error(GOT_ERR_REBASE_REQUIRED);
11098 got_worktree_integrate_abort(worktree, fileindex, repo,
11099 branch_ref, base_branch_ref);
11100 goto done;
11103 memset(&upa, 0, sizeof(upa));
11104 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11105 branch_ref, base_branch_ref, update_progress, &upa,
11106 check_cancelled, NULL);
11107 if (error)
11108 goto done;
11110 printf("Integrated %s into %s\n", refname, base_refname);
11111 print_update_progress_stats(&upa);
11112 done:
11113 if (repo) {
11114 const struct got_error *close_err = got_repo_close(repo);
11115 if (error == NULL)
11116 error = close_err;
11118 if (worktree)
11119 got_worktree_close(worktree);
11120 free(cwd);
11121 free(base_commit_id);
11122 free(commit_id);
11123 free(refname);
11124 free(base_refname);
11125 return error;
11128 __dead static void
11129 usage_merge(void)
11131 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11132 getprogname());
11133 exit(1);
11136 static const struct got_error *
11137 cmd_merge(int argc, char *argv[])
11139 const struct got_error *error = NULL;
11140 struct got_worktree *worktree = NULL;
11141 struct got_repository *repo = NULL;
11142 struct got_fileindex *fileindex = NULL;
11143 char *cwd = NULL, *id_str = NULL, *author = NULL;
11144 struct got_reference *branch = NULL, *wt_branch = NULL;
11145 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11146 struct got_object_id *wt_branch_tip = NULL;
11147 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11148 int interrupt_merge = 0;
11149 struct got_update_progress_arg upa;
11150 struct got_object_id *merge_commit_id = NULL;
11151 char *branch_name = NULL;
11153 memset(&upa, 0, sizeof(upa));
11155 while ((ch = getopt(argc, argv, "acn")) != -1) {
11156 switch (ch) {
11157 case 'a':
11158 abort_merge = 1;
11159 break;
11160 case 'c':
11161 continue_merge = 1;
11162 break;
11163 case 'n':
11164 interrupt_merge = 1;
11165 break;
11166 default:
11167 usage_rebase();
11168 /* NOTREACHED */
11172 argc -= optind;
11173 argv += optind;
11175 #ifndef PROFILE
11176 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11177 "unveil", NULL) == -1)
11178 err(1, "pledge");
11179 #endif
11181 if (abort_merge && continue_merge)
11182 option_conflict('a', 'c');
11183 if (abort_merge || continue_merge) {
11184 if (argc != 0)
11185 usage_merge();
11186 } else if (argc != 1)
11187 usage_merge();
11189 cwd = getcwd(NULL, 0);
11190 if (cwd == NULL) {
11191 error = got_error_from_errno("getcwd");
11192 goto done;
11195 error = got_worktree_open(&worktree, cwd);
11196 if (error) {
11197 if (error->code == GOT_ERR_NOT_WORKTREE)
11198 error = wrap_not_worktree_error(error,
11199 "merge", cwd);
11200 goto done;
11203 error = got_repo_open(&repo,
11204 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11205 if (error != NULL)
11206 goto done;
11208 error = apply_unveil(got_repo_get_path(repo), 0,
11209 worktree ? got_worktree_get_root_path(worktree) : NULL);
11210 if (error)
11211 goto done;
11213 error = check_rebase_or_histedit_in_progress(worktree);
11214 if (error)
11215 goto done;
11217 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11218 repo);
11219 if (error)
11220 goto done;
11222 if (abort_merge) {
11223 if (!merge_in_progress) {
11224 error = got_error(GOT_ERR_NOT_MERGING);
11225 goto done;
11227 error = got_worktree_merge_continue(&branch_name,
11228 &branch_tip, &fileindex, worktree, repo);
11229 if (error)
11230 goto done;
11231 error = got_worktree_merge_abort(worktree, fileindex, repo,
11232 abort_progress, &upa);
11233 if (error)
11234 goto done;
11235 printf("Merge of %s aborted\n", branch_name);
11236 goto done; /* nothing else to do */
11239 error = get_author(&author, repo, worktree);
11240 if (error)
11241 goto done;
11243 if (continue_merge) {
11244 if (!merge_in_progress) {
11245 error = got_error(GOT_ERR_NOT_MERGING);
11246 goto done;
11248 error = got_worktree_merge_continue(&branch_name,
11249 &branch_tip, &fileindex, worktree, repo);
11250 if (error)
11251 goto done;
11252 } else {
11253 error = got_ref_open(&branch, repo, argv[0], 0);
11254 if (error != NULL)
11255 goto done;
11256 branch_name = strdup(got_ref_get_name(branch));
11257 if (branch_name == NULL) {
11258 error = got_error_from_errno("strdup");
11259 goto done;
11261 error = got_ref_resolve(&branch_tip, repo, branch);
11262 if (error)
11263 goto done;
11266 error = got_ref_open(&wt_branch, repo,
11267 got_worktree_get_head_ref_name(worktree), 0);
11268 if (error)
11269 goto done;
11270 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11271 if (error)
11272 goto done;
11273 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11274 wt_branch_tip, branch_tip, 0, repo,
11275 check_cancelled, NULL);
11276 if (error && error->code != GOT_ERR_ANCESTRY)
11277 goto done;
11279 if (!continue_merge) {
11280 error = check_path_prefix(wt_branch_tip, branch_tip,
11281 got_worktree_get_path_prefix(worktree),
11282 GOT_ERR_MERGE_PATH, repo);
11283 if (error)
11284 goto done;
11285 if (yca_id) {
11286 error = check_same_branch(wt_branch_tip, branch,
11287 yca_id, repo);
11288 if (error) {
11289 if (error->code != GOT_ERR_ANCESTRY)
11290 goto done;
11291 error = NULL;
11292 } else {
11293 static char msg[512];
11294 snprintf(msg, sizeof(msg),
11295 "cannot create a merge commit because "
11296 "%s is based on %s; %s can be integrated "
11297 "with 'got integrate' instead", branch_name,
11298 got_worktree_get_head_ref_name(worktree),
11299 branch_name);
11300 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11301 goto done;
11304 error = got_worktree_merge_prepare(&fileindex, worktree,
11305 branch, repo);
11306 if (error)
11307 goto done;
11309 error = got_worktree_merge_branch(worktree, fileindex,
11310 yca_id, branch_tip, repo, update_progress, &upa,
11311 check_cancelled, NULL);
11312 if (error)
11313 goto done;
11314 print_merge_progress_stats(&upa);
11315 if (!upa.did_something) {
11316 error = got_worktree_merge_abort(worktree, fileindex,
11317 repo, abort_progress, &upa);
11318 if (error)
11319 goto done;
11320 printf("Already up-to-date\n");
11321 goto done;
11325 if (interrupt_merge) {
11326 error = got_worktree_merge_postpone(worktree, fileindex);
11327 if (error)
11328 goto done;
11329 printf("Merge of %s interrupted on request\n", branch_name);
11330 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11331 upa.not_deleted > 0 || upa.unversioned > 0) {
11332 error = got_worktree_merge_postpone(worktree, fileindex);
11333 if (error)
11334 goto done;
11335 if (upa.conflicts > 0 && upa.missing == 0 &&
11336 upa.not_deleted == 0 && upa.unversioned == 0) {
11337 error = got_error_msg(GOT_ERR_CONFLICTS,
11338 "conflicts must be resolved before merging "
11339 "can continue");
11340 } else if (upa.conflicts > 0) {
11341 error = got_error_msg(GOT_ERR_CONFLICTS,
11342 "conflicts must be resolved before merging "
11343 "can continue; changes destined for some "
11344 "files were not yet merged and "
11345 "should be merged manually if required before the "
11346 "merge operation is continued");
11347 } else {
11348 error = got_error_msg(GOT_ERR_CONFLICTS,
11349 "changes destined for some "
11350 "files were not yet merged and should be "
11351 "merged manually if required before the "
11352 "merge operation is continued");
11354 goto done;
11355 } else {
11356 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11357 fileindex, author, NULL, 1, branch_tip, branch_name,
11358 repo, continue_merge ? print_status : NULL, NULL);
11359 if (error)
11360 goto done;
11361 error = got_worktree_merge_complete(worktree, fileindex, repo);
11362 if (error)
11363 goto done;
11364 error = got_object_id_str(&id_str, merge_commit_id);
11365 if (error)
11366 goto done;
11367 printf("Merged %s into %s: %s\n", branch_name,
11368 got_worktree_get_head_ref_name(worktree),
11369 id_str);
11372 done:
11373 free(id_str);
11374 free(merge_commit_id);
11375 free(author);
11376 free(branch_tip);
11377 free(branch_name);
11378 free(yca_id);
11379 if (branch)
11380 got_ref_close(branch);
11381 if (wt_branch)
11382 got_ref_close(wt_branch);
11383 if (worktree)
11384 got_worktree_close(worktree);
11385 if (repo) {
11386 const struct got_error *close_err = got_repo_close(repo);
11387 if (error == NULL)
11388 error = close_err;
11390 return error;
11393 __dead static void
11394 usage_stage(void)
11396 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11397 "[-S] [file-path ...]\n",
11398 getprogname());
11399 exit(1);
11402 static const struct got_error *
11403 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11404 const char *path, struct got_object_id *blob_id,
11405 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11406 int dirfd, const char *de_name)
11408 const struct got_error *err = NULL;
11409 char *id_str = NULL;
11411 if (staged_status != GOT_STATUS_ADD &&
11412 staged_status != GOT_STATUS_MODIFY &&
11413 staged_status != GOT_STATUS_DELETE)
11414 return NULL;
11416 if (staged_status == GOT_STATUS_ADD ||
11417 staged_status == GOT_STATUS_MODIFY)
11418 err = got_object_id_str(&id_str, staged_blob_id);
11419 else
11420 err = got_object_id_str(&id_str, blob_id);
11421 if (err)
11422 return err;
11424 printf("%s %c %s\n", id_str, staged_status, path);
11425 free(id_str);
11426 return NULL;
11429 static const struct got_error *
11430 cmd_stage(int argc, char *argv[])
11432 const struct got_error *error = NULL;
11433 struct got_repository *repo = NULL;
11434 struct got_worktree *worktree = NULL;
11435 char *cwd = NULL;
11436 struct got_pathlist_head paths;
11437 struct got_pathlist_entry *pe;
11438 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11439 FILE *patch_script_file = NULL;
11440 const char *patch_script_path = NULL;
11441 struct choose_patch_arg cpa;
11443 TAILQ_INIT(&paths);
11445 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11446 switch (ch) {
11447 case 'l':
11448 list_stage = 1;
11449 break;
11450 case 'p':
11451 pflag = 1;
11452 break;
11453 case 'F':
11454 patch_script_path = optarg;
11455 break;
11456 case 'S':
11457 allow_bad_symlinks = 1;
11458 break;
11459 default:
11460 usage_stage();
11461 /* NOTREACHED */
11465 argc -= optind;
11466 argv += optind;
11468 #ifndef PROFILE
11469 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11470 "unveil", NULL) == -1)
11471 err(1, "pledge");
11472 #endif
11473 if (list_stage && (pflag || patch_script_path))
11474 errx(1, "-l option cannot be used with other options");
11475 if (patch_script_path && !pflag)
11476 errx(1, "-F option can only be used together with -p option");
11478 cwd = getcwd(NULL, 0);
11479 if (cwd == NULL) {
11480 error = got_error_from_errno("getcwd");
11481 goto done;
11484 error = got_worktree_open(&worktree, cwd);
11485 if (error) {
11486 if (error->code == GOT_ERR_NOT_WORKTREE)
11487 error = wrap_not_worktree_error(error, "stage", cwd);
11488 goto done;
11491 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11492 NULL);
11493 if (error != NULL)
11494 goto done;
11496 if (patch_script_path) {
11497 patch_script_file = fopen(patch_script_path, "re");
11498 if (patch_script_file == NULL) {
11499 error = got_error_from_errno2("fopen",
11500 patch_script_path);
11501 goto done;
11504 error = apply_unveil(got_repo_get_path(repo), 0,
11505 got_worktree_get_root_path(worktree));
11506 if (error)
11507 goto done;
11509 error = check_merge_in_progress(worktree, repo);
11510 if (error)
11511 goto done;
11513 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11514 if (error)
11515 goto done;
11517 if (list_stage)
11518 error = got_worktree_status(worktree, &paths, repo, 0,
11519 print_stage, NULL, check_cancelled, NULL);
11520 else {
11521 cpa.patch_script_file = patch_script_file;
11522 cpa.action = "stage";
11523 error = got_worktree_stage(worktree, &paths,
11524 pflag ? NULL : print_status, NULL,
11525 pflag ? choose_patch : NULL, &cpa,
11526 allow_bad_symlinks, repo);
11528 done:
11529 if (patch_script_file && fclose(patch_script_file) == EOF &&
11530 error == NULL)
11531 error = got_error_from_errno2("fclose", patch_script_path);
11532 if (repo) {
11533 const struct got_error *close_err = got_repo_close(repo);
11534 if (error == NULL)
11535 error = close_err;
11537 if (worktree)
11538 got_worktree_close(worktree);
11539 TAILQ_FOREACH(pe, &paths, entry)
11540 free((char *)pe->path);
11541 got_pathlist_free(&paths);
11542 free(cwd);
11543 return error;
11546 __dead static void
11547 usage_unstage(void)
11549 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11550 "[file-path ...]\n",
11551 getprogname());
11552 exit(1);
11556 static const struct got_error *
11557 cmd_unstage(int argc, char *argv[])
11559 const struct got_error *error = NULL;
11560 struct got_repository *repo = NULL;
11561 struct got_worktree *worktree = NULL;
11562 char *cwd = NULL;
11563 struct got_pathlist_head paths;
11564 struct got_pathlist_entry *pe;
11565 int ch, pflag = 0;
11566 struct got_update_progress_arg upa;
11567 FILE *patch_script_file = NULL;
11568 const char *patch_script_path = NULL;
11569 struct choose_patch_arg cpa;
11571 TAILQ_INIT(&paths);
11573 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11574 switch (ch) {
11575 case 'p':
11576 pflag = 1;
11577 break;
11578 case 'F':
11579 patch_script_path = optarg;
11580 break;
11581 default:
11582 usage_unstage();
11583 /* NOTREACHED */
11587 argc -= optind;
11588 argv += optind;
11590 #ifndef PROFILE
11591 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11592 "unveil", NULL) == -1)
11593 err(1, "pledge");
11594 #endif
11595 if (patch_script_path && !pflag)
11596 errx(1, "-F option can only be used together with -p option");
11598 cwd = getcwd(NULL, 0);
11599 if (cwd == NULL) {
11600 error = got_error_from_errno("getcwd");
11601 goto done;
11604 error = got_worktree_open(&worktree, cwd);
11605 if (error) {
11606 if (error->code == GOT_ERR_NOT_WORKTREE)
11607 error = wrap_not_worktree_error(error, "unstage", cwd);
11608 goto done;
11611 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11612 NULL);
11613 if (error != NULL)
11614 goto done;
11616 if (patch_script_path) {
11617 patch_script_file = fopen(patch_script_path, "re");
11618 if (patch_script_file == NULL) {
11619 error = got_error_from_errno2("fopen",
11620 patch_script_path);
11621 goto done;
11625 error = apply_unveil(got_repo_get_path(repo), 0,
11626 got_worktree_get_root_path(worktree));
11627 if (error)
11628 goto done;
11630 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11631 if (error)
11632 goto done;
11634 cpa.patch_script_file = patch_script_file;
11635 cpa.action = "unstage";
11636 memset(&upa, 0, sizeof(upa));
11637 error = got_worktree_unstage(worktree, &paths, update_progress,
11638 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11639 if (!error)
11640 print_merge_progress_stats(&upa);
11641 done:
11642 if (patch_script_file && fclose(patch_script_file) == EOF &&
11643 error == NULL)
11644 error = got_error_from_errno2("fclose", patch_script_path);
11645 if (repo) {
11646 const struct got_error *close_err = got_repo_close(repo);
11647 if (error == NULL)
11648 error = close_err;
11650 if (worktree)
11651 got_worktree_close(worktree);
11652 TAILQ_FOREACH(pe, &paths, entry)
11653 free((char *)pe->path);
11654 got_pathlist_free(&paths);
11655 free(cwd);
11656 return error;
11659 __dead static void
11660 usage_cat(void)
11662 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11663 "arg1 [arg2 ...]\n", getprogname());
11664 exit(1);
11667 static const struct got_error *
11668 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11670 const struct got_error *err;
11671 struct got_blob_object *blob;
11673 err = got_object_open_as_blob(&blob, repo, id, 8192);
11674 if (err)
11675 return err;
11677 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11678 got_object_blob_close(blob);
11679 return err;
11682 static const struct got_error *
11683 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11685 const struct got_error *err;
11686 struct got_tree_object *tree;
11687 int nentries, i;
11689 err = got_object_open_as_tree(&tree, repo, id);
11690 if (err)
11691 return err;
11693 nentries = got_object_tree_get_nentries(tree);
11694 for (i = 0; i < nentries; i++) {
11695 struct got_tree_entry *te;
11696 char *id_str;
11697 if (sigint_received || sigpipe_received)
11698 break;
11699 te = got_object_tree_get_entry(tree, i);
11700 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11701 if (err)
11702 break;
11703 fprintf(outfile, "%s %.7o %s\n", id_str,
11704 got_tree_entry_get_mode(te),
11705 got_tree_entry_get_name(te));
11706 free(id_str);
11709 got_object_tree_close(tree);
11710 return err;
11713 static void
11714 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11716 long long h, m;
11717 char sign = '+';
11719 if (gmtoff < 0) {
11720 sign = '-';
11721 gmtoff = -gmtoff;
11724 h = (long long)gmtoff / 3600;
11725 m = ((long long)gmtoff - h*3600) / 60;
11726 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11729 static const struct got_error *
11730 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11732 const struct got_error *err;
11733 struct got_commit_object *commit;
11734 const struct got_object_id_queue *parent_ids;
11735 struct got_object_qid *pid;
11736 char *id_str = NULL;
11737 const char *logmsg = NULL;
11738 char gmtoff[6];
11740 err = got_object_open_as_commit(&commit, repo, id);
11741 if (err)
11742 return err;
11744 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11745 if (err)
11746 goto done;
11748 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11749 parent_ids = got_object_commit_get_parent_ids(commit);
11750 fprintf(outfile, "numparents %d\n",
11751 got_object_commit_get_nparents(commit));
11752 STAILQ_FOREACH(pid, parent_ids, entry) {
11753 char *pid_str;
11754 err = got_object_id_str(&pid_str, pid->id);
11755 if (err)
11756 goto done;
11757 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11758 free(pid_str);
11760 format_gmtoff(gmtoff, sizeof(gmtoff),
11761 got_object_commit_get_author_gmtoff(commit));
11762 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11763 got_object_commit_get_author(commit),
11764 (long long)got_object_commit_get_author_time(commit),
11765 gmtoff);
11767 format_gmtoff(gmtoff, sizeof(gmtoff),
11768 got_object_commit_get_committer_gmtoff(commit));
11769 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11770 got_object_commit_get_author(commit),
11771 (long long)got_object_commit_get_committer_time(commit),
11772 gmtoff);
11774 logmsg = got_object_commit_get_logmsg_raw(commit);
11775 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11776 fprintf(outfile, "%s", logmsg);
11777 done:
11778 free(id_str);
11779 got_object_commit_close(commit);
11780 return err;
11783 static const struct got_error *
11784 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11786 const struct got_error *err;
11787 struct got_tag_object *tag;
11788 char *id_str = NULL;
11789 const char *tagmsg = NULL;
11790 char gmtoff[6];
11792 err = got_object_open_as_tag(&tag, repo, id);
11793 if (err)
11794 return err;
11796 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11797 if (err)
11798 goto done;
11800 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11802 switch (got_object_tag_get_object_type(tag)) {
11803 case GOT_OBJ_TYPE_BLOB:
11804 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11805 GOT_OBJ_LABEL_BLOB);
11806 break;
11807 case GOT_OBJ_TYPE_TREE:
11808 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11809 GOT_OBJ_LABEL_TREE);
11810 break;
11811 case GOT_OBJ_TYPE_COMMIT:
11812 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11813 GOT_OBJ_LABEL_COMMIT);
11814 break;
11815 case GOT_OBJ_TYPE_TAG:
11816 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11817 GOT_OBJ_LABEL_TAG);
11818 break;
11819 default:
11820 break;
11823 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11824 got_object_tag_get_name(tag));
11826 format_gmtoff(gmtoff, sizeof(gmtoff),
11827 got_object_tag_get_tagger_gmtoff(tag));
11828 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11829 got_object_tag_get_tagger(tag),
11830 (long long)got_object_tag_get_tagger_time(tag),
11831 gmtoff);
11833 tagmsg = got_object_tag_get_message(tag);
11834 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11835 fprintf(outfile, "%s", tagmsg);
11836 done:
11837 free(id_str);
11838 got_object_tag_close(tag);
11839 return err;
11842 static const struct got_error *
11843 cmd_cat(int argc, char *argv[])
11845 const struct got_error *error;
11846 struct got_repository *repo = NULL;
11847 struct got_worktree *worktree = NULL;
11848 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11849 const char *commit_id_str = NULL;
11850 struct got_object_id *id = NULL, *commit_id = NULL;
11851 struct got_commit_object *commit = NULL;
11852 int ch, obj_type, i, force_path = 0;
11853 struct got_reflist_head refs;
11855 TAILQ_INIT(&refs);
11857 #ifndef PROFILE
11858 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11859 NULL) == -1)
11860 err(1, "pledge");
11861 #endif
11863 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11864 switch (ch) {
11865 case 'c':
11866 commit_id_str = optarg;
11867 break;
11868 case 'r':
11869 repo_path = realpath(optarg, NULL);
11870 if (repo_path == NULL)
11871 return got_error_from_errno2("realpath",
11872 optarg);
11873 got_path_strip_trailing_slashes(repo_path);
11874 break;
11875 case 'P':
11876 force_path = 1;
11877 break;
11878 default:
11879 usage_cat();
11880 /* NOTREACHED */
11884 argc -= optind;
11885 argv += optind;
11887 cwd = getcwd(NULL, 0);
11888 if (cwd == NULL) {
11889 error = got_error_from_errno("getcwd");
11890 goto done;
11893 if (repo_path == NULL) {
11894 error = got_worktree_open(&worktree, cwd);
11895 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11896 goto done;
11897 if (worktree) {
11898 repo_path = strdup(
11899 got_worktree_get_repo_path(worktree));
11900 if (repo_path == NULL) {
11901 error = got_error_from_errno("strdup");
11902 goto done;
11905 /* Release work tree lock. */
11906 got_worktree_close(worktree);
11907 worktree = NULL;
11911 if (repo_path == NULL) {
11912 repo_path = strdup(cwd);
11913 if (repo_path == NULL)
11914 return got_error_from_errno("strdup");
11917 error = got_repo_open(&repo, repo_path, NULL);
11918 free(repo_path);
11919 if (error != NULL)
11920 goto done;
11922 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
11923 if (error)
11924 goto done;
11926 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11927 if (error)
11928 goto done;
11930 if (commit_id_str == NULL)
11931 commit_id_str = GOT_REF_HEAD;
11932 error = got_repo_match_object_id(&commit_id, NULL,
11933 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
11934 if (error)
11935 goto done;
11937 error = got_object_open_as_commit(&commit, repo, commit_id);
11938 if (error)
11939 goto done;
11941 for (i = 0; i < argc; i++) {
11942 if (force_path) {
11943 error = got_object_id_by_path(&id, repo, commit,
11944 argv[i]);
11945 if (error)
11946 break;
11947 } else {
11948 error = got_repo_match_object_id(&id, &label, argv[i],
11949 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
11950 repo);
11951 if (error) {
11952 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
11953 error->code != GOT_ERR_NOT_REF)
11954 break;
11955 error = got_object_id_by_path(&id, repo,
11956 commit, argv[i]);
11957 if (error)
11958 break;
11962 error = got_object_get_type(&obj_type, repo, id);
11963 if (error)
11964 break;
11966 switch (obj_type) {
11967 case GOT_OBJ_TYPE_BLOB:
11968 error = cat_blob(id, repo, stdout);
11969 break;
11970 case GOT_OBJ_TYPE_TREE:
11971 error = cat_tree(id, repo, stdout);
11972 break;
11973 case GOT_OBJ_TYPE_COMMIT:
11974 error = cat_commit(id, repo, stdout);
11975 break;
11976 case GOT_OBJ_TYPE_TAG:
11977 error = cat_tag(id, repo, stdout);
11978 break;
11979 default:
11980 error = got_error(GOT_ERR_OBJ_TYPE);
11981 break;
11983 if (error)
11984 break;
11985 free(label);
11986 label = NULL;
11987 free(id);
11988 id = NULL;
11990 done:
11991 free(label);
11992 free(id);
11993 free(commit_id);
11994 if (commit)
11995 got_object_commit_close(commit);
11996 if (worktree)
11997 got_worktree_close(worktree);
11998 if (repo) {
11999 const struct got_error *close_err = got_repo_close(repo);
12000 if (error == NULL)
12001 error = close_err;
12003 got_ref_list_free(&refs);
12004 return error;
12007 __dead static void
12008 usage_info(void)
12010 fprintf(stderr, "usage: %s info [path ...]\n",
12011 getprogname());
12012 exit(1);
12015 static const struct got_error *
12016 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12017 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12018 struct got_object_id *commit_id)
12020 const struct got_error *err = NULL;
12021 char *id_str = NULL;
12022 char datebuf[128];
12023 struct tm mytm, *tm;
12024 struct got_pathlist_head *paths = arg;
12025 struct got_pathlist_entry *pe;
12028 * Clear error indication from any of the path arguments which
12029 * would cause this file index entry to be displayed.
12031 TAILQ_FOREACH(pe, paths, entry) {
12032 if (got_path_cmp(path, pe->path, strlen(path),
12033 pe->path_len) == 0 ||
12034 got_path_is_child(path, pe->path, pe->path_len))
12035 pe->data = NULL; /* no error */
12038 printf(GOT_COMMIT_SEP_STR);
12039 if (S_ISLNK(mode))
12040 printf("symlink: %s\n", path);
12041 else if (S_ISREG(mode)) {
12042 printf("file: %s\n", path);
12043 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12044 } else if (S_ISDIR(mode))
12045 printf("directory: %s\n", path);
12046 else
12047 printf("something: %s\n", path);
12049 tm = localtime_r(&mtime, &mytm);
12050 if (tm == NULL)
12051 return NULL;
12052 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12053 return got_error(GOT_ERR_NO_SPACE);
12054 printf("timestamp: %s\n", datebuf);
12056 if (blob_id) {
12057 err = got_object_id_str(&id_str, blob_id);
12058 if (err)
12059 return err;
12060 printf("based on blob: %s\n", id_str);
12061 free(id_str);
12064 if (staged_blob_id) {
12065 err = got_object_id_str(&id_str, staged_blob_id);
12066 if (err)
12067 return err;
12068 printf("based on staged blob: %s\n", id_str);
12069 free(id_str);
12072 if (commit_id) {
12073 err = got_object_id_str(&id_str, commit_id);
12074 if (err)
12075 return err;
12076 printf("based on commit: %s\n", id_str);
12077 free(id_str);
12080 return NULL;
12083 static const struct got_error *
12084 cmd_info(int argc, char *argv[])
12086 const struct got_error *error = NULL;
12087 struct got_worktree *worktree = NULL;
12088 char *cwd = NULL, *id_str = NULL;
12089 struct got_pathlist_head paths;
12090 struct got_pathlist_entry *pe;
12091 char *uuidstr = NULL;
12092 int ch, show_files = 0;
12094 TAILQ_INIT(&paths);
12096 while ((ch = getopt(argc, argv, "")) != -1) {
12097 switch (ch) {
12098 default:
12099 usage_info();
12100 /* NOTREACHED */
12104 argc -= optind;
12105 argv += optind;
12107 #ifndef PROFILE
12108 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12109 NULL) == -1)
12110 err(1, "pledge");
12111 #endif
12112 cwd = getcwd(NULL, 0);
12113 if (cwd == NULL) {
12114 error = got_error_from_errno("getcwd");
12115 goto done;
12118 error = got_worktree_open(&worktree, cwd);
12119 if (error) {
12120 if (error->code == GOT_ERR_NOT_WORKTREE)
12121 error = wrap_not_worktree_error(error, "info", cwd);
12122 goto done;
12125 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12126 if (error)
12127 goto done;
12129 if (argc >= 1) {
12130 error = get_worktree_paths_from_argv(&paths, argc, argv,
12131 worktree);
12132 if (error)
12133 goto done;
12134 show_files = 1;
12137 error = got_object_id_str(&id_str,
12138 got_worktree_get_base_commit_id(worktree));
12139 if (error)
12140 goto done;
12142 error = got_worktree_get_uuid(&uuidstr, worktree);
12143 if (error)
12144 goto done;
12146 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12147 printf("work tree base commit: %s\n", id_str);
12148 printf("work tree path prefix: %s\n",
12149 got_worktree_get_path_prefix(worktree));
12150 printf("work tree branch reference: %s\n",
12151 got_worktree_get_head_ref_name(worktree));
12152 printf("work tree UUID: %s\n", uuidstr);
12153 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12155 if (show_files) {
12156 struct got_pathlist_entry *pe;
12157 TAILQ_FOREACH(pe, &paths, entry) {
12158 if (pe->path_len == 0)
12159 continue;
12161 * Assume this path will fail. This will be corrected
12162 * in print_path_info() in case the path does suceeed.
12164 pe->data = (void *)got_error_path(pe->path,
12165 GOT_ERR_BAD_PATH);
12167 error = got_worktree_path_info(worktree, &paths,
12168 print_path_info, &paths, check_cancelled, NULL);
12169 if (error)
12170 goto done;
12171 TAILQ_FOREACH(pe, &paths, entry) {
12172 if (pe->data != NULL) {
12173 error = pe->data; /* bad path */
12174 break;
12178 done:
12179 TAILQ_FOREACH(pe, &paths, entry)
12180 free((char *)pe->path);
12181 got_pathlist_free(&paths);
12182 free(cwd);
12183 free(id_str);
12184 free(uuidstr);
12185 return error;