Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 static 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;
717 int *pack_fds = NULL;
719 TAILQ_INIT(&ignores);
721 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
722 switch (ch) {
723 case 'b':
724 branch_name = optarg;
725 break;
726 case 'm':
727 logmsg = strdup(optarg);
728 if (logmsg == NULL) {
729 error = got_error_from_errno("strdup");
730 goto done;
732 break;
733 case 'r':
734 repo_path = realpath(optarg, NULL);
735 if (repo_path == NULL) {
736 error = got_error_from_errno2("realpath",
737 optarg);
738 goto done;
740 break;
741 case 'I':
742 if (optarg[0] == '\0')
743 break;
744 error = got_pathlist_insert(&pe, &ignores, optarg,
745 NULL);
746 if (error)
747 goto done;
748 break;
749 default:
750 usage_import();
751 /* NOTREACHED */
755 argc -= optind;
756 argv += optind;
758 #ifndef PROFILE
759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
760 "unveil",
761 NULL) == -1)
762 err(1, "pledge");
763 #endif
764 if (argc != 1)
765 usage_import();
767 if (repo_path == NULL) {
768 repo_path = getcwd(NULL, 0);
769 if (repo_path == NULL)
770 return got_error_from_errno("getcwd");
772 got_path_strip_trailing_slashes(repo_path);
773 error = get_gitconfig_path(&gitconfig_path);
774 if (error)
775 goto done;
776 error = got_repo_pack_fds_open(&pack_fds);
777 if (error != NULL)
778 goto done;
779 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
780 if (error)
781 goto done;
783 error = get_author(&author, repo, NULL);
784 if (error)
785 return error;
787 /*
788 * Don't let the user create a branch name with a leading '-'.
789 * While technically a valid reference name, this case is usually
790 * an unintended typo.
791 */
792 if (branch_name[0] == '-')
793 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
795 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
796 error = got_error_from_errno("asprintf");
797 goto done;
800 error = got_ref_open(&branch_ref, repo, refname, 0);
801 if (error) {
802 if (error->code != GOT_ERR_NOT_REF)
803 goto done;
804 } else {
805 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
806 "import target branch already exists");
807 goto done;
810 path_dir = realpath(argv[0], NULL);
811 if (path_dir == NULL) {
812 error = got_error_from_errno2("realpath", argv[0]);
813 goto done;
815 got_path_strip_trailing_slashes(path_dir);
817 /*
818 * unveil(2) traverses exec(2); if an editor is used we have
819 * to apply unveil after the log message has been written.
820 */
821 if (logmsg == NULL || strlen(logmsg) == 0) {
822 error = get_editor(&editor);
823 if (error)
824 goto done;
825 free(logmsg);
826 error = collect_import_msg(&logmsg, &logmsg_path, editor,
827 path_dir, refname);
828 if (error) {
829 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
830 logmsg_path != NULL)
831 preserve_logmsg = 1;
832 goto done;
836 if (unveil(path_dir, "r") != 0) {
837 error = got_error_from_errno2("unveil", path_dir);
838 if (logmsg_path)
839 preserve_logmsg = 1;
840 goto done;
843 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
844 if (error) {
845 if (logmsg_path)
846 preserve_logmsg = 1;
847 goto done;
850 error = got_repo_import(&new_commit_id, path_dir, logmsg,
851 author, &ignores, repo, import_progress, NULL);
852 if (error) {
853 if (logmsg_path)
854 preserve_logmsg = 1;
855 goto done;
858 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
859 if (error) {
860 if (logmsg_path)
861 preserve_logmsg = 1;
862 goto done;
865 error = got_ref_write(branch_ref, repo);
866 if (error) {
867 if (logmsg_path)
868 preserve_logmsg = 1;
869 goto done;
872 error = got_object_id_str(&id_str, new_commit_id);
873 if (error) {
874 if (logmsg_path)
875 preserve_logmsg = 1;
876 goto done;
879 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
880 if (error) {
881 if (error->code != GOT_ERR_NOT_REF) {
882 if (logmsg_path)
883 preserve_logmsg = 1;
884 goto done;
887 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
888 branch_ref);
889 if (error) {
890 if (logmsg_path)
891 preserve_logmsg = 1;
892 goto done;
895 error = got_ref_write(head_ref, repo);
896 if (error) {
897 if (logmsg_path)
898 preserve_logmsg = 1;
899 goto done;
903 printf("Created branch %s with commit %s\n",
904 got_ref_get_name(branch_ref), id_str);
905 done:
906 if (pack_fds) {
907 const struct got_error *pack_err =
908 got_repo_pack_fds_close(pack_fds);
909 if (error == NULL)
910 error = pack_err;
912 if (preserve_logmsg) {
913 fprintf(stderr, "%s: log message preserved in %s\n",
914 getprogname(), logmsg_path);
915 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
916 error = got_error_from_errno2("unlink", logmsg_path);
917 free(logmsg);
918 free(logmsg_path);
919 free(repo_path);
920 free(editor);
921 free(refname);
922 free(new_commit_id);
923 free(id_str);
924 free(author);
925 free(gitconfig_path);
926 if (branch_ref)
927 got_ref_close(branch_ref);
928 if (head_ref)
929 got_ref_close(head_ref);
930 return error;
933 __dead static void
934 usage_clone(void)
936 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
937 "[-R reference] repository-url [directory]\n", getprogname());
938 exit(1);
941 struct got_fetch_progress_arg {
942 char last_scaled_size[FMT_SCALED_STRSIZE];
943 int last_p_indexed;
944 int last_p_resolved;
945 int verbosity;
947 struct got_repository *repo;
949 int create_configs;
950 int configs_created;
951 struct {
952 struct got_pathlist_head *symrefs;
953 struct got_pathlist_head *wanted_branches;
954 struct got_pathlist_head *wanted_refs;
955 const char *proto;
956 const char *host;
957 const char *port;
958 const char *remote_repo_path;
959 const char *git_url;
960 int fetch_all_branches;
961 int mirror_references;
962 } config_info;
963 };
965 /* XXX forward declaration */
966 static const struct got_error *
967 create_config_files(const char *proto, const char *host, const char *port,
968 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
969 int mirror_references, struct got_pathlist_head *symrefs,
970 struct got_pathlist_head *wanted_branches,
971 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
973 static const struct got_error *
974 fetch_progress(void *arg, const char *message, off_t packfile_size,
975 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
977 const struct got_error *err = NULL;
978 struct got_fetch_progress_arg *a = arg;
979 char scaled_size[FMT_SCALED_STRSIZE];
980 int p_indexed, p_resolved;
981 int print_size = 0, print_indexed = 0, print_resolved = 0;
983 /*
984 * In order to allow a failed clone to be resumed with 'got fetch'
985 * we try to create configuration files as soon as possible.
986 * Once the server has sent information about its default branch
987 * we have all required information.
988 */
989 if (a->create_configs && !a->configs_created &&
990 !TAILQ_EMPTY(a->config_info.symrefs)) {
991 err = create_config_files(a->config_info.proto,
992 a->config_info.host, a->config_info.port,
993 a->config_info.remote_repo_path,
994 a->config_info.git_url,
995 a->config_info.fetch_all_branches,
996 a->config_info.mirror_references,
997 a->config_info.symrefs,
998 a->config_info.wanted_branches,
999 a->config_info.wanted_refs, a->repo);
1000 if (err)
1001 return err;
1002 a->configs_created = 1;
1005 if (a->verbosity < 0)
1006 return NULL;
1008 if (message && message[0] != '\0') {
1009 printf("\rserver: %s", message);
1010 fflush(stdout);
1011 return NULL;
1014 if (packfile_size > 0 || nobj_indexed > 0) {
1015 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1016 (a->last_scaled_size[0] == '\0' ||
1017 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1018 print_size = 1;
1019 if (strlcpy(a->last_scaled_size, scaled_size,
1020 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1021 return got_error(GOT_ERR_NO_SPACE);
1023 if (nobj_indexed > 0) {
1024 p_indexed = (nobj_indexed * 100) / nobj_total;
1025 if (p_indexed != a->last_p_indexed) {
1026 a->last_p_indexed = p_indexed;
1027 print_indexed = 1;
1028 print_size = 1;
1031 if (nobj_resolved > 0) {
1032 p_resolved = (nobj_resolved * 100) /
1033 (nobj_total - nobj_loose);
1034 if (p_resolved != a->last_p_resolved) {
1035 a->last_p_resolved = p_resolved;
1036 print_resolved = 1;
1037 print_indexed = 1;
1038 print_size = 1;
1043 if (print_size || print_indexed || print_resolved)
1044 printf("\r");
1045 if (print_size)
1046 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1047 if (print_indexed)
1048 printf("; indexing %d%%", p_indexed);
1049 if (print_resolved)
1050 printf("; resolving deltas %d%%", p_resolved);
1051 if (print_size || print_indexed || print_resolved)
1052 fflush(stdout);
1054 return NULL;
1057 static const struct got_error *
1058 create_symref(const char *refname, struct got_reference *target_ref,
1059 int verbosity, struct got_repository *repo)
1061 const struct got_error *err;
1062 struct got_reference *head_symref;
1064 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1065 if (err)
1066 return err;
1068 err = got_ref_write(head_symref, repo);
1069 if (err == NULL && verbosity > 0) {
1070 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1071 got_ref_get_name(target_ref));
1073 got_ref_close(head_symref);
1074 return err;
1077 static const struct got_error *
1078 list_remote_refs(struct got_pathlist_head *symrefs,
1079 struct got_pathlist_head *refs)
1081 const struct got_error *err;
1082 struct got_pathlist_entry *pe;
1084 TAILQ_FOREACH(pe, symrefs, entry) {
1085 const char *refname = pe->path;
1086 const char *targetref = pe->data;
1088 printf("%s: %s\n", refname, targetref);
1091 TAILQ_FOREACH(pe, refs, entry) {
1092 const char *refname = pe->path;
1093 struct got_object_id *id = pe->data;
1094 char *id_str;
1096 err = got_object_id_str(&id_str, id);
1097 if (err)
1098 return err;
1099 printf("%s: %s\n", refname, id_str);
1100 free(id_str);
1103 return NULL;
1106 static const struct got_error *
1107 create_ref(const char *refname, struct got_object_id *id,
1108 int verbosity, struct got_repository *repo)
1110 const struct got_error *err = NULL;
1111 struct got_reference *ref;
1112 char *id_str;
1114 err = got_object_id_str(&id_str, id);
1115 if (err)
1116 return err;
1118 err = got_ref_alloc(&ref, refname, id);
1119 if (err)
1120 goto done;
1122 err = got_ref_write(ref, repo);
1123 got_ref_close(ref);
1125 if (err == NULL && verbosity >= 0)
1126 printf("Created reference %s: %s\n", refname, id_str);
1127 done:
1128 free(id_str);
1129 return err;
1132 static int
1133 match_wanted_ref(const char *refname, const char *wanted_ref)
1135 if (strncmp(refname, "refs/", 5) != 0)
1136 return 0;
1137 refname += 5;
1140 * Prevent fetching of references that won't make any
1141 * sense outside of the remote repository's context.
1143 if (strncmp(refname, "got/", 4) == 0)
1144 return 0;
1145 if (strncmp(refname, "remotes/", 8) == 0)
1146 return 0;
1148 if (strncmp(wanted_ref, "refs/", 5) == 0)
1149 wanted_ref += 5;
1151 /* Allow prefix match. */
1152 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1153 return 1;
1155 /* Allow exact match. */
1156 return (strcmp(refname, wanted_ref) == 0);
1159 static int
1160 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1162 struct got_pathlist_entry *pe;
1164 TAILQ_FOREACH(pe, wanted_refs, entry) {
1165 if (match_wanted_ref(refname, pe->path))
1166 return 1;
1169 return 0;
1172 static const struct got_error *
1173 create_wanted_ref(const char *refname, struct got_object_id *id,
1174 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1176 const struct got_error *err;
1177 char *remote_refname;
1179 if (strncmp("refs/", refname, 5) == 0)
1180 refname += 5;
1182 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1183 remote_repo_name, refname) == -1)
1184 return got_error_from_errno("asprintf");
1186 err = create_ref(remote_refname, id, verbosity, repo);
1187 free(remote_refname);
1188 return err;
1191 static const struct got_error *
1192 create_gotconfig(const char *proto, const char *host, const char *port,
1193 const char *remote_repo_path, const char *default_branch,
1194 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1195 struct got_pathlist_head *wanted_refs, int mirror_references,
1196 struct got_repository *repo)
1198 const struct got_error *err = NULL;
1199 char *gotconfig_path = NULL;
1200 char *gotconfig = NULL;
1201 FILE *gotconfig_file = NULL;
1202 const char *branchname = NULL;
1203 char *branches = NULL, *refs = NULL;
1204 ssize_t n;
1206 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1207 struct got_pathlist_entry *pe;
1208 TAILQ_FOREACH(pe, wanted_branches, entry) {
1209 char *s;
1210 branchname = pe->path;
1211 if (strncmp(branchname, "refs/heads/", 11) == 0)
1212 branchname += 11;
1213 if (asprintf(&s, "%s\"%s\" ",
1214 branches ? branches : "", branchname) == -1) {
1215 err = got_error_from_errno("asprintf");
1216 goto done;
1218 free(branches);
1219 branches = s;
1221 } else if (!fetch_all_branches && default_branch) {
1222 branchname = default_branch;
1223 if (strncmp(branchname, "refs/heads/", 11) == 0)
1224 branchname += 11;
1225 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1226 err = got_error_from_errno("asprintf");
1227 goto done;
1230 if (!TAILQ_EMPTY(wanted_refs)) {
1231 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 char *s;
1234 const char *refname = pe->path;
1235 if (strncmp(refname, "refs/", 5) == 0)
1236 branchname += 5;
1237 if (asprintf(&s, "%s\"%s\" ",
1238 refs ? refs : "", refname) == -1) {
1239 err = got_error_from_errno("asprintf");
1240 goto done;
1242 free(refs);
1243 refs = s;
1247 /* Create got.conf(5). */
1248 gotconfig_path = got_repo_get_path_gotconfig(repo);
1249 if (gotconfig_path == NULL) {
1250 err = got_error_from_errno("got_repo_get_path_gotconfig");
1251 goto done;
1253 gotconfig_file = fopen(gotconfig_path, "ae");
1254 if (gotconfig_file == NULL) {
1255 err = got_error_from_errno2("fopen", gotconfig_path);
1256 goto done;
1258 if (asprintf(&gotconfig,
1259 "remote \"%s\" {\n"
1260 "\tserver %s\n"
1261 "\tprotocol %s\n"
1262 "%s%s%s"
1263 "\trepository \"%s\"\n"
1264 "%s%s%s"
1265 "%s%s%s"
1266 "%s"
1267 "%s"
1268 "}\n",
1269 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1270 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1271 remote_repo_path, branches ? "\tbranch { " : "",
1272 branches ? branches : "", branches ? "}\n" : "",
1273 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1274 mirror_references ? "\tmirror-references yes\n" : "",
1275 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1276 err = got_error_from_errno("asprintf");
1277 goto done;
1279 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1280 if (n != strlen(gotconfig)) {
1281 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1282 goto done;
1285 done:
1286 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1287 err = got_error_from_errno2("fclose", gotconfig_path);
1288 free(gotconfig_path);
1289 free(branches);
1290 return err;
1293 static const struct got_error *
1294 create_gitconfig(const char *git_url, const char *default_branch,
1295 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1296 struct got_pathlist_head *wanted_refs, int mirror_references,
1297 struct got_repository *repo)
1299 const struct got_error *err = NULL;
1300 char *gitconfig_path = NULL;
1301 char *gitconfig = NULL;
1302 FILE *gitconfig_file = NULL;
1303 char *branches = NULL, *refs = NULL;
1304 const char *branchname;
1305 ssize_t n;
1307 /* Create a config file Git can understand. */
1308 gitconfig_path = got_repo_get_path_gitconfig(repo);
1309 if (gitconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gitconfig");
1311 goto done;
1313 gitconfig_file = fopen(gitconfig_path, "ae");
1314 if (gitconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gitconfig_path);
1316 goto done;
1318 if (fetch_all_branches) {
1319 if (mirror_references) {
1320 if (asprintf(&branches,
1321 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1322 err = got_error_from_errno("asprintf");
1323 goto done;
1325 } else if (asprintf(&branches,
1326 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1327 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1328 err = got_error_from_errno("asprintf");
1329 goto done;
1331 } else if (!TAILQ_EMPTY(wanted_branches)) {
1332 struct got_pathlist_entry *pe;
1333 TAILQ_FOREACH(pe, wanted_branches, entry) {
1334 char *s;
1335 branchname = pe->path;
1336 if (strncmp(branchname, "refs/heads/", 11) == 0)
1337 branchname += 11;
1338 if (mirror_references) {
1339 if (asprintf(&s,
1340 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1341 branches ? branches : "",
1342 branchname, branchname) == -1) {
1343 err = got_error_from_errno("asprintf");
1344 goto done;
1346 } else if (asprintf(&s,
1347 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1348 branches ? branches : "",
1349 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1350 branchname) == -1) {
1351 err = got_error_from_errno("asprintf");
1352 goto done;
1354 free(branches);
1355 branches = s;
1357 } else {
1359 * If the server specified a default branch, use just that one.
1360 * Otherwise fall back to fetching all branches on next fetch.
1362 if (default_branch) {
1363 branchname = default_branch;
1364 if (strncmp(branchname, "refs/heads/", 11) == 0)
1365 branchname += 11;
1366 } else
1367 branchname = "*"; /* fall back to all branches */
1368 if (mirror_references) {
1369 if (asprintf(&branches,
1370 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1371 branchname, branchname) == -1) {
1372 err = got_error_from_errno("asprintf");
1373 goto done;
1375 } else if (asprintf(&branches,
1376 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1377 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1378 branchname) == -1) {
1379 err = got_error_from_errno("asprintf");
1380 goto done;
1383 if (!TAILQ_EMPTY(wanted_refs)) {
1384 struct got_pathlist_entry *pe;
1385 TAILQ_FOREACH(pe, wanted_refs, entry) {
1386 char *s;
1387 const char *refname = pe->path;
1388 if (strncmp(refname, "refs/", 5) == 0)
1389 refname += 5;
1390 if (mirror_references) {
1391 if (asprintf(&s,
1392 "%s\tfetch = refs/%s:refs/%s\n",
1393 refs ? refs : "", refname, refname) == -1) {
1394 err = got_error_from_errno("asprintf");
1395 goto done;
1397 } else if (asprintf(&s,
1398 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1399 refs ? refs : "",
1400 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1401 refname) == -1) {
1402 err = got_error_from_errno("asprintf");
1403 goto done;
1405 free(refs);
1406 refs = s;
1410 if (asprintf(&gitconfig,
1411 "[remote \"%s\"]\n"
1412 "\turl = %s\n"
1413 "%s"
1414 "%s"
1415 "\tfetch = refs/tags/*:refs/tags/*\n",
1416 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1417 refs ? refs : "") == -1) {
1418 err = got_error_from_errno("asprintf");
1419 goto done;
1421 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1422 if (n != strlen(gitconfig)) {
1423 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1424 goto done;
1426 done:
1427 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1428 err = got_error_from_errno2("fclose", gitconfig_path);
1429 free(gitconfig_path);
1430 free(branches);
1431 return err;
1434 static const struct got_error *
1435 create_config_files(const char *proto, const char *host, const char *port,
1436 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1437 int mirror_references, struct got_pathlist_head *symrefs,
1438 struct got_pathlist_head *wanted_branches,
1439 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1441 const struct got_error *err = NULL;
1442 const char *default_branch = NULL;
1443 struct got_pathlist_entry *pe;
1446 * If we asked for a set of wanted branches then use the first
1447 * one of those.
1449 if (!TAILQ_EMPTY(wanted_branches)) {
1450 pe = TAILQ_FIRST(wanted_branches);
1451 default_branch = pe->path;
1452 } else {
1453 /* First HEAD ref listed by server is the default branch. */
1454 TAILQ_FOREACH(pe, symrefs, entry) {
1455 const char *refname = pe->path;
1456 const char *target = pe->data;
1458 if (strcmp(refname, GOT_REF_HEAD) != 0)
1459 continue;
1461 default_branch = target;
1462 break;
1466 /* Create got.conf(5). */
1467 err = create_gotconfig(proto, host, port, remote_repo_path,
1468 default_branch, fetch_all_branches, wanted_branches,
1469 wanted_refs, mirror_references, repo);
1470 if (err)
1471 return err;
1473 /* Create a config file Git can understand. */
1474 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1475 wanted_branches, wanted_refs, mirror_references, repo);
1478 static const struct got_error *
1479 cmd_clone(int argc, char *argv[])
1481 const struct got_error *error = NULL;
1482 const char *uri, *dirname;
1483 char *proto, *host, *port, *repo_name, *server_path;
1484 char *default_destdir = NULL, *id_str = NULL;
1485 const char *repo_path;
1486 struct got_repository *repo = NULL;
1487 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1488 struct got_pathlist_entry *pe;
1489 struct got_object_id *pack_hash = NULL;
1490 int ch, fetchfd = -1, fetchstatus;
1491 pid_t fetchpid = -1;
1492 struct got_fetch_progress_arg fpa;
1493 char *git_url = NULL;
1494 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1495 int list_refs_only = 0;
1496 int *pack_fds = NULL;
1498 TAILQ_INIT(&refs);
1499 TAILQ_INIT(&symrefs);
1500 TAILQ_INIT(&wanted_branches);
1501 TAILQ_INIT(&wanted_refs);
1503 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1504 switch (ch) {
1505 case 'a':
1506 fetch_all_branches = 1;
1507 break;
1508 case 'b':
1509 error = got_pathlist_append(&wanted_branches,
1510 optarg, NULL);
1511 if (error)
1512 return error;
1513 break;
1514 case 'l':
1515 list_refs_only = 1;
1516 break;
1517 case 'm':
1518 mirror_references = 1;
1519 break;
1520 case 'v':
1521 if (verbosity < 0)
1522 verbosity = 0;
1523 else if (verbosity < 3)
1524 verbosity++;
1525 break;
1526 case 'q':
1527 verbosity = -1;
1528 break;
1529 case 'R':
1530 error = got_pathlist_append(&wanted_refs,
1531 optarg, NULL);
1532 if (error)
1533 return error;
1534 break;
1535 default:
1536 usage_clone();
1537 break;
1540 argc -= optind;
1541 argv += optind;
1543 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1544 option_conflict('a', 'b');
1545 if (list_refs_only) {
1546 if (!TAILQ_EMPTY(&wanted_branches))
1547 option_conflict('l', 'b');
1548 if (fetch_all_branches)
1549 option_conflict('l', 'a');
1550 if (mirror_references)
1551 option_conflict('l', 'm');
1552 if (!TAILQ_EMPTY(&wanted_refs))
1553 option_conflict('l', 'R');
1556 uri = argv[0];
1558 if (argc == 1)
1559 dirname = NULL;
1560 else if (argc == 2)
1561 dirname = argv[1];
1562 else
1563 usage_clone();
1565 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1566 &repo_name, uri);
1567 if (error)
1568 goto done;
1570 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1571 host, port ? ":" : "", port ? port : "",
1572 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1573 error = got_error_from_errno("asprintf");
1574 goto done;
1577 if (strcmp(proto, "git") == 0) {
1578 #ifndef PROFILE
1579 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1580 "sendfd dns inet unveil", NULL) == -1)
1581 err(1, "pledge");
1582 #endif
1583 } else if (strcmp(proto, "git+ssh") == 0 ||
1584 strcmp(proto, "ssh") == 0) {
1585 #ifndef PROFILE
1586 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1587 "sendfd unveil", NULL) == -1)
1588 err(1, "pledge");
1589 #endif
1590 } else if (strcmp(proto, "http") == 0 ||
1591 strcmp(proto, "git+http") == 0) {
1592 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1593 goto done;
1594 } else {
1595 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1596 goto done;
1598 if (dirname == NULL) {
1599 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1600 error = got_error_from_errno("asprintf");
1601 goto done;
1603 repo_path = default_destdir;
1604 } else
1605 repo_path = dirname;
1607 if (!list_refs_only) {
1608 error = got_path_mkdir(repo_path);
1609 if (error &&
1610 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1611 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1612 goto done;
1613 if (!got_path_dir_is_empty(repo_path)) {
1614 error = got_error_path(repo_path,
1615 GOT_ERR_DIR_NOT_EMPTY);
1616 goto done;
1620 error = got_dial_apply_unveil(proto);
1621 if (error)
1622 goto done;
1624 error = apply_unveil(repo_path, 0, NULL);
1625 if (error)
1626 goto done;
1628 if (verbosity >= 0)
1629 printf("Connecting to %s%s%s\n", host,
1630 port ? ":" : "", port ? port : "");
1632 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1633 server_path, verbosity);
1634 if (error)
1635 goto done;
1637 if (!list_refs_only) {
1638 error = got_repo_init(repo_path);
1639 if (error)
1640 goto done;
1641 error = got_repo_pack_fds_open(&pack_fds);
1642 if (error != NULL)
1643 goto done;
1644 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1645 if (error)
1646 goto done;
1649 fpa.last_scaled_size[0] = '\0';
1650 fpa.last_p_indexed = -1;
1651 fpa.last_p_resolved = -1;
1652 fpa.verbosity = verbosity;
1653 fpa.create_configs = 1;
1654 fpa.configs_created = 0;
1655 fpa.repo = repo;
1656 fpa.config_info.symrefs = &symrefs;
1657 fpa.config_info.wanted_branches = &wanted_branches;
1658 fpa.config_info.wanted_refs = &wanted_refs;
1659 fpa.config_info.proto = proto;
1660 fpa.config_info.host = host;
1661 fpa.config_info.port = port;
1662 fpa.config_info.remote_repo_path = server_path;
1663 fpa.config_info.git_url = git_url;
1664 fpa.config_info.fetch_all_branches = fetch_all_branches;
1665 fpa.config_info.mirror_references = mirror_references;
1666 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1667 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1668 fetch_all_branches, &wanted_branches, &wanted_refs,
1669 list_refs_only, verbosity, fetchfd, repo,
1670 fetch_progress, &fpa);
1671 if (error)
1672 goto done;
1674 if (list_refs_only) {
1675 error = list_remote_refs(&symrefs, &refs);
1676 goto done;
1679 if (pack_hash == NULL) {
1680 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1681 "server sent an empty pack file");
1682 goto done;
1684 error = got_object_id_str(&id_str, pack_hash);
1685 if (error)
1686 goto done;
1687 if (verbosity >= 0)
1688 printf("\nFetched %s.pack\n", id_str);
1689 free(id_str);
1691 /* Set up references provided with the pack file. */
1692 TAILQ_FOREACH(pe, &refs, entry) {
1693 const char *refname = pe->path;
1694 struct got_object_id *id = pe->data;
1695 char *remote_refname;
1697 if (is_wanted_ref(&wanted_refs, refname) &&
1698 !mirror_references) {
1699 error = create_wanted_ref(refname, id,
1700 GOT_FETCH_DEFAULT_REMOTE_NAME,
1701 verbosity - 1, repo);
1702 if (error)
1703 goto done;
1704 continue;
1707 error = create_ref(refname, id, verbosity - 1, repo);
1708 if (error)
1709 goto done;
1711 if (mirror_references)
1712 continue;
1714 if (strncmp("refs/heads/", refname, 11) != 0)
1715 continue;
1717 if (asprintf(&remote_refname,
1718 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1719 refname + 11) == -1) {
1720 error = got_error_from_errno("asprintf");
1721 goto done;
1723 error = create_ref(remote_refname, id, verbosity - 1, repo);
1724 free(remote_refname);
1725 if (error)
1726 goto done;
1729 /* Set the HEAD reference if the server provided one. */
1730 TAILQ_FOREACH(pe, &symrefs, entry) {
1731 struct got_reference *target_ref;
1732 const char *refname = pe->path;
1733 const char *target = pe->data;
1734 char *remote_refname = NULL, *remote_target = NULL;
1736 if (strcmp(refname, GOT_REF_HEAD) != 0)
1737 continue;
1739 error = got_ref_open(&target_ref, repo, target, 0);
1740 if (error) {
1741 if (error->code == GOT_ERR_NOT_REF) {
1742 error = NULL;
1743 continue;
1745 goto done;
1748 error = create_symref(refname, target_ref, verbosity, repo);
1749 got_ref_close(target_ref);
1750 if (error)
1751 goto done;
1753 if (mirror_references)
1754 continue;
1756 if (strncmp("refs/heads/", target, 11) != 0)
1757 continue;
1759 if (asprintf(&remote_refname,
1760 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1761 refname) == -1) {
1762 error = got_error_from_errno("asprintf");
1763 goto done;
1765 if (asprintf(&remote_target,
1766 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1767 target + 11) == -1) {
1768 error = got_error_from_errno("asprintf");
1769 free(remote_refname);
1770 goto done;
1772 error = got_ref_open(&target_ref, repo, remote_target, 0);
1773 if (error) {
1774 free(remote_refname);
1775 free(remote_target);
1776 if (error->code == GOT_ERR_NOT_REF) {
1777 error = NULL;
1778 continue;
1780 goto done;
1782 error = create_symref(remote_refname, target_ref,
1783 verbosity - 1, repo);
1784 free(remote_refname);
1785 free(remote_target);
1786 got_ref_close(target_ref);
1787 if (error)
1788 goto done;
1790 if (pe == NULL) {
1792 * We failed to set the HEAD reference. If we asked for
1793 * a set of wanted branches use the first of one of those
1794 * which could be fetched instead.
1796 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1797 const char *target = pe->path;
1798 struct got_reference *target_ref;
1800 error = got_ref_open(&target_ref, repo, target, 0);
1801 if (error) {
1802 if (error->code == GOT_ERR_NOT_REF) {
1803 error = NULL;
1804 continue;
1806 goto done;
1809 error = create_symref(GOT_REF_HEAD, target_ref,
1810 verbosity, repo);
1811 got_ref_close(target_ref);
1812 if (error)
1813 goto done;
1814 break;
1818 if (verbosity >= 0)
1819 printf("Created %s repository '%s'\n",
1820 mirror_references ? "mirrored" : "cloned", repo_path);
1821 done:
1822 if (pack_fds) {
1823 const struct got_error *pack_err =
1824 got_repo_pack_fds_close(pack_fds);
1825 if (error == NULL)
1826 error = pack_err;
1828 if (fetchpid > 0) {
1829 if (kill(fetchpid, SIGTERM) == -1)
1830 error = got_error_from_errno("kill");
1831 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1832 error = got_error_from_errno("waitpid");
1834 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1835 error = got_error_from_errno("close");
1836 if (repo) {
1837 const struct got_error *close_err = got_repo_close(repo);
1838 if (error == NULL)
1839 error = close_err;
1841 TAILQ_FOREACH(pe, &refs, entry) {
1842 free((void *)pe->path);
1843 free(pe->data);
1845 got_pathlist_free(&refs);
1846 TAILQ_FOREACH(pe, &symrefs, entry) {
1847 free((void *)pe->path);
1848 free(pe->data);
1850 got_pathlist_free(&symrefs);
1851 got_pathlist_free(&wanted_branches);
1852 got_pathlist_free(&wanted_refs);
1853 free(pack_hash);
1854 free(proto);
1855 free(host);
1856 free(port);
1857 free(server_path);
1858 free(repo_name);
1859 free(default_destdir);
1860 free(git_url);
1861 return error;
1864 static const struct got_error *
1865 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1866 int replace_tags, int verbosity, struct got_repository *repo)
1868 const struct got_error *err = NULL;
1869 char *new_id_str = NULL;
1870 struct got_object_id *old_id = NULL;
1872 err = got_object_id_str(&new_id_str, new_id);
1873 if (err)
1874 goto done;
1876 if (!replace_tags &&
1877 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1878 err = got_ref_resolve(&old_id, repo, ref);
1879 if (err)
1880 goto done;
1881 if (got_object_id_cmp(old_id, new_id) == 0)
1882 goto done;
1883 if (verbosity >= 0) {
1884 printf("Rejecting update of existing tag %s: %s\n",
1885 got_ref_get_name(ref), new_id_str);
1887 goto done;
1890 if (got_ref_is_symbolic(ref)) {
1891 if (verbosity >= 0) {
1892 printf("Replacing reference %s: %s\n",
1893 got_ref_get_name(ref),
1894 got_ref_get_symref_target(ref));
1896 err = got_ref_change_symref_to_ref(ref, new_id);
1897 if (err)
1898 goto done;
1899 err = got_ref_write(ref, repo);
1900 if (err)
1901 goto done;
1902 } else {
1903 err = got_ref_resolve(&old_id, repo, ref);
1904 if (err)
1905 goto done;
1906 if (got_object_id_cmp(old_id, new_id) == 0)
1907 goto done;
1909 err = got_ref_change_ref(ref, new_id);
1910 if (err)
1911 goto done;
1912 err = got_ref_write(ref, repo);
1913 if (err)
1914 goto done;
1917 if (verbosity >= 0)
1918 printf("Updated %s: %s\n", got_ref_get_name(ref),
1919 new_id_str);
1920 done:
1921 free(old_id);
1922 free(new_id_str);
1923 return err;
1926 static const struct got_error *
1927 update_symref(const char *refname, struct got_reference *target_ref,
1928 int verbosity, struct got_repository *repo)
1930 const struct got_error *err = NULL, *unlock_err;
1931 struct got_reference *symref;
1932 int symref_is_locked = 0;
1934 err = got_ref_open(&symref, repo, refname, 1);
1935 if (err) {
1936 if (err->code != GOT_ERR_NOT_REF)
1937 return err;
1938 err = got_ref_alloc_symref(&symref, refname, 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("Created reference %s: %s\n",
1948 got_ref_get_name(symref),
1949 got_ref_get_symref_target(symref));
1950 } else {
1951 symref_is_locked = 1;
1953 if (strcmp(got_ref_get_symref_target(symref),
1954 got_ref_get_name(target_ref)) == 0)
1955 goto done;
1957 err = got_ref_change_symref(symref,
1958 got_ref_get_name(target_ref));
1959 if (err)
1960 goto done;
1962 err = got_ref_write(symref, repo);
1963 if (err)
1964 goto done;
1966 if (verbosity >= 0)
1967 printf("Updated %s: %s\n", got_ref_get_name(symref),
1968 got_ref_get_symref_target(symref));
1971 done:
1972 if (symref_is_locked) {
1973 unlock_err = got_ref_unlock(symref);
1974 if (unlock_err && err == NULL)
1975 err = unlock_err;
1977 got_ref_close(symref);
1978 return err;
1981 __dead static void
1982 usage_fetch(void)
1984 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1985 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1986 "[remote-repository-name]\n",
1987 getprogname());
1988 exit(1);
1991 static const struct got_error *
1992 delete_missing_ref(struct got_reference *ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL;
1996 struct got_object_id *id = NULL;
1997 char *id_str = NULL;
1999 if (got_ref_is_symbolic(ref)) {
2000 err = got_ref_delete(ref, repo);
2001 if (err)
2002 return err;
2003 if (verbosity >= 0) {
2004 printf("Deleted %s: %s\n",
2005 got_ref_get_name(ref),
2006 got_ref_get_symref_target(ref));
2008 } else {
2009 err = got_ref_resolve(&id, repo, ref);
2010 if (err)
2011 return err;
2012 err = got_object_id_str(&id_str, id);
2013 if (err)
2014 goto done;
2016 err = got_ref_delete(ref, repo);
2017 if (err)
2018 goto done;
2019 if (verbosity >= 0) {
2020 printf("Deleted %s: %s\n",
2021 got_ref_get_name(ref), id_str);
2024 done:
2025 free(id);
2026 free(id_str);
2027 return NULL;
2030 static const struct got_error *
2031 delete_missing_refs(struct got_pathlist_head *their_refs,
2032 struct got_pathlist_head *their_symrefs,
2033 const struct got_remote_repo *remote,
2034 int verbosity, struct got_repository *repo)
2036 const struct got_error *err = NULL, *unlock_err;
2037 struct got_reflist_head my_refs;
2038 struct got_reflist_entry *re;
2039 struct got_pathlist_entry *pe;
2040 char *remote_namespace = NULL;
2041 char *local_refname = NULL;
2043 TAILQ_INIT(&my_refs);
2045 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2046 == -1)
2047 return got_error_from_errno("asprintf");
2049 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2050 if (err)
2051 goto done;
2053 TAILQ_FOREACH(re, &my_refs, entry) {
2054 const char *refname = got_ref_get_name(re->ref);
2055 const char *their_refname;
2057 if (remote->mirror_references) {
2058 their_refname = refname;
2059 } else {
2060 if (strncmp(refname, remote_namespace,
2061 strlen(remote_namespace)) == 0) {
2062 if (strcmp(refname + strlen(remote_namespace),
2063 GOT_REF_HEAD) == 0)
2064 continue;
2065 if (asprintf(&local_refname, "refs/heads/%s",
2066 refname + strlen(remote_namespace)) == -1) {
2067 err = got_error_from_errno("asprintf");
2068 goto done;
2070 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2071 continue;
2073 their_refname = local_refname;
2076 TAILQ_FOREACH(pe, their_refs, entry) {
2077 if (strcmp(their_refname, pe->path) == 0)
2078 break;
2080 if (pe != NULL)
2081 continue;
2083 TAILQ_FOREACH(pe, their_symrefs, entry) {
2084 if (strcmp(their_refname, pe->path) == 0)
2085 break;
2087 if (pe != NULL)
2088 continue;
2090 err = delete_missing_ref(re->ref, verbosity, repo);
2091 if (err)
2092 break;
2094 if (local_refname) {
2095 struct got_reference *ref;
2096 err = got_ref_open(&ref, repo, local_refname, 1);
2097 if (err) {
2098 if (err->code != GOT_ERR_NOT_REF)
2099 break;
2100 free(local_refname);
2101 local_refname = NULL;
2102 continue;
2104 err = delete_missing_ref(ref, verbosity, repo);
2105 if (err)
2106 break;
2107 unlock_err = got_ref_unlock(ref);
2108 got_ref_close(ref);
2109 if (unlock_err && err == NULL) {
2110 err = unlock_err;
2111 break;
2114 free(local_refname);
2115 local_refname = NULL;
2118 done:
2119 free(remote_namespace);
2120 free(local_refname);
2121 return err;
2124 static const struct got_error *
2125 update_wanted_ref(const char *refname, struct got_object_id *id,
2126 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2128 const struct got_error *err, *unlock_err;
2129 char *remote_refname;
2130 struct got_reference *ref;
2132 if (strncmp("refs/", refname, 5) == 0)
2133 refname += 5;
2135 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2136 remote_repo_name, refname) == -1)
2137 return got_error_from_errno("asprintf");
2139 err = got_ref_open(&ref, repo, remote_refname, 1);
2140 if (err) {
2141 if (err->code != GOT_ERR_NOT_REF)
2142 goto done;
2143 err = create_ref(remote_refname, id, verbosity, repo);
2144 } else {
2145 err = update_ref(ref, id, 0, verbosity, repo);
2146 unlock_err = got_ref_unlock(ref);
2147 if (unlock_err && err == NULL)
2148 err = unlock_err;
2149 got_ref_close(ref);
2151 done:
2152 free(remote_refname);
2153 return err;
2156 static const struct got_error *
2157 delete_ref(struct got_repository *repo, struct got_reference *ref)
2159 const struct got_error *err = NULL;
2160 struct got_object_id *id = NULL;
2161 char *id_str = NULL;
2162 const char *target;
2164 if (got_ref_is_symbolic(ref)) {
2165 target = got_ref_get_symref_target(ref);
2166 } else {
2167 err = got_ref_resolve(&id, repo, ref);
2168 if (err)
2169 goto done;
2170 err = got_object_id_str(&id_str, id);
2171 if (err)
2172 goto done;
2173 target = id_str;
2176 err = got_ref_delete(ref, repo);
2177 if (err)
2178 goto done;
2180 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2181 done:
2182 free(id);
2183 free(id_str);
2184 return err;
2187 static const struct got_error *
2188 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2190 const struct got_error *err = NULL;
2191 struct got_reflist_head refs;
2192 struct got_reflist_entry *re;
2193 char *prefix;
2195 TAILQ_INIT(&refs);
2197 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2198 err = got_error_from_errno("asprintf");
2199 goto done;
2201 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2202 if (err)
2203 goto done;
2205 TAILQ_FOREACH(re, &refs, entry)
2206 delete_ref(repo, re->ref);
2207 done:
2208 got_ref_list_free(&refs);
2209 return err;
2212 static const struct got_error *
2213 cmd_fetch(int argc, char *argv[])
2215 const struct got_error *error = NULL, *unlock_err;
2216 char *cwd = NULL, *repo_path = NULL;
2217 const char *remote_name;
2218 char *proto = NULL, *host = NULL, *port = NULL;
2219 char *repo_name = NULL, *server_path = NULL;
2220 const struct got_remote_repo *remotes, *remote = NULL;
2221 int nremotes;
2222 char *id_str = NULL;
2223 struct got_repository *repo = NULL;
2224 struct got_worktree *worktree = NULL;
2225 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2226 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2227 struct got_pathlist_entry *pe;
2228 struct got_object_id *pack_hash = NULL;
2229 int i, ch, fetchfd = -1, fetchstatus;
2230 pid_t fetchpid = -1;
2231 struct got_fetch_progress_arg fpa;
2232 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2233 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2234 int *pack_fds = NULL;
2236 TAILQ_INIT(&refs);
2237 TAILQ_INIT(&symrefs);
2238 TAILQ_INIT(&wanted_branches);
2239 TAILQ_INIT(&wanted_refs);
2241 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2242 switch (ch) {
2243 case 'a':
2244 fetch_all_branches = 1;
2245 break;
2246 case 'b':
2247 error = got_pathlist_append(&wanted_branches,
2248 optarg, NULL);
2249 if (error)
2250 return error;
2251 break;
2252 case 'd':
2253 delete_refs = 1;
2254 break;
2255 case 'l':
2256 list_refs_only = 1;
2257 break;
2258 case 'r':
2259 repo_path = realpath(optarg, NULL);
2260 if (repo_path == NULL)
2261 return got_error_from_errno2("realpath",
2262 optarg);
2263 got_path_strip_trailing_slashes(repo_path);
2264 break;
2265 case 't':
2266 replace_tags = 1;
2267 break;
2268 case 'v':
2269 if (verbosity < 0)
2270 verbosity = 0;
2271 else if (verbosity < 3)
2272 verbosity++;
2273 break;
2274 case 'q':
2275 verbosity = -1;
2276 break;
2277 case 'R':
2278 error = got_pathlist_append(&wanted_refs,
2279 optarg, NULL);
2280 if (error)
2281 return error;
2282 break;
2283 case 'X':
2284 delete_remote = 1;
2285 break;
2286 default:
2287 usage_fetch();
2288 break;
2291 argc -= optind;
2292 argv += optind;
2294 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2295 option_conflict('a', 'b');
2296 if (list_refs_only) {
2297 if (!TAILQ_EMPTY(&wanted_branches))
2298 option_conflict('l', 'b');
2299 if (fetch_all_branches)
2300 option_conflict('l', 'a');
2301 if (delete_refs)
2302 option_conflict('l', 'd');
2303 if (delete_remote)
2304 option_conflict('l', 'X');
2306 if (delete_remote) {
2307 if (fetch_all_branches)
2308 option_conflict('X', 'a');
2309 if (!TAILQ_EMPTY(&wanted_branches))
2310 option_conflict('X', 'b');
2311 if (delete_refs)
2312 option_conflict('X', 'd');
2313 if (replace_tags)
2314 option_conflict('X', 't');
2315 if (!TAILQ_EMPTY(&wanted_refs))
2316 option_conflict('X', 'R');
2319 if (argc == 0) {
2320 if (delete_remote)
2321 errx(1, "-X option requires a remote name");
2322 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2323 } else if (argc == 1)
2324 remote_name = argv[0];
2325 else
2326 usage_fetch();
2328 cwd = getcwd(NULL, 0);
2329 if (cwd == NULL) {
2330 error = got_error_from_errno("getcwd");
2331 goto done;
2334 error = got_repo_pack_fds_open(&pack_fds);
2335 if (error != NULL)
2336 goto done;
2338 if (repo_path == NULL) {
2339 error = got_worktree_open(&worktree, cwd);
2340 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2341 goto done;
2342 else
2343 error = NULL;
2344 if (worktree) {
2345 repo_path =
2346 strdup(got_worktree_get_repo_path(worktree));
2347 if (repo_path == NULL)
2348 error = got_error_from_errno("strdup");
2349 if (error)
2350 goto done;
2351 } else {
2352 repo_path = strdup(cwd);
2353 if (repo_path == NULL) {
2354 error = got_error_from_errno("strdup");
2355 goto done;
2360 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2361 if (error)
2362 goto done;
2364 if (delete_remote) {
2365 error = delete_refs_for_remote(repo, remote_name);
2366 goto done; /* nothing else to do */
2369 if (worktree) {
2370 worktree_conf = got_worktree_get_gotconfig(worktree);
2371 if (worktree_conf) {
2372 got_gotconfig_get_remotes(&nremotes, &remotes,
2373 worktree_conf);
2374 for (i = 0; i < nremotes; i++) {
2375 if (strcmp(remotes[i].name, remote_name) == 0) {
2376 remote = &remotes[i];
2377 break;
2382 if (remote == NULL) {
2383 repo_conf = got_repo_get_gotconfig(repo);
2384 if (repo_conf) {
2385 got_gotconfig_get_remotes(&nremotes, &remotes,
2386 repo_conf);
2387 for (i = 0; i < nremotes; i++) {
2388 if (strcmp(remotes[i].name, remote_name) == 0) {
2389 remote = &remotes[i];
2390 break;
2395 if (remote == NULL) {
2396 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2397 for (i = 0; i < nremotes; i++) {
2398 if (strcmp(remotes[i].name, remote_name) == 0) {
2399 remote = &remotes[i];
2400 break;
2404 if (remote == NULL) {
2405 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2406 goto done;
2409 if (TAILQ_EMPTY(&wanted_branches)) {
2410 if (!fetch_all_branches)
2411 fetch_all_branches = remote->fetch_all_branches;
2412 for (i = 0; i < remote->nfetch_branches; i++) {
2413 got_pathlist_append(&wanted_branches,
2414 remote->fetch_branches[i], NULL);
2417 if (TAILQ_EMPTY(&wanted_refs)) {
2418 for (i = 0; i < remote->nfetch_refs; i++) {
2419 got_pathlist_append(&wanted_refs,
2420 remote->fetch_refs[i], NULL);
2424 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2425 &repo_name, remote->fetch_url);
2426 if (error)
2427 goto done;
2429 if (strcmp(proto, "git") == 0) {
2430 #ifndef PROFILE
2431 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2432 "sendfd dns inet unveil", NULL) == -1)
2433 err(1, "pledge");
2434 #endif
2435 } else if (strcmp(proto, "git+ssh") == 0 ||
2436 strcmp(proto, "ssh") == 0) {
2437 #ifndef PROFILE
2438 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2439 "sendfd unveil", NULL) == -1)
2440 err(1, "pledge");
2441 #endif
2442 } else if (strcmp(proto, "http") == 0 ||
2443 strcmp(proto, "git+http") == 0) {
2444 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2445 goto done;
2446 } else {
2447 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2448 goto done;
2451 error = got_dial_apply_unveil(proto);
2452 if (error)
2453 goto done;
2455 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2456 if (error)
2457 goto done;
2459 if (verbosity >= 0)
2460 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2461 port ? ":" : "", port ? port : "");
2463 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2464 server_path, verbosity);
2465 if (error)
2466 goto done;
2468 fpa.last_scaled_size[0] = '\0';
2469 fpa.last_p_indexed = -1;
2470 fpa.last_p_resolved = -1;
2471 fpa.verbosity = verbosity;
2472 fpa.repo = repo;
2473 fpa.create_configs = 0;
2474 fpa.configs_created = 0;
2475 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2476 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2477 remote->mirror_references, fetch_all_branches, &wanted_branches,
2478 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2479 fetch_progress, &fpa);
2480 if (error)
2481 goto done;
2483 if (list_refs_only) {
2484 error = list_remote_refs(&symrefs, &refs);
2485 goto done;
2488 if (pack_hash == NULL) {
2489 if (verbosity >= 0)
2490 printf("Already up-to-date\n");
2491 } else if (verbosity >= 0) {
2492 error = got_object_id_str(&id_str, pack_hash);
2493 if (error)
2494 goto done;
2495 printf("\nFetched %s.pack\n", id_str);
2496 free(id_str);
2497 id_str = NULL;
2500 /* Update references provided with the pack file. */
2501 TAILQ_FOREACH(pe, &refs, entry) {
2502 const char *refname = pe->path;
2503 struct got_object_id *id = pe->data;
2504 struct got_reference *ref;
2505 char *remote_refname;
2507 if (is_wanted_ref(&wanted_refs, refname) &&
2508 !remote->mirror_references) {
2509 error = update_wanted_ref(refname, id,
2510 remote->name, verbosity, repo);
2511 if (error)
2512 goto done;
2513 continue;
2516 if (remote->mirror_references ||
2517 strncmp("refs/tags/", refname, 10) == 0) {
2518 error = got_ref_open(&ref, repo, refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(refname, id, verbosity,
2523 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;
2536 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2537 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2538 remote_name, refname + 11) == -1) {
2539 error = got_error_from_errno("asprintf");
2540 goto done;
2543 error = got_ref_open(&ref, repo, remote_refname, 1);
2544 if (error) {
2545 if (error->code != GOT_ERR_NOT_REF)
2546 goto done;
2547 error = create_ref(remote_refname, id,
2548 verbosity, repo);
2549 if (error)
2550 goto done;
2551 } else {
2552 error = update_ref(ref, id, replace_tags,
2553 verbosity, repo);
2554 unlock_err = got_ref_unlock(ref);
2555 if (unlock_err && error == NULL)
2556 error = unlock_err;
2557 got_ref_close(ref);
2558 if (error)
2559 goto done;
2562 /* Also create a local branch if none exists yet. */
2563 error = got_ref_open(&ref, repo, refname, 1);
2564 if (error) {
2565 if (error->code != GOT_ERR_NOT_REF)
2566 goto done;
2567 error = create_ref(refname, id, verbosity,
2568 repo);
2569 if (error)
2570 goto done;
2571 } else {
2572 unlock_err = got_ref_unlock(ref);
2573 if (unlock_err && error == NULL)
2574 error = unlock_err;
2575 got_ref_close(ref);
2579 if (delete_refs) {
2580 error = delete_missing_refs(&refs, &symrefs, remote,
2581 verbosity, repo);
2582 if (error)
2583 goto done;
2586 if (!remote->mirror_references) {
2587 /* Update remote HEAD reference if the server provided one. */
2588 TAILQ_FOREACH(pe, &symrefs, entry) {
2589 struct got_reference *target_ref;
2590 const char *refname = pe->path;
2591 const char *target = pe->data;
2592 char *remote_refname = NULL, *remote_target = NULL;
2594 if (strcmp(refname, GOT_REF_HEAD) != 0)
2595 continue;
2597 if (strncmp("refs/heads/", target, 11) != 0)
2598 continue;
2600 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2601 remote->name, refname) == -1) {
2602 error = got_error_from_errno("asprintf");
2603 goto done;
2605 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2606 remote->name, target + 11) == -1) {
2607 error = got_error_from_errno("asprintf");
2608 free(remote_refname);
2609 goto done;
2612 error = got_ref_open(&target_ref, repo, remote_target,
2613 0);
2614 if (error) {
2615 free(remote_refname);
2616 free(remote_target);
2617 if (error->code == GOT_ERR_NOT_REF) {
2618 error = NULL;
2619 continue;
2621 goto done;
2623 error = update_symref(remote_refname, target_ref,
2624 verbosity, repo);
2625 free(remote_refname);
2626 free(remote_target);
2627 got_ref_close(target_ref);
2628 if (error)
2629 goto done;
2632 done:
2633 if (fetchpid > 0) {
2634 if (kill(fetchpid, SIGTERM) == -1)
2635 error = got_error_from_errno("kill");
2636 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2637 error = got_error_from_errno("waitpid");
2639 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2640 error = got_error_from_errno("close");
2641 if (repo) {
2642 const struct got_error *close_err = got_repo_close(repo);
2643 if (error == NULL)
2644 error = close_err;
2646 if (worktree)
2647 got_worktree_close(worktree);
2648 if (pack_fds) {
2649 const struct got_error *pack_err =
2650 got_repo_pack_fds_close(pack_fds);
2651 if (error == NULL)
2652 error = pack_err;
2654 TAILQ_FOREACH(pe, &refs, entry) {
2655 free((void *)pe->path);
2656 free(pe->data);
2658 got_pathlist_free(&refs);
2659 TAILQ_FOREACH(pe, &symrefs, entry) {
2660 free((void *)pe->path);
2661 free(pe->data);
2663 got_pathlist_free(&symrefs);
2664 got_pathlist_free(&wanted_branches);
2665 got_pathlist_free(&wanted_refs);
2666 free(id_str);
2667 free(cwd);
2668 free(repo_path);
2669 free(pack_hash);
2670 free(proto);
2671 free(host);
2672 free(port);
2673 free(server_path);
2674 free(repo_name);
2675 return error;
2679 __dead static void
2680 usage_checkout(void)
2682 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2683 "[-p prefix] [-q] repository-path [worktree-path]\n",
2684 getprogname());
2685 exit(1);
2688 static void
2689 show_worktree_base_ref_warning(void)
2691 fprintf(stderr, "%s: warning: could not create a reference "
2692 "to the work tree's base commit; the commit could be "
2693 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2694 "repository writable and running 'got update' will prevent this\n",
2695 getprogname());
2698 struct got_checkout_progress_arg {
2699 const char *worktree_path;
2700 int had_base_commit_ref_error;
2701 int verbosity;
2704 static const struct got_error *
2705 checkout_progress(void *arg, unsigned char status, const char *path)
2707 struct got_checkout_progress_arg *a = arg;
2709 /* Base commit bump happens silently. */
2710 if (status == GOT_STATUS_BUMP_BASE)
2711 return NULL;
2713 if (status == GOT_STATUS_BASE_REF_ERR) {
2714 a->had_base_commit_ref_error = 1;
2715 return NULL;
2718 while (path[0] == '/')
2719 path++;
2721 if (a->verbosity >= 0)
2722 printf("%c %s/%s\n", status, a->worktree_path, path);
2724 return NULL;
2727 static const struct got_error *
2728 check_cancelled(void *arg)
2730 if (sigint_received || sigpipe_received)
2731 return got_error(GOT_ERR_CANCELLED);
2732 return NULL;
2735 static const struct got_error *
2736 check_linear_ancestry(struct got_object_id *commit_id,
2737 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2738 struct got_repository *repo)
2740 const struct got_error *err = NULL;
2741 struct got_object_id *yca_id;
2743 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2744 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2745 if (err)
2746 return err;
2748 if (yca_id == NULL)
2749 return got_error(GOT_ERR_ANCESTRY);
2752 * Require a straight line of history between the target commit
2753 * and the work tree's base commit.
2755 * Non-linear situations such as this require a rebase:
2757 * (commit) D F (base_commit)
2758 * \ /
2759 * C E
2760 * \ /
2761 * B (yca)
2762 * |
2763 * A
2765 * 'got update' only handles linear cases:
2766 * Update forwards in time: A (base/yca) - B - C - D (commit)
2767 * Update backwards in time: D (base) - C - B - A (commit/yca)
2769 if (allow_forwards_in_time_only) {
2770 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2771 return got_error(GOT_ERR_ANCESTRY);
2772 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2773 got_object_id_cmp(base_commit_id, yca_id) != 0)
2774 return got_error(GOT_ERR_ANCESTRY);
2776 free(yca_id);
2777 return NULL;
2780 static const struct got_error *
2781 check_same_branch(struct got_object_id *commit_id,
2782 struct got_reference *head_ref, struct got_object_id *yca_id,
2783 struct got_repository *repo)
2785 const struct got_error *err = NULL;
2786 struct got_commit_graph *graph = NULL;
2787 struct got_object_id *head_commit_id = NULL;
2788 int is_same_branch = 0;
2790 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2791 if (err)
2792 goto done;
2794 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 goto done;
2798 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2799 is_same_branch = 1;
2800 goto done;
2803 err = got_commit_graph_open(&graph, "/", 1);
2804 if (err)
2805 goto done;
2807 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2808 check_cancelled, NULL);
2809 if (err)
2810 goto done;
2812 for (;;) {
2813 struct got_object_id *id;
2814 err = got_commit_graph_iter_next(&id, graph, repo,
2815 check_cancelled, NULL);
2816 if (err) {
2817 if (err->code == GOT_ERR_ITER_COMPLETED)
2818 err = NULL;
2819 break;
2822 if (id) {
2823 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2824 break;
2825 if (got_object_id_cmp(id, commit_id) == 0) {
2826 is_same_branch = 1;
2827 break;
2831 done:
2832 if (graph)
2833 got_commit_graph_close(graph);
2834 free(head_commit_id);
2835 if (!err && !is_same_branch)
2836 err = got_error(GOT_ERR_ANCESTRY);
2837 return err;
2840 static const struct got_error *
2841 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2843 static char msg[512];
2844 const char *branch_name;
2846 if (got_ref_is_symbolic(ref))
2847 branch_name = got_ref_get_symref_target(ref);
2848 else
2849 branch_name = got_ref_get_name(ref);
2851 if (strncmp("refs/heads/", branch_name, 11) == 0)
2852 branch_name += 11;
2854 snprintf(msg, sizeof(msg),
2855 "target commit is not contained in branch '%s'; "
2856 "the branch to use must be specified with -b; "
2857 "if necessary a new branch can be created for "
2858 "this commit with 'got branch -c %s BRANCH_NAME'",
2859 branch_name, commit_id_str);
2861 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2864 static const struct got_error *
2865 cmd_checkout(int argc, char *argv[])
2867 const struct got_error *error = NULL;
2868 struct got_repository *repo = NULL;
2869 struct got_reference *head_ref = NULL, *ref = NULL;
2870 struct got_worktree *worktree = NULL;
2871 char *repo_path = NULL;
2872 char *worktree_path = NULL;
2873 const char *path_prefix = "";
2874 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2875 char *commit_id_str = NULL;
2876 struct got_object_id *commit_id = NULL;
2877 char *cwd = NULL;
2878 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2879 struct got_pathlist_head paths;
2880 struct got_checkout_progress_arg cpa;
2881 int *pack_fds = NULL;
2883 TAILQ_INIT(&paths);
2885 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2886 switch (ch) {
2887 case 'b':
2888 branch_name = optarg;
2889 break;
2890 case 'c':
2891 commit_id_str = strdup(optarg);
2892 if (commit_id_str == NULL)
2893 return got_error_from_errno("strdup");
2894 break;
2895 case 'E':
2896 allow_nonempty = 1;
2897 break;
2898 case 'p':
2899 path_prefix = optarg;
2900 break;
2901 case 'q':
2902 verbosity = -1;
2903 break;
2904 default:
2905 usage_checkout();
2906 /* NOTREACHED */
2910 argc -= optind;
2911 argv += optind;
2913 #ifndef PROFILE
2914 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2915 "unveil", NULL) == -1)
2916 err(1, "pledge");
2917 #endif
2918 if (argc == 1) {
2919 char *base, *dotgit;
2920 const char *path;
2921 repo_path = realpath(argv[0], NULL);
2922 if (repo_path == NULL)
2923 return got_error_from_errno2("realpath", argv[0]);
2924 cwd = getcwd(NULL, 0);
2925 if (cwd == NULL) {
2926 error = got_error_from_errno("getcwd");
2927 goto done;
2929 if (path_prefix[0])
2930 path = path_prefix;
2931 else
2932 path = repo_path;
2933 error = got_path_basename(&base, path);
2934 if (error)
2935 goto done;
2936 dotgit = strstr(base, ".git");
2937 if (dotgit)
2938 *dotgit = '\0';
2939 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2940 error = got_error_from_errno("asprintf");
2941 free(base);
2942 goto done;
2944 free(base);
2945 } else if (argc == 2) {
2946 repo_path = realpath(argv[0], NULL);
2947 if (repo_path == NULL) {
2948 error = got_error_from_errno2("realpath", argv[0]);
2949 goto done;
2951 worktree_path = realpath(argv[1], NULL);
2952 if (worktree_path == NULL) {
2953 if (errno != ENOENT) {
2954 error = got_error_from_errno2("realpath",
2955 argv[1]);
2956 goto done;
2958 worktree_path = strdup(argv[1]);
2959 if (worktree_path == NULL) {
2960 error = got_error_from_errno("strdup");
2961 goto done;
2964 } else
2965 usage_checkout();
2967 got_path_strip_trailing_slashes(repo_path);
2968 got_path_strip_trailing_slashes(worktree_path);
2970 error = got_repo_pack_fds_open(&pack_fds);
2971 if (error != NULL)
2972 goto done;
2974 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2975 if (error != NULL)
2976 goto done;
2978 /* Pre-create work tree path for unveil(2) */
2979 error = got_path_mkdir(worktree_path);
2980 if (error) {
2981 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2982 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2983 goto done;
2984 if (!allow_nonempty &&
2985 !got_path_dir_is_empty(worktree_path)) {
2986 error = got_error_path(worktree_path,
2987 GOT_ERR_DIR_NOT_EMPTY);
2988 goto done;
2992 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2993 if (error)
2994 goto done;
2996 error = got_ref_open(&head_ref, repo, branch_name, 0);
2997 if (error != NULL)
2998 goto done;
3000 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3001 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3002 goto done;
3004 error = got_worktree_open(&worktree, worktree_path);
3005 if (error != NULL)
3006 goto done;
3008 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3009 path_prefix);
3010 if (error != NULL)
3011 goto done;
3012 if (!same_path_prefix) {
3013 error = got_error(GOT_ERR_PATH_PREFIX);
3014 goto done;
3017 if (commit_id_str) {
3018 struct got_reflist_head refs;
3019 TAILQ_INIT(&refs);
3020 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3021 NULL);
3022 if (error)
3023 goto done;
3024 error = got_repo_match_object_id(&commit_id, NULL,
3025 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3026 got_ref_list_free(&refs);
3027 if (error)
3028 goto done;
3029 error = check_linear_ancestry(commit_id,
3030 got_worktree_get_base_commit_id(worktree), 0, repo);
3031 if (error != NULL) {
3032 if (error->code == GOT_ERR_ANCESTRY) {
3033 error = checkout_ancestry_error(
3034 head_ref, commit_id_str);
3036 goto done;
3038 error = check_same_branch(commit_id, head_ref, NULL, repo);
3039 if (error) {
3040 if (error->code == GOT_ERR_ANCESTRY) {
3041 error = checkout_ancestry_error(
3042 head_ref, commit_id_str);
3044 goto done;
3046 error = got_worktree_set_base_commit_id(worktree, repo,
3047 commit_id);
3048 if (error)
3049 goto done;
3050 /* Expand potentially abbreviated commit ID string. */
3051 free(commit_id_str);
3052 error = got_object_id_str(&commit_id_str, commit_id);
3053 if (error)
3054 goto done;
3055 } else {
3056 commit_id = got_object_id_dup(
3057 got_worktree_get_base_commit_id(worktree));
3058 if (commit_id == NULL) {
3059 error = got_error_from_errno("got_object_id_dup");
3060 goto done;
3062 error = got_object_id_str(&commit_id_str, commit_id);
3063 if (error)
3064 goto done;
3067 error = got_pathlist_append(&paths, "", NULL);
3068 if (error)
3069 goto done;
3070 cpa.worktree_path = worktree_path;
3071 cpa.had_base_commit_ref_error = 0;
3072 cpa.verbosity = verbosity;
3073 error = got_worktree_checkout_files(worktree, &paths, repo,
3074 checkout_progress, &cpa, check_cancelled, NULL);
3075 if (error != NULL)
3076 goto done;
3078 if (got_ref_is_symbolic(head_ref)) {
3079 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3080 if (error)
3081 goto done;
3082 refname = got_ref_get_name(ref);
3083 } else
3084 refname = got_ref_get_name(head_ref);
3085 printf("Checked out %s: %s\n", refname, commit_id_str);
3086 printf("Now shut up and hack\n");
3087 if (cpa.had_base_commit_ref_error)
3088 show_worktree_base_ref_warning();
3089 done:
3090 if (pack_fds) {
3091 const struct got_error *pack_err =
3092 got_repo_pack_fds_close(pack_fds);
3093 if (error == NULL)
3094 error = pack_err;
3096 if (head_ref)
3097 got_ref_close(head_ref);
3098 if (ref)
3099 got_ref_close(ref);
3100 got_pathlist_free(&paths);
3101 free(commit_id_str);
3102 free(commit_id);
3103 free(repo_path);
3104 free(worktree_path);
3105 free(cwd);
3106 return error;
3109 struct got_update_progress_arg {
3110 int did_something;
3111 int conflicts;
3112 int obstructed;
3113 int not_updated;
3114 int missing;
3115 int not_deleted;
3116 int unversioned;
3117 int verbosity;
3120 static void
3121 print_update_progress_stats(struct got_update_progress_arg *upa)
3123 if (!upa->did_something)
3124 return;
3126 if (upa->conflicts > 0)
3127 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3128 if (upa->obstructed > 0)
3129 printf("File paths obstructed by a non-regular file: %d\n",
3130 upa->obstructed);
3131 if (upa->not_updated > 0)
3132 printf("Files not updated because of existing merge "
3133 "conflicts: %d\n", upa->not_updated);
3137 * The meaning of some status codes differs between merge-style operations and
3138 * update operations. For example, the ! status code means "file was missing"
3139 * if changes were merged into the work tree, and "missing file was restored"
3140 * if the work tree was updated. This function should be used by any operation
3141 * which merges changes into the work tree without updating the work tree.
3143 static void
3144 print_merge_progress_stats(struct got_update_progress_arg *upa)
3146 if (!upa->did_something)
3147 return;
3149 if (upa->conflicts > 0)
3150 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3151 if (upa->obstructed > 0)
3152 printf("File paths obstructed by a non-regular file: %d\n",
3153 upa->obstructed);
3154 if (upa->missing > 0)
3155 printf("Files which had incoming changes but could not be "
3156 "found in the work tree: %d\n", upa->missing);
3157 if (upa->not_deleted > 0)
3158 printf("Files not deleted due to differences in deleted "
3159 "content: %d\n", upa->not_deleted);
3160 if (upa->unversioned > 0)
3161 printf("Files not merged because an unversioned file was "
3162 "found in the work tree: %d\n", upa->unversioned);
3165 __dead static void
3166 usage_update(void)
3168 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3169 "[path ...]\n",
3170 getprogname());
3171 exit(1);
3174 static const struct got_error *
3175 update_progress(void *arg, unsigned char status, const char *path)
3177 struct got_update_progress_arg *upa = arg;
3179 if (status == GOT_STATUS_EXISTS ||
3180 status == GOT_STATUS_BASE_REF_ERR)
3181 return NULL;
3183 upa->did_something = 1;
3185 /* Base commit bump happens silently. */
3186 if (status == GOT_STATUS_BUMP_BASE)
3187 return NULL;
3189 if (status == GOT_STATUS_CONFLICT)
3190 upa->conflicts++;
3191 if (status == GOT_STATUS_OBSTRUCTED)
3192 upa->obstructed++;
3193 if (status == GOT_STATUS_CANNOT_UPDATE)
3194 upa->not_updated++;
3195 if (status == GOT_STATUS_MISSING)
3196 upa->missing++;
3197 if (status == GOT_STATUS_CANNOT_DELETE)
3198 upa->not_deleted++;
3199 if (status == GOT_STATUS_UNVERSIONED)
3200 upa->unversioned++;
3202 while (path[0] == '/')
3203 path++;
3204 if (upa->verbosity >= 0)
3205 printf("%c %s\n", status, path);
3207 return NULL;
3210 static const struct got_error *
3211 switch_head_ref(struct got_reference *head_ref,
3212 struct got_object_id *commit_id, struct got_worktree *worktree,
3213 struct got_repository *repo)
3215 const struct got_error *err = NULL;
3216 char *base_id_str;
3217 int ref_has_moved = 0;
3219 /* Trivial case: switching between two different references. */
3220 if (strcmp(got_ref_get_name(head_ref),
3221 got_worktree_get_head_ref_name(worktree)) != 0) {
3222 printf("Switching work tree from %s to %s\n",
3223 got_worktree_get_head_ref_name(worktree),
3224 got_ref_get_name(head_ref));
3225 return got_worktree_set_head_ref(worktree, head_ref);
3228 err = check_linear_ancestry(commit_id,
3229 got_worktree_get_base_commit_id(worktree), 0, repo);
3230 if (err) {
3231 if (err->code != GOT_ERR_ANCESTRY)
3232 return err;
3233 ref_has_moved = 1;
3235 if (!ref_has_moved)
3236 return NULL;
3238 /* Switching to a rebased branch with the same reference name. */
3239 err = got_object_id_str(&base_id_str,
3240 got_worktree_get_base_commit_id(worktree));
3241 if (err)
3242 return err;
3243 printf("Reference %s now points at a different branch\n",
3244 got_worktree_get_head_ref_name(worktree));
3245 printf("Switching work tree from %s to %s\n", base_id_str,
3246 got_worktree_get_head_ref_name(worktree));
3247 return NULL;
3250 static const struct got_error *
3251 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3253 const struct got_error *err;
3254 int in_progress;
3256 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3257 if (err)
3258 return err;
3259 if (in_progress)
3260 return got_error(GOT_ERR_REBASING);
3262 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3263 if (err)
3264 return err;
3265 if (in_progress)
3266 return got_error(GOT_ERR_HISTEDIT_BUSY);
3268 return NULL;
3271 static const struct got_error *
3272 check_merge_in_progress(struct got_worktree *worktree,
3273 struct got_repository *repo)
3275 const struct got_error *err;
3276 int in_progress;
3278 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3279 if (err)
3280 return err;
3281 if (in_progress)
3282 return got_error(GOT_ERR_MERGE_BUSY);
3284 return NULL;
3287 static const struct got_error *
3288 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3289 char *argv[], struct got_worktree *worktree)
3291 const struct got_error *err = NULL;
3292 char *path;
3293 struct got_pathlist_entry *new;
3294 int i;
3296 if (argc == 0) {
3297 path = strdup("");
3298 if (path == NULL)
3299 return got_error_from_errno("strdup");
3300 return got_pathlist_append(paths, path, NULL);
3303 for (i = 0; i < argc; i++) {
3304 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3305 if (err)
3306 break;
3307 err = got_pathlist_insert(&new, paths, path, NULL);
3308 if (err || new == NULL /* duplicate */) {
3309 free(path);
3310 if (err)
3311 break;
3315 return err;
3318 static const struct got_error *
3319 wrap_not_worktree_error(const struct got_error *orig_err,
3320 const char *cmdname, const char *path)
3322 const struct got_error *err;
3323 struct got_repository *repo;
3324 static char msg[512];
3325 int *pack_fds = NULL;
3327 err = got_repo_pack_fds_open(&pack_fds);
3328 if (err)
3329 return err;
3331 err = got_repo_open(&repo, path, NULL, pack_fds);
3332 if (err)
3333 return orig_err;
3335 snprintf(msg, sizeof(msg),
3336 "'got %s' needs a work tree in addition to a git repository\n"
3337 "Work trees can be checked out from this Git repository with "
3338 "'got checkout'.\n"
3339 "The got(1) manual page contains more information.", cmdname);
3340 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3341 got_repo_close(repo);
3342 if (pack_fds) {
3343 const struct got_error *pack_err =
3344 got_repo_pack_fds_close(pack_fds);
3345 if (err == NULL)
3346 err = pack_err;
3348 return err;
3351 static const struct got_error *
3352 cmd_update(int argc, char *argv[])
3354 const struct got_error *error = NULL;
3355 struct got_repository *repo = NULL;
3356 struct got_worktree *worktree = NULL;
3357 char *worktree_path = NULL;
3358 struct got_object_id *commit_id = NULL;
3359 char *commit_id_str = NULL;
3360 const char *branch_name = NULL;
3361 struct got_reference *head_ref = NULL;
3362 struct got_pathlist_head paths;
3363 struct got_pathlist_entry *pe;
3364 int ch, verbosity = 0;
3365 struct got_update_progress_arg upa;
3366 int *pack_fds = NULL;
3368 TAILQ_INIT(&paths);
3370 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3371 switch (ch) {
3372 case 'b':
3373 branch_name = optarg;
3374 break;
3375 case 'c':
3376 commit_id_str = strdup(optarg);
3377 if (commit_id_str == NULL)
3378 return got_error_from_errno("strdup");
3379 break;
3380 case 'q':
3381 verbosity = -1;
3382 break;
3383 default:
3384 usage_update();
3385 /* NOTREACHED */
3389 argc -= optind;
3390 argv += optind;
3392 #ifndef PROFILE
3393 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3394 "unveil", NULL) == -1)
3395 err(1, "pledge");
3396 #endif
3397 worktree_path = getcwd(NULL, 0);
3398 if (worktree_path == NULL) {
3399 error = got_error_from_errno("getcwd");
3400 goto done;
3403 error = got_repo_pack_fds_open(&pack_fds);
3404 if (error != NULL)
3405 goto done;
3407 error = got_worktree_open(&worktree, worktree_path);
3408 if (error) {
3409 if (error->code == GOT_ERR_NOT_WORKTREE)
3410 error = wrap_not_worktree_error(error, "update",
3411 worktree_path);
3412 goto done;
3415 error = check_rebase_or_histedit_in_progress(worktree);
3416 if (error)
3417 goto done;
3419 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3420 NULL, pack_fds);
3421 if (error != NULL)
3422 goto done;
3424 error = apply_unveil(got_repo_get_path(repo), 0,
3425 got_worktree_get_root_path(worktree));
3426 if (error)
3427 goto done;
3429 error = check_merge_in_progress(worktree, repo);
3430 if (error)
3431 goto done;
3433 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3434 if (error)
3435 goto done;
3437 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3438 got_worktree_get_head_ref_name(worktree), 0);
3439 if (error != NULL)
3440 goto done;
3441 if (commit_id_str == NULL) {
3442 error = got_ref_resolve(&commit_id, repo, head_ref);
3443 if (error != NULL)
3444 goto done;
3445 error = got_object_id_str(&commit_id_str, commit_id);
3446 if (error != NULL)
3447 goto done;
3448 } else {
3449 struct got_reflist_head refs;
3450 TAILQ_INIT(&refs);
3451 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3452 NULL);
3453 if (error)
3454 goto done;
3455 error = got_repo_match_object_id(&commit_id, NULL,
3456 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3457 got_ref_list_free(&refs);
3458 free(commit_id_str);
3459 commit_id_str = NULL;
3460 if (error)
3461 goto done;
3462 error = got_object_id_str(&commit_id_str, commit_id);
3463 if (error)
3464 goto done;
3467 if (branch_name) {
3468 struct got_object_id *head_commit_id;
3469 TAILQ_FOREACH(pe, &paths, entry) {
3470 if (pe->path_len == 0)
3471 continue;
3472 error = got_error_msg(GOT_ERR_BAD_PATH,
3473 "switching between branches requires that "
3474 "the entire work tree gets updated");
3475 goto done;
3477 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3478 if (error)
3479 goto done;
3480 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3481 repo);
3482 free(head_commit_id);
3483 if (error != NULL)
3484 goto done;
3485 error = check_same_branch(commit_id, head_ref, NULL, repo);
3486 if (error)
3487 goto done;
3488 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3489 if (error)
3490 goto done;
3491 } else {
3492 error = check_linear_ancestry(commit_id,
3493 got_worktree_get_base_commit_id(worktree), 0, repo);
3494 if (error != NULL) {
3495 if (error->code == GOT_ERR_ANCESTRY)
3496 error = got_error(GOT_ERR_BRANCH_MOVED);
3497 goto done;
3499 error = check_same_branch(commit_id, head_ref, NULL, repo);
3500 if (error)
3501 goto done;
3504 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3505 commit_id) != 0) {
3506 error = got_worktree_set_base_commit_id(worktree, repo,
3507 commit_id);
3508 if (error)
3509 goto done;
3512 memset(&upa, 0, sizeof(upa));
3513 upa.verbosity = verbosity;
3514 error = got_worktree_checkout_files(worktree, &paths, repo,
3515 update_progress, &upa, check_cancelled, NULL);
3516 if (error != NULL)
3517 goto done;
3519 if (upa.did_something) {
3520 printf("Updated to %s: %s\n",
3521 got_worktree_get_head_ref_name(worktree), commit_id_str);
3522 } else
3523 printf("Already up-to-date\n");
3525 print_update_progress_stats(&upa);
3526 done:
3527 if (pack_fds) {
3528 const struct got_error *pack_err =
3529 got_repo_pack_fds_close(pack_fds);
3530 if (error == NULL)
3531 error = pack_err;
3533 free(worktree_path);
3534 TAILQ_FOREACH(pe, &paths, entry)
3535 free((char *)pe->path);
3536 got_pathlist_free(&paths);
3537 free(commit_id);
3538 free(commit_id_str);
3539 return error;
3542 static const struct got_error *
3543 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3544 const char *path, int diff_context, int ignore_whitespace,
3545 int force_text_diff, struct got_repository *repo, FILE *outfile)
3547 const struct got_error *err = NULL;
3548 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3549 FILE *f1 = NULL, *f2 = NULL;
3550 int fd1 = -1, fd2 = -1;
3552 fd1 = got_opentempfd();
3553 if (fd1 == -1)
3554 return got_error_from_errno("got_opentempfd");
3555 fd2 = got_opentempfd();
3556 if (fd2 == -1) {
3557 err = got_error_from_errno("got_opentempfd");
3558 goto done;
3561 if (blob_id1) {
3562 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3563 fd1);
3564 if (err)
3565 goto done;
3566 f1 = got_opentemp();
3567 if (f1 == NULL) {
3568 err = got_error_from_errno("got_opentemp");
3569 goto done;
3573 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3574 if (err)
3575 goto done;
3577 f2 = got_opentemp();
3578 if (f2 == NULL) {
3579 err = got_error_from_errno("got_opentemp");
3580 goto done;
3583 while (path[0] == '/')
3584 path++;
3585 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3586 diff_context, ignore_whitespace, force_text_diff, outfile);
3587 done:
3588 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3589 err = got_error_from_errno("close");
3590 if (blob1)
3591 got_object_blob_close(blob1);
3592 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3593 err = got_error_from_errno("close");
3594 got_object_blob_close(blob2);
3595 if (f1 && fclose(f1) == EOF && err == NULL)
3596 err = got_error_from_errno("fclose");
3597 if (f2 && fclose(f2) == EOF && err == NULL)
3598 err = got_error_from_errno("fclose");
3599 return err;
3602 static const struct got_error *
3603 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3604 const char *path, int diff_context, int ignore_whitespace,
3605 int force_text_diff, struct got_repository *repo, FILE *outfile)
3607 const struct got_error *err = NULL;
3608 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3609 struct got_diff_blob_output_unidiff_arg arg;
3610 FILE *f1 = NULL, *f2 = NULL;
3611 int fd1 = -1, fd2 = -1;
3613 if (tree_id1) {
3614 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3615 if (err)
3616 goto done;
3617 f1 = got_opentemp();
3618 if (f1 == NULL) {
3619 err = got_error_from_errno("got_opentemp");
3620 goto done;
3623 fd1 = got_opentempfd();
3624 if (fd1 == -1) {
3625 err = got_error_from_errno("got_opentempfd");
3626 goto done;
3630 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3631 if (err)
3632 goto done;
3634 f2 = got_opentemp();
3635 if (f2 == NULL) {
3636 err = got_error_from_errno("got_opentemp");
3637 goto done;
3639 fd2 = got_opentempfd();
3640 if (fd2 == -1) {
3641 err = got_error_from_errno("got_opentempfd");
3642 goto done;
3644 arg.diff_context = diff_context;
3645 arg.ignore_whitespace = ignore_whitespace;
3646 arg.force_text_diff = force_text_diff;
3647 arg.outfile = outfile;
3648 arg.line_offsets = NULL;
3649 arg.nlines = 0;
3650 while (path[0] == '/')
3651 path++;
3652 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3653 got_diff_blob_output_unidiff, &arg, 1);
3654 done:
3655 if (tree1)
3656 got_object_tree_close(tree1);
3657 if (tree2)
3658 got_object_tree_close(tree2);
3659 if (f1 && fclose(f1) == EOF && err == NULL)
3660 err = got_error_from_errno("fclose");
3661 if (f2 && fclose(f2) == EOF && err == NULL)
3662 err = got_error_from_errno("fclose");
3663 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3664 err = got_error_from_errno("close");
3665 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3666 err = got_error_from_errno("close");
3667 return err;
3670 static const struct got_error *
3671 get_changed_paths(struct got_pathlist_head *paths,
3672 struct got_commit_object *commit, struct got_repository *repo)
3674 const struct got_error *err = NULL;
3675 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3676 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3677 struct got_object_qid *qid;
3679 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3680 if (qid != NULL) {
3681 struct got_commit_object *pcommit;
3682 err = got_object_open_as_commit(&pcommit, repo,
3683 &qid->id);
3684 if (err)
3685 return err;
3687 tree_id1 = got_object_id_dup(
3688 got_object_commit_get_tree_id(pcommit));
3689 if (tree_id1 == NULL) {
3690 got_object_commit_close(pcommit);
3691 return got_error_from_errno("got_object_id_dup");
3693 got_object_commit_close(pcommit);
3697 if (tree_id1) {
3698 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3699 if (err)
3700 goto done;
3703 tree_id2 = got_object_commit_get_tree_id(commit);
3704 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3705 if (err)
3706 goto done;
3708 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3709 got_diff_tree_collect_changed_paths, paths, 0);
3710 done:
3711 if (tree1)
3712 got_object_tree_close(tree1);
3713 if (tree2)
3714 got_object_tree_close(tree2);
3715 free(tree_id1);
3716 return err;
3719 static const struct got_error *
3720 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3721 const char *path, int diff_context, struct got_repository *repo,
3722 FILE *outfile)
3724 const struct got_error *err = NULL;
3725 struct got_commit_object *pcommit = NULL;
3726 char *id_str1 = NULL, *id_str2 = NULL;
3727 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3728 struct got_object_qid *qid;
3730 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3731 if (qid != NULL) {
3732 err = got_object_open_as_commit(&pcommit, repo,
3733 &qid->id);
3734 if (err)
3735 return err;
3736 err = got_object_id_str(&id_str1, &qid->id);
3737 if (err)
3738 goto done;
3741 err = got_object_id_str(&id_str2, id);
3742 if (err)
3743 goto done;
3745 if (path && path[0] != '\0') {
3746 int obj_type;
3747 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3748 if (err)
3749 goto done;
3750 if (pcommit) {
3751 err = got_object_id_by_path(&obj_id1, repo,
3752 pcommit, path);
3753 if (err) {
3754 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3755 free(obj_id2);
3756 goto done;
3760 err = got_object_get_type(&obj_type, repo, obj_id2);
3761 if (err) {
3762 free(obj_id2);
3763 goto done;
3765 fprintf(outfile,
3766 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3767 fprintf(outfile, "commit - %s\n",
3768 id_str1 ? id_str1 : "/dev/null");
3769 fprintf(outfile, "commit + %s\n", id_str2);
3770 switch (obj_type) {
3771 case GOT_OBJ_TYPE_BLOB:
3772 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3773 0, 0, repo, outfile);
3774 break;
3775 case GOT_OBJ_TYPE_TREE:
3776 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3777 0, 0, repo, outfile);
3778 break;
3779 default:
3780 err = got_error(GOT_ERR_OBJ_TYPE);
3781 break;
3783 free(obj_id1);
3784 free(obj_id2);
3785 } else {
3786 obj_id2 = got_object_commit_get_tree_id(commit);
3787 if (pcommit)
3788 obj_id1 = got_object_commit_get_tree_id(pcommit);
3789 fprintf(outfile,
3790 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3791 fprintf(outfile, "commit - %s\n",
3792 id_str1 ? id_str1 : "/dev/null");
3793 fprintf(outfile, "commit + %s\n", id_str2);
3794 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3795 repo, outfile);
3797 done:
3798 free(id_str1);
3799 free(id_str2);
3800 if (pcommit)
3801 got_object_commit_close(pcommit);
3802 return err;
3805 static char *
3806 get_datestr(time_t *time, char *datebuf)
3808 struct tm mytm, *tm;
3809 char *p, *s;
3811 tm = gmtime_r(time, &mytm);
3812 if (tm == NULL)
3813 return NULL;
3814 s = asctime_r(tm, datebuf);
3815 if (s == NULL)
3816 return NULL;
3817 p = strchr(s, '\n');
3818 if (p)
3819 *p = '\0';
3820 return s;
3823 static const struct got_error *
3824 match_commit(int *have_match, struct got_object_id *id,
3825 struct got_commit_object *commit, regex_t *regex)
3827 const struct got_error *err = NULL;
3828 regmatch_t regmatch;
3829 char *id_str = NULL, *logmsg = NULL;
3831 *have_match = 0;
3833 err = got_object_id_str(&id_str, id);
3834 if (err)
3835 return err;
3837 err = got_object_commit_get_logmsg(&logmsg, commit);
3838 if (err)
3839 goto done;
3841 if (regexec(regex, got_object_commit_get_author(commit), 1,
3842 &regmatch, 0) == 0 ||
3843 regexec(regex, got_object_commit_get_committer(commit), 1,
3844 &regmatch, 0) == 0 ||
3845 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3846 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3847 *have_match = 1;
3848 done:
3849 free(id_str);
3850 free(logmsg);
3851 return err;
3854 static void
3855 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3856 regex_t *regex)
3858 regmatch_t regmatch;
3859 struct got_pathlist_entry *pe;
3861 *have_match = 0;
3863 TAILQ_FOREACH(pe, changed_paths, entry) {
3864 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3865 *have_match = 1;
3866 break;
3871 static const struct got_error *
3872 match_patch(int *have_match, struct got_commit_object *commit,
3873 struct got_object_id *id, const char *path, int diff_context,
3874 struct got_repository *repo, regex_t *regex, FILE *f)
3876 const struct got_error *err = NULL;
3877 char *line = NULL;
3878 size_t linesize = 0;
3879 ssize_t linelen;
3880 regmatch_t regmatch;
3882 *have_match = 0;
3884 err = got_opentemp_truncate(f);
3885 if (err)
3886 return err;
3888 err = print_patch(commit, id, path, diff_context, repo, f);
3889 if (err)
3890 goto done;
3892 if (fseeko(f, 0L, SEEK_SET) == -1) {
3893 err = got_error_from_errno("fseeko");
3894 goto done;
3897 while ((linelen = getline(&line, &linesize, f)) != -1) {
3898 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3899 *have_match = 1;
3900 break;
3903 done:
3904 free(line);
3905 return err;
3908 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3910 static const struct got_error*
3911 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3912 struct got_object_id *id, struct got_repository *repo,
3913 int local_only)
3915 static const struct got_error *err = NULL;
3916 struct got_reflist_entry *re;
3917 char *s;
3918 const char *name;
3920 *refs_str = NULL;
3922 TAILQ_FOREACH(re, refs, entry) {
3923 struct got_tag_object *tag = NULL;
3924 struct got_object_id *ref_id;
3925 int cmp;
3927 name = got_ref_get_name(re->ref);
3928 if (strcmp(name, GOT_REF_HEAD) == 0)
3929 continue;
3930 if (strncmp(name, "refs/", 5) == 0)
3931 name += 5;
3932 if (strncmp(name, "got/", 4) == 0)
3933 continue;
3934 if (strncmp(name, "heads/", 6) == 0)
3935 name += 6;
3936 if (strncmp(name, "remotes/", 8) == 0) {
3937 if (local_only)
3938 continue;
3939 name += 8;
3940 s = strstr(name, "/" GOT_REF_HEAD);
3941 if (s != NULL && s[strlen(s)] == '\0')
3942 continue;
3944 err = got_ref_resolve(&ref_id, repo, re->ref);
3945 if (err)
3946 break;
3947 if (strncmp(name, "tags/", 5) == 0) {
3948 err = got_object_open_as_tag(&tag, repo, ref_id);
3949 if (err) {
3950 if (err->code != GOT_ERR_OBJ_TYPE) {
3951 free(ref_id);
3952 break;
3954 /* Ref points at something other than a tag. */
3955 err = NULL;
3956 tag = NULL;
3959 cmp = got_object_id_cmp(tag ?
3960 got_object_tag_get_object_id(tag) : ref_id, id);
3961 free(ref_id);
3962 if (tag)
3963 got_object_tag_close(tag);
3964 if (cmp != 0)
3965 continue;
3966 s = *refs_str;
3967 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3968 s ? ", " : "", name) == -1) {
3969 err = got_error_from_errno("asprintf");
3970 free(s);
3971 *refs_str = NULL;
3972 break;
3974 free(s);
3977 return err;
3980 static const struct got_error *
3981 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3982 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3984 const struct got_error *err = NULL;
3985 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3986 char *comma, *s, *nl;
3987 struct got_reflist_head *refs;
3988 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3989 struct tm tm;
3990 time_t committer_time;
3992 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3993 if (refs) {
3994 err = build_refs_str(&ref_str, refs, id, repo, 1);
3995 if (err)
3996 return err;
3998 /* Display the first matching ref only. */
3999 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4000 *comma = '\0';
4003 if (ref_str == NULL) {
4004 err = got_object_id_str(&id_str, id);
4005 if (err)
4006 return err;
4009 committer_time = got_object_commit_get_committer_time(commit);
4010 if (gmtime_r(&committer_time, &tm) == NULL) {
4011 err = got_error_from_errno("gmtime_r");
4012 goto done;
4014 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4015 err = got_error(GOT_ERR_NO_SPACE);
4016 goto done;
4019 err = got_object_commit_get_logmsg(&logmsg0, commit);
4020 if (err)
4021 goto done;
4023 s = logmsg0;
4024 while (isspace((unsigned char)s[0]))
4025 s++;
4027 nl = strchr(s, '\n');
4028 if (nl) {
4029 *nl = '\0';
4032 if (ref_str)
4033 printf("%s%-7s %s\n", datebuf, ref_str, s);
4034 else
4035 printf("%s%.7s %s\n", datebuf, id_str, s);
4037 if (fflush(stdout) != 0 && err == NULL)
4038 err = got_error_from_errno("fflush");
4039 done:
4040 free(id_str);
4041 free(ref_str);
4042 free(logmsg0);
4043 return err;
4046 static const struct got_error *
4047 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4048 struct got_repository *repo, const char *path,
4049 struct got_pathlist_head *changed_paths, int show_patch,
4050 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4051 const char *custom_refs_str)
4053 const struct got_error *err = NULL;
4054 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4055 char datebuf[26];
4056 time_t committer_time;
4057 const char *author, *committer;
4058 char *refs_str = NULL;
4060 err = got_object_id_str(&id_str, id);
4061 if (err)
4062 return err;
4064 if (custom_refs_str == NULL) {
4065 struct got_reflist_head *refs;
4066 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4067 if (refs) {
4068 err = build_refs_str(&refs_str, refs, id, repo, 0);
4069 if (err)
4070 goto done;
4074 printf(GOT_COMMIT_SEP_STR);
4075 if (custom_refs_str)
4076 printf("commit %s (%s)\n", id_str, custom_refs_str);
4077 else
4078 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4079 refs_str ? refs_str : "", refs_str ? ")" : "");
4080 free(id_str);
4081 id_str = NULL;
4082 free(refs_str);
4083 refs_str = NULL;
4084 printf("from: %s\n", got_object_commit_get_author(commit));
4085 committer_time = got_object_commit_get_committer_time(commit);
4086 datestr = get_datestr(&committer_time, datebuf);
4087 if (datestr)
4088 printf("date: %s UTC\n", datestr);
4089 author = got_object_commit_get_author(commit);
4090 committer = got_object_commit_get_committer(commit);
4091 if (strcmp(author, committer) != 0)
4092 printf("via: %s\n", committer);
4093 if (got_object_commit_get_nparents(commit) > 1) {
4094 const struct got_object_id_queue *parent_ids;
4095 struct got_object_qid *qid;
4096 int n = 1;
4097 parent_ids = got_object_commit_get_parent_ids(commit);
4098 STAILQ_FOREACH(qid, parent_ids, entry) {
4099 err = got_object_id_str(&id_str, &qid->id);
4100 if (err)
4101 goto done;
4102 printf("parent %d: %s\n", n++, id_str);
4103 free(id_str);
4104 id_str = NULL;
4108 err = got_object_commit_get_logmsg(&logmsg0, commit);
4109 if (err)
4110 goto done;
4112 logmsg = logmsg0;
4113 do {
4114 line = strsep(&logmsg, "\n");
4115 if (line)
4116 printf(" %s\n", line);
4117 } while (line);
4118 free(logmsg0);
4120 if (changed_paths) {
4121 struct got_pathlist_entry *pe;
4122 TAILQ_FOREACH(pe, changed_paths, entry) {
4123 struct got_diff_changed_path *cp = pe->data;
4124 printf(" %c %s\n", cp->status, pe->path);
4126 printf("\n");
4128 if (show_patch) {
4129 err = print_patch(commit, id, path, diff_context, repo, stdout);
4130 if (err == 0)
4131 printf("\n");
4134 if (fflush(stdout) != 0 && err == NULL)
4135 err = got_error_from_errno("fflush");
4136 done:
4137 free(id_str);
4138 free(refs_str);
4139 return err;
4142 static const struct got_error *
4143 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4144 struct got_repository *repo, const char *path, int show_changed_paths,
4145 int show_patch, const char *search_pattern, int diff_context, int limit,
4146 int log_branches, int reverse_display_order,
4147 struct got_reflist_object_id_map *refs_idmap, int one_line,
4148 FILE *tmpfile)
4150 const struct got_error *err;
4151 struct got_commit_graph *graph;
4152 regex_t regex;
4153 int have_match;
4154 struct got_object_id_queue reversed_commits;
4155 struct got_object_qid *qid;
4156 struct got_commit_object *commit;
4157 struct got_pathlist_head changed_paths;
4158 struct got_pathlist_entry *pe;
4160 STAILQ_INIT(&reversed_commits);
4161 TAILQ_INIT(&changed_paths);
4163 if (search_pattern && regcomp(&regex, search_pattern,
4164 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4165 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4167 err = got_commit_graph_open(&graph, path, !log_branches);
4168 if (err)
4169 return err;
4170 err = got_commit_graph_iter_start(graph, root_id, repo,
4171 check_cancelled, NULL);
4172 if (err)
4173 goto done;
4174 for (;;) {
4175 struct got_object_id *id;
4177 if (sigint_received || sigpipe_received)
4178 break;
4180 err = got_commit_graph_iter_next(&id, graph, repo,
4181 check_cancelled, NULL);
4182 if (err) {
4183 if (err->code == GOT_ERR_ITER_COMPLETED)
4184 err = NULL;
4185 break;
4187 if (id == NULL)
4188 break;
4190 err = got_object_open_as_commit(&commit, repo, id);
4191 if (err)
4192 break;
4194 if (show_changed_paths && !reverse_display_order) {
4195 err = get_changed_paths(&changed_paths, commit, repo);
4196 if (err)
4197 break;
4200 if (search_pattern) {
4201 err = match_commit(&have_match, id, commit, &regex);
4202 if (err) {
4203 got_object_commit_close(commit);
4204 break;
4206 if (have_match == 0 && show_changed_paths)
4207 match_changed_paths(&have_match,
4208 &changed_paths, &regex);
4209 if (have_match == 0 && show_patch) {
4210 err = match_patch(&have_match, commit, id,
4211 path, diff_context, repo, &regex,
4212 tmpfile);
4213 if (err)
4214 break;
4216 if (have_match == 0) {
4217 got_object_commit_close(commit);
4218 TAILQ_FOREACH(pe, &changed_paths, entry) {
4219 free((char *)pe->path);
4220 free(pe->data);
4222 got_pathlist_free(&changed_paths);
4223 continue;
4227 if (reverse_display_order) {
4228 err = got_object_qid_alloc(&qid, id);
4229 if (err)
4230 break;
4231 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4232 got_object_commit_close(commit);
4233 } else {
4234 if (one_line)
4235 err = print_commit_oneline(commit, id,
4236 repo, refs_idmap);
4237 else
4238 err = print_commit(commit, id, repo, path,
4239 show_changed_paths ? &changed_paths : NULL,
4240 show_patch, diff_context, refs_idmap, NULL);
4241 got_object_commit_close(commit);
4242 if (err)
4243 break;
4245 if ((limit && --limit == 0) ||
4246 (end_id && got_object_id_cmp(id, end_id) == 0))
4247 break;
4249 TAILQ_FOREACH(pe, &changed_paths, entry) {
4250 free((char *)pe->path);
4251 free(pe->data);
4253 got_pathlist_free(&changed_paths);
4255 if (reverse_display_order) {
4256 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4257 err = got_object_open_as_commit(&commit, repo,
4258 &qid->id);
4259 if (err)
4260 break;
4261 if (show_changed_paths) {
4262 err = get_changed_paths(&changed_paths,
4263 commit, repo);
4264 if (err)
4265 break;
4267 if (one_line)
4268 err = print_commit_oneline(commit, &qid->id,
4269 repo, refs_idmap);
4270 else
4271 err = print_commit(commit, &qid->id, repo, path,
4272 show_changed_paths ? &changed_paths : NULL,
4273 show_patch, diff_context, refs_idmap, NULL);
4274 got_object_commit_close(commit);
4275 if (err)
4276 break;
4277 TAILQ_FOREACH(pe, &changed_paths, entry) {
4278 free((char *)pe->path);
4279 free(pe->data);
4281 got_pathlist_free(&changed_paths);
4284 done:
4285 while (!STAILQ_EMPTY(&reversed_commits)) {
4286 qid = STAILQ_FIRST(&reversed_commits);
4287 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4288 got_object_qid_free(qid);
4290 TAILQ_FOREACH(pe, &changed_paths, entry) {
4291 free((char *)pe->path);
4292 free(pe->data);
4294 got_pathlist_free(&changed_paths);
4295 if (search_pattern)
4296 regfree(&regex);
4297 got_commit_graph_close(graph);
4298 return err;
4301 __dead static void
4302 usage_log(void)
4304 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4305 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4306 "[-r repository-path] [-R] [path]\n", getprogname());
4307 exit(1);
4310 static int
4311 get_default_log_limit(void)
4313 const char *got_default_log_limit;
4314 long long n;
4315 const char *errstr;
4317 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4318 if (got_default_log_limit == NULL)
4319 return 0;
4320 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4321 if (errstr != NULL)
4322 return 0;
4323 return n;
4326 static const struct got_error *
4327 cmd_log(int argc, char *argv[])
4329 const struct got_error *error;
4330 struct got_repository *repo = NULL;
4331 struct got_worktree *worktree = NULL;
4332 struct got_object_id *start_id = NULL, *end_id = NULL;
4333 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4334 const char *start_commit = NULL, *end_commit = NULL;
4335 const char *search_pattern = NULL;
4336 int diff_context = -1, ch;
4337 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4338 int reverse_display_order = 0, one_line = 0;
4339 const char *errstr;
4340 struct got_reflist_head refs;
4341 struct got_reflist_object_id_map *refs_idmap = NULL;
4342 FILE *tmpfile = NULL;
4343 int *pack_fds = NULL;
4345 TAILQ_INIT(&refs);
4347 #ifndef PROFILE
4348 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4349 NULL)
4350 == -1)
4351 err(1, "pledge");
4352 #endif
4354 limit = get_default_log_limit();
4356 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4357 switch (ch) {
4358 case 'p':
4359 show_patch = 1;
4360 break;
4361 case 'P':
4362 show_changed_paths = 1;
4363 break;
4364 case 'c':
4365 start_commit = optarg;
4366 break;
4367 case 'C':
4368 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4369 &errstr);
4370 if (errstr != NULL)
4371 errx(1, "number of context lines is %s: %s",
4372 errstr, optarg);
4373 break;
4374 case 'l':
4375 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4376 if (errstr != NULL)
4377 errx(1, "number of commits is %s: %s",
4378 errstr, optarg);
4379 break;
4380 case 'b':
4381 log_branches = 1;
4382 break;
4383 case 'r':
4384 repo_path = realpath(optarg, NULL);
4385 if (repo_path == NULL)
4386 return got_error_from_errno2("realpath",
4387 optarg);
4388 got_path_strip_trailing_slashes(repo_path);
4389 break;
4390 case 'R':
4391 reverse_display_order = 1;
4392 break;
4393 case 's':
4394 one_line = 1;
4395 break;
4396 case 'S':
4397 search_pattern = optarg;
4398 break;
4399 case 'x':
4400 end_commit = optarg;
4401 break;
4402 default:
4403 usage_log();
4404 /* NOTREACHED */
4408 argc -= optind;
4409 argv += optind;
4411 if (diff_context == -1)
4412 diff_context = 3;
4413 else if (!show_patch)
4414 errx(1, "-C requires -p");
4416 if (one_line && (show_patch || show_changed_paths))
4417 errx(1, "cannot use -s with -p or -P");
4419 cwd = getcwd(NULL, 0);
4420 if (cwd == NULL) {
4421 error = got_error_from_errno("getcwd");
4422 goto done;
4425 error = got_repo_pack_fds_open(&pack_fds);
4426 if (error != NULL)
4427 goto done;
4429 if (repo_path == NULL) {
4430 error = got_worktree_open(&worktree, cwd);
4431 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4432 goto done;
4433 error = NULL;
4436 if (argc == 1) {
4437 if (worktree) {
4438 error = got_worktree_resolve_path(&path, worktree,
4439 argv[0]);
4440 if (error)
4441 goto done;
4442 } else {
4443 path = strdup(argv[0]);
4444 if (path == NULL) {
4445 error = got_error_from_errno("strdup");
4446 goto done;
4449 } else if (argc != 0)
4450 usage_log();
4452 if (repo_path == NULL) {
4453 repo_path = worktree ?
4454 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4456 if (repo_path == NULL) {
4457 error = got_error_from_errno("strdup");
4458 goto done;
4461 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4462 if (error != NULL)
4463 goto done;
4465 error = apply_unveil(got_repo_get_path(repo), 1,
4466 worktree ? got_worktree_get_root_path(worktree) : NULL);
4467 if (error)
4468 goto done;
4470 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4471 if (error)
4472 goto done;
4474 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4475 if (error)
4476 goto done;
4478 if (start_commit == NULL) {
4479 struct got_reference *head_ref;
4480 struct got_commit_object *commit = NULL;
4481 error = got_ref_open(&head_ref, repo,
4482 worktree ? got_worktree_get_head_ref_name(worktree)
4483 : GOT_REF_HEAD, 0);
4484 if (error != NULL)
4485 goto done;
4486 error = got_ref_resolve(&start_id, repo, head_ref);
4487 got_ref_close(head_ref);
4488 if (error != NULL)
4489 goto done;
4490 error = got_object_open_as_commit(&commit, repo,
4491 start_id);
4492 if (error != NULL)
4493 goto done;
4494 got_object_commit_close(commit);
4495 } else {
4496 error = got_repo_match_object_id(&start_id, NULL,
4497 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4498 if (error != NULL)
4499 goto done;
4501 if (end_commit != NULL) {
4502 error = got_repo_match_object_id(&end_id, NULL,
4503 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4504 if (error != NULL)
4505 goto done;
4508 if (worktree) {
4510 * If a path was specified on the command line it was resolved
4511 * to a path in the work tree above. Prepend the work tree's
4512 * path prefix to obtain the corresponding in-repository path.
4514 if (path) {
4515 const char *prefix;
4516 prefix = got_worktree_get_path_prefix(worktree);
4517 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4518 (path[0] != '\0') ? "/" : "", path) == -1) {
4519 error = got_error_from_errno("asprintf");
4520 goto done;
4523 } else
4524 error = got_repo_map_path(&in_repo_path, repo,
4525 path ? path : "");
4526 if (error != NULL)
4527 goto done;
4528 if (in_repo_path) {
4529 free(path);
4530 path = in_repo_path;
4533 if (worktree) {
4534 /* Release work tree lock. */
4535 got_worktree_close(worktree);
4536 worktree = NULL;
4539 if (search_pattern && show_patch) {
4540 tmpfile = got_opentemp();
4541 if (tmpfile == NULL) {
4542 error = got_error_from_errno("got_opentemp");
4543 goto done;
4547 error = print_commits(start_id, end_id, repo, path ? path : "",
4548 show_changed_paths, show_patch, search_pattern, diff_context,
4549 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4550 tmpfile);
4551 done:
4552 free(path);
4553 free(repo_path);
4554 free(cwd);
4555 if (worktree)
4556 got_worktree_close(worktree);
4557 if (repo) {
4558 const struct got_error *close_err = got_repo_close(repo);
4559 if (error == NULL)
4560 error = close_err;
4562 if (pack_fds) {
4563 const struct got_error *pack_err =
4564 got_repo_pack_fds_close(pack_fds);
4565 if (error == NULL)
4566 error = pack_err;
4568 if (refs_idmap)
4569 got_reflist_object_id_map_free(refs_idmap);
4570 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4571 error = got_error_from_errno("fclose");
4572 got_ref_list_free(&refs);
4573 return error;
4576 __dead static void
4577 usage_diff(void)
4579 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4580 "[-r repository-path] [-s] [-w] [-P] "
4581 "[object1 object2 | path ...]\n", getprogname());
4582 exit(1);
4585 struct print_diff_arg {
4586 struct got_repository *repo;
4587 struct got_worktree *worktree;
4588 int diff_context;
4589 const char *id_str;
4590 int header_shown;
4591 int diff_staged;
4592 int ignore_whitespace;
4593 int force_text_diff;
4597 * Create a file which contains the target path of a symlink so we can feed
4598 * it as content to the diff engine.
4600 static const struct got_error *
4601 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4602 const char *abspath)
4604 const struct got_error *err = NULL;
4605 char target_path[PATH_MAX];
4606 ssize_t target_len, outlen;
4608 *fd = -1;
4610 if (dirfd != -1) {
4611 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4612 if (target_len == -1)
4613 return got_error_from_errno2("readlinkat", abspath);
4614 } else {
4615 target_len = readlink(abspath, target_path, PATH_MAX);
4616 if (target_len == -1)
4617 return got_error_from_errno2("readlink", abspath);
4620 *fd = got_opentempfd();
4621 if (*fd == -1)
4622 return got_error_from_errno("got_opentempfd");
4624 outlen = write(*fd, target_path, target_len);
4625 if (outlen == -1) {
4626 err = got_error_from_errno("got_opentempfd");
4627 goto done;
4630 if (lseek(*fd, 0, SEEK_SET) == -1) {
4631 err = got_error_from_errno2("lseek", abspath);
4632 goto done;
4634 done:
4635 if (err) {
4636 close(*fd);
4637 *fd = -1;
4639 return err;
4642 static const struct got_error *
4643 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4644 const char *path, struct got_object_id *blob_id,
4645 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4646 int dirfd, const char *de_name)
4648 struct print_diff_arg *a = arg;
4649 const struct got_error *err = NULL;
4650 struct got_blob_object *blob1 = NULL;
4651 int fd = -1, fd1 = -1, fd2 = -1;
4652 FILE *f1 = NULL, *f2 = NULL;
4653 char *abspath = NULL, *label1 = NULL;
4654 struct stat sb;
4655 off_t size1 = 0;
4657 if (a->diff_staged) {
4658 if (staged_status != GOT_STATUS_MODIFY &&
4659 staged_status != GOT_STATUS_ADD &&
4660 staged_status != GOT_STATUS_DELETE)
4661 return NULL;
4662 } else {
4663 if (staged_status == GOT_STATUS_DELETE)
4664 return NULL;
4665 if (status == GOT_STATUS_NONEXISTENT)
4666 return got_error_set_errno(ENOENT, path);
4667 if (status != GOT_STATUS_MODIFY &&
4668 status != GOT_STATUS_ADD &&
4669 status != GOT_STATUS_DELETE &&
4670 status != GOT_STATUS_CONFLICT)
4671 return NULL;
4674 if (!a->header_shown) {
4675 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4676 got_worktree_get_root_path(a->worktree));
4677 printf("commit - %s\n", a->id_str);
4678 printf("path + %s%s\n",
4679 got_worktree_get_root_path(a->worktree),
4680 a->diff_staged ? " (staged changes)" : "");
4681 a->header_shown = 1;
4684 if (a->diff_staged) {
4685 const char *label1 = NULL, *label2 = NULL;
4686 switch (staged_status) {
4687 case GOT_STATUS_MODIFY:
4688 label1 = path;
4689 label2 = path;
4690 break;
4691 case GOT_STATUS_ADD:
4692 label2 = path;
4693 break;
4694 case GOT_STATUS_DELETE:
4695 label1 = path;
4696 break;
4697 default:
4698 return got_error(GOT_ERR_FILE_STATUS);
4700 f1 = got_opentemp();
4701 if (f1 == NULL) {
4702 err = got_error_from_errno("got_opentemp");
4703 goto done;
4705 f2 = got_opentemp();
4706 if (f2 == NULL) {
4707 err = got_error_from_errno("got_opentemp");
4708 goto done;
4710 fd1 = got_opentempfd();
4711 if (fd1 == -1) {
4712 err = got_error_from_errno("got_opentempfd");
4713 goto done;
4715 fd2 = got_opentempfd();
4716 if (fd2 == -1) {
4717 err = got_error_from_errno("got_opentempfd");
4718 goto done;
4720 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2, fd1, fd2,
4721 blob_id, staged_blob_id, label1, label2, a->diff_context,
4722 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4723 goto done;
4726 fd1 = got_opentempfd();
4727 if (fd1 == -1) {
4728 err = got_error_from_errno("got_opentempfd");
4729 goto done;
4732 if (staged_status == GOT_STATUS_ADD ||
4733 staged_status == GOT_STATUS_MODIFY) {
4734 char *id_str;
4735 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4736 8192, fd1);
4737 if (err)
4738 goto done;
4739 err = got_object_id_str(&id_str, staged_blob_id);
4740 if (err)
4741 goto done;
4742 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4743 err = got_error_from_errno("asprintf");
4744 free(id_str);
4745 goto done;
4747 free(id_str);
4748 } else if (status != GOT_STATUS_ADD) {
4749 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4750 fd1);
4751 if (err)
4752 goto done;
4755 if (status != GOT_STATUS_DELETE) {
4756 if (asprintf(&abspath, "%s/%s",
4757 got_worktree_get_root_path(a->worktree), path) == -1) {
4758 err = got_error_from_errno("asprintf");
4759 goto done;
4762 if (dirfd != -1) {
4763 fd = openat(dirfd, de_name,
4764 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4765 if (fd == -1) {
4766 if (!got_err_open_nofollow_on_symlink()) {
4767 err = got_error_from_errno2("openat",
4768 abspath);
4769 goto done;
4771 err = get_symlink_target_file(&fd, dirfd,
4772 de_name, abspath);
4773 if (err)
4774 goto done;
4776 } else {
4777 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4778 if (fd == -1) {
4779 if (!got_err_open_nofollow_on_symlink()) {
4780 err = got_error_from_errno2("open",
4781 abspath);
4782 goto done;
4784 err = get_symlink_target_file(&fd, dirfd,
4785 de_name, abspath);
4786 if (err)
4787 goto done;
4790 if (fstat(fd, &sb) == -1) {
4791 err = got_error_from_errno2("fstat", abspath);
4792 goto done;
4794 f2 = fdopen(fd, "r");
4795 if (f2 == NULL) {
4796 err = got_error_from_errno2("fdopen", abspath);
4797 goto done;
4799 fd = -1;
4800 } else
4801 sb.st_size = 0;
4803 if (blob1) {
4804 f1 = got_opentemp();
4805 if (f1 == NULL) {
4806 err = got_error_from_errno("got_opentemp");
4807 goto done;
4809 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4810 blob1);
4811 if (err)
4812 goto done;
4815 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4816 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4817 stdout);
4818 done:
4819 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4820 err = got_error_from_errno("close");
4821 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4822 err = got_error_from_errno("close");
4823 if (blob1)
4824 got_object_blob_close(blob1);
4825 if (f1 && fclose(f1) == EOF && err == NULL)
4826 err = got_error_from_errno("fclose");
4827 if (f2 && fclose(f2) == EOF && err == NULL)
4828 err = got_error_from_errno("fclose");
4829 if (fd != -1 && close(fd) == -1 && err == NULL)
4830 err = got_error_from_errno("close");
4831 free(abspath);
4832 return err;
4835 static const struct got_error *
4836 cmd_diff(int argc, char *argv[])
4838 const struct got_error *error;
4839 struct got_repository *repo = NULL;
4840 struct got_worktree *worktree = NULL;
4841 char *cwd = NULL, *repo_path = NULL;
4842 const char *commit_args[2] = { NULL, NULL };
4843 int ncommit_args = 0;
4844 struct got_object_id *ids[2] = { NULL, NULL };
4845 char *labels[2] = { NULL, NULL };
4846 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4847 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4848 int force_text_diff = 0, force_path = 0, rflag = 0;
4849 const char *errstr;
4850 struct got_reflist_head refs;
4851 struct got_pathlist_head paths;
4852 struct got_pathlist_entry *pe;
4853 FILE *f1 = NULL, *f2 = NULL;
4854 int fd1 = -1, fd2 = -1;
4855 int *pack_fds = NULL;
4857 TAILQ_INIT(&refs);
4858 TAILQ_INIT(&paths);
4860 #ifndef PROFILE
4861 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4862 NULL) == -1)
4863 err(1, "pledge");
4864 #endif
4866 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4867 switch (ch) {
4868 case 'a':
4869 force_text_diff = 1;
4870 break;
4871 case 'c':
4872 if (ncommit_args >= 2)
4873 errx(1, "too many -c options used");
4874 commit_args[ncommit_args++] = optarg;
4875 break;
4876 case 'C':
4877 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4878 &errstr);
4879 if (errstr != NULL)
4880 errx(1, "number of context lines is %s: %s",
4881 errstr, optarg);
4882 break;
4883 case 'r':
4884 repo_path = realpath(optarg, NULL);
4885 if (repo_path == NULL)
4886 return got_error_from_errno2("realpath",
4887 optarg);
4888 got_path_strip_trailing_slashes(repo_path);
4889 rflag = 1;
4890 break;
4891 case 's':
4892 diff_staged = 1;
4893 break;
4894 case 'w':
4895 ignore_whitespace = 1;
4896 break;
4897 case 'P':
4898 force_path = 1;
4899 break;
4900 default:
4901 usage_diff();
4902 /* NOTREACHED */
4906 argc -= optind;
4907 argv += optind;
4909 cwd = getcwd(NULL, 0);
4910 if (cwd == NULL) {
4911 error = got_error_from_errno("getcwd");
4912 goto done;
4915 error = got_repo_pack_fds_open(&pack_fds);
4916 if (error != NULL)
4917 goto done;
4919 if (repo_path == NULL) {
4920 error = got_worktree_open(&worktree, cwd);
4921 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4922 goto done;
4923 else
4924 error = NULL;
4925 if (worktree) {
4926 repo_path =
4927 strdup(got_worktree_get_repo_path(worktree));
4928 if (repo_path == NULL) {
4929 error = got_error_from_errno("strdup");
4930 goto done;
4932 } else {
4933 repo_path = strdup(cwd);
4934 if (repo_path == NULL) {
4935 error = got_error_from_errno("strdup");
4936 goto done;
4941 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4942 free(repo_path);
4943 if (error != NULL)
4944 goto done;
4946 if (rflag || worktree == NULL || ncommit_args > 0) {
4947 if (force_path) {
4948 error = got_error_msg(GOT_ERR_NOT_IMPL,
4949 "-P option can only be used when diffing "
4950 "a work tree");
4951 goto done;
4953 if (diff_staged) {
4954 error = got_error_msg(GOT_ERR_NOT_IMPL,
4955 "-s option can only be used when diffing "
4956 "a work tree");
4957 goto done;
4961 error = apply_unveil(got_repo_get_path(repo), 1,
4962 worktree ? got_worktree_get_root_path(worktree) : NULL);
4963 if (error)
4964 goto done;
4966 if ((!force_path && argc == 2) || ncommit_args > 0) {
4967 int obj_type = (ncommit_args > 0 ?
4968 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4969 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4970 NULL);
4971 if (error)
4972 goto done;
4973 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4974 const char *arg;
4975 if (ncommit_args > 0)
4976 arg = commit_args[i];
4977 else
4978 arg = argv[i];
4979 error = got_repo_match_object_id(&ids[i], &labels[i],
4980 arg, obj_type, &refs, repo);
4981 if (error) {
4982 if (error->code != GOT_ERR_NOT_REF &&
4983 error->code != GOT_ERR_NO_OBJ)
4984 goto done;
4985 if (ncommit_args > 0)
4986 goto done;
4987 error = NULL;
4988 break;
4993 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4994 struct print_diff_arg arg;
4995 char *id_str;
4997 if (worktree == NULL) {
4998 if (argc == 2 && ids[0] == NULL) {
4999 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5000 goto done;
5001 } else if (argc == 2 && ids[1] == NULL) {
5002 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5003 goto done;
5004 } else if (argc > 0) {
5005 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5006 "%s", "specified paths cannot be resolved");
5007 goto done;
5008 } else {
5009 error = got_error(GOT_ERR_NOT_WORKTREE);
5010 goto done;
5014 error = get_worktree_paths_from_argv(&paths, argc, argv,
5015 worktree);
5016 if (error)
5017 goto done;
5019 error = got_object_id_str(&id_str,
5020 got_worktree_get_base_commit_id(worktree));
5021 if (error)
5022 goto done;
5023 arg.repo = repo;
5024 arg.worktree = worktree;
5025 arg.diff_context = diff_context;
5026 arg.id_str = id_str;
5027 arg.header_shown = 0;
5028 arg.diff_staged = diff_staged;
5029 arg.ignore_whitespace = ignore_whitespace;
5030 arg.force_text_diff = force_text_diff;
5032 error = got_worktree_status(worktree, &paths, repo, 0,
5033 print_diff, &arg, check_cancelled, NULL);
5034 free(id_str);
5035 goto done;
5038 if (ncommit_args == 1) {
5039 struct got_commit_object *commit;
5040 error = got_object_open_as_commit(&commit, repo, ids[0]);
5041 if (error)
5042 goto done;
5044 labels[1] = labels[0];
5045 ids[1] = ids[0];
5046 if (got_object_commit_get_nparents(commit) > 0) {
5047 const struct got_object_id_queue *pids;
5048 struct got_object_qid *pid;
5049 pids = got_object_commit_get_parent_ids(commit);
5050 pid = STAILQ_FIRST(pids);
5051 ids[0] = got_object_id_dup(&pid->id);
5052 if (ids[0] == NULL) {
5053 error = got_error_from_errno(
5054 "got_object_id_dup");
5055 got_object_commit_close(commit);
5056 goto done;
5058 error = got_object_id_str(&labels[0], ids[0]);
5059 if (error) {
5060 got_object_commit_close(commit);
5061 goto done;
5063 } else {
5064 ids[0] = NULL;
5065 labels[0] = strdup("/dev/null");
5066 if (labels[0] == NULL) {
5067 error = got_error_from_errno("strdup");
5068 got_object_commit_close(commit);
5069 goto done;
5073 got_object_commit_close(commit);
5076 if (ncommit_args == 0 && argc > 2) {
5077 error = got_error_msg(GOT_ERR_BAD_PATH,
5078 "path arguments cannot be used when diffing two objects");
5079 goto done;
5082 if (ids[0]) {
5083 error = got_object_get_type(&type1, repo, ids[0]);
5084 if (error)
5085 goto done;
5088 error = got_object_get_type(&type2, repo, ids[1]);
5089 if (error)
5090 goto done;
5091 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5092 error = got_error(GOT_ERR_OBJ_TYPE);
5093 goto done;
5095 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5096 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5097 "path arguments cannot be used when diffing blobs");
5098 goto done;
5101 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5102 char *in_repo_path;
5103 struct got_pathlist_entry *new;
5104 if (worktree) {
5105 const char *prefix;
5106 char *p;
5107 error = got_worktree_resolve_path(&p, worktree,
5108 argv[i]);
5109 if (error)
5110 goto done;
5111 prefix = got_worktree_get_path_prefix(worktree);
5112 while (prefix[0] == '/')
5113 prefix++;
5114 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5115 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5116 p) == -1) {
5117 error = got_error_from_errno("asprintf");
5118 free(p);
5119 goto done;
5121 free(p);
5122 } else {
5123 char *mapped_path, *s;
5124 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5125 if (error)
5126 goto done;
5127 s = mapped_path;
5128 while (s[0] == '/')
5129 s++;
5130 in_repo_path = strdup(s);
5131 if (in_repo_path == NULL) {
5132 error = got_error_from_errno("asprintf");
5133 free(mapped_path);
5134 goto done;
5136 free(mapped_path);
5139 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5140 if (error || new == NULL /* duplicate */)
5141 free(in_repo_path);
5142 if (error)
5143 goto done;
5146 if (worktree) {
5147 /* Release work tree lock. */
5148 got_worktree_close(worktree);
5149 worktree = NULL;
5152 f1 = got_opentemp();
5153 if (f1 == NULL) {
5154 error = got_error_from_errno("got_opentemp");
5155 goto done;
5158 f2 = got_opentemp();
5159 if (f2 == NULL) {
5160 error = got_error_from_errno("got_opentemp");
5161 goto done;
5164 fd1 = got_opentempfd();
5165 if (fd1 == -1) {
5166 error = got_error_from_errno("got_opentempfd");
5167 goto done;
5170 fd2 = got_opentempfd();
5171 if (fd2 == -1) {
5172 error = got_error_from_errno("got_opentempfd");
5173 goto done;
5176 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5177 case GOT_OBJ_TYPE_BLOB:
5178 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5179 fd1, fd2, ids[0], ids[1], NULL, NULL, diff_context,
5180 ignore_whitespace, force_text_diff, repo, stdout);
5181 break;
5182 case GOT_OBJ_TYPE_TREE:
5183 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5184 ids[0], ids[1], &paths, "", "", diff_context,
5185 ignore_whitespace, force_text_diff, repo, stdout);
5186 break;
5187 case GOT_OBJ_TYPE_COMMIT:
5188 printf("diff %s %s\n", labels[0], labels[1]);
5189 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5190 fd1, fd2, ids[0], ids[1], &paths, diff_context,
5191 ignore_whitespace, force_text_diff, repo, stdout);
5192 break;
5193 default:
5194 error = got_error(GOT_ERR_OBJ_TYPE);
5196 done:
5197 free(labels[0]);
5198 free(labels[1]);
5199 free(ids[0]);
5200 free(ids[1]);
5201 if (worktree)
5202 got_worktree_close(worktree);
5203 if (repo) {
5204 const struct got_error *close_err = got_repo_close(repo);
5205 if (error == NULL)
5206 error = close_err;
5208 if (pack_fds) {
5209 const struct got_error *pack_err =
5210 got_repo_pack_fds_close(pack_fds);
5211 if (error == NULL)
5212 error = pack_err;
5214 TAILQ_FOREACH(pe, &paths, entry)
5215 free((char *)pe->path);
5216 got_pathlist_free(&paths);
5217 got_ref_list_free(&refs);
5218 if (f1 && fclose(f1) == EOF && error == NULL)
5219 error = got_error_from_errno("fclose");
5220 if (f2 && fclose(f2) == EOF && error == NULL)
5221 error = got_error_from_errno("fclose");
5222 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5223 error = got_error_from_errno("close");
5224 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5225 error = got_error_from_errno("close");
5226 return error;
5229 __dead static void
5230 usage_blame(void)
5232 fprintf(stderr,
5233 "usage: %s blame [-c commit] [-r repository-path] path\n",
5234 getprogname());
5235 exit(1);
5238 struct blame_line {
5239 int annotated;
5240 char *id_str;
5241 char *committer;
5242 char datebuf[11]; /* YYYY-MM-DD + NUL */
5245 struct blame_cb_args {
5246 struct blame_line *lines;
5247 int nlines;
5248 int nlines_prec;
5249 int lineno_cur;
5250 off_t *line_offsets;
5251 FILE *f;
5252 struct got_repository *repo;
5255 static const struct got_error *
5256 blame_cb(void *arg, int nlines, int lineno,
5257 struct got_commit_object *commit, struct got_object_id *id)
5259 const struct got_error *err = NULL;
5260 struct blame_cb_args *a = arg;
5261 struct blame_line *bline;
5262 char *line = NULL;
5263 size_t linesize = 0;
5264 off_t offset;
5265 struct tm tm;
5266 time_t committer_time;
5268 if (nlines != a->nlines ||
5269 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5270 return got_error(GOT_ERR_RANGE);
5272 if (sigint_received)
5273 return got_error(GOT_ERR_ITER_COMPLETED);
5275 if (lineno == -1)
5276 return NULL; /* no change in this commit */
5278 /* Annotate this line. */
5279 bline = &a->lines[lineno - 1];
5280 if (bline->annotated)
5281 return NULL;
5282 err = got_object_id_str(&bline->id_str, id);
5283 if (err)
5284 return err;
5286 bline->committer = strdup(got_object_commit_get_committer(commit));
5287 if (bline->committer == NULL) {
5288 err = got_error_from_errno("strdup");
5289 goto done;
5292 committer_time = got_object_commit_get_committer_time(commit);
5293 if (gmtime_r(&committer_time, &tm) == NULL)
5294 return got_error_from_errno("gmtime_r");
5295 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5296 &tm) == 0) {
5297 err = got_error(GOT_ERR_NO_SPACE);
5298 goto done;
5300 bline->annotated = 1;
5302 /* Print lines annotated so far. */
5303 bline = &a->lines[a->lineno_cur - 1];
5304 if (!bline->annotated)
5305 goto done;
5307 offset = a->line_offsets[a->lineno_cur - 1];
5308 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5309 err = got_error_from_errno("fseeko");
5310 goto done;
5313 while (bline->annotated) {
5314 char *smallerthan, *at, *nl, *committer;
5315 size_t len;
5317 if (getline(&line, &linesize, a->f) == -1) {
5318 if (ferror(a->f))
5319 err = got_error_from_errno("getline");
5320 break;
5323 committer = bline->committer;
5324 smallerthan = strchr(committer, '<');
5325 if (smallerthan && smallerthan[1] != '\0')
5326 committer = smallerthan + 1;
5327 at = strchr(committer, '@');
5328 if (at)
5329 *at = '\0';
5330 len = strlen(committer);
5331 if (len >= 9)
5332 committer[8] = '\0';
5334 nl = strchr(line, '\n');
5335 if (nl)
5336 *nl = '\0';
5337 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5338 bline->id_str, bline->datebuf, committer, line);
5340 a->lineno_cur++;
5341 bline = &a->lines[a->lineno_cur - 1];
5343 done:
5344 free(line);
5345 return err;
5348 static const struct got_error *
5349 cmd_blame(int argc, char *argv[])
5351 const struct got_error *error;
5352 struct got_repository *repo = NULL;
5353 struct got_worktree *worktree = NULL;
5354 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5355 char *link_target = NULL;
5356 struct got_object_id *obj_id = NULL;
5357 struct got_object_id *commit_id = NULL;
5358 struct got_commit_object *commit = NULL;
5359 struct got_blob_object *blob = NULL;
5360 char *commit_id_str = NULL;
5361 struct blame_cb_args bca;
5362 int ch, obj_type, i, fd = -1, fd1 = -1;
5363 off_t filesize;
5364 int *pack_fds = NULL;
5366 fd = got_opentempfd();
5367 if (fd == -1)
5368 return got_error_from_errno("got_opentempfd");
5370 memset(&bca, 0, sizeof(bca));
5372 #ifndef PROFILE
5373 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5374 NULL) == -1)
5375 err(1, "pledge");
5376 #endif
5378 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5379 switch (ch) {
5380 case 'c':
5381 commit_id_str = optarg;
5382 break;
5383 case 'r':
5384 repo_path = realpath(optarg, NULL);
5385 if (repo_path == NULL)
5386 return got_error_from_errno2("realpath",
5387 optarg);
5388 got_path_strip_trailing_slashes(repo_path);
5389 break;
5390 default:
5391 usage_blame();
5392 /* NOTREACHED */
5396 argc -= optind;
5397 argv += optind;
5399 if (argc == 1)
5400 path = argv[0];
5401 else
5402 usage_blame();
5404 cwd = getcwd(NULL, 0);
5405 if (cwd == NULL) {
5406 error = got_error_from_errno("getcwd");
5407 goto done;
5410 error = got_repo_pack_fds_open(&pack_fds);
5411 if (error != NULL)
5412 goto done;
5414 if (repo_path == NULL) {
5415 error = got_worktree_open(&worktree, cwd);
5416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5417 goto done;
5418 else
5419 error = NULL;
5420 if (worktree) {
5421 repo_path =
5422 strdup(got_worktree_get_repo_path(worktree));
5423 if (repo_path == NULL) {
5424 error = got_error_from_errno("strdup");
5425 if (error)
5426 goto done;
5428 } else {
5429 repo_path = strdup(cwd);
5430 if (repo_path == NULL) {
5431 error = got_error_from_errno("strdup");
5432 goto done;
5437 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5438 if (error != NULL)
5439 goto done;
5441 if (worktree) {
5442 const char *prefix = got_worktree_get_path_prefix(worktree);
5443 char *p;
5445 error = got_worktree_resolve_path(&p, worktree, path);
5446 if (error)
5447 goto done;
5448 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5449 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5450 p) == -1) {
5451 error = got_error_from_errno("asprintf");
5452 free(p);
5453 goto done;
5455 free(p);
5456 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5457 } else {
5458 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5459 if (error)
5460 goto done;
5461 error = got_repo_map_path(&in_repo_path, repo, path);
5463 if (error)
5464 goto done;
5466 if (commit_id_str == NULL) {
5467 struct got_reference *head_ref;
5468 error = got_ref_open(&head_ref, repo, worktree ?
5469 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5470 if (error != NULL)
5471 goto done;
5472 error = got_ref_resolve(&commit_id, repo, head_ref);
5473 got_ref_close(head_ref);
5474 if (error != NULL)
5475 goto done;
5476 } else {
5477 struct got_reflist_head refs;
5478 TAILQ_INIT(&refs);
5479 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5480 NULL);
5481 if (error)
5482 goto done;
5483 error = got_repo_match_object_id(&commit_id, NULL,
5484 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5485 got_ref_list_free(&refs);
5486 if (error)
5487 goto done;
5490 if (worktree) {
5491 /* Release work tree lock. */
5492 got_worktree_close(worktree);
5493 worktree = NULL;
5496 error = got_object_open_as_commit(&commit, repo, commit_id);
5497 if (error)
5498 goto done;
5500 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5501 commit, repo);
5502 if (error)
5503 goto done;
5505 error = got_object_id_by_path(&obj_id, repo, commit,
5506 link_target ? link_target : in_repo_path);
5507 if (error)
5508 goto done;
5510 error = got_object_get_type(&obj_type, repo, obj_id);
5511 if (error)
5512 goto done;
5514 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5515 error = got_error_path(link_target ? link_target : in_repo_path,
5516 GOT_ERR_OBJ_TYPE);
5517 goto done;
5520 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd);
5521 if (error)
5522 goto done;
5523 bca.f = got_opentemp();
5524 if (bca.f == NULL) {
5525 error = got_error_from_errno("got_opentemp");
5526 goto done;
5528 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5529 &bca.line_offsets, bca.f, blob);
5530 if (error || bca.nlines == 0)
5531 goto done;
5533 /* Don't include \n at EOF in the blame line count. */
5534 if (bca.line_offsets[bca.nlines - 1] == filesize)
5535 bca.nlines--;
5537 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5538 if (bca.lines == NULL) {
5539 error = got_error_from_errno("calloc");
5540 goto done;
5542 bca.lineno_cur = 1;
5543 bca.nlines_prec = 0;
5544 i = bca.nlines;
5545 while (i > 0) {
5546 i /= 10;
5547 bca.nlines_prec++;
5549 bca.repo = repo;
5551 fd1 = got_opentempfd();
5552 if (fd1 == -1) {
5553 error = got_error_from_errno("got_opentempfd");
5554 goto done;
5556 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5557 repo, blame_cb, &bca, check_cancelled, NULL, fd1);
5558 done:
5559 free(in_repo_path);
5560 free(link_target);
5561 free(repo_path);
5562 free(cwd);
5563 free(commit_id);
5564 free(obj_id);
5565 if (commit)
5566 got_object_commit_close(commit);
5567 if (fd != -1 && close(fd) == -1 && error == NULL)
5568 error = got_error_from_errno("close");
5569 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5570 error = got_error_from_errno("close");
5571 if (blob)
5572 got_object_blob_close(blob);
5573 if (worktree)
5574 got_worktree_close(worktree);
5575 if (repo) {
5576 const struct got_error *close_err = got_repo_close(repo);
5577 if (error == NULL)
5578 error = close_err;
5580 if (pack_fds) {
5581 const struct got_error *pack_err =
5582 got_repo_pack_fds_close(pack_fds);
5583 if (error == NULL)
5584 error = pack_err;
5586 if (bca.lines) {
5587 for (i = 0; i < bca.nlines; i++) {
5588 struct blame_line *bline = &bca.lines[i];
5589 free(bline->id_str);
5590 free(bline->committer);
5592 free(bca.lines);
5594 free(bca.line_offsets);
5595 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5596 error = got_error_from_errno("fclose");
5597 return error;
5600 __dead static void
5601 usage_tree(void)
5603 fprintf(stderr,
5604 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5605 getprogname());
5606 exit(1);
5609 static const struct got_error *
5610 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5611 const char *root_path, struct got_repository *repo)
5613 const struct got_error *err = NULL;
5614 int is_root_path = (strcmp(path, root_path) == 0);
5615 const char *modestr = "";
5616 mode_t mode = got_tree_entry_get_mode(te);
5617 char *link_target = NULL;
5619 path += strlen(root_path);
5620 while (path[0] == '/')
5621 path++;
5623 if (got_object_tree_entry_is_submodule(te))
5624 modestr = "$";
5625 else if (S_ISLNK(mode)) {
5626 int i;
5628 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5629 if (err)
5630 return err;
5631 for (i = 0; i < strlen(link_target); i++) {
5632 if (!isprint((unsigned char)link_target[i]))
5633 link_target[i] = '?';
5636 modestr = "@";
5638 else if (S_ISDIR(mode))
5639 modestr = "/";
5640 else if (mode & S_IXUSR)
5641 modestr = "*";
5643 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5644 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5645 link_target ? " -> ": "", link_target ? link_target : "");
5647 free(link_target);
5648 return NULL;
5651 static const struct got_error *
5652 print_tree(const char *path, struct got_commit_object *commit,
5653 int show_ids, int recurse, const char *root_path,
5654 struct got_repository *repo)
5656 const struct got_error *err = NULL;
5657 struct got_object_id *tree_id = NULL;
5658 struct got_tree_object *tree = NULL;
5659 int nentries, i;
5661 err = got_object_id_by_path(&tree_id, repo, commit, path);
5662 if (err)
5663 goto done;
5665 err = got_object_open_as_tree(&tree, repo, tree_id);
5666 if (err)
5667 goto done;
5668 nentries = got_object_tree_get_nentries(tree);
5669 for (i = 0; i < nentries; i++) {
5670 struct got_tree_entry *te;
5671 char *id = NULL;
5673 if (sigint_received || sigpipe_received)
5674 break;
5676 te = got_object_tree_get_entry(tree, i);
5677 if (show_ids) {
5678 char *id_str;
5679 err = got_object_id_str(&id_str,
5680 got_tree_entry_get_id(te));
5681 if (err)
5682 goto done;
5683 if (asprintf(&id, "%s ", id_str) == -1) {
5684 err = got_error_from_errno("asprintf");
5685 free(id_str);
5686 goto done;
5688 free(id_str);
5690 err = print_entry(te, id, path, root_path, repo);
5691 free(id);
5692 if (err)
5693 goto done;
5695 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5696 char *child_path;
5697 if (asprintf(&child_path, "%s%s%s", path,
5698 path[0] == '/' && path[1] == '\0' ? "" : "/",
5699 got_tree_entry_get_name(te)) == -1) {
5700 err = got_error_from_errno("asprintf");
5701 goto done;
5703 err = print_tree(child_path, commit, show_ids, 1,
5704 root_path, repo);
5705 free(child_path);
5706 if (err)
5707 goto done;
5710 done:
5711 if (tree)
5712 got_object_tree_close(tree);
5713 free(tree_id);
5714 return err;
5717 static const struct got_error *
5718 cmd_tree(int argc, char *argv[])
5720 const struct got_error *error;
5721 struct got_repository *repo = NULL;
5722 struct got_worktree *worktree = NULL;
5723 const char *path, *refname = NULL;
5724 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5725 struct got_object_id *commit_id = NULL;
5726 struct got_commit_object *commit = NULL;
5727 char *commit_id_str = NULL;
5728 int show_ids = 0, recurse = 0;
5729 int ch;
5730 int *pack_fds = NULL;
5732 #ifndef PROFILE
5733 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5734 NULL) == -1)
5735 err(1, "pledge");
5736 #endif
5738 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5739 switch (ch) {
5740 case 'c':
5741 commit_id_str = optarg;
5742 break;
5743 case 'r':
5744 repo_path = realpath(optarg, NULL);
5745 if (repo_path == NULL)
5746 return got_error_from_errno2("realpath",
5747 optarg);
5748 got_path_strip_trailing_slashes(repo_path);
5749 break;
5750 case 'i':
5751 show_ids = 1;
5752 break;
5753 case 'R':
5754 recurse = 1;
5755 break;
5756 default:
5757 usage_tree();
5758 /* NOTREACHED */
5762 argc -= optind;
5763 argv += optind;
5765 if (argc == 1)
5766 path = argv[0];
5767 else if (argc > 1)
5768 usage_tree();
5769 else
5770 path = NULL;
5772 cwd = getcwd(NULL, 0);
5773 if (cwd == NULL) {
5774 error = got_error_from_errno("getcwd");
5775 goto done;
5778 error = got_repo_pack_fds_open(&pack_fds);
5779 if (error != NULL)
5780 goto done;
5782 if (repo_path == NULL) {
5783 error = got_worktree_open(&worktree, cwd);
5784 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5785 goto done;
5786 else
5787 error = NULL;
5788 if (worktree) {
5789 repo_path =
5790 strdup(got_worktree_get_repo_path(worktree));
5791 if (repo_path == NULL)
5792 error = got_error_from_errno("strdup");
5793 if (error)
5794 goto done;
5795 } else {
5796 repo_path = strdup(cwd);
5797 if (repo_path == NULL) {
5798 error = got_error_from_errno("strdup");
5799 goto done;
5804 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5805 if (error != NULL)
5806 goto done;
5808 if (worktree) {
5809 const char *prefix = got_worktree_get_path_prefix(worktree);
5810 char *p;
5812 if (path == NULL)
5813 path = "";
5814 error = got_worktree_resolve_path(&p, worktree, path);
5815 if (error)
5816 goto done;
5817 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5818 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5819 p) == -1) {
5820 error = got_error_from_errno("asprintf");
5821 free(p);
5822 goto done;
5824 free(p);
5825 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5826 if (error)
5827 goto done;
5828 } else {
5829 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5830 if (error)
5831 goto done;
5832 if (path == NULL)
5833 path = "/";
5834 error = got_repo_map_path(&in_repo_path, repo, path);
5835 if (error != NULL)
5836 goto done;
5839 if (commit_id_str == NULL) {
5840 struct got_reference *head_ref;
5841 if (worktree)
5842 refname = got_worktree_get_head_ref_name(worktree);
5843 else
5844 refname = GOT_REF_HEAD;
5845 error = got_ref_open(&head_ref, repo, refname, 0);
5846 if (error != NULL)
5847 goto done;
5848 error = got_ref_resolve(&commit_id, repo, head_ref);
5849 got_ref_close(head_ref);
5850 if (error != NULL)
5851 goto done;
5852 } else {
5853 struct got_reflist_head refs;
5854 TAILQ_INIT(&refs);
5855 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5856 NULL);
5857 if (error)
5858 goto done;
5859 error = got_repo_match_object_id(&commit_id, NULL,
5860 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5861 got_ref_list_free(&refs);
5862 if (error)
5863 goto done;
5866 if (worktree) {
5867 /* Release work tree lock. */
5868 got_worktree_close(worktree);
5869 worktree = NULL;
5872 error = got_object_open_as_commit(&commit, repo, commit_id);
5873 if (error)
5874 goto done;
5876 error = print_tree(in_repo_path, commit, show_ids, recurse,
5877 in_repo_path, repo);
5878 done:
5879 free(in_repo_path);
5880 free(repo_path);
5881 free(cwd);
5882 free(commit_id);
5883 if (commit)
5884 got_object_commit_close(commit);
5885 if (worktree)
5886 got_worktree_close(worktree);
5887 if (repo) {
5888 const struct got_error *close_err = got_repo_close(repo);
5889 if (error == NULL)
5890 error = close_err;
5892 if (pack_fds) {
5893 const struct got_error *pack_err =
5894 got_repo_pack_fds_close(pack_fds);
5895 if (error == NULL)
5896 error = pack_err;
5898 return error;
5901 __dead static void
5902 usage_status(void)
5904 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5905 "[-S status-codes] [path ...]\n", getprogname());
5906 exit(1);
5909 struct got_status_arg {
5910 char *status_codes;
5911 int suppress;
5914 static const struct got_error *
5915 print_status(void *arg, unsigned char status, unsigned char staged_status,
5916 const char *path, struct got_object_id *blob_id,
5917 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5918 int dirfd, const char *de_name)
5920 struct got_status_arg *st = arg;
5922 if (status == staged_status && (status == GOT_STATUS_DELETE))
5923 status = GOT_STATUS_NO_CHANGE;
5924 if (st != NULL && st->status_codes) {
5925 size_t ncodes = strlen(st->status_codes);
5926 int i, j = 0;
5928 for (i = 0; i < ncodes ; i++) {
5929 if (st->suppress) {
5930 if (status == st->status_codes[i] ||
5931 staged_status == st->status_codes[i]) {
5932 j++;
5933 continue;
5935 } else {
5936 if (status == st->status_codes[i] ||
5937 staged_status == st->status_codes[i])
5938 break;
5942 if (st->suppress && j == 0)
5943 goto print;
5945 if (i == ncodes)
5946 return NULL;
5948 print:
5949 printf("%c%c %s\n", status, staged_status, path);
5950 return NULL;
5953 static const struct got_error *
5954 cmd_status(int argc, char *argv[])
5956 const struct got_error *error = NULL;
5957 struct got_repository *repo = NULL;
5958 struct got_worktree *worktree = NULL;
5959 struct got_status_arg st;
5960 char *cwd = NULL;
5961 struct got_pathlist_head paths;
5962 struct got_pathlist_entry *pe;
5963 int ch, i, no_ignores = 0;
5964 int *pack_fds = NULL;
5966 TAILQ_INIT(&paths);
5968 memset(&st, 0, sizeof(st));
5969 st.status_codes = NULL;
5970 st.suppress = 0;
5972 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5973 switch (ch) {
5974 case 'I':
5975 no_ignores = 1;
5976 break;
5977 case 'S':
5978 if (st.status_codes != NULL && st.suppress == 0)
5979 option_conflict('S', 's');
5980 st.suppress = 1;
5981 /* fallthrough */
5982 case 's':
5983 for (i = 0; i < strlen(optarg); i++) {
5984 switch (optarg[i]) {
5985 case GOT_STATUS_MODIFY:
5986 case GOT_STATUS_ADD:
5987 case GOT_STATUS_DELETE:
5988 case GOT_STATUS_CONFLICT:
5989 case GOT_STATUS_MISSING:
5990 case GOT_STATUS_OBSTRUCTED:
5991 case GOT_STATUS_UNVERSIONED:
5992 case GOT_STATUS_MODE_CHANGE:
5993 case GOT_STATUS_NONEXISTENT:
5994 break;
5995 default:
5996 errx(1, "invalid status code '%c'",
5997 optarg[i]);
6000 if (ch == 's' && st.suppress)
6001 option_conflict('s', 'S');
6002 st.status_codes = optarg;
6003 break;
6004 default:
6005 usage_status();
6006 /* NOTREACHED */
6010 argc -= optind;
6011 argv += optind;
6013 #ifndef PROFILE
6014 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6015 NULL) == -1)
6016 err(1, "pledge");
6017 #endif
6018 cwd = getcwd(NULL, 0);
6019 if (cwd == NULL) {
6020 error = got_error_from_errno("getcwd");
6021 goto done;
6024 error = got_repo_pack_fds_open(&pack_fds);
6025 if (error != NULL)
6026 goto done;
6028 error = got_worktree_open(&worktree, cwd);
6029 if (error) {
6030 if (error->code == GOT_ERR_NOT_WORKTREE)
6031 error = wrap_not_worktree_error(error, "status", cwd);
6032 goto done;
6035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6036 NULL, pack_fds);
6037 if (error != NULL)
6038 goto done;
6040 error = apply_unveil(got_repo_get_path(repo), 1,
6041 got_worktree_get_root_path(worktree));
6042 if (error)
6043 goto done;
6045 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6046 if (error)
6047 goto done;
6049 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6050 print_status, &st, check_cancelled, NULL);
6051 done:
6052 if (pack_fds) {
6053 const struct got_error *pack_err =
6054 got_repo_pack_fds_close(pack_fds);
6055 if (error == NULL)
6056 error = pack_err;
6059 TAILQ_FOREACH(pe, &paths, entry)
6060 free((char *)pe->path);
6061 got_pathlist_free(&paths);
6062 free(cwd);
6063 return error;
6066 __dead static void
6067 usage_ref(void)
6069 fprintf(stderr,
6070 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6071 "[-s reference] [-d] [name]\n",
6072 getprogname());
6073 exit(1);
6076 static const struct got_error *
6077 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6079 static const struct got_error *err = NULL;
6080 struct got_reflist_head refs;
6081 struct got_reflist_entry *re;
6083 TAILQ_INIT(&refs);
6084 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6085 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6086 repo);
6087 if (err)
6088 return err;
6090 TAILQ_FOREACH(re, &refs, entry) {
6091 char *refstr;
6092 refstr = got_ref_to_str(re->ref);
6093 if (refstr == NULL) {
6094 err = got_error_from_errno("got_ref_to_str");
6095 break;
6097 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6098 free(refstr);
6101 got_ref_list_free(&refs);
6102 return err;
6105 static const struct got_error *
6106 delete_ref_by_name(struct got_repository *repo, const char *refname)
6108 const struct got_error *err;
6109 struct got_reference *ref;
6111 err = got_ref_open(&ref, repo, refname, 0);
6112 if (err)
6113 return err;
6115 err = delete_ref(repo, ref);
6116 got_ref_close(ref);
6117 return err;
6120 static const struct got_error *
6121 add_ref(struct got_repository *repo, const char *refname, const char *target)
6123 const struct got_error *err = NULL;
6124 struct got_object_id *id = NULL;
6125 struct got_reference *ref = NULL;
6126 struct got_reflist_head refs;
6129 * Don't let the user create a reference name with a leading '-'.
6130 * While technically a valid reference name, this case is usually
6131 * an unintended typo.
6133 if (refname[0] == '-')
6134 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6136 TAILQ_INIT(&refs);
6137 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6138 if (err)
6139 goto done;
6140 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6141 &refs, repo);
6142 got_ref_list_free(&refs);
6143 if (err)
6144 goto done;
6146 err = got_ref_alloc(&ref, refname, id);
6147 if (err)
6148 goto done;
6150 err = got_ref_write(ref, repo);
6151 done:
6152 if (ref)
6153 got_ref_close(ref);
6154 free(id);
6155 return err;
6158 static const struct got_error *
6159 add_symref(struct got_repository *repo, const char *refname, const char *target)
6161 const struct got_error *err = NULL;
6162 struct got_reference *ref = NULL;
6163 struct got_reference *target_ref = NULL;
6166 * Don't let the user create a reference name with a leading '-'.
6167 * While technically a valid reference name, this case is usually
6168 * an unintended typo.
6170 if (refname[0] == '-')
6171 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6173 err = got_ref_open(&target_ref, repo, target, 0);
6174 if (err)
6175 return err;
6177 err = got_ref_alloc_symref(&ref, refname, target_ref);
6178 if (err)
6179 goto done;
6181 err = got_ref_write(ref, repo);
6182 done:
6183 if (target_ref)
6184 got_ref_close(target_ref);
6185 if (ref)
6186 got_ref_close(ref);
6187 return err;
6190 static const struct got_error *
6191 cmd_ref(int argc, char *argv[])
6193 const struct got_error *error = NULL;
6194 struct got_repository *repo = NULL;
6195 struct got_worktree *worktree = NULL;
6196 char *cwd = NULL, *repo_path = NULL;
6197 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6198 const char *obj_arg = NULL, *symref_target= NULL;
6199 char *refname = NULL;
6200 int *pack_fds = NULL;
6202 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6203 switch (ch) {
6204 case 'c':
6205 obj_arg = optarg;
6206 break;
6207 case 'd':
6208 do_delete = 1;
6209 break;
6210 case 'r':
6211 repo_path = realpath(optarg, NULL);
6212 if (repo_path == NULL)
6213 return got_error_from_errno2("realpath",
6214 optarg);
6215 got_path_strip_trailing_slashes(repo_path);
6216 break;
6217 case 'l':
6218 do_list = 1;
6219 break;
6220 case 's':
6221 symref_target = optarg;
6222 break;
6223 case 't':
6224 sort_by_time = 1;
6225 break;
6226 default:
6227 usage_ref();
6228 /* NOTREACHED */
6232 if (obj_arg && do_list)
6233 option_conflict('c', 'l');
6234 if (obj_arg && do_delete)
6235 option_conflict('c', 'd');
6236 if (obj_arg && symref_target)
6237 option_conflict('c', 's');
6238 if (symref_target && do_delete)
6239 option_conflict('s', 'd');
6240 if (symref_target && do_list)
6241 option_conflict('s', 'l');
6242 if (do_delete && do_list)
6243 option_conflict('d', 'l');
6244 if (sort_by_time && !do_list)
6245 errx(1, "-t option requires -l option");
6247 argc -= optind;
6248 argv += optind;
6250 if (do_list) {
6251 if (argc != 0 && argc != 1)
6252 usage_ref();
6253 if (argc == 1) {
6254 refname = strdup(argv[0]);
6255 if (refname == NULL) {
6256 error = got_error_from_errno("strdup");
6257 goto done;
6260 } else {
6261 if (argc != 1)
6262 usage_ref();
6263 refname = strdup(argv[0]);
6264 if (refname == NULL) {
6265 error = got_error_from_errno("strdup");
6266 goto done;
6270 if (refname)
6271 got_path_strip_trailing_slashes(refname);
6273 #ifndef PROFILE
6274 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6275 "sendfd unveil", NULL) == -1)
6276 err(1, "pledge");
6277 #endif
6278 cwd = getcwd(NULL, 0);
6279 if (cwd == NULL) {
6280 error = got_error_from_errno("getcwd");
6281 goto done;
6284 error = got_repo_pack_fds_open(&pack_fds);
6285 if (error != NULL)
6286 goto done;
6288 if (repo_path == NULL) {
6289 error = got_worktree_open(&worktree, cwd);
6290 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6291 goto done;
6292 else
6293 error = NULL;
6294 if (worktree) {
6295 repo_path =
6296 strdup(got_worktree_get_repo_path(worktree));
6297 if (repo_path == NULL)
6298 error = got_error_from_errno("strdup");
6299 if (error)
6300 goto done;
6301 } else {
6302 repo_path = strdup(cwd);
6303 if (repo_path == NULL) {
6304 error = got_error_from_errno("strdup");
6305 goto done;
6310 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6311 if (error != NULL)
6312 goto done;
6314 #ifndef PROFILE
6315 if (do_list) {
6316 /* Remove "cpath" promise. */
6317 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6318 NULL) == -1)
6319 err(1, "pledge");
6321 #endif
6323 error = apply_unveil(got_repo_get_path(repo), do_list,
6324 worktree ? got_worktree_get_root_path(worktree) : NULL);
6325 if (error)
6326 goto done;
6328 if (do_list)
6329 error = list_refs(repo, refname, sort_by_time);
6330 else if (do_delete)
6331 error = delete_ref_by_name(repo, refname);
6332 else if (symref_target)
6333 error = add_symref(repo, refname, symref_target);
6334 else {
6335 if (obj_arg == NULL)
6336 usage_ref();
6337 error = add_ref(repo, refname, obj_arg);
6339 done:
6340 free(refname);
6341 if (repo) {
6342 const struct got_error *close_err = got_repo_close(repo);
6343 if (error == NULL)
6344 error = close_err;
6346 if (worktree)
6347 got_worktree_close(worktree);
6348 if (pack_fds) {
6349 const struct got_error *pack_err =
6350 got_repo_pack_fds_close(pack_fds);
6351 if (error == NULL)
6352 error = pack_err;
6354 free(cwd);
6355 free(repo_path);
6356 return error;
6359 __dead static void
6360 usage_branch(void)
6362 fprintf(stderr,
6363 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6364 "[-n] [name]\n", getprogname());
6365 exit(1);
6368 static const struct got_error *
6369 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6370 struct got_reference *ref)
6372 const struct got_error *err = NULL;
6373 const char *refname, *marker = " ";
6374 char *refstr;
6376 refname = got_ref_get_name(ref);
6377 if (worktree && strcmp(refname,
6378 got_worktree_get_head_ref_name(worktree)) == 0) {
6379 struct got_object_id *id = NULL;
6381 err = got_ref_resolve(&id, repo, ref);
6382 if (err)
6383 return err;
6384 if (got_object_id_cmp(id,
6385 got_worktree_get_base_commit_id(worktree)) == 0)
6386 marker = "* ";
6387 else
6388 marker = "~ ";
6389 free(id);
6392 if (strncmp(refname, "refs/heads/", 11) == 0)
6393 refname += 11;
6394 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6395 refname += 18;
6396 if (strncmp(refname, "refs/remotes/", 13) == 0)
6397 refname += 13;
6399 refstr = got_ref_to_str(ref);
6400 if (refstr == NULL)
6401 return got_error_from_errno("got_ref_to_str");
6403 printf("%s%s: %s\n", marker, refname, refstr);
6404 free(refstr);
6405 return NULL;
6408 static const struct got_error *
6409 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6411 const char *refname;
6413 if (worktree == NULL)
6414 return got_error(GOT_ERR_NOT_WORKTREE);
6416 refname = got_worktree_get_head_ref_name(worktree);
6418 if (strncmp(refname, "refs/heads/", 11) == 0)
6419 refname += 11;
6420 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6421 refname += 18;
6423 printf("%s\n", refname);
6425 return NULL;
6428 static const struct got_error *
6429 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6430 int sort_by_time)
6432 static const struct got_error *err = NULL;
6433 struct got_reflist_head refs;
6434 struct got_reflist_entry *re;
6435 struct got_reference *temp_ref = NULL;
6436 int rebase_in_progress, histedit_in_progress;
6438 TAILQ_INIT(&refs);
6440 if (worktree) {
6441 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6442 worktree);
6443 if (err)
6444 return err;
6446 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6447 worktree);
6448 if (err)
6449 return err;
6451 if (rebase_in_progress || histedit_in_progress) {
6452 err = got_ref_open(&temp_ref, repo,
6453 got_worktree_get_head_ref_name(worktree), 0);
6454 if (err)
6455 return err;
6456 list_branch(repo, worktree, temp_ref);
6457 got_ref_close(temp_ref);
6461 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6462 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6463 repo);
6464 if (err)
6465 return err;
6467 TAILQ_FOREACH(re, &refs, entry)
6468 list_branch(repo, worktree, re->ref);
6470 got_ref_list_free(&refs);
6472 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6473 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6474 repo);
6475 if (err)
6476 return err;
6478 TAILQ_FOREACH(re, &refs, entry)
6479 list_branch(repo, worktree, re->ref);
6481 got_ref_list_free(&refs);
6483 return NULL;
6486 static const struct got_error *
6487 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6488 const char *branch_name)
6490 const struct got_error *err = NULL;
6491 struct got_reference *ref = NULL;
6492 char *refname, *remote_refname = NULL;
6494 if (strncmp(branch_name, "refs/", 5) == 0)
6495 branch_name += 5;
6496 if (strncmp(branch_name, "heads/", 6) == 0)
6497 branch_name += 6;
6498 else if (strncmp(branch_name, "remotes/", 8) == 0)
6499 branch_name += 8;
6501 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6502 return got_error_from_errno("asprintf");
6504 if (asprintf(&remote_refname, "refs/remotes/%s",
6505 branch_name) == -1) {
6506 err = got_error_from_errno("asprintf");
6507 goto done;
6510 err = got_ref_open(&ref, repo, refname, 0);
6511 if (err) {
6512 const struct got_error *err2;
6513 if (err->code != GOT_ERR_NOT_REF)
6514 goto done;
6516 * Keep 'err' intact such that if neither branch exists
6517 * we report "refs/heads" rather than "refs/remotes" in
6518 * our error message.
6520 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6521 if (err2)
6522 goto done;
6523 err = NULL;
6526 if (worktree &&
6527 strcmp(got_worktree_get_head_ref_name(worktree),
6528 got_ref_get_name(ref)) == 0) {
6529 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6530 "will not delete this work tree's current branch");
6531 goto done;
6534 err = delete_ref(repo, ref);
6535 done:
6536 if (ref)
6537 got_ref_close(ref);
6538 free(refname);
6539 free(remote_refname);
6540 return err;
6543 static const struct got_error *
6544 add_branch(struct got_repository *repo, const char *branch_name,
6545 struct got_object_id *base_commit_id)
6547 const struct got_error *err = NULL;
6548 struct got_reference *ref = NULL;
6549 char *base_refname = NULL, *refname = NULL;
6552 * Don't let the user create a branch name with a leading '-'.
6553 * While technically a valid reference name, this case is usually
6554 * an unintended typo.
6556 if (branch_name[0] == '-')
6557 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6559 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6560 branch_name += 11;
6562 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6563 err = got_error_from_errno("asprintf");
6564 goto done;
6567 err = got_ref_open(&ref, repo, refname, 0);
6568 if (err == NULL) {
6569 err = got_error(GOT_ERR_BRANCH_EXISTS);
6570 goto done;
6571 } else if (err->code != GOT_ERR_NOT_REF)
6572 goto done;
6574 err = got_ref_alloc(&ref, refname, base_commit_id);
6575 if (err)
6576 goto done;
6578 err = got_ref_write(ref, repo);
6579 done:
6580 if (ref)
6581 got_ref_close(ref);
6582 free(base_refname);
6583 free(refname);
6584 return err;
6587 static const struct got_error *
6588 cmd_branch(int argc, char *argv[])
6590 const struct got_error *error = NULL;
6591 struct got_repository *repo = NULL;
6592 struct got_worktree *worktree = NULL;
6593 char *cwd = NULL, *repo_path = NULL;
6594 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6595 const char *delref = NULL, *commit_id_arg = NULL;
6596 struct got_reference *ref = NULL;
6597 struct got_pathlist_head paths;
6598 struct got_pathlist_entry *pe;
6599 struct got_object_id *commit_id = NULL;
6600 char *commit_id_str = NULL;
6601 int *pack_fds = NULL;
6603 TAILQ_INIT(&paths);
6605 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6606 switch (ch) {
6607 case 'c':
6608 commit_id_arg = optarg;
6609 break;
6610 case 'd':
6611 delref = optarg;
6612 break;
6613 case 'r':
6614 repo_path = realpath(optarg, NULL);
6615 if (repo_path == NULL)
6616 return got_error_from_errno2("realpath",
6617 optarg);
6618 got_path_strip_trailing_slashes(repo_path);
6619 break;
6620 case 'l':
6621 do_list = 1;
6622 break;
6623 case 'n':
6624 do_update = 0;
6625 break;
6626 case 't':
6627 sort_by_time = 1;
6628 break;
6629 default:
6630 usage_branch();
6631 /* NOTREACHED */
6635 if (do_list && delref)
6636 option_conflict('l', 'd');
6637 if (sort_by_time && !do_list)
6638 errx(1, "-t option requires -l option");
6640 argc -= optind;
6641 argv += optind;
6643 if (!do_list && !delref && argc == 0)
6644 do_show = 1;
6646 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6647 errx(1, "-c option can only be used when creating a branch");
6649 if (do_list || delref) {
6650 if (argc > 0)
6651 usage_branch();
6652 } else if (!do_show && argc != 1)
6653 usage_branch();
6655 #ifndef PROFILE
6656 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6657 "sendfd unveil", NULL) == -1)
6658 err(1, "pledge");
6659 #endif
6660 cwd = getcwd(NULL, 0);
6661 if (cwd == NULL) {
6662 error = got_error_from_errno("getcwd");
6663 goto done;
6666 error = got_repo_pack_fds_open(&pack_fds);
6667 if (error != NULL)
6668 goto done;
6670 if (repo_path == NULL) {
6671 error = got_worktree_open(&worktree, cwd);
6672 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6673 goto done;
6674 else
6675 error = NULL;
6676 if (worktree) {
6677 repo_path =
6678 strdup(got_worktree_get_repo_path(worktree));
6679 if (repo_path == NULL)
6680 error = got_error_from_errno("strdup");
6681 if (error)
6682 goto done;
6683 } else {
6684 repo_path = strdup(cwd);
6685 if (repo_path == NULL) {
6686 error = got_error_from_errno("strdup");
6687 goto done;
6692 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6693 if (error != NULL)
6694 goto done;
6696 #ifndef PROFILE
6697 if (do_list || do_show) {
6698 /* Remove "cpath" promise. */
6699 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6700 NULL) == -1)
6701 err(1, "pledge");
6703 #endif
6705 error = apply_unveil(got_repo_get_path(repo), do_list,
6706 worktree ? got_worktree_get_root_path(worktree) : NULL);
6707 if (error)
6708 goto done;
6710 if (do_show)
6711 error = show_current_branch(repo, worktree);
6712 else if (do_list)
6713 error = list_branches(repo, worktree, sort_by_time);
6714 else if (delref)
6715 error = delete_branch(repo, worktree, delref);
6716 else {
6717 struct got_reflist_head refs;
6718 TAILQ_INIT(&refs);
6719 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6720 NULL);
6721 if (error)
6722 goto done;
6723 if (commit_id_arg == NULL)
6724 commit_id_arg = worktree ?
6725 got_worktree_get_head_ref_name(worktree) :
6726 GOT_REF_HEAD;
6727 error = got_repo_match_object_id(&commit_id, NULL,
6728 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6729 got_ref_list_free(&refs);
6730 if (error)
6731 goto done;
6732 error = add_branch(repo, argv[0], commit_id);
6733 if (error)
6734 goto done;
6735 if (worktree && do_update) {
6736 struct got_update_progress_arg upa;
6737 char *branch_refname = NULL;
6739 error = got_object_id_str(&commit_id_str, commit_id);
6740 if (error)
6741 goto done;
6742 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6743 worktree);
6744 if (error)
6745 goto done;
6746 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6747 == -1) {
6748 error = got_error_from_errno("asprintf");
6749 goto done;
6751 error = got_ref_open(&ref, repo, branch_refname, 0);
6752 free(branch_refname);
6753 if (error)
6754 goto done;
6755 error = switch_head_ref(ref, commit_id, worktree,
6756 repo);
6757 if (error)
6758 goto done;
6759 error = got_worktree_set_base_commit_id(worktree, repo,
6760 commit_id);
6761 if (error)
6762 goto done;
6763 memset(&upa, 0, sizeof(upa));
6764 error = got_worktree_checkout_files(worktree, &paths,
6765 repo, update_progress, &upa, check_cancelled,
6766 NULL);
6767 if (error)
6768 goto done;
6769 if (upa.did_something) {
6770 printf("Updated to %s: %s\n",
6771 got_worktree_get_head_ref_name(worktree),
6772 commit_id_str);
6774 print_update_progress_stats(&upa);
6777 done:
6778 if (ref)
6779 got_ref_close(ref);
6780 if (repo) {
6781 const struct got_error *close_err = got_repo_close(repo);
6782 if (error == NULL)
6783 error = close_err;
6785 if (worktree)
6786 got_worktree_close(worktree);
6787 if (pack_fds) {
6788 const struct got_error *pack_err =
6789 got_repo_pack_fds_close(pack_fds);
6790 if (error == NULL)
6791 error = pack_err;
6793 free(cwd);
6794 free(repo_path);
6795 free(commit_id);
6796 free(commit_id_str);
6797 TAILQ_FOREACH(pe, &paths, entry)
6798 free((char *)pe->path);
6799 got_pathlist_free(&paths);
6800 return error;
6804 __dead static void
6805 usage_tag(void)
6807 fprintf(stderr,
6808 "usage: %s tag [-c commit] [-r repository] [-l] "
6809 "[-m message] name\n", getprogname());
6810 exit(1);
6813 #if 0
6814 static const struct got_error *
6815 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6817 const struct got_error *err = NULL;
6818 struct got_reflist_entry *re, *se, *new;
6819 struct got_object_id *re_id, *se_id;
6820 struct got_tag_object *re_tag, *se_tag;
6821 time_t re_time, se_time;
6823 STAILQ_FOREACH(re, tags, entry) {
6824 se = STAILQ_FIRST(sorted);
6825 if (se == NULL) {
6826 err = got_reflist_entry_dup(&new, re);
6827 if (err)
6828 return err;
6829 STAILQ_INSERT_HEAD(sorted, new, entry);
6830 continue;
6831 } else {
6832 err = got_ref_resolve(&re_id, repo, re->ref);
6833 if (err)
6834 break;
6835 err = got_object_open_as_tag(&re_tag, repo, re_id);
6836 free(re_id);
6837 if (err)
6838 break;
6839 re_time = got_object_tag_get_tagger_time(re_tag);
6840 got_object_tag_close(re_tag);
6843 while (se) {
6844 err = got_ref_resolve(&se_id, repo, re->ref);
6845 if (err)
6846 break;
6847 err = got_object_open_as_tag(&se_tag, repo, se_id);
6848 free(se_id);
6849 if (err)
6850 break;
6851 se_time = got_object_tag_get_tagger_time(se_tag);
6852 got_object_tag_close(se_tag);
6854 if (se_time > re_time) {
6855 err = got_reflist_entry_dup(&new, re);
6856 if (err)
6857 return err;
6858 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6859 break;
6861 se = STAILQ_NEXT(se, entry);
6862 continue;
6865 done:
6866 return err;
6868 #endif
6870 static const struct got_error *
6871 get_tag_refname(char **refname, const char *tag_name)
6873 const struct got_error *err;
6875 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6876 *refname = strdup(tag_name);
6877 if (*refname == NULL)
6878 return got_error_from_errno("strdup");
6879 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6880 err = got_error_from_errno("asprintf");
6881 *refname = NULL;
6882 return err;
6885 return NULL;
6888 static const struct got_error *
6889 list_tags(struct got_repository *repo, const char *tag_name)
6891 static const struct got_error *err = NULL;
6892 struct got_reflist_head refs;
6893 struct got_reflist_entry *re;
6894 char *wanted_refname = NULL;
6896 TAILQ_INIT(&refs);
6898 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6899 if (err)
6900 return err;
6902 if (tag_name) {
6903 struct got_reference *ref;
6904 err = get_tag_refname(&wanted_refname, tag_name);
6905 if (err)
6906 goto done;
6907 /* Wanted tag reference should exist. */
6908 err = got_ref_open(&ref, repo, wanted_refname, 0);
6909 if (err)
6910 goto done;
6911 got_ref_close(ref);
6914 TAILQ_FOREACH(re, &refs, entry) {
6915 const char *refname;
6916 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6917 char datebuf[26];
6918 const char *tagger;
6919 time_t tagger_time;
6920 struct got_object_id *id;
6921 struct got_tag_object *tag;
6922 struct got_commit_object *commit = NULL;
6924 refname = got_ref_get_name(re->ref);
6925 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6926 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6927 continue;
6928 refname += 10;
6929 refstr = got_ref_to_str(re->ref);
6930 if (refstr == NULL) {
6931 err = got_error_from_errno("got_ref_to_str");
6932 break;
6934 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6935 free(refstr);
6937 err = got_ref_resolve(&id, repo, re->ref);
6938 if (err)
6939 break;
6940 err = got_object_open_as_tag(&tag, repo, id);
6941 if (err) {
6942 if (err->code != GOT_ERR_OBJ_TYPE) {
6943 free(id);
6944 break;
6946 /* "lightweight" tag */
6947 err = got_object_open_as_commit(&commit, repo, id);
6948 if (err) {
6949 free(id);
6950 break;
6952 tagger = got_object_commit_get_committer(commit);
6953 tagger_time =
6954 got_object_commit_get_committer_time(commit);
6955 err = got_object_id_str(&id_str, id);
6956 free(id);
6957 if (err)
6958 break;
6959 } else {
6960 free(id);
6961 tagger = got_object_tag_get_tagger(tag);
6962 tagger_time = got_object_tag_get_tagger_time(tag);
6963 err = got_object_id_str(&id_str,
6964 got_object_tag_get_object_id(tag));
6965 if (err)
6966 break;
6968 printf("from: %s\n", tagger);
6969 datestr = get_datestr(&tagger_time, datebuf);
6970 if (datestr)
6971 printf("date: %s UTC\n", datestr);
6972 if (commit)
6973 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6974 else {
6975 switch (got_object_tag_get_object_type(tag)) {
6976 case GOT_OBJ_TYPE_BLOB:
6977 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6978 id_str);
6979 break;
6980 case GOT_OBJ_TYPE_TREE:
6981 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6982 id_str);
6983 break;
6984 case GOT_OBJ_TYPE_COMMIT:
6985 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6986 id_str);
6987 break;
6988 case GOT_OBJ_TYPE_TAG:
6989 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6990 id_str);
6991 break;
6992 default:
6993 break;
6996 free(id_str);
6997 if (commit) {
6998 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6999 if (err)
7000 break;
7001 got_object_commit_close(commit);
7002 } else {
7003 tagmsg0 = strdup(got_object_tag_get_message(tag));
7004 got_object_tag_close(tag);
7005 if (tagmsg0 == NULL) {
7006 err = got_error_from_errno("strdup");
7007 break;
7011 tagmsg = tagmsg0;
7012 do {
7013 line = strsep(&tagmsg, "\n");
7014 if (line)
7015 printf(" %s\n", line);
7016 } while (line);
7017 free(tagmsg0);
7019 done:
7020 got_ref_list_free(&refs);
7021 free(wanted_refname);
7022 return err;
7025 static const struct got_error *
7026 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7027 const char *tag_name, const char *repo_path)
7029 const struct got_error *err = NULL;
7030 char *template = NULL, *initial_content = NULL;
7031 char *editor = NULL;
7032 int initial_content_len;
7033 int fd = -1;
7035 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7036 err = got_error_from_errno("asprintf");
7037 goto done;
7040 initial_content_len = asprintf(&initial_content,
7041 "\n# tagging commit %s as %s\n",
7042 commit_id_str, tag_name);
7043 if (initial_content_len == -1) {
7044 err = got_error_from_errno("asprintf");
7045 goto done;
7048 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7049 if (err)
7050 goto done;
7052 if (write(fd, initial_content, initial_content_len) == -1) {
7053 err = got_error_from_errno2("write", *tagmsg_path);
7054 goto done;
7057 err = get_editor(&editor);
7058 if (err)
7059 goto done;
7060 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7061 initial_content_len, 1);
7062 done:
7063 free(initial_content);
7064 free(template);
7065 free(editor);
7067 if (fd != -1 && close(fd) == -1 && err == NULL)
7068 err = got_error_from_errno2("close", *tagmsg_path);
7070 /* Editor is done; we can now apply unveil(2) */
7071 if (err == NULL)
7072 err = apply_unveil(repo_path, 0, NULL);
7073 if (err) {
7074 free(*tagmsg);
7075 *tagmsg = NULL;
7077 return err;
7080 static const struct got_error *
7081 add_tag(struct got_repository *repo, const char *tagger,
7082 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
7084 const struct got_error *err = NULL;
7085 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7086 char *label = NULL, *commit_id_str = NULL;
7087 struct got_reference *ref = NULL;
7088 char *refname = NULL, *tagmsg = NULL;
7089 char *tagmsg_path = NULL, *tag_id_str = NULL;
7090 int preserve_tagmsg = 0;
7091 struct got_reflist_head refs;
7093 TAILQ_INIT(&refs);
7096 * Don't let the user create a tag name with a leading '-'.
7097 * While technically a valid reference name, this case is usually
7098 * an unintended typo.
7100 if (tag_name[0] == '-')
7101 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7103 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7104 if (err)
7105 goto done;
7107 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7108 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7109 if (err)
7110 goto done;
7112 err = got_object_id_str(&commit_id_str, commit_id);
7113 if (err)
7114 goto done;
7116 err = get_tag_refname(&refname, tag_name);
7117 if (err)
7118 goto done;
7119 if (strncmp("refs/tags/", tag_name, 10) == 0)
7120 tag_name += 10;
7122 err = got_ref_open(&ref, repo, refname, 0);
7123 if (err == NULL) {
7124 err = got_error(GOT_ERR_TAG_EXISTS);
7125 goto done;
7126 } else if (err->code != GOT_ERR_NOT_REF)
7127 goto done;
7129 if (tagmsg_arg == NULL) {
7130 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7131 tag_name, got_repo_get_path(repo));
7132 if (err) {
7133 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7134 tagmsg_path != NULL)
7135 preserve_tagmsg = 1;
7136 goto done;
7140 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7141 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
7142 if (err) {
7143 if (tagmsg_path)
7144 preserve_tagmsg = 1;
7145 goto done;
7148 err = got_ref_alloc(&ref, refname, tag_id);
7149 if (err) {
7150 if (tagmsg_path)
7151 preserve_tagmsg = 1;
7152 goto done;
7155 err = got_ref_write(ref, repo);
7156 if (err) {
7157 if (tagmsg_path)
7158 preserve_tagmsg = 1;
7159 goto done;
7162 err = got_object_id_str(&tag_id_str, tag_id);
7163 if (err) {
7164 if (tagmsg_path)
7165 preserve_tagmsg = 1;
7166 goto done;
7168 printf("Created tag %s\n", tag_id_str);
7169 done:
7170 if (preserve_tagmsg) {
7171 fprintf(stderr, "%s: tag message preserved in %s\n",
7172 getprogname(), tagmsg_path);
7173 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7174 err = got_error_from_errno2("unlink", tagmsg_path);
7175 free(tag_id_str);
7176 if (ref)
7177 got_ref_close(ref);
7178 free(commit_id);
7179 free(commit_id_str);
7180 free(refname);
7181 free(tagmsg);
7182 free(tagmsg_path);
7183 got_ref_list_free(&refs);
7184 return err;
7187 static const struct got_error *
7188 cmd_tag(int argc, char *argv[])
7190 const struct got_error *error = NULL;
7191 struct got_repository *repo = NULL;
7192 struct got_worktree *worktree = NULL;
7193 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7194 char *gitconfig_path = NULL, *tagger = NULL;
7195 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7196 int ch, do_list = 0;
7197 int *pack_fds = NULL;
7199 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
7200 switch (ch) {
7201 case 'c':
7202 commit_id_arg = optarg;
7203 break;
7204 case 'm':
7205 tagmsg = optarg;
7206 break;
7207 case 'r':
7208 repo_path = realpath(optarg, NULL);
7209 if (repo_path == NULL)
7210 return got_error_from_errno2("realpath",
7211 optarg);
7212 got_path_strip_trailing_slashes(repo_path);
7213 break;
7214 case 'l':
7215 do_list = 1;
7216 break;
7217 default:
7218 usage_tag();
7219 /* NOTREACHED */
7223 argc -= optind;
7224 argv += optind;
7226 if (do_list) {
7227 if (commit_id_arg != NULL)
7228 errx(1,
7229 "-c option can only be used when creating a tag");
7230 if (tagmsg)
7231 option_conflict('l', 'm');
7232 if (argc > 1)
7233 usage_tag();
7234 } else if (argc != 1)
7235 usage_tag();
7237 if (argc == 1)
7238 tag_name = argv[0];
7240 #ifndef PROFILE
7241 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7242 "sendfd unveil", NULL) == -1)
7243 err(1, "pledge");
7244 #endif
7245 cwd = getcwd(NULL, 0);
7246 if (cwd == NULL) {
7247 error = got_error_from_errno("getcwd");
7248 goto done;
7251 error = got_repo_pack_fds_open(&pack_fds);
7252 if (error != NULL)
7253 goto done;
7255 if (repo_path == NULL) {
7256 error = got_worktree_open(&worktree, cwd);
7257 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7258 goto done;
7259 else
7260 error = NULL;
7261 if (worktree) {
7262 repo_path =
7263 strdup(got_worktree_get_repo_path(worktree));
7264 if (repo_path == NULL)
7265 error = got_error_from_errno("strdup");
7266 if (error)
7267 goto done;
7268 } else {
7269 repo_path = strdup(cwd);
7270 if (repo_path == NULL) {
7271 error = got_error_from_errno("strdup");
7272 goto done;
7277 if (do_list) {
7278 if (worktree) {
7279 /* Release work tree lock. */
7280 got_worktree_close(worktree);
7281 worktree = NULL;
7283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7284 if (error != NULL)
7285 goto done;
7287 #ifndef PROFILE
7288 /* Remove "cpath" promise. */
7289 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7290 NULL) == -1)
7291 err(1, "pledge");
7292 #endif
7293 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7294 if (error)
7295 goto done;
7296 error = list_tags(repo, tag_name);
7297 } else {
7298 error = get_gitconfig_path(&gitconfig_path);
7299 if (error)
7300 goto done;
7301 error = got_repo_open(&repo, repo_path, gitconfig_path,
7302 pack_fds);
7303 if (error != NULL)
7304 goto done;
7306 error = get_author(&tagger, repo, worktree);
7307 if (error)
7308 goto done;
7309 if (worktree) {
7310 /* Release work tree lock. */
7311 got_worktree_close(worktree);
7312 worktree = NULL;
7315 if (tagmsg) {
7316 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7317 if (error)
7318 goto done;
7321 if (commit_id_arg == NULL) {
7322 struct got_reference *head_ref;
7323 struct got_object_id *commit_id;
7324 error = got_ref_open(&head_ref, repo,
7325 worktree ? got_worktree_get_head_ref_name(worktree)
7326 : GOT_REF_HEAD, 0);
7327 if (error)
7328 goto done;
7329 error = got_ref_resolve(&commit_id, repo, head_ref);
7330 got_ref_close(head_ref);
7331 if (error)
7332 goto done;
7333 error = got_object_id_str(&commit_id_str, commit_id);
7334 free(commit_id);
7335 if (error)
7336 goto done;
7339 error = add_tag(repo, tagger, tag_name,
7340 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
7342 done:
7343 if (repo) {
7344 const struct got_error *close_err = got_repo_close(repo);
7345 if (error == NULL)
7346 error = close_err;
7348 if (worktree)
7349 got_worktree_close(worktree);
7350 if (pack_fds) {
7351 const struct got_error *pack_err =
7352 got_repo_pack_fds_close(pack_fds);
7353 if (error == NULL)
7354 error = pack_err;
7356 free(cwd);
7357 free(repo_path);
7358 free(gitconfig_path);
7359 free(commit_id_str);
7360 free(tagger);
7361 return error;
7364 __dead static void
7365 usage_add(void)
7367 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7368 getprogname());
7369 exit(1);
7372 static const struct got_error *
7373 add_progress(void *arg, unsigned char status, const char *path)
7375 while (path[0] == '/')
7376 path++;
7377 printf("%c %s\n", status, path);
7378 return NULL;
7381 static const struct got_error *
7382 cmd_add(int argc, char *argv[])
7384 const struct got_error *error = NULL;
7385 struct got_repository *repo = NULL;
7386 struct got_worktree *worktree = NULL;
7387 char *cwd = NULL;
7388 struct got_pathlist_head paths;
7389 struct got_pathlist_entry *pe;
7390 int ch, can_recurse = 0, no_ignores = 0;
7391 int *pack_fds = NULL;
7393 TAILQ_INIT(&paths);
7395 while ((ch = getopt(argc, argv, "IR")) != -1) {
7396 switch (ch) {
7397 case 'I':
7398 no_ignores = 1;
7399 break;
7400 case 'R':
7401 can_recurse = 1;
7402 break;
7403 default:
7404 usage_add();
7405 /* NOTREACHED */
7409 argc -= optind;
7410 argv += optind;
7412 #ifndef PROFILE
7413 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7414 NULL) == -1)
7415 err(1, "pledge");
7416 #endif
7417 if (argc < 1)
7418 usage_add();
7420 cwd = getcwd(NULL, 0);
7421 if (cwd == NULL) {
7422 error = got_error_from_errno("getcwd");
7423 goto done;
7426 error = got_repo_pack_fds_open(&pack_fds);
7427 if (error != NULL)
7428 goto done;
7430 error = got_worktree_open(&worktree, cwd);
7431 if (error) {
7432 if (error->code == GOT_ERR_NOT_WORKTREE)
7433 error = wrap_not_worktree_error(error, "add", cwd);
7434 goto done;
7437 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7438 NULL, pack_fds);
7439 if (error != NULL)
7440 goto done;
7442 error = apply_unveil(got_repo_get_path(repo), 1,
7443 got_worktree_get_root_path(worktree));
7444 if (error)
7445 goto done;
7447 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7448 if (error)
7449 goto done;
7451 if (!can_recurse) {
7452 char *ondisk_path;
7453 struct stat sb;
7454 TAILQ_FOREACH(pe, &paths, entry) {
7455 if (asprintf(&ondisk_path, "%s/%s",
7456 got_worktree_get_root_path(worktree),
7457 pe->path) == -1) {
7458 error = got_error_from_errno("asprintf");
7459 goto done;
7461 if (lstat(ondisk_path, &sb) == -1) {
7462 if (errno == ENOENT) {
7463 free(ondisk_path);
7464 continue;
7466 error = got_error_from_errno2("lstat",
7467 ondisk_path);
7468 free(ondisk_path);
7469 goto done;
7471 free(ondisk_path);
7472 if (S_ISDIR(sb.st_mode)) {
7473 error = got_error_msg(GOT_ERR_BAD_PATH,
7474 "adding directories requires -R option");
7475 goto done;
7480 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7481 NULL, repo, no_ignores);
7482 done:
7483 if (repo) {
7484 const struct got_error *close_err = got_repo_close(repo);
7485 if (error == NULL)
7486 error = close_err;
7488 if (worktree)
7489 got_worktree_close(worktree);
7490 if (pack_fds) {
7491 const struct got_error *pack_err =
7492 got_repo_pack_fds_close(pack_fds);
7493 if (error == NULL)
7494 error = pack_err;
7496 TAILQ_FOREACH(pe, &paths, entry)
7497 free((char *)pe->path);
7498 got_pathlist_free(&paths);
7499 free(cwd);
7500 return error;
7503 __dead static void
7504 usage_remove(void)
7506 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7507 "path ...\n", getprogname());
7508 exit(1);
7511 static const struct got_error *
7512 print_remove_status(void *arg, unsigned char status,
7513 unsigned char staged_status, const char *path)
7515 while (path[0] == '/')
7516 path++;
7517 if (status == GOT_STATUS_NONEXISTENT)
7518 return NULL;
7519 if (status == staged_status && (status == GOT_STATUS_DELETE))
7520 status = GOT_STATUS_NO_CHANGE;
7521 printf("%c%c %s\n", status, staged_status, path);
7522 return NULL;
7525 static const struct got_error *
7526 cmd_remove(int argc, char *argv[])
7528 const struct got_error *error = NULL;
7529 struct got_worktree *worktree = NULL;
7530 struct got_repository *repo = NULL;
7531 const char *status_codes = NULL;
7532 char *cwd = NULL;
7533 struct got_pathlist_head paths;
7534 struct got_pathlist_entry *pe;
7535 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7536 int ignore_missing_paths = 0;
7537 int *pack_fds = NULL;
7539 TAILQ_INIT(&paths);
7541 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7542 switch (ch) {
7543 case 'f':
7544 delete_local_mods = 1;
7545 ignore_missing_paths = 1;
7546 break;
7547 case 'k':
7548 keep_on_disk = 1;
7549 break;
7550 case 'R':
7551 can_recurse = 1;
7552 break;
7553 case 's':
7554 for (i = 0; i < strlen(optarg); i++) {
7555 switch (optarg[i]) {
7556 case GOT_STATUS_MODIFY:
7557 delete_local_mods = 1;
7558 break;
7559 case GOT_STATUS_MISSING:
7560 ignore_missing_paths = 1;
7561 break;
7562 default:
7563 errx(1, "invalid status code '%c'",
7564 optarg[i]);
7567 status_codes = optarg;
7568 break;
7569 default:
7570 usage_remove();
7571 /* NOTREACHED */
7575 argc -= optind;
7576 argv += optind;
7578 #ifndef PROFILE
7579 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7580 NULL) == -1)
7581 err(1, "pledge");
7582 #endif
7583 if (argc < 1)
7584 usage_remove();
7586 cwd = getcwd(NULL, 0);
7587 if (cwd == NULL) {
7588 error = got_error_from_errno("getcwd");
7589 goto done;
7592 error = got_repo_pack_fds_open(&pack_fds);
7593 if (error != NULL)
7594 goto done;
7596 error = got_worktree_open(&worktree, cwd);
7597 if (error) {
7598 if (error->code == GOT_ERR_NOT_WORKTREE)
7599 error = wrap_not_worktree_error(error, "remove", cwd);
7600 goto done;
7603 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7604 NULL, pack_fds);
7605 if (error)
7606 goto done;
7608 error = apply_unveil(got_repo_get_path(repo), 1,
7609 got_worktree_get_root_path(worktree));
7610 if (error)
7611 goto done;
7613 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7614 if (error)
7615 goto done;
7617 if (!can_recurse) {
7618 char *ondisk_path;
7619 struct stat sb;
7620 TAILQ_FOREACH(pe, &paths, entry) {
7621 if (asprintf(&ondisk_path, "%s/%s",
7622 got_worktree_get_root_path(worktree),
7623 pe->path) == -1) {
7624 error = got_error_from_errno("asprintf");
7625 goto done;
7627 if (lstat(ondisk_path, &sb) == -1) {
7628 if (errno == ENOENT) {
7629 free(ondisk_path);
7630 continue;
7632 error = got_error_from_errno2("lstat",
7633 ondisk_path);
7634 free(ondisk_path);
7635 goto done;
7637 free(ondisk_path);
7638 if (S_ISDIR(sb.st_mode)) {
7639 error = got_error_msg(GOT_ERR_BAD_PATH,
7640 "removing directories requires -R option");
7641 goto done;
7646 error = got_worktree_schedule_delete(worktree, &paths,
7647 delete_local_mods, status_codes, print_remove_status, NULL,
7648 repo, keep_on_disk, ignore_missing_paths);
7649 done:
7650 if (repo) {
7651 const struct got_error *close_err = got_repo_close(repo);
7652 if (error == NULL)
7653 error = close_err;
7655 if (worktree)
7656 got_worktree_close(worktree);
7657 if (pack_fds) {
7658 const struct got_error *pack_err =
7659 got_repo_pack_fds_close(pack_fds);
7660 if (error == NULL)
7661 error = pack_err;
7663 TAILQ_FOREACH(pe, &paths, entry)
7664 free((char *)pe->path);
7665 got_pathlist_free(&paths);
7666 free(cwd);
7667 return error;
7670 __dead static void
7671 usage_patch(void)
7673 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7674 "[-R] [patchfile]\n", getprogname());
7675 exit(1);
7678 static const struct got_error *
7679 patch_from_stdin(int *patchfd)
7681 const struct got_error *err = NULL;
7682 ssize_t r;
7683 char *path, buf[BUFSIZ];
7684 sig_t sighup, sigint, sigquit;
7686 err = got_opentemp_named_fd(&path, patchfd,
7687 GOT_TMPDIR_STR "/got-patch");
7688 if (err)
7689 return err;
7690 unlink(path);
7691 free(path);
7693 sighup = signal(SIGHUP, SIG_DFL);
7694 sigint = signal(SIGINT, SIG_DFL);
7695 sigquit = signal(SIGQUIT, SIG_DFL);
7697 for (;;) {
7698 r = read(0, buf, sizeof(buf));
7699 if (r == -1) {
7700 err = got_error_from_errno("read");
7701 break;
7703 if (r == 0)
7704 break;
7705 if (write(*patchfd, buf, r) == -1) {
7706 err = got_error_from_errno("write");
7707 break;
7711 signal(SIGHUP, sighup);
7712 signal(SIGINT, sigint);
7713 signal(SIGQUIT, sigquit);
7715 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7716 err = got_error_from_errno("lseek");
7718 if (err != NULL) {
7719 close(*patchfd);
7720 *patchfd = -1;
7723 return err;
7726 static const struct got_error *
7727 patch_progress(void *arg, const char *old, const char *new,
7728 unsigned char status, const struct got_error *error, long old_from,
7729 long old_lines, long new_from, long new_lines, long offset,
7730 const struct got_error *hunk_err)
7732 const char *path = new == NULL ? old : new;
7734 while (*path == '/')
7735 path++;
7737 if (status != 0)
7738 printf("%c %s\n", status, path);
7740 if (error != NULL)
7741 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7743 if (offset != 0 || hunk_err != NULL) {
7744 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7745 old_lines, new_from, new_lines);
7746 if (hunk_err != NULL)
7747 printf("%s\n", hunk_err->msg);
7748 else
7749 printf("applied with offset %ld\n", offset);
7752 return NULL;
7755 static const struct got_error *
7756 cmd_patch(int argc, char *argv[])
7758 const struct got_error *error = NULL, *close_error = NULL;
7759 struct got_worktree *worktree = NULL;
7760 struct got_repository *repo = NULL;
7761 const char *errstr;
7762 char *cwd = NULL;
7763 int ch, nop = 0, strip = -1, reverse = 0;
7764 int patchfd;
7765 int *pack_fds = NULL;
7767 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7768 switch (ch) {
7769 case 'n':
7770 nop = 1;
7771 break;
7772 case 'p':
7773 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7774 if (errstr != NULL)
7775 errx(1, "pathname strip count is %s: %s",
7776 errstr, optarg);
7777 break;
7778 case 'R':
7779 reverse = 1;
7780 break;
7781 default:
7782 usage_patch();
7783 /* NOTREACHED */
7787 argc -= optind;
7788 argv += optind;
7790 if (argc == 0) {
7791 error = patch_from_stdin(&patchfd);
7792 if (error)
7793 return error;
7794 } else if (argc == 1) {
7795 patchfd = open(argv[0], O_RDONLY);
7796 if (patchfd == -1) {
7797 error = got_error_from_errno2("open", argv[0]);
7798 return error;
7800 } else
7801 usage_patch();
7803 if ((cwd = getcwd(NULL, 0)) == NULL) {
7804 error = got_error_from_errno("getcwd");
7805 goto done;
7808 error = got_repo_pack_fds_open(&pack_fds);
7809 if (error != NULL)
7810 goto done;
7812 error = got_worktree_open(&worktree, cwd);
7813 if (error != NULL)
7814 goto done;
7816 const char *repo_path = got_worktree_get_repo_path(worktree);
7817 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7818 if (error != NULL)
7819 goto done;
7821 error = apply_unveil(got_repo_get_path(repo), 0,
7822 got_worktree_get_root_path(worktree));
7823 if (error != NULL)
7824 goto done;
7826 #ifndef PROFILE
7827 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7828 NULL) == -1)
7829 err(1, "pledge");
7830 #endif
7832 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7833 &patch_progress, NULL, check_cancelled, NULL);
7835 done:
7836 if (repo) {
7837 close_error = got_repo_close(repo);
7838 if (error == NULL)
7839 error = close_error;
7841 if (worktree != NULL) {
7842 close_error = got_worktree_close(worktree);
7843 if (error == NULL)
7844 error = close_error;
7846 if (pack_fds) {
7847 const struct got_error *pack_err =
7848 got_repo_pack_fds_close(pack_fds);
7849 if (error == NULL)
7850 error = pack_err;
7852 free(cwd);
7853 return error;
7856 __dead static void
7857 usage_revert(void)
7859 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7860 "path ...\n", getprogname());
7861 exit(1);
7864 static const struct got_error *
7865 revert_progress(void *arg, unsigned char status, const char *path)
7867 if (status == GOT_STATUS_UNVERSIONED)
7868 return NULL;
7870 while (path[0] == '/')
7871 path++;
7872 printf("%c %s\n", status, path);
7873 return NULL;
7876 struct choose_patch_arg {
7877 FILE *patch_script_file;
7878 const char *action;
7881 static const struct got_error *
7882 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7883 int nchanges, const char *action)
7885 const struct got_error *err;
7886 char *line = NULL;
7887 size_t linesize = 0;
7888 ssize_t linelen;
7890 switch (status) {
7891 case GOT_STATUS_ADD:
7892 printf("A %s\n%s this addition? [y/n] ", path, action);
7893 break;
7894 case GOT_STATUS_DELETE:
7895 printf("D %s\n%s this deletion? [y/n] ", path, action);
7896 break;
7897 case GOT_STATUS_MODIFY:
7898 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7899 return got_error_from_errno("fseek");
7900 printf(GOT_COMMIT_SEP_STR);
7901 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7902 printf("%s", line);
7903 if (linelen == -1 && ferror(patch_file)) {
7904 err = got_error_from_errno("getline");
7905 free(line);
7906 return err;
7908 free(line);
7909 printf(GOT_COMMIT_SEP_STR);
7910 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7911 path, n, nchanges, action);
7912 break;
7913 default:
7914 return got_error_path(path, GOT_ERR_FILE_STATUS);
7917 return NULL;
7920 static const struct got_error *
7921 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7922 FILE *patch_file, int n, int nchanges)
7924 const struct got_error *err = NULL;
7925 char *line = NULL;
7926 size_t linesize = 0;
7927 ssize_t linelen;
7928 int resp = ' ';
7929 struct choose_patch_arg *a = arg;
7931 *choice = GOT_PATCH_CHOICE_NONE;
7933 if (a->patch_script_file) {
7934 char *nl;
7935 err = show_change(status, path, patch_file, n, nchanges,
7936 a->action);
7937 if (err)
7938 return err;
7939 linelen = getline(&line, &linesize, a->patch_script_file);
7940 if (linelen == -1) {
7941 if (ferror(a->patch_script_file))
7942 return got_error_from_errno("getline");
7943 return NULL;
7945 nl = strchr(line, '\n');
7946 if (nl)
7947 *nl = '\0';
7948 if (strcmp(line, "y") == 0) {
7949 *choice = GOT_PATCH_CHOICE_YES;
7950 printf("y\n");
7951 } else if (strcmp(line, "n") == 0) {
7952 *choice = GOT_PATCH_CHOICE_NO;
7953 printf("n\n");
7954 } else if (strcmp(line, "q") == 0 &&
7955 status == GOT_STATUS_MODIFY) {
7956 *choice = GOT_PATCH_CHOICE_QUIT;
7957 printf("q\n");
7958 } else
7959 printf("invalid response '%s'\n", line);
7960 free(line);
7961 return NULL;
7964 while (resp != 'y' && resp != 'n' && resp != 'q') {
7965 err = show_change(status, path, patch_file, n, nchanges,
7966 a->action);
7967 if (err)
7968 return err;
7969 resp = getchar();
7970 if (resp == '\n')
7971 resp = getchar();
7972 if (status == GOT_STATUS_MODIFY) {
7973 if (resp != 'y' && resp != 'n' && resp != 'q') {
7974 printf("invalid response '%c'\n", resp);
7975 resp = ' ';
7977 } else if (resp != 'y' && resp != 'n') {
7978 printf("invalid response '%c'\n", resp);
7979 resp = ' ';
7983 if (resp == 'y')
7984 *choice = GOT_PATCH_CHOICE_YES;
7985 else if (resp == 'n')
7986 *choice = GOT_PATCH_CHOICE_NO;
7987 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7988 *choice = GOT_PATCH_CHOICE_QUIT;
7990 return NULL;
7993 static const struct got_error *
7994 cmd_revert(int argc, char *argv[])
7996 const struct got_error *error = NULL;
7997 struct got_worktree *worktree = NULL;
7998 struct got_repository *repo = NULL;
7999 char *cwd = NULL, *path = NULL;
8000 struct got_pathlist_head paths;
8001 struct got_pathlist_entry *pe;
8002 int ch, can_recurse = 0, pflag = 0;
8003 FILE *patch_script_file = NULL;
8004 const char *patch_script_path = NULL;
8005 struct choose_patch_arg cpa;
8006 int *pack_fds = NULL;
8008 TAILQ_INIT(&paths);
8010 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8011 switch (ch) {
8012 case 'p':
8013 pflag = 1;
8014 break;
8015 case 'F':
8016 patch_script_path = optarg;
8017 break;
8018 case 'R':
8019 can_recurse = 1;
8020 break;
8021 default:
8022 usage_revert();
8023 /* NOTREACHED */
8027 argc -= optind;
8028 argv += optind;
8030 #ifndef PROFILE
8031 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8032 "unveil", NULL) == -1)
8033 err(1, "pledge");
8034 #endif
8035 if (argc < 1)
8036 usage_revert();
8037 if (patch_script_path && !pflag)
8038 errx(1, "-F option can only be used together with -p option");
8040 cwd = getcwd(NULL, 0);
8041 if (cwd == NULL) {
8042 error = got_error_from_errno("getcwd");
8043 goto done;
8046 error = got_repo_pack_fds_open(&pack_fds);
8047 if (error != NULL)
8048 goto done;
8050 error = got_worktree_open(&worktree, cwd);
8051 if (error) {
8052 if (error->code == GOT_ERR_NOT_WORKTREE)
8053 error = wrap_not_worktree_error(error, "revert", cwd);
8054 goto done;
8057 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8058 NULL, pack_fds);
8059 if (error != NULL)
8060 goto done;
8062 if (patch_script_path) {
8063 patch_script_file = fopen(patch_script_path, "re");
8064 if (patch_script_file == NULL) {
8065 error = got_error_from_errno2("fopen",
8066 patch_script_path);
8067 goto done;
8070 error = apply_unveil(got_repo_get_path(repo), 1,
8071 got_worktree_get_root_path(worktree));
8072 if (error)
8073 goto done;
8075 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8076 if (error)
8077 goto done;
8079 if (!can_recurse) {
8080 char *ondisk_path;
8081 struct stat sb;
8082 TAILQ_FOREACH(pe, &paths, entry) {
8083 if (asprintf(&ondisk_path, "%s/%s",
8084 got_worktree_get_root_path(worktree),
8085 pe->path) == -1) {
8086 error = got_error_from_errno("asprintf");
8087 goto done;
8089 if (lstat(ondisk_path, &sb) == -1) {
8090 if (errno == ENOENT) {
8091 free(ondisk_path);
8092 continue;
8094 error = got_error_from_errno2("lstat",
8095 ondisk_path);
8096 free(ondisk_path);
8097 goto done;
8099 free(ondisk_path);
8100 if (S_ISDIR(sb.st_mode)) {
8101 error = got_error_msg(GOT_ERR_BAD_PATH,
8102 "reverting directories requires -R option");
8103 goto done;
8108 cpa.patch_script_file = patch_script_file;
8109 cpa.action = "revert";
8110 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8111 pflag ? choose_patch : NULL, &cpa, repo);
8112 done:
8113 if (patch_script_file && fclose(patch_script_file) == EOF &&
8114 error == NULL)
8115 error = got_error_from_errno2("fclose", patch_script_path);
8116 if (repo) {
8117 const struct got_error *close_err = got_repo_close(repo);
8118 if (error == NULL)
8119 error = close_err;
8121 if (worktree)
8122 got_worktree_close(worktree);
8123 if (pack_fds) {
8124 const struct got_error *pack_err =
8125 got_repo_pack_fds_close(pack_fds);
8126 if (error == NULL)
8127 error = pack_err;
8129 free(path);
8130 free(cwd);
8131 return error;
8134 __dead static void
8135 usage_commit(void)
8137 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8138 "[path ...]\n", getprogname());
8139 exit(1);
8142 struct collect_commit_logmsg_arg {
8143 const char *cmdline_log;
8144 const char *prepared_log;
8145 int non_interactive;
8146 const char *editor;
8147 const char *worktree_path;
8148 const char *branch_name;
8149 const char *repo_path;
8150 char *logmsg_path;
8154 static const struct got_error *
8155 read_prepared_logmsg(char **logmsg, const char *path)
8157 const struct got_error *err = NULL;
8158 FILE *f = NULL;
8159 struct stat sb;
8160 size_t r;
8162 *logmsg = NULL;
8163 memset(&sb, 0, sizeof(sb));
8165 f = fopen(path, "re");
8166 if (f == NULL)
8167 return got_error_from_errno2("fopen", path);
8169 if (fstat(fileno(f), &sb) == -1) {
8170 err = got_error_from_errno2("fstat", path);
8171 goto done;
8173 if (sb.st_size == 0) {
8174 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8175 goto done;
8178 *logmsg = malloc(sb.st_size + 1);
8179 if (*logmsg == NULL) {
8180 err = got_error_from_errno("malloc");
8181 goto done;
8184 r = fread(*logmsg, 1, sb.st_size, f);
8185 if (r != sb.st_size) {
8186 if (ferror(f))
8187 err = got_error_from_errno2("fread", path);
8188 else
8189 err = got_error(GOT_ERR_IO);
8190 goto done;
8192 (*logmsg)[sb.st_size] = '\0';
8193 done:
8194 if (fclose(f) == EOF && err == NULL)
8195 err = got_error_from_errno2("fclose", path);
8196 if (err) {
8197 free(*logmsg);
8198 *logmsg = NULL;
8200 return err;
8204 static const struct got_error *
8205 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8206 void *arg)
8208 char *initial_content = NULL;
8209 struct got_pathlist_entry *pe;
8210 const struct got_error *err = NULL;
8211 char *template = NULL;
8212 struct collect_commit_logmsg_arg *a = arg;
8213 int initial_content_len;
8214 int fd = -1;
8215 size_t len;
8217 /* if a message was specified on the command line, just use it */
8218 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8219 len = strlen(a->cmdline_log) + 1;
8220 *logmsg = malloc(len + 1);
8221 if (*logmsg == NULL)
8222 return got_error_from_errno("malloc");
8223 strlcpy(*logmsg, a->cmdline_log, len);
8224 return NULL;
8225 } else if (a->prepared_log != NULL && a->non_interactive)
8226 return read_prepared_logmsg(logmsg, a->prepared_log);
8228 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8229 return got_error_from_errno("asprintf");
8231 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8232 if (err)
8233 goto done;
8235 if (a->prepared_log) {
8236 char *msg;
8237 err = read_prepared_logmsg(&msg, a->prepared_log);
8238 if (err)
8239 goto done;
8240 if (write(fd, msg, strlen(msg)) == -1) {
8241 err = got_error_from_errno2("write", a->logmsg_path);
8242 free(msg);
8243 goto done;
8245 free(msg);
8248 initial_content_len = asprintf(&initial_content,
8249 "\n# changes to be committed on branch %s:\n",
8250 a->branch_name);
8251 if (initial_content_len == -1) {
8252 err = got_error_from_errno("asprintf");
8253 goto done;
8256 if (write(fd, initial_content, initial_content_len) == -1) {
8257 err = got_error_from_errno2("write", a->logmsg_path);
8258 goto done;
8261 TAILQ_FOREACH(pe, commitable_paths, entry) {
8262 struct got_commitable *ct = pe->data;
8263 dprintf(fd, "# %c %s\n",
8264 got_commitable_get_status(ct),
8265 got_commitable_get_path(ct));
8268 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8269 initial_content_len, a->prepared_log ? 0 : 1);
8270 done:
8271 free(initial_content);
8272 free(template);
8274 if (fd != -1 && close(fd) == -1 && err == NULL)
8275 err = got_error_from_errno2("close", a->logmsg_path);
8277 /* Editor is done; we can now apply unveil(2) */
8278 if (err == NULL)
8279 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8280 if (err) {
8281 free(*logmsg);
8282 *logmsg = NULL;
8284 return err;
8287 static const struct got_error *
8288 cmd_commit(int argc, char *argv[])
8290 const struct got_error *error = NULL;
8291 struct got_worktree *worktree = NULL;
8292 struct got_repository *repo = NULL;
8293 char *cwd = NULL, *id_str = NULL;
8294 struct got_object_id *id = NULL;
8295 const char *logmsg = NULL;
8296 char *prepared_logmsg = NULL;
8297 struct collect_commit_logmsg_arg cl_arg;
8298 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8299 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8300 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8301 struct got_pathlist_head paths;
8302 int *pack_fds = NULL;
8304 TAILQ_INIT(&paths);
8305 cl_arg.logmsg_path = NULL;
8307 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8308 switch (ch) {
8309 case 'F':
8310 if (logmsg != NULL)
8311 option_conflict('F', 'm');
8312 prepared_logmsg = realpath(optarg, NULL);
8313 if (prepared_logmsg == NULL)
8314 return got_error_from_errno2("realpath",
8315 optarg);
8316 break;
8317 case 'm':
8318 if (prepared_logmsg)
8319 option_conflict('m', 'F');
8320 logmsg = optarg;
8321 break;
8322 case 'N':
8323 non_interactive = 1;
8324 break;
8325 case 'S':
8326 allow_bad_symlinks = 1;
8327 break;
8328 default:
8329 usage_commit();
8330 /* NOTREACHED */
8334 argc -= optind;
8335 argv += optind;
8337 #ifndef PROFILE
8338 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8339 "unveil", NULL) == -1)
8340 err(1, "pledge");
8341 #endif
8342 cwd = getcwd(NULL, 0);
8343 if (cwd == NULL) {
8344 error = got_error_from_errno("getcwd");
8345 goto done;
8348 error = got_repo_pack_fds_open(&pack_fds);
8349 if (error != NULL)
8350 goto done;
8352 error = got_worktree_open(&worktree, cwd);
8353 if (error) {
8354 if (error->code == GOT_ERR_NOT_WORKTREE)
8355 error = wrap_not_worktree_error(error, "commit", cwd);
8356 goto done;
8359 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8360 if (error)
8361 goto done;
8362 if (rebase_in_progress) {
8363 error = got_error(GOT_ERR_REBASING);
8364 goto done;
8367 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8368 worktree);
8369 if (error)
8370 goto done;
8372 error = get_gitconfig_path(&gitconfig_path);
8373 if (error)
8374 goto done;
8375 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8376 gitconfig_path, pack_fds);
8377 if (error != NULL)
8378 goto done;
8380 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8381 if (error)
8382 goto done;
8383 if (merge_in_progress) {
8384 error = got_error(GOT_ERR_MERGE_BUSY);
8385 goto done;
8388 error = get_author(&author, repo, worktree);
8389 if (error)
8390 return error;
8393 * unveil(2) traverses exec(2); if an editor is used we have
8394 * to apply unveil after the log message has been written.
8396 if (logmsg == NULL || strlen(logmsg) == 0)
8397 error = get_editor(&editor);
8398 else
8399 error = apply_unveil(got_repo_get_path(repo), 0,
8400 got_worktree_get_root_path(worktree));
8401 if (error)
8402 goto done;
8404 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8405 if (error)
8406 goto done;
8408 cl_arg.editor = editor;
8409 cl_arg.cmdline_log = logmsg;
8410 cl_arg.prepared_log = prepared_logmsg;
8411 cl_arg.non_interactive = non_interactive;
8412 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8413 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8414 if (!histedit_in_progress) {
8415 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8416 error = got_error(GOT_ERR_COMMIT_BRANCH);
8417 goto done;
8419 cl_arg.branch_name += 11;
8421 cl_arg.repo_path = got_repo_get_path(repo);
8422 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8423 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8424 print_status, NULL, repo);
8425 if (error) {
8426 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8427 cl_arg.logmsg_path != NULL)
8428 preserve_logmsg = 1;
8429 goto done;
8432 error = got_object_id_str(&id_str, id);
8433 if (error)
8434 goto done;
8435 printf("Created commit %s\n", id_str);
8436 done:
8437 if (preserve_logmsg) {
8438 fprintf(stderr, "%s: log message preserved in %s\n",
8439 getprogname(), cl_arg.logmsg_path);
8440 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8441 error == NULL)
8442 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8443 free(cl_arg.logmsg_path);
8444 if (repo) {
8445 const struct got_error *close_err = got_repo_close(repo);
8446 if (error == NULL)
8447 error = close_err;
8449 if (worktree)
8450 got_worktree_close(worktree);
8451 if (pack_fds) {
8452 const struct got_error *pack_err =
8453 got_repo_pack_fds_close(pack_fds);
8454 if (error == NULL)
8455 error = pack_err;
8457 free(cwd);
8458 free(id_str);
8459 free(gitconfig_path);
8460 free(editor);
8461 free(author);
8462 free(prepared_logmsg);
8463 return error;
8466 __dead static void
8467 usage_send(void)
8469 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8470 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8471 "[remote-repository]\n", getprogname());
8472 exit(1);
8475 static void
8476 print_load_info(int print_colored, int print_found, int print_trees,
8477 int ncolored, int nfound, int ntrees)
8479 if (print_colored) {
8480 printf("%d commit%s colored", ncolored,
8481 ncolored == 1 ? "" : "s");
8483 if (print_found) {
8484 printf("%s%d object%s found",
8485 ncolored > 0 ? "; " : "",
8486 nfound, nfound == 1 ? "" : "s");
8488 if (print_trees) {
8489 printf("; %d tree%s scanned", ntrees,
8490 ntrees == 1 ? "" : "s");
8494 struct got_send_progress_arg {
8495 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8496 int verbosity;
8497 int last_ncolored;
8498 int last_nfound;
8499 int last_ntrees;
8500 int loading_done;
8501 int last_ncommits;
8502 int last_nobj_total;
8503 int last_p_deltify;
8504 int last_p_written;
8505 int last_p_sent;
8506 int printed_something;
8507 int sent_something;
8508 struct got_pathlist_head *delete_branches;
8511 static const struct got_error *
8512 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8513 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8514 int nobj_written, off_t bytes_sent, const char *refname, int success)
8516 struct got_send_progress_arg *a = arg;
8517 char scaled_packsize[FMT_SCALED_STRSIZE];
8518 char scaled_sent[FMT_SCALED_STRSIZE];
8519 int p_deltify = 0, p_written = 0, p_sent = 0;
8520 int print_colored = 0, print_found = 0, print_trees = 0;
8521 int print_searching = 0, print_total = 0;
8522 int print_deltify = 0, print_written = 0, print_sent = 0;
8524 if (a->verbosity < 0)
8525 return NULL;
8527 if (refname) {
8528 const char *status = success ? "accepted" : "rejected";
8530 if (success) {
8531 struct got_pathlist_entry *pe;
8532 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8533 const char *branchname = pe->path;
8534 if (got_path_cmp(branchname, refname,
8535 strlen(branchname), strlen(refname)) == 0) {
8536 status = "deleted";
8537 a->sent_something = 1;
8538 break;
8543 if (a->printed_something)
8544 putchar('\n');
8545 printf("Server has %s %s", status, refname);
8546 a->printed_something = 1;
8547 return NULL;
8550 if (a->last_ncolored != ncolored) {
8551 print_colored = 1;
8552 a->last_ncolored = ncolored;
8555 if (a->last_nfound != nfound) {
8556 print_colored = 1;
8557 print_found = 1;
8558 a->last_nfound = nfound;
8561 if (a->last_ntrees != ntrees) {
8562 print_colored = 1;
8563 print_found = 1;
8564 print_trees = 1;
8565 a->last_ntrees = ntrees;
8568 if ((print_colored || print_found || print_trees) &&
8569 !a->loading_done) {
8570 printf("\r");
8571 print_load_info(print_colored, print_found, print_trees,
8572 ncolored, nfound, ntrees);
8573 a->printed_something = 1;
8574 fflush(stdout);
8575 return NULL;
8576 } else if (!a->loading_done) {
8577 printf("\r");
8578 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8579 printf("\n");
8580 a->loading_done = 1;
8583 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8584 return got_error_from_errno("fmt_scaled");
8585 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8586 return got_error_from_errno("fmt_scaled");
8588 if (a->last_ncommits != ncommits) {
8589 print_searching = 1;
8590 a->last_ncommits = ncommits;
8593 if (a->last_nobj_total != nobj_total) {
8594 print_searching = 1;
8595 print_total = 1;
8596 a->last_nobj_total = nobj_total;
8599 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8600 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8601 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8602 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8603 return got_error(GOT_ERR_NO_SPACE);
8606 if (nobj_deltify > 0 || nobj_written > 0) {
8607 if (nobj_deltify > 0) {
8608 p_deltify = (nobj_deltify * 100) / nobj_total;
8609 if (p_deltify != a->last_p_deltify) {
8610 a->last_p_deltify = p_deltify;
8611 print_searching = 1;
8612 print_total = 1;
8613 print_deltify = 1;
8616 if (nobj_written > 0) {
8617 p_written = (nobj_written * 100) / nobj_total;
8618 if (p_written != a->last_p_written) {
8619 a->last_p_written = p_written;
8620 print_searching = 1;
8621 print_total = 1;
8622 print_deltify = 1;
8623 print_written = 1;
8628 if (bytes_sent > 0) {
8629 p_sent = (bytes_sent * 100) / packfile_size;
8630 if (p_sent != a->last_p_sent) {
8631 a->last_p_sent = p_sent;
8632 print_searching = 1;
8633 print_total = 1;
8634 print_deltify = 1;
8635 print_written = 1;
8636 print_sent = 1;
8638 a->sent_something = 1;
8641 if (print_searching || print_total || print_deltify || print_written ||
8642 print_sent)
8643 printf("\r");
8644 if (print_searching)
8645 printf("packing %d reference%s", ncommits,
8646 ncommits == 1 ? "" : "s");
8647 if (print_total)
8648 printf("; %d object%s", nobj_total,
8649 nobj_total == 1 ? "" : "s");
8650 if (print_deltify)
8651 printf("; deltify: %d%%", p_deltify);
8652 if (print_sent)
8653 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8654 scaled_packsize, p_sent);
8655 else if (print_written)
8656 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8657 scaled_packsize, p_written);
8658 if (print_searching || print_total || print_deltify ||
8659 print_written || print_sent) {
8660 a->printed_something = 1;
8661 fflush(stdout);
8663 return NULL;
8666 static const struct got_error *
8667 cmd_send(int argc, char *argv[])
8669 const struct got_error *error = NULL;
8670 char *cwd = NULL, *repo_path = NULL;
8671 const char *remote_name;
8672 char *proto = NULL, *host = NULL, *port = NULL;
8673 char *repo_name = NULL, *server_path = NULL;
8674 const struct got_remote_repo *remotes, *remote = NULL;
8675 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8676 struct got_repository *repo = NULL;
8677 struct got_worktree *worktree = NULL;
8678 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8679 struct got_pathlist_head branches;
8680 struct got_pathlist_head tags;
8681 struct got_reflist_head all_branches;
8682 struct got_reflist_head all_tags;
8683 struct got_pathlist_head delete_args;
8684 struct got_pathlist_head delete_branches;
8685 struct got_reflist_entry *re;
8686 struct got_pathlist_entry *pe;
8687 int i, ch, sendfd = -1, sendstatus;
8688 pid_t sendpid = -1;
8689 struct got_send_progress_arg spa;
8690 int verbosity = 0, overwrite_refs = 0;
8691 int send_all_branches = 0, send_all_tags = 0;
8692 struct got_reference *ref = NULL;
8693 int *pack_fds = NULL;
8695 TAILQ_INIT(&branches);
8696 TAILQ_INIT(&tags);
8697 TAILQ_INIT(&all_branches);
8698 TAILQ_INIT(&all_tags);
8699 TAILQ_INIT(&delete_args);
8700 TAILQ_INIT(&delete_branches);
8702 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8703 switch (ch) {
8704 case 'a':
8705 send_all_branches = 1;
8706 break;
8707 case 'b':
8708 error = got_pathlist_append(&branches, optarg, NULL);
8709 if (error)
8710 return error;
8711 nbranches++;
8712 break;
8713 case 'd':
8714 error = got_pathlist_append(&delete_args, optarg, NULL);
8715 if (error)
8716 return error;
8717 break;
8718 case 'f':
8719 overwrite_refs = 1;
8720 break;
8721 case 'r':
8722 repo_path = realpath(optarg, NULL);
8723 if (repo_path == NULL)
8724 return got_error_from_errno2("realpath",
8725 optarg);
8726 got_path_strip_trailing_slashes(repo_path);
8727 break;
8728 case 't':
8729 error = got_pathlist_append(&tags, optarg, NULL);
8730 if (error)
8731 return error;
8732 ntags++;
8733 break;
8734 case 'T':
8735 send_all_tags = 1;
8736 break;
8737 case 'v':
8738 if (verbosity < 0)
8739 verbosity = 0;
8740 else if (verbosity < 3)
8741 verbosity++;
8742 break;
8743 case 'q':
8744 verbosity = -1;
8745 break;
8746 default:
8747 usage_send();
8748 /* NOTREACHED */
8751 argc -= optind;
8752 argv += optind;
8754 if (send_all_branches && !TAILQ_EMPTY(&branches))
8755 option_conflict('a', 'b');
8756 if (send_all_tags && !TAILQ_EMPTY(&tags))
8757 option_conflict('T', 't');
8760 if (argc == 0)
8761 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8762 else if (argc == 1)
8763 remote_name = argv[0];
8764 else
8765 usage_send();
8767 cwd = getcwd(NULL, 0);
8768 if (cwd == NULL) {
8769 error = got_error_from_errno("getcwd");
8770 goto done;
8773 error = got_repo_pack_fds_open(&pack_fds);
8774 if (error != NULL)
8775 goto done;
8777 if (repo_path == NULL) {
8778 error = got_worktree_open(&worktree, cwd);
8779 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8780 goto done;
8781 else
8782 error = NULL;
8783 if (worktree) {
8784 repo_path =
8785 strdup(got_worktree_get_repo_path(worktree));
8786 if (repo_path == NULL)
8787 error = got_error_from_errno("strdup");
8788 if (error)
8789 goto done;
8790 } else {
8791 repo_path = strdup(cwd);
8792 if (repo_path == NULL) {
8793 error = got_error_from_errno("strdup");
8794 goto done;
8799 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8800 if (error)
8801 goto done;
8803 if (worktree) {
8804 worktree_conf = got_worktree_get_gotconfig(worktree);
8805 if (worktree_conf) {
8806 got_gotconfig_get_remotes(&nremotes, &remotes,
8807 worktree_conf);
8808 for (i = 0; i < nremotes; i++) {
8809 if (strcmp(remotes[i].name, remote_name) == 0) {
8810 remote = &remotes[i];
8811 break;
8816 if (remote == NULL) {
8817 repo_conf = got_repo_get_gotconfig(repo);
8818 if (repo_conf) {
8819 got_gotconfig_get_remotes(&nremotes, &remotes,
8820 repo_conf);
8821 for (i = 0; i < nremotes; i++) {
8822 if (strcmp(remotes[i].name, remote_name) == 0) {
8823 remote = &remotes[i];
8824 break;
8829 if (remote == NULL) {
8830 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8831 for (i = 0; i < nremotes; i++) {
8832 if (strcmp(remotes[i].name, remote_name) == 0) {
8833 remote = &remotes[i];
8834 break;
8838 if (remote == NULL) {
8839 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8840 goto done;
8843 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8844 &repo_name, remote->send_url);
8845 if (error)
8846 goto done;
8848 if (strcmp(proto, "git") == 0) {
8849 #ifndef PROFILE
8850 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8851 "sendfd dns inet unveil", NULL) == -1)
8852 err(1, "pledge");
8853 #endif
8854 } else if (strcmp(proto, "git+ssh") == 0 ||
8855 strcmp(proto, "ssh") == 0) {
8856 #ifndef PROFILE
8857 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8858 "sendfd unveil", NULL) == -1)
8859 err(1, "pledge");
8860 #endif
8861 } else if (strcmp(proto, "http") == 0 ||
8862 strcmp(proto, "git+http") == 0) {
8863 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8864 goto done;
8865 } else {
8866 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8867 goto done;
8870 error = got_dial_apply_unveil(proto);
8871 if (error)
8872 goto done;
8874 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8875 if (error)
8876 goto done;
8878 if (send_all_branches) {
8879 error = got_ref_list(&all_branches, repo, "refs/heads",
8880 got_ref_cmp_by_name, NULL);
8881 if (error)
8882 goto done;
8883 TAILQ_FOREACH(re, &all_branches, entry) {
8884 const char *branchname = got_ref_get_name(re->ref);
8885 error = got_pathlist_append(&branches,
8886 branchname, NULL);
8887 if (error)
8888 goto done;
8889 nbranches++;
8891 } else if (nbranches == 0) {
8892 for (i = 0; i < remote->nsend_branches; i++) {
8893 got_pathlist_append(&branches,
8894 remote->send_branches[i], NULL);
8898 if (send_all_tags) {
8899 error = got_ref_list(&all_tags, repo, "refs/tags",
8900 got_ref_cmp_by_name, NULL);
8901 if (error)
8902 goto done;
8903 TAILQ_FOREACH(re, &all_tags, entry) {
8904 const char *tagname = got_ref_get_name(re->ref);
8905 error = got_pathlist_append(&tags,
8906 tagname, NULL);
8907 if (error)
8908 goto done;
8909 ntags++;
8914 * To prevent accidents only branches in refs/heads/ can be deleted
8915 * with 'got send -d'.
8916 * Deleting anything else requires local repository access or Git.
8918 TAILQ_FOREACH(pe, &delete_args, entry) {
8919 const char *branchname = pe->path;
8920 char *s;
8921 struct got_pathlist_entry *new;
8922 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8923 s = strdup(branchname);
8924 if (s == NULL) {
8925 error = got_error_from_errno("strdup");
8926 goto done;
8928 } else {
8929 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8930 error = got_error_from_errno("asprintf");
8931 goto done;
8934 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8935 if (error || new == NULL /* duplicate */)
8936 free(s);
8937 if (error)
8938 goto done;
8939 ndelete_branches++;
8942 if (nbranches == 0 && ndelete_branches == 0) {
8943 struct got_reference *head_ref;
8944 if (worktree)
8945 error = got_ref_open(&head_ref, repo,
8946 got_worktree_get_head_ref_name(worktree), 0);
8947 else
8948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8949 if (error)
8950 goto done;
8951 if (got_ref_is_symbolic(head_ref)) {
8952 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8953 got_ref_close(head_ref);
8954 if (error)
8955 goto done;
8956 } else
8957 ref = head_ref;
8958 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8959 NULL);
8960 if (error)
8961 goto done;
8962 nbranches++;
8965 if (verbosity >= 0)
8966 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8967 port ? ":" : "", port ? port : "");
8969 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8970 server_path, verbosity);
8971 if (error)
8972 goto done;
8974 memset(&spa, 0, sizeof(spa));
8975 spa.last_scaled_packsize[0] = '\0';
8976 spa.last_p_deltify = -1;
8977 spa.last_p_written = -1;
8978 spa.verbosity = verbosity;
8979 spa.delete_branches = &delete_branches;
8980 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8981 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8982 check_cancelled, NULL);
8983 if (spa.printed_something)
8984 putchar('\n');
8985 if (error)
8986 goto done;
8987 if (!spa.sent_something && verbosity >= 0)
8988 printf("Already up-to-date\n");
8989 done:
8990 if (sendpid > 0) {
8991 if (kill(sendpid, SIGTERM) == -1)
8992 error = got_error_from_errno("kill");
8993 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8994 error = got_error_from_errno("waitpid");
8996 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8997 error = got_error_from_errno("close");
8998 if (repo) {
8999 const struct got_error *close_err = got_repo_close(repo);
9000 if (error == NULL)
9001 error = close_err;
9003 if (worktree)
9004 got_worktree_close(worktree);
9005 if (pack_fds) {
9006 const struct got_error *pack_err =
9007 got_repo_pack_fds_close(pack_fds);
9008 if (error == NULL)
9009 error = pack_err;
9011 if (ref)
9012 got_ref_close(ref);
9013 got_pathlist_free(&branches);
9014 got_pathlist_free(&tags);
9015 got_ref_list_free(&all_branches);
9016 got_ref_list_free(&all_tags);
9017 got_pathlist_free(&delete_args);
9018 TAILQ_FOREACH(pe, &delete_branches, entry)
9019 free((char *)pe->path);
9020 got_pathlist_free(&delete_branches);
9021 free(cwd);
9022 free(repo_path);
9023 free(proto);
9024 free(host);
9025 free(port);
9026 free(server_path);
9027 free(repo_name);
9028 return error;
9031 __dead static void
9032 usage_cherrypick(void)
9034 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9035 exit(1);
9038 static const struct got_error *
9039 cmd_cherrypick(int argc, char *argv[])
9041 const struct got_error *error = NULL;
9042 struct got_worktree *worktree = NULL;
9043 struct got_repository *repo = NULL;
9044 char *cwd = NULL, *commit_id_str = NULL;
9045 struct got_object_id *commit_id = NULL;
9046 struct got_commit_object *commit = NULL;
9047 struct got_object_qid *pid;
9048 int ch;
9049 struct got_update_progress_arg upa;
9050 int *pack_fds = NULL;
9052 while ((ch = getopt(argc, argv, "")) != -1) {
9053 switch (ch) {
9054 default:
9055 usage_cherrypick();
9056 /* NOTREACHED */
9060 argc -= optind;
9061 argv += optind;
9063 #ifndef PROFILE
9064 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9065 "unveil", NULL) == -1)
9066 err(1, "pledge");
9067 #endif
9068 if (argc != 1)
9069 usage_cherrypick();
9071 cwd = getcwd(NULL, 0);
9072 if (cwd == NULL) {
9073 error = got_error_from_errno("getcwd");
9074 goto done;
9077 error = got_repo_pack_fds_open(&pack_fds);
9078 if (error != NULL)
9079 goto done;
9081 error = got_worktree_open(&worktree, cwd);
9082 if (error) {
9083 if (error->code == GOT_ERR_NOT_WORKTREE)
9084 error = wrap_not_worktree_error(error, "cherrypick",
9085 cwd);
9086 goto done;
9089 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9090 NULL, pack_fds);
9091 if (error != NULL)
9092 goto done;
9094 error = apply_unveil(got_repo_get_path(repo), 0,
9095 got_worktree_get_root_path(worktree));
9096 if (error)
9097 goto done;
9099 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9100 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9101 if (error)
9102 goto done;
9103 error = got_object_id_str(&commit_id_str, commit_id);
9104 if (error)
9105 goto done;
9107 error = got_object_open_as_commit(&commit, repo, commit_id);
9108 if (error)
9109 goto done;
9110 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9111 memset(&upa, 0, sizeof(upa));
9112 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9113 commit_id, repo, update_progress, &upa, check_cancelled,
9114 NULL);
9115 if (error != NULL)
9116 goto done;
9118 if (upa.did_something)
9119 printf("Merged commit %s\n", commit_id_str);
9120 print_merge_progress_stats(&upa);
9121 done:
9122 if (commit)
9123 got_object_commit_close(commit);
9124 free(commit_id_str);
9125 if (worktree)
9126 got_worktree_close(worktree);
9127 if (repo) {
9128 const struct got_error *close_err = got_repo_close(repo);
9129 if (error == NULL)
9130 error = close_err;
9132 if (pack_fds) {
9133 const struct got_error *pack_err =
9134 got_repo_pack_fds_close(pack_fds);
9135 if (error == NULL)
9136 error = pack_err;
9139 return error;
9142 __dead static void
9143 usage_backout(void)
9145 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9146 exit(1);
9149 static const struct got_error *
9150 cmd_backout(int argc, char *argv[])
9152 const struct got_error *error = NULL;
9153 struct got_worktree *worktree = NULL;
9154 struct got_repository *repo = NULL;
9155 char *cwd = NULL, *commit_id_str = NULL;
9156 struct got_object_id *commit_id = NULL;
9157 struct got_commit_object *commit = NULL;
9158 struct got_object_qid *pid;
9159 int ch;
9160 struct got_update_progress_arg upa;
9161 int *pack_fds = NULL;
9163 while ((ch = getopt(argc, argv, "")) != -1) {
9164 switch (ch) {
9165 default:
9166 usage_backout();
9167 /* NOTREACHED */
9171 argc -= optind;
9172 argv += optind;
9174 #ifndef PROFILE
9175 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9176 "unveil", NULL) == -1)
9177 err(1, "pledge");
9178 #endif
9179 if (argc != 1)
9180 usage_backout();
9182 cwd = getcwd(NULL, 0);
9183 if (cwd == NULL) {
9184 error = got_error_from_errno("getcwd");
9185 goto done;
9188 error = got_repo_pack_fds_open(&pack_fds);
9189 if (error != NULL)
9190 goto done;
9192 error = got_worktree_open(&worktree, cwd);
9193 if (error) {
9194 if (error->code == GOT_ERR_NOT_WORKTREE)
9195 error = wrap_not_worktree_error(error, "backout", cwd);
9196 goto done;
9199 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9200 NULL, pack_fds);
9201 if (error != NULL)
9202 goto done;
9204 error = apply_unveil(got_repo_get_path(repo), 0,
9205 got_worktree_get_root_path(worktree));
9206 if (error)
9207 goto done;
9209 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9210 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9211 if (error)
9212 goto done;
9213 error = got_object_id_str(&commit_id_str, commit_id);
9214 if (error)
9215 goto done;
9217 error = got_object_open_as_commit(&commit, repo, commit_id);
9218 if (error)
9219 goto done;
9220 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9221 if (pid == NULL) {
9222 error = got_error(GOT_ERR_ROOT_COMMIT);
9223 goto done;
9226 memset(&upa, 0, sizeof(upa));
9227 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9228 repo, update_progress, &upa, check_cancelled, NULL);
9229 if (error != NULL)
9230 goto done;
9232 if (upa.did_something)
9233 printf("Backed out commit %s\n", commit_id_str);
9234 print_merge_progress_stats(&upa);
9235 done:
9236 if (commit)
9237 got_object_commit_close(commit);
9238 free(commit_id_str);
9239 if (worktree)
9240 got_worktree_close(worktree);
9241 if (repo) {
9242 const struct got_error *close_err = got_repo_close(repo);
9243 if (error == NULL)
9244 error = close_err;
9246 if (pack_fds) {
9247 const struct got_error *pack_err =
9248 got_repo_pack_fds_close(pack_fds);
9249 if (error == NULL)
9250 error = pack_err;
9252 return error;
9255 __dead static void
9256 usage_rebase(void)
9258 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9259 getprogname());
9260 exit(1);
9263 static void
9264 trim_logmsg(char *logmsg, int limit)
9266 char *nl;
9267 size_t len;
9269 len = strlen(logmsg);
9270 if (len > limit)
9271 len = limit;
9272 logmsg[len] = '\0';
9273 nl = strchr(logmsg, '\n');
9274 if (nl)
9275 *nl = '\0';
9278 static const struct got_error *
9279 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9281 const struct got_error *err;
9282 char *logmsg0 = NULL;
9283 const char *s;
9285 err = got_object_commit_get_logmsg(&logmsg0, commit);
9286 if (err)
9287 return err;
9289 s = logmsg0;
9290 while (isspace((unsigned char)s[0]))
9291 s++;
9293 *logmsg = strdup(s);
9294 if (*logmsg == NULL) {
9295 err = got_error_from_errno("strdup");
9296 goto done;
9299 trim_logmsg(*logmsg, limit);
9300 done:
9301 free(logmsg0);
9302 return err;
9305 static const struct got_error *
9306 show_rebase_merge_conflict(struct got_object_id *id,
9307 struct got_repository *repo)
9309 const struct got_error *err;
9310 struct got_commit_object *commit = NULL;
9311 char *id_str = NULL, *logmsg = NULL;
9313 err = got_object_open_as_commit(&commit, repo, id);
9314 if (err)
9315 return err;
9317 err = got_object_id_str(&id_str, id);
9318 if (err)
9319 goto done;
9321 id_str[12] = '\0';
9323 err = get_short_logmsg(&logmsg, 42, commit);
9324 if (err)
9325 goto done;
9327 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9328 done:
9329 free(id_str);
9330 got_object_commit_close(commit);
9331 free(logmsg);
9332 return err;
9335 static const struct got_error *
9336 show_rebase_progress(struct got_commit_object *commit,
9337 struct got_object_id *old_id, struct got_object_id *new_id)
9339 const struct got_error *err;
9340 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9342 err = got_object_id_str(&old_id_str, old_id);
9343 if (err)
9344 goto done;
9346 if (new_id) {
9347 err = got_object_id_str(&new_id_str, new_id);
9348 if (err)
9349 goto done;
9352 old_id_str[12] = '\0';
9353 if (new_id_str)
9354 new_id_str[12] = '\0';
9356 err = get_short_logmsg(&logmsg, 42, commit);
9357 if (err)
9358 goto done;
9360 printf("%s -> %s: %s\n", old_id_str,
9361 new_id_str ? new_id_str : "no-op change", logmsg);
9362 done:
9363 free(old_id_str);
9364 free(new_id_str);
9365 free(logmsg);
9366 return err;
9369 static const struct got_error *
9370 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9371 struct got_reference *branch, struct got_reference *new_base_branch,
9372 struct got_reference *tmp_branch, struct got_repository *repo,
9373 int create_backup)
9375 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9376 return got_worktree_rebase_complete(worktree, fileindex,
9377 new_base_branch, tmp_branch, branch, repo, create_backup);
9380 static const struct got_error *
9381 rebase_commit(struct got_pathlist_head *merged_paths,
9382 struct got_worktree *worktree, struct got_fileindex *fileindex,
9383 struct got_reference *tmp_branch,
9384 struct got_object_id *commit_id, struct got_repository *repo)
9386 const struct got_error *error;
9387 struct got_commit_object *commit;
9388 struct got_object_id *new_commit_id;
9390 error = got_object_open_as_commit(&commit, repo, commit_id);
9391 if (error)
9392 return error;
9394 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9395 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9396 if (error) {
9397 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9398 goto done;
9399 error = show_rebase_progress(commit, commit_id, NULL);
9400 } else {
9401 error = show_rebase_progress(commit, commit_id, new_commit_id);
9402 free(new_commit_id);
9404 done:
9405 got_object_commit_close(commit);
9406 return error;
9409 struct check_path_prefix_arg {
9410 const char *path_prefix;
9411 size_t len;
9412 int errcode;
9415 static const struct got_error *
9416 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9417 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9418 struct got_object_id *id1, struct got_object_id *id2,
9419 const char *path1, const char *path2,
9420 mode_t mode1, mode_t mode2, struct got_repository *repo)
9422 struct check_path_prefix_arg *a = arg;
9424 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9425 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9426 return got_error(a->errcode);
9428 return NULL;
9431 static const struct got_error *
9432 check_path_prefix(struct got_object_id *parent_id,
9433 struct got_object_id *commit_id, const char *path_prefix,
9434 int errcode, struct got_repository *repo)
9436 const struct got_error *err;
9437 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9438 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9439 struct check_path_prefix_arg cpp_arg;
9441 if (got_path_is_root_dir(path_prefix))
9442 return NULL;
9444 err = got_object_open_as_commit(&commit, repo, commit_id);
9445 if (err)
9446 goto done;
9448 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9449 if (err)
9450 goto done;
9452 err = got_object_open_as_tree(&tree1, repo,
9453 got_object_commit_get_tree_id(parent_commit));
9454 if (err)
9455 goto done;
9457 err = got_object_open_as_tree(&tree2, repo,
9458 got_object_commit_get_tree_id(commit));
9459 if (err)
9460 goto done;
9462 cpp_arg.path_prefix = path_prefix;
9463 while (cpp_arg.path_prefix[0] == '/')
9464 cpp_arg.path_prefix++;
9465 cpp_arg.len = strlen(cpp_arg.path_prefix);
9466 cpp_arg.errcode = errcode;
9467 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9468 check_path_prefix_in_diff, &cpp_arg, 0);
9469 done:
9470 if (tree1)
9471 got_object_tree_close(tree1);
9472 if (tree2)
9473 got_object_tree_close(tree2);
9474 if (commit)
9475 got_object_commit_close(commit);
9476 if (parent_commit)
9477 got_object_commit_close(parent_commit);
9478 return err;
9481 static const struct got_error *
9482 collect_commits(struct got_object_id_queue *commits,
9483 struct got_object_id *initial_commit_id,
9484 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9485 const char *path_prefix, int path_prefix_errcode,
9486 struct got_repository *repo)
9488 const struct got_error *err = NULL;
9489 struct got_commit_graph *graph = NULL;
9490 struct got_object_id *parent_id = NULL;
9491 struct got_object_qid *qid;
9492 struct got_object_id *commit_id = initial_commit_id;
9494 err = got_commit_graph_open(&graph, "/", 1);
9495 if (err)
9496 return err;
9498 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9499 check_cancelled, NULL);
9500 if (err)
9501 goto done;
9502 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9503 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9504 check_cancelled, NULL);
9505 if (err) {
9506 if (err->code == GOT_ERR_ITER_COMPLETED) {
9507 err = got_error_msg(GOT_ERR_ANCESTRY,
9508 "ran out of commits to rebase before "
9509 "youngest common ancestor commit has "
9510 "been reached?!?");
9512 goto done;
9513 } else {
9514 err = check_path_prefix(parent_id, commit_id,
9515 path_prefix, path_prefix_errcode, repo);
9516 if (err)
9517 goto done;
9519 err = got_object_qid_alloc(&qid, commit_id);
9520 if (err)
9521 goto done;
9522 STAILQ_INSERT_HEAD(commits, qid, entry);
9523 commit_id = parent_id;
9526 done:
9527 got_commit_graph_close(graph);
9528 return err;
9531 static const struct got_error *
9532 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9534 const struct got_error *err = NULL;
9535 time_t committer_time;
9536 struct tm tm;
9537 char datebuf[11]; /* YYYY-MM-DD + NUL */
9538 char *author0 = NULL, *author, *smallerthan;
9539 char *logmsg0 = NULL, *logmsg, *newline;
9541 committer_time = got_object_commit_get_committer_time(commit);
9542 if (gmtime_r(&committer_time, &tm) == NULL)
9543 return got_error_from_errno("gmtime_r");
9544 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9545 return got_error(GOT_ERR_NO_SPACE);
9547 author0 = strdup(got_object_commit_get_author(commit));
9548 if (author0 == NULL)
9549 return got_error_from_errno("strdup");
9550 author = author0;
9551 smallerthan = strchr(author, '<');
9552 if (smallerthan && smallerthan[1] != '\0')
9553 author = smallerthan + 1;
9554 author[strcspn(author, "@>")] = '\0';
9556 err = got_object_commit_get_logmsg(&logmsg0, commit);
9557 if (err)
9558 goto done;
9559 logmsg = logmsg0;
9560 while (*logmsg == '\n')
9561 logmsg++;
9562 newline = strchr(logmsg, '\n');
9563 if (newline)
9564 *newline = '\0';
9566 if (asprintf(brief_str, "%s %s %s",
9567 datebuf, author, logmsg) == -1)
9568 err = got_error_from_errno("asprintf");
9569 done:
9570 free(author0);
9571 free(logmsg0);
9572 return err;
9575 static const struct got_error *
9576 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9577 struct got_repository *repo)
9579 const struct got_error *err;
9580 char *id_str;
9582 err = got_object_id_str(&id_str, id);
9583 if (err)
9584 return err;
9586 err = got_ref_delete(ref, repo);
9587 if (err)
9588 goto done;
9590 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9591 done:
9592 free(id_str);
9593 return err;
9596 static const struct got_error *
9597 print_backup_ref(const char *branch_name, const char *new_id_str,
9598 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9599 struct got_reflist_object_id_map *refs_idmap,
9600 struct got_repository *repo)
9602 const struct got_error *err = NULL;
9603 struct got_reflist_head *refs;
9604 char *refs_str = NULL;
9605 struct got_object_id *new_commit_id = NULL;
9606 struct got_commit_object *new_commit = NULL;
9607 char *new_commit_brief_str = NULL;
9608 struct got_object_id *yca_id = NULL;
9609 struct got_commit_object *yca_commit = NULL;
9610 char *yca_id_str = NULL, *yca_brief_str = NULL;
9611 char *custom_refs_str;
9613 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9614 return got_error_from_errno("asprintf");
9616 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9617 0, 0, refs_idmap, custom_refs_str);
9618 if (err)
9619 goto done;
9621 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9622 if (err)
9623 goto done;
9625 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9626 if (refs) {
9627 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9628 if (err)
9629 goto done;
9632 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9633 if (err)
9634 goto done;
9636 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9637 if (err)
9638 goto done;
9640 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9641 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9642 if (err)
9643 goto done;
9645 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9646 refs_str ? " (" : "", refs_str ? refs_str : "",
9647 refs_str ? ")" : "", new_commit_brief_str);
9648 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9649 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9650 free(refs_str);
9651 refs_str = NULL;
9653 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9654 if (err)
9655 goto done;
9657 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9658 if (err)
9659 goto done;
9661 err = got_object_id_str(&yca_id_str, yca_id);
9662 if (err)
9663 goto done;
9665 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9666 if (refs) {
9667 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9668 if (err)
9669 goto done;
9671 printf("history forked at %s%s%s%s\n %s\n",
9672 yca_id_str,
9673 refs_str ? " (" : "", refs_str ? refs_str : "",
9674 refs_str ? ")" : "", yca_brief_str);
9676 done:
9677 free(custom_refs_str);
9678 free(new_commit_id);
9679 free(refs_str);
9680 free(yca_id);
9681 free(yca_id_str);
9682 free(yca_brief_str);
9683 if (new_commit)
9684 got_object_commit_close(new_commit);
9685 if (yca_commit)
9686 got_object_commit_close(yca_commit);
9688 return NULL;
9691 static const struct got_error *
9692 process_backup_refs(const char *backup_ref_prefix,
9693 const char *wanted_branch_name,
9694 int delete, struct got_repository *repo)
9696 const struct got_error *err;
9697 struct got_reflist_head refs, backup_refs;
9698 struct got_reflist_entry *re;
9699 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9700 struct got_object_id *old_commit_id = NULL;
9701 char *branch_name = NULL;
9702 struct got_commit_object *old_commit = NULL;
9703 struct got_reflist_object_id_map *refs_idmap = NULL;
9704 int wanted_branch_found = 0;
9706 TAILQ_INIT(&refs);
9707 TAILQ_INIT(&backup_refs);
9709 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9710 if (err)
9711 return err;
9713 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9714 if (err)
9715 goto done;
9717 if (wanted_branch_name) {
9718 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9719 wanted_branch_name += 11;
9722 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9723 got_ref_cmp_by_commit_timestamp_descending, repo);
9724 if (err)
9725 goto done;
9727 TAILQ_FOREACH(re, &backup_refs, entry) {
9728 const char *refname = got_ref_get_name(re->ref);
9729 char *slash;
9731 err = check_cancelled(NULL);
9732 if (err)
9733 break;
9735 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9736 if (err)
9737 break;
9739 err = got_object_open_as_commit(&old_commit, repo,
9740 old_commit_id);
9741 if (err)
9742 break;
9744 if (strncmp(backup_ref_prefix, refname,
9745 backup_ref_prefix_len) == 0)
9746 refname += backup_ref_prefix_len;
9748 while (refname[0] == '/')
9749 refname++;
9751 branch_name = strdup(refname);
9752 if (branch_name == NULL) {
9753 err = got_error_from_errno("strdup");
9754 break;
9756 slash = strrchr(branch_name, '/');
9757 if (slash) {
9758 *slash = '\0';
9759 refname += strlen(branch_name) + 1;
9762 if (wanted_branch_name == NULL ||
9763 strcmp(wanted_branch_name, branch_name) == 0) {
9764 wanted_branch_found = 1;
9765 if (delete) {
9766 err = delete_backup_ref(re->ref,
9767 old_commit_id, repo);
9768 } else {
9769 err = print_backup_ref(branch_name, refname,
9770 old_commit_id, old_commit, refs_idmap,
9771 repo);
9773 if (err)
9774 break;
9777 free(old_commit_id);
9778 old_commit_id = NULL;
9779 free(branch_name);
9780 branch_name = NULL;
9781 got_object_commit_close(old_commit);
9782 old_commit = NULL;
9785 if (wanted_branch_name && !wanted_branch_found) {
9786 err = got_error_fmt(GOT_ERR_NOT_REF,
9787 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9789 done:
9790 if (refs_idmap)
9791 got_reflist_object_id_map_free(refs_idmap);
9792 got_ref_list_free(&refs);
9793 got_ref_list_free(&backup_refs);
9794 free(old_commit_id);
9795 free(branch_name);
9796 if (old_commit)
9797 got_object_commit_close(old_commit);
9798 return err;
9801 static const struct got_error *
9802 abort_progress(void *arg, unsigned char status, const char *path)
9805 * Unversioned files should not clutter progress output when
9806 * an operation is aborted.
9808 if (status == GOT_STATUS_UNVERSIONED)
9809 return NULL;
9811 return update_progress(arg, status, path);
9814 static const struct got_error *
9815 cmd_rebase(int argc, char *argv[])
9817 const struct got_error *error = NULL;
9818 struct got_worktree *worktree = NULL;
9819 struct got_repository *repo = NULL;
9820 struct got_fileindex *fileindex = NULL;
9821 char *cwd = NULL;
9822 struct got_reference *branch = NULL;
9823 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9824 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9825 struct got_object_id *resume_commit_id = NULL;
9826 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9827 struct got_commit_object *commit = NULL;
9828 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9829 int histedit_in_progress = 0, merge_in_progress = 0;
9830 int create_backup = 1, list_backups = 0, delete_backups = 0;
9831 struct got_object_id_queue commits;
9832 struct got_pathlist_head merged_paths;
9833 const struct got_object_id_queue *parent_ids;
9834 struct got_object_qid *qid, *pid;
9835 struct got_update_progress_arg upa;
9836 int *pack_fds = NULL;
9838 STAILQ_INIT(&commits);
9839 TAILQ_INIT(&merged_paths);
9840 memset(&upa, 0, sizeof(upa));
9842 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9843 switch (ch) {
9844 case 'a':
9845 abort_rebase = 1;
9846 break;
9847 case 'c':
9848 continue_rebase = 1;
9849 break;
9850 case 'l':
9851 list_backups = 1;
9852 break;
9853 case 'X':
9854 delete_backups = 1;
9855 break;
9856 default:
9857 usage_rebase();
9858 /* NOTREACHED */
9862 argc -= optind;
9863 argv += optind;
9865 #ifndef PROFILE
9866 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9867 "unveil", NULL) == -1)
9868 err(1, "pledge");
9869 #endif
9870 if (list_backups) {
9871 if (abort_rebase)
9872 option_conflict('l', 'a');
9873 if (continue_rebase)
9874 option_conflict('l', 'c');
9875 if (delete_backups)
9876 option_conflict('l', 'X');
9877 if (argc != 0 && argc != 1)
9878 usage_rebase();
9879 } else if (delete_backups) {
9880 if (abort_rebase)
9881 option_conflict('X', 'a');
9882 if (continue_rebase)
9883 option_conflict('X', 'c');
9884 if (list_backups)
9885 option_conflict('l', 'X');
9886 if (argc != 0 && argc != 1)
9887 usage_rebase();
9888 } else {
9889 if (abort_rebase && continue_rebase)
9890 usage_rebase();
9891 else if (abort_rebase || continue_rebase) {
9892 if (argc != 0)
9893 usage_rebase();
9894 } else if (argc != 1)
9895 usage_rebase();
9898 cwd = getcwd(NULL, 0);
9899 if (cwd == NULL) {
9900 error = got_error_from_errno("getcwd");
9901 goto done;
9904 error = got_repo_pack_fds_open(&pack_fds);
9905 if (error != NULL)
9906 goto done;
9908 error = got_worktree_open(&worktree, cwd);
9909 if (error) {
9910 if (list_backups || delete_backups) {
9911 if (error->code != GOT_ERR_NOT_WORKTREE)
9912 goto done;
9913 } else {
9914 if (error->code == GOT_ERR_NOT_WORKTREE)
9915 error = wrap_not_worktree_error(error,
9916 "rebase", cwd);
9917 goto done;
9921 error = got_repo_open(&repo,
9922 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
9923 pack_fds);
9924 if (error != NULL)
9925 goto done;
9927 error = apply_unveil(got_repo_get_path(repo), 0,
9928 worktree ? got_worktree_get_root_path(worktree) : NULL);
9929 if (error)
9930 goto done;
9932 if (list_backups || delete_backups) {
9933 error = process_backup_refs(
9934 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9935 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9936 goto done; /* nothing else to do */
9939 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9940 worktree);
9941 if (error)
9942 goto done;
9943 if (histedit_in_progress) {
9944 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9945 goto done;
9948 error = got_worktree_merge_in_progress(&merge_in_progress,
9949 worktree, repo);
9950 if (error)
9951 goto done;
9952 if (merge_in_progress) {
9953 error = got_error(GOT_ERR_MERGE_BUSY);
9954 goto done;
9957 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9958 if (error)
9959 goto done;
9961 if (abort_rebase) {
9962 if (!rebase_in_progress) {
9963 error = got_error(GOT_ERR_NOT_REBASING);
9964 goto done;
9966 error = got_worktree_rebase_continue(&resume_commit_id,
9967 &new_base_branch, &tmp_branch, &branch, &fileindex,
9968 worktree, repo);
9969 if (error)
9970 goto done;
9971 printf("Switching work tree to %s\n",
9972 got_ref_get_symref_target(new_base_branch));
9973 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9974 new_base_branch, abort_progress, &upa);
9975 if (error)
9976 goto done;
9977 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9978 print_merge_progress_stats(&upa);
9979 goto done; /* nothing else to do */
9982 if (continue_rebase) {
9983 if (!rebase_in_progress) {
9984 error = got_error(GOT_ERR_NOT_REBASING);
9985 goto done;
9987 error = got_worktree_rebase_continue(&resume_commit_id,
9988 &new_base_branch, &tmp_branch, &branch, &fileindex,
9989 worktree, repo);
9990 if (error)
9991 goto done;
9993 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9994 resume_commit_id, repo);
9995 if (error)
9996 goto done;
9998 yca_id = got_object_id_dup(resume_commit_id);
9999 if (yca_id == NULL) {
10000 error = got_error_from_errno("got_object_id_dup");
10001 goto done;
10003 } else {
10004 error = got_ref_open(&branch, repo, argv[0], 0);
10005 if (error != NULL)
10006 goto done;
10009 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10010 if (error)
10011 goto done;
10013 if (!continue_rebase) {
10014 struct got_object_id *base_commit_id;
10016 base_commit_id = got_worktree_get_base_commit_id(worktree);
10017 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10018 base_commit_id, branch_head_commit_id, 1, repo,
10019 check_cancelled, NULL);
10020 if (error)
10021 goto done;
10022 if (yca_id == NULL) {
10023 error = got_error_msg(GOT_ERR_ANCESTRY,
10024 "specified branch shares no common ancestry "
10025 "with work tree's branch");
10026 goto done;
10029 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10030 if (error) {
10031 if (error->code != GOT_ERR_ANCESTRY)
10032 goto done;
10033 error = NULL;
10034 } else {
10035 struct got_pathlist_head paths;
10036 printf("%s is already based on %s\n",
10037 got_ref_get_name(branch),
10038 got_worktree_get_head_ref_name(worktree));
10039 error = switch_head_ref(branch, branch_head_commit_id,
10040 worktree, repo);
10041 if (error)
10042 goto done;
10043 error = got_worktree_set_base_commit_id(worktree, repo,
10044 branch_head_commit_id);
10045 if (error)
10046 goto done;
10047 TAILQ_INIT(&paths);
10048 error = got_pathlist_append(&paths, "", NULL);
10049 if (error)
10050 goto done;
10051 error = got_worktree_checkout_files(worktree,
10052 &paths, repo, update_progress, &upa,
10053 check_cancelled, NULL);
10054 got_pathlist_free(&paths);
10055 if (error)
10056 goto done;
10057 if (upa.did_something) {
10058 char *id_str;
10059 error = got_object_id_str(&id_str,
10060 branch_head_commit_id);
10061 if (error)
10062 goto done;
10063 printf("Updated to %s: %s\n",
10064 got_worktree_get_head_ref_name(worktree),
10065 id_str);
10066 free(id_str);
10067 } else
10068 printf("Already up-to-date\n");
10069 print_update_progress_stats(&upa);
10070 goto done;
10074 commit_id = branch_head_commit_id;
10075 error = got_object_open_as_commit(&commit, repo, commit_id);
10076 if (error)
10077 goto done;
10079 parent_ids = got_object_commit_get_parent_ids(commit);
10080 pid = STAILQ_FIRST(parent_ids);
10081 if (pid == NULL) {
10082 error = got_error(GOT_ERR_EMPTY_REBASE);
10083 goto done;
10085 error = collect_commits(&commits, commit_id, &pid->id,
10086 yca_id, got_worktree_get_path_prefix(worktree),
10087 GOT_ERR_REBASE_PATH, repo);
10088 got_object_commit_close(commit);
10089 commit = NULL;
10090 if (error)
10091 goto done;
10093 if (!continue_rebase) {
10094 error = got_worktree_rebase_prepare(&new_base_branch,
10095 &tmp_branch, &fileindex, worktree, branch, repo);
10096 if (error)
10097 goto done;
10100 if (STAILQ_EMPTY(&commits)) {
10101 if (continue_rebase) {
10102 error = rebase_complete(worktree, fileindex,
10103 branch, new_base_branch, tmp_branch, repo,
10104 create_backup);
10105 goto done;
10106 } else {
10107 /* Fast-forward the reference of the branch. */
10108 struct got_object_id *new_head_commit_id;
10109 char *id_str;
10110 error = got_ref_resolve(&new_head_commit_id, repo,
10111 new_base_branch);
10112 if (error)
10113 goto done;
10114 error = got_object_id_str(&id_str, new_head_commit_id);
10115 printf("Forwarding %s to commit %s\n",
10116 got_ref_get_name(branch), id_str);
10117 free(id_str);
10118 error = got_ref_change_ref(branch,
10119 new_head_commit_id);
10120 if (error)
10121 goto done;
10122 /* No backup needed since objects did not change. */
10123 create_backup = 0;
10127 pid = NULL;
10128 STAILQ_FOREACH(qid, &commits, entry) {
10130 commit_id = &qid->id;
10131 parent_id = pid ? &pid->id : yca_id;
10132 pid = qid;
10134 memset(&upa, 0, sizeof(upa));
10135 error = got_worktree_rebase_merge_files(&merged_paths,
10136 worktree, fileindex, parent_id, commit_id, repo,
10137 update_progress, &upa, check_cancelled, NULL);
10138 if (error)
10139 goto done;
10141 print_merge_progress_stats(&upa);
10142 if (upa.conflicts > 0 || upa.missing > 0 ||
10143 upa.not_deleted > 0 || upa.unversioned > 0) {
10144 if (upa.conflicts > 0) {
10145 error = show_rebase_merge_conflict(&qid->id,
10146 repo);
10147 if (error)
10148 goto done;
10150 got_worktree_rebase_pathlist_free(&merged_paths);
10151 break;
10154 error = rebase_commit(&merged_paths, worktree, fileindex,
10155 tmp_branch, commit_id, repo);
10156 got_worktree_rebase_pathlist_free(&merged_paths);
10157 if (error)
10158 goto done;
10161 if (upa.conflicts > 0 || upa.missing > 0 ||
10162 upa.not_deleted > 0 || upa.unversioned > 0) {
10163 error = got_worktree_rebase_postpone(worktree, fileindex);
10164 if (error)
10165 goto done;
10166 if (upa.conflicts > 0 && upa.missing == 0 &&
10167 upa.not_deleted == 0 && upa.unversioned == 0) {
10168 error = got_error_msg(GOT_ERR_CONFLICTS,
10169 "conflicts must be resolved before rebasing "
10170 "can continue");
10171 } else if (upa.conflicts > 0) {
10172 error = got_error_msg(GOT_ERR_CONFLICTS,
10173 "conflicts must be resolved before rebasing "
10174 "can continue; changes destined for some "
10175 "files were not yet merged and should be "
10176 "merged manually if required before the "
10177 "rebase operation is continued");
10178 } else {
10179 error = got_error_msg(GOT_ERR_CONFLICTS,
10180 "changes destined for some files were not "
10181 "yet merged and should be merged manually "
10182 "if required before the rebase operation "
10183 "is continued");
10185 } else
10186 error = rebase_complete(worktree, fileindex, branch,
10187 new_base_branch, tmp_branch, repo, create_backup);
10188 done:
10189 got_object_id_queue_free(&commits);
10190 free(branch_head_commit_id);
10191 free(resume_commit_id);
10192 free(yca_id);
10193 if (commit)
10194 got_object_commit_close(commit);
10195 if (branch)
10196 got_ref_close(branch);
10197 if (new_base_branch)
10198 got_ref_close(new_base_branch);
10199 if (tmp_branch)
10200 got_ref_close(tmp_branch);
10201 if (worktree)
10202 got_worktree_close(worktree);
10203 if (repo) {
10204 const struct got_error *close_err = got_repo_close(repo);
10205 if (error == NULL)
10206 error = close_err;
10208 if (pack_fds) {
10209 const struct got_error *pack_err =
10210 got_repo_pack_fds_close(pack_fds);
10211 if (error == NULL)
10212 error = pack_err;
10214 return error;
10217 __dead static void
10218 usage_histedit(void)
10220 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10221 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10222 getprogname());
10223 exit(1);
10226 #define GOT_HISTEDIT_PICK 'p'
10227 #define GOT_HISTEDIT_EDIT 'e'
10228 #define GOT_HISTEDIT_FOLD 'f'
10229 #define GOT_HISTEDIT_DROP 'd'
10230 #define GOT_HISTEDIT_MESG 'm'
10232 static const struct got_histedit_cmd {
10233 unsigned char code;
10234 const char *name;
10235 const char *desc;
10236 } got_histedit_cmds[] = {
10237 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10238 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10239 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10240 "be used" },
10241 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10242 { GOT_HISTEDIT_MESG, "mesg",
10243 "single-line log message for commit above (open editor if empty)" },
10246 struct got_histedit_list_entry {
10247 TAILQ_ENTRY(got_histedit_list_entry) entry;
10248 struct got_object_id *commit_id;
10249 const struct got_histedit_cmd *cmd;
10250 char *logmsg;
10252 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10254 static const struct got_error *
10255 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10256 FILE *f, struct got_repository *repo)
10258 const struct got_error *err = NULL;
10259 char *logmsg = NULL, *id_str = NULL;
10260 struct got_commit_object *commit = NULL;
10261 int n;
10263 err = got_object_open_as_commit(&commit, repo, commit_id);
10264 if (err)
10265 goto done;
10267 err = get_short_logmsg(&logmsg, 34, commit);
10268 if (err)
10269 goto done;
10271 err = got_object_id_str(&id_str, commit_id);
10272 if (err)
10273 goto done;
10275 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10276 if (n < 0)
10277 err = got_ferror(f, GOT_ERR_IO);
10278 done:
10279 if (commit)
10280 got_object_commit_close(commit);
10281 free(id_str);
10282 free(logmsg);
10283 return err;
10286 static const struct got_error *
10287 histedit_write_commit_list(struct got_object_id_queue *commits,
10288 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10289 struct got_repository *repo)
10291 const struct got_error *err = NULL;
10292 struct got_object_qid *qid;
10293 const char *histedit_cmd = NULL;
10295 if (STAILQ_EMPTY(commits))
10296 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10298 STAILQ_FOREACH(qid, commits, entry) {
10299 histedit_cmd = got_histedit_cmds[0].name;
10300 if (edit_only)
10301 histedit_cmd = "edit";
10302 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10303 histedit_cmd = "fold";
10304 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10305 if (err)
10306 break;
10307 if (edit_logmsg_only) {
10308 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10309 if (n < 0) {
10310 err = got_ferror(f, GOT_ERR_IO);
10311 break;
10316 return err;
10319 static const struct got_error *
10320 write_cmd_list(FILE *f, const char *branch_name,
10321 struct got_object_id_queue *commits)
10323 const struct got_error *err = NULL;
10324 size_t i;
10325 int n;
10326 char *id_str;
10327 struct got_object_qid *qid;
10329 qid = STAILQ_FIRST(commits);
10330 err = got_object_id_str(&id_str, &qid->id);
10331 if (err)
10332 return err;
10334 n = fprintf(f,
10335 "# Editing the history of branch '%s' starting at\n"
10336 "# commit %s\n"
10337 "# Commits will be processed in order from top to "
10338 "bottom of this file.\n", branch_name, id_str);
10339 if (n < 0) {
10340 err = got_ferror(f, GOT_ERR_IO);
10341 goto done;
10344 n = fprintf(f, "# Available histedit commands:\n");
10345 if (n < 0) {
10346 err = got_ferror(f, GOT_ERR_IO);
10347 goto done;
10350 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10351 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10352 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10353 cmd->desc);
10354 if (n < 0) {
10355 err = got_ferror(f, GOT_ERR_IO);
10356 break;
10359 done:
10360 free(id_str);
10361 return err;
10364 static const struct got_error *
10365 histedit_syntax_error(int lineno)
10367 static char msg[42];
10368 int ret;
10370 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10371 lineno);
10372 if (ret == -1 || ret >= sizeof(msg))
10373 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10375 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10378 static const struct got_error *
10379 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10380 char *logmsg, struct got_repository *repo)
10382 const struct got_error *err;
10383 struct got_commit_object *folded_commit = NULL;
10384 char *id_str, *folded_logmsg = NULL;
10386 err = got_object_id_str(&id_str, hle->commit_id);
10387 if (err)
10388 return err;
10390 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10391 if (err)
10392 goto done;
10394 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10395 if (err)
10396 goto done;
10397 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10398 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10399 folded_logmsg) == -1) {
10400 err = got_error_from_errno("asprintf");
10402 done:
10403 if (folded_commit)
10404 got_object_commit_close(folded_commit);
10405 free(id_str);
10406 free(folded_logmsg);
10407 return err;
10410 static struct got_histedit_list_entry *
10411 get_folded_commits(struct got_histedit_list_entry *hle)
10413 struct got_histedit_list_entry *prev, *folded = NULL;
10415 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10416 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10417 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10418 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10419 folded = prev;
10420 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10423 return folded;
10426 static const struct got_error *
10427 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10428 struct got_repository *repo)
10430 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10431 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10432 const struct got_error *err = NULL;
10433 struct got_commit_object *commit = NULL;
10434 int logmsg_len;
10435 int fd;
10436 struct got_histedit_list_entry *folded = NULL;
10438 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10439 if (err)
10440 return err;
10442 folded = get_folded_commits(hle);
10443 if (folded) {
10444 while (folded != hle) {
10445 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10446 folded = TAILQ_NEXT(folded, entry);
10447 continue;
10449 err = append_folded_commit_msg(&new_msg, folded,
10450 logmsg, repo);
10451 if (err)
10452 goto done;
10453 free(logmsg);
10454 logmsg = new_msg;
10455 folded = TAILQ_NEXT(folded, entry);
10459 err = got_object_id_str(&id_str, hle->commit_id);
10460 if (err)
10461 goto done;
10462 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10463 if (err)
10464 goto done;
10465 logmsg_len = asprintf(&new_msg,
10466 "%s\n# original log message of commit %s: %s",
10467 logmsg ? logmsg : "", id_str, orig_logmsg);
10468 if (logmsg_len == -1) {
10469 err = got_error_from_errno("asprintf");
10470 goto done;
10472 free(logmsg);
10473 logmsg = new_msg;
10475 err = got_object_id_str(&id_str, hle->commit_id);
10476 if (err)
10477 goto done;
10479 err = got_opentemp_named_fd(&logmsg_path, &fd,
10480 GOT_TMPDIR_STR "/got-logmsg");
10481 if (err)
10482 goto done;
10484 write(fd, logmsg, logmsg_len);
10485 close(fd);
10487 err = get_editor(&editor);
10488 if (err)
10489 goto done;
10491 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10492 logmsg_len, 0);
10493 if (err) {
10494 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10495 goto done;
10496 err = NULL;
10497 hle->logmsg = strdup(new_msg);
10498 if (hle->logmsg == NULL)
10499 err = got_error_from_errno("strdup");
10501 done:
10502 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10503 err = got_error_from_errno2("unlink", logmsg_path);
10504 free(logmsg_path);
10505 free(logmsg);
10506 free(orig_logmsg);
10507 free(editor);
10508 if (commit)
10509 got_object_commit_close(commit);
10510 return err;
10513 static const struct got_error *
10514 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10515 FILE *f, struct got_repository *repo)
10517 const struct got_error *err = NULL;
10518 char *line = NULL, *p, *end;
10519 size_t i, size;
10520 ssize_t len;
10521 int lineno = 0;
10522 const struct got_histedit_cmd *cmd;
10523 struct got_object_id *commit_id = NULL;
10524 struct got_histedit_list_entry *hle = NULL;
10526 for (;;) {
10527 len = getline(&line, &size, f);
10528 if (len == -1) {
10529 const struct got_error *getline_err;
10530 if (feof(f))
10531 break;
10532 getline_err = got_error_from_errno("getline");
10533 err = got_ferror(f, getline_err->code);
10534 break;
10536 lineno++;
10537 p = line;
10538 while (isspace((unsigned char)p[0]))
10539 p++;
10540 if (p[0] == '#' || p[0] == '\0') {
10541 free(line);
10542 line = NULL;
10543 continue;
10545 cmd = NULL;
10546 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10547 cmd = &got_histedit_cmds[i];
10548 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10549 isspace((unsigned char)p[strlen(cmd->name)])) {
10550 p += strlen(cmd->name);
10551 break;
10553 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10554 p++;
10555 break;
10558 if (i == nitems(got_histedit_cmds)) {
10559 err = histedit_syntax_error(lineno);
10560 break;
10562 while (isspace((unsigned char)p[0]))
10563 p++;
10564 if (cmd->code == GOT_HISTEDIT_MESG) {
10565 if (hle == NULL || hle->logmsg != NULL) {
10566 err = got_error(GOT_ERR_HISTEDIT_CMD);
10567 break;
10569 if (p[0] == '\0') {
10570 err = histedit_edit_logmsg(hle, repo);
10571 if (err)
10572 break;
10573 } else {
10574 hle->logmsg = strdup(p);
10575 if (hle->logmsg == NULL) {
10576 err = got_error_from_errno("strdup");
10577 break;
10580 free(line);
10581 line = NULL;
10582 continue;
10583 } else {
10584 end = p;
10585 while (end[0] && !isspace((unsigned char)end[0]))
10586 end++;
10587 *end = '\0';
10589 err = got_object_resolve_id_str(&commit_id, repo, p);
10590 if (err) {
10591 /* override error code */
10592 err = histedit_syntax_error(lineno);
10593 break;
10596 hle = malloc(sizeof(*hle));
10597 if (hle == NULL) {
10598 err = got_error_from_errno("malloc");
10599 break;
10601 hle->cmd = cmd;
10602 hle->commit_id = commit_id;
10603 hle->logmsg = NULL;
10604 commit_id = NULL;
10605 free(line);
10606 line = NULL;
10607 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10610 free(line);
10611 free(commit_id);
10612 return err;
10615 static const struct got_error *
10616 histedit_check_script(struct got_histedit_list *histedit_cmds,
10617 struct got_object_id_queue *commits, struct got_repository *repo)
10619 const struct got_error *err = NULL;
10620 struct got_object_qid *qid;
10621 struct got_histedit_list_entry *hle;
10622 static char msg[92];
10623 char *id_str;
10625 if (TAILQ_EMPTY(histedit_cmds))
10626 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10627 "histedit script contains no commands");
10628 if (STAILQ_EMPTY(commits))
10629 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10631 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10632 struct got_histedit_list_entry *hle2;
10633 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10634 if (hle == hle2)
10635 continue;
10636 if (got_object_id_cmp(hle->commit_id,
10637 hle2->commit_id) != 0)
10638 continue;
10639 err = got_object_id_str(&id_str, hle->commit_id);
10640 if (err)
10641 return err;
10642 snprintf(msg, sizeof(msg), "commit %s is listed "
10643 "more than once in histedit script", id_str);
10644 free(id_str);
10645 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10649 STAILQ_FOREACH(qid, commits, entry) {
10650 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10651 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10652 break;
10654 if (hle == NULL) {
10655 err = got_object_id_str(&id_str, &qid->id);
10656 if (err)
10657 return err;
10658 snprintf(msg, sizeof(msg),
10659 "commit %s missing from histedit script", id_str);
10660 free(id_str);
10661 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10665 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10666 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10667 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10668 "last commit in histedit script cannot be folded");
10670 return NULL;
10673 static const struct got_error *
10674 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10675 const char *path, struct got_object_id_queue *commits,
10676 struct got_repository *repo)
10678 const struct got_error *err = NULL;
10679 char *editor;
10680 FILE *f = NULL;
10682 err = get_editor(&editor);
10683 if (err)
10684 return err;
10686 if (spawn_editor(editor, path) == -1) {
10687 err = got_error_from_errno("failed spawning editor");
10688 goto done;
10691 f = fopen(path, "re");
10692 if (f == NULL) {
10693 err = got_error_from_errno("fopen");
10694 goto done;
10696 err = histedit_parse_list(histedit_cmds, f, repo);
10697 if (err)
10698 goto done;
10700 err = histedit_check_script(histedit_cmds, commits, repo);
10701 done:
10702 if (f && fclose(f) == EOF && err == NULL)
10703 err = got_error_from_errno("fclose");
10704 free(editor);
10705 return err;
10708 static const struct got_error *
10709 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10710 struct got_object_id_queue *, const char *, const char *,
10711 struct got_repository *);
10713 static const struct got_error *
10714 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10715 struct got_object_id_queue *commits, const char *branch_name,
10716 int edit_logmsg_only, int fold_only, int edit_only,
10717 struct got_repository *repo)
10719 const struct got_error *err;
10720 FILE *f = NULL;
10721 char *path = NULL;
10723 err = got_opentemp_named(&path, &f, "got-histedit");
10724 if (err)
10725 return err;
10727 err = write_cmd_list(f, branch_name, commits);
10728 if (err)
10729 goto done;
10731 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10732 fold_only, edit_only, repo);
10733 if (err)
10734 goto done;
10736 if (edit_logmsg_only || fold_only || edit_only) {
10737 rewind(f);
10738 err = histedit_parse_list(histedit_cmds, f, repo);
10739 } else {
10740 if (fclose(f) == EOF) {
10741 err = got_error_from_errno("fclose");
10742 goto done;
10744 f = NULL;
10745 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10746 if (err) {
10747 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10748 err->code != GOT_ERR_HISTEDIT_CMD)
10749 goto done;
10750 err = histedit_edit_list_retry(histedit_cmds, err,
10751 commits, path, branch_name, repo);
10754 done:
10755 if (f && fclose(f) == EOF && err == NULL)
10756 err = got_error_from_errno("fclose");
10757 if (path && unlink(path) != 0 && err == NULL)
10758 err = got_error_from_errno2("unlink", path);
10759 free(path);
10760 return err;
10763 static const struct got_error *
10764 histedit_save_list(struct got_histedit_list *histedit_cmds,
10765 struct got_worktree *worktree, struct got_repository *repo)
10767 const struct got_error *err = NULL;
10768 char *path = NULL;
10769 FILE *f = NULL;
10770 struct got_histedit_list_entry *hle;
10771 struct got_commit_object *commit = NULL;
10773 err = got_worktree_get_histedit_script_path(&path, worktree);
10774 if (err)
10775 return err;
10777 f = fopen(path, "we");
10778 if (f == NULL) {
10779 err = got_error_from_errno2("fopen", path);
10780 goto done;
10782 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10783 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10784 repo);
10785 if (err)
10786 break;
10788 if (hle->logmsg) {
10789 int n = fprintf(f, "%c %s\n",
10790 GOT_HISTEDIT_MESG, hle->logmsg);
10791 if (n < 0) {
10792 err = got_ferror(f, GOT_ERR_IO);
10793 break;
10797 done:
10798 if (f && fclose(f) == EOF && err == NULL)
10799 err = got_error_from_errno("fclose");
10800 free(path);
10801 if (commit)
10802 got_object_commit_close(commit);
10803 return err;
10806 static void
10807 histedit_free_list(struct got_histedit_list *histedit_cmds)
10809 struct got_histedit_list_entry *hle;
10811 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10812 TAILQ_REMOVE(histedit_cmds, hle, entry);
10813 free(hle);
10817 static const struct got_error *
10818 histedit_load_list(struct got_histedit_list *histedit_cmds,
10819 const char *path, struct got_repository *repo)
10821 const struct got_error *err = NULL;
10822 FILE *f = NULL;
10824 f = fopen(path, "re");
10825 if (f == NULL) {
10826 err = got_error_from_errno2("fopen", path);
10827 goto done;
10830 err = histedit_parse_list(histedit_cmds, f, repo);
10831 done:
10832 if (f && fclose(f) == EOF && err == NULL)
10833 err = got_error_from_errno("fclose");
10834 return err;
10837 static const struct got_error *
10838 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10839 const struct got_error *edit_err, struct got_object_id_queue *commits,
10840 const char *path, const char *branch_name, struct got_repository *repo)
10842 const struct got_error *err = NULL, *prev_err = edit_err;
10843 int resp = ' ';
10845 while (resp != 'c' && resp != 'r' && resp != 'a') {
10846 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10847 "or (a)bort: ", getprogname(), prev_err->msg);
10848 resp = getchar();
10849 if (resp == '\n')
10850 resp = getchar();
10851 if (resp == 'c') {
10852 histedit_free_list(histedit_cmds);
10853 err = histedit_run_editor(histedit_cmds, path, commits,
10854 repo);
10855 if (err) {
10856 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10857 err->code != GOT_ERR_HISTEDIT_CMD)
10858 break;
10859 prev_err = err;
10860 resp = ' ';
10861 continue;
10863 break;
10864 } else if (resp == 'r') {
10865 histedit_free_list(histedit_cmds);
10866 err = histedit_edit_script(histedit_cmds,
10867 commits, branch_name, 0, 0, 0, repo);
10868 if (err) {
10869 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10870 err->code != GOT_ERR_HISTEDIT_CMD)
10871 break;
10872 prev_err = err;
10873 resp = ' ';
10874 continue;
10876 break;
10877 } else if (resp == 'a') {
10878 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10879 break;
10880 } else
10881 printf("invalid response '%c'\n", resp);
10884 return err;
10887 static const struct got_error *
10888 histedit_complete(struct got_worktree *worktree,
10889 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10890 struct got_reference *branch, struct got_repository *repo)
10892 printf("Switching work tree to %s\n",
10893 got_ref_get_symref_target(branch));
10894 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10895 branch, repo);
10898 static const struct got_error *
10899 show_histedit_progress(struct got_commit_object *commit,
10900 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10902 const struct got_error *err;
10903 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10905 err = got_object_id_str(&old_id_str, hle->commit_id);
10906 if (err)
10907 goto done;
10909 if (new_id) {
10910 err = got_object_id_str(&new_id_str, new_id);
10911 if (err)
10912 goto done;
10915 old_id_str[12] = '\0';
10916 if (new_id_str)
10917 new_id_str[12] = '\0';
10919 if (hle->logmsg) {
10920 logmsg = strdup(hle->logmsg);
10921 if (logmsg == NULL) {
10922 err = got_error_from_errno("strdup");
10923 goto done;
10925 trim_logmsg(logmsg, 42);
10926 } else {
10927 err = get_short_logmsg(&logmsg, 42, commit);
10928 if (err)
10929 goto done;
10932 switch (hle->cmd->code) {
10933 case GOT_HISTEDIT_PICK:
10934 case GOT_HISTEDIT_EDIT:
10935 printf("%s -> %s: %s\n", old_id_str,
10936 new_id_str ? new_id_str : "no-op change", logmsg);
10937 break;
10938 case GOT_HISTEDIT_DROP:
10939 case GOT_HISTEDIT_FOLD:
10940 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10941 logmsg);
10942 break;
10943 default:
10944 break;
10946 done:
10947 free(old_id_str);
10948 free(new_id_str);
10949 return err;
10952 static const struct got_error *
10953 histedit_commit(struct got_pathlist_head *merged_paths,
10954 struct got_worktree *worktree, struct got_fileindex *fileindex,
10955 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10956 struct got_repository *repo)
10958 const struct got_error *err;
10959 struct got_commit_object *commit;
10960 struct got_object_id *new_commit_id;
10962 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10963 && hle->logmsg == NULL) {
10964 err = histedit_edit_logmsg(hle, repo);
10965 if (err)
10966 return err;
10969 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10970 if (err)
10971 return err;
10973 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10974 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10975 hle->logmsg, repo);
10976 if (err) {
10977 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10978 goto done;
10979 err = show_histedit_progress(commit, hle, NULL);
10980 } else {
10981 err = show_histedit_progress(commit, hle, new_commit_id);
10982 free(new_commit_id);
10984 done:
10985 got_object_commit_close(commit);
10986 return err;
10989 static const struct got_error *
10990 histedit_skip_commit(struct got_histedit_list_entry *hle,
10991 struct got_worktree *worktree, struct got_repository *repo)
10993 const struct got_error *error;
10994 struct got_commit_object *commit;
10996 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10997 repo);
10998 if (error)
10999 return error;
11001 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11002 if (error)
11003 return error;
11005 error = show_histedit_progress(commit, hle, NULL);
11006 got_object_commit_close(commit);
11007 return error;
11010 static const struct got_error *
11011 check_local_changes(void *arg, unsigned char status,
11012 unsigned char staged_status, const char *path,
11013 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11014 struct got_object_id *commit_id, int dirfd, const char *de_name)
11016 int *have_local_changes = arg;
11018 switch (status) {
11019 case GOT_STATUS_ADD:
11020 case GOT_STATUS_DELETE:
11021 case GOT_STATUS_MODIFY:
11022 case GOT_STATUS_CONFLICT:
11023 *have_local_changes = 1;
11024 return got_error(GOT_ERR_CANCELLED);
11025 default:
11026 break;
11029 switch (staged_status) {
11030 case GOT_STATUS_ADD:
11031 case GOT_STATUS_DELETE:
11032 case GOT_STATUS_MODIFY:
11033 *have_local_changes = 1;
11034 return got_error(GOT_ERR_CANCELLED);
11035 default:
11036 break;
11039 return NULL;
11042 static const struct got_error *
11043 cmd_histedit(int argc, char *argv[])
11045 const struct got_error *error = NULL;
11046 struct got_worktree *worktree = NULL;
11047 struct got_fileindex *fileindex = NULL;
11048 struct got_repository *repo = NULL;
11049 char *cwd = NULL;
11050 struct got_reference *branch = NULL;
11051 struct got_reference *tmp_branch = NULL;
11052 struct got_object_id *resume_commit_id = NULL;
11053 struct got_object_id *base_commit_id = NULL;
11054 struct got_object_id *head_commit_id = NULL;
11055 struct got_commit_object *commit = NULL;
11056 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11057 struct got_update_progress_arg upa;
11058 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11059 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11060 int list_backups = 0, delete_backups = 0;
11061 const char *edit_script_path = NULL;
11062 struct got_object_id_queue commits;
11063 struct got_pathlist_head merged_paths;
11064 const struct got_object_id_queue *parent_ids;
11065 struct got_object_qid *pid;
11066 struct got_histedit_list histedit_cmds;
11067 struct got_histedit_list_entry *hle;
11068 int *pack_fds = NULL;
11070 STAILQ_INIT(&commits);
11071 TAILQ_INIT(&histedit_cmds);
11072 TAILQ_INIT(&merged_paths);
11073 memset(&upa, 0, sizeof(upa));
11075 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11076 switch (ch) {
11077 case 'a':
11078 abort_edit = 1;
11079 break;
11080 case 'c':
11081 continue_edit = 1;
11082 break;
11083 case 'e':
11084 edit_only = 1;
11085 break;
11086 case 'f':
11087 fold_only = 1;
11088 break;
11089 case 'F':
11090 edit_script_path = optarg;
11091 break;
11092 case 'm':
11093 edit_logmsg_only = 1;
11094 break;
11095 case 'l':
11096 list_backups = 1;
11097 break;
11098 case 'X':
11099 delete_backups = 1;
11100 break;
11101 default:
11102 usage_histedit();
11103 /* NOTREACHED */
11107 argc -= optind;
11108 argv += optind;
11110 #ifndef PROFILE
11111 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11112 "unveil", NULL) == -1)
11113 err(1, "pledge");
11114 #endif
11115 if (abort_edit && continue_edit)
11116 option_conflict('a', 'c');
11117 if (edit_script_path && edit_logmsg_only)
11118 option_conflict('F', 'm');
11119 if (abort_edit && edit_logmsg_only)
11120 option_conflict('a', 'm');
11121 if (continue_edit && edit_logmsg_only)
11122 option_conflict('c', 'm');
11123 if (abort_edit && fold_only)
11124 option_conflict('a', 'f');
11125 if (continue_edit && fold_only)
11126 option_conflict('c', 'f');
11127 if (fold_only && edit_logmsg_only)
11128 option_conflict('f', 'm');
11129 if (edit_script_path && fold_only)
11130 option_conflict('F', 'f');
11131 if (abort_edit && edit_only)
11132 option_conflict('a', 'e');
11133 if (continue_edit && edit_only)
11134 option_conflict('c', 'e');
11135 if (edit_only && edit_logmsg_only)
11136 option_conflict('e', 'm');
11137 if (edit_script_path && edit_only)
11138 option_conflict('F', 'e');
11139 if (list_backups) {
11140 if (abort_edit)
11141 option_conflict('l', 'a');
11142 if (continue_edit)
11143 option_conflict('l', 'c');
11144 if (edit_script_path)
11145 option_conflict('l', 'F');
11146 if (edit_logmsg_only)
11147 option_conflict('l', 'm');
11148 if (fold_only)
11149 option_conflict('l', 'f');
11150 if (edit_only)
11151 option_conflict('l', 'e');
11152 if (delete_backups)
11153 option_conflict('l', 'X');
11154 if (argc != 0 && argc != 1)
11155 usage_histedit();
11156 } else if (delete_backups) {
11157 if (abort_edit)
11158 option_conflict('X', 'a');
11159 if (continue_edit)
11160 option_conflict('X', 'c');
11161 if (edit_script_path)
11162 option_conflict('X', 'F');
11163 if (edit_logmsg_only)
11164 option_conflict('X', 'm');
11165 if (fold_only)
11166 option_conflict('X', 'f');
11167 if (edit_only)
11168 option_conflict('X', 'e');
11169 if (list_backups)
11170 option_conflict('X', 'l');
11171 if (argc != 0 && argc != 1)
11172 usage_histedit();
11173 } else if (argc != 0)
11174 usage_histedit();
11177 * This command cannot apply unveil(2) in all cases because the
11178 * user may choose to run an editor to edit the histedit script
11179 * and to edit individual commit log messages.
11180 * unveil(2) traverses exec(2); if an editor is used we have to
11181 * apply unveil after edit script and log messages have been written.
11182 * XXX TODO: Make use of unveil(2) where possible.
11185 cwd = getcwd(NULL, 0);
11186 if (cwd == NULL) {
11187 error = got_error_from_errno("getcwd");
11188 goto done;
11191 error = got_repo_pack_fds_open(&pack_fds);
11192 if (error != NULL)
11193 goto done;
11195 error = got_worktree_open(&worktree, cwd);
11196 if (error) {
11197 if (list_backups || delete_backups) {
11198 if (error->code != GOT_ERR_NOT_WORKTREE)
11199 goto done;
11200 } else {
11201 if (error->code == GOT_ERR_NOT_WORKTREE)
11202 error = wrap_not_worktree_error(error,
11203 "histedit", cwd);
11204 goto done;
11208 if (list_backups || delete_backups) {
11209 error = got_repo_open(&repo,
11210 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11211 NULL, pack_fds);
11212 if (error != NULL)
11213 goto done;
11214 error = apply_unveil(got_repo_get_path(repo), 0,
11215 worktree ? got_worktree_get_root_path(worktree) : NULL);
11216 if (error)
11217 goto done;
11218 error = process_backup_refs(
11219 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11220 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11221 goto done; /* nothing else to do */
11224 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11225 NULL, pack_fds);
11226 if (error != NULL)
11227 goto done;
11229 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11230 if (error)
11231 goto done;
11232 if (rebase_in_progress) {
11233 error = got_error(GOT_ERR_REBASING);
11234 goto done;
11237 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11238 repo);
11239 if (error)
11240 goto done;
11241 if (merge_in_progress) {
11242 error = got_error(GOT_ERR_MERGE_BUSY);
11243 goto done;
11246 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11247 if (error)
11248 goto done;
11250 if (edit_in_progress && edit_logmsg_only) {
11251 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11252 "histedit operation is in progress in this "
11253 "work tree and must be continued or aborted "
11254 "before the -m option can be used");
11255 goto done;
11257 if (edit_in_progress && fold_only) {
11258 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11259 "histedit operation is in progress in this "
11260 "work tree and must be continued or aborted "
11261 "before the -f option can be used");
11262 goto done;
11264 if (edit_in_progress && edit_only) {
11265 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11266 "histedit operation is in progress in this "
11267 "work tree and must be continued or aborted "
11268 "before the -e option can be used");
11269 goto done;
11272 if (edit_in_progress && abort_edit) {
11273 error = got_worktree_histedit_continue(&resume_commit_id,
11274 &tmp_branch, &branch, &base_commit_id, &fileindex,
11275 worktree, repo);
11276 if (error)
11277 goto done;
11278 printf("Switching work tree to %s\n",
11279 got_ref_get_symref_target(branch));
11280 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11281 branch, base_commit_id, abort_progress, &upa);
11282 if (error)
11283 goto done;
11284 printf("Histedit of %s aborted\n",
11285 got_ref_get_symref_target(branch));
11286 print_merge_progress_stats(&upa);
11287 goto done; /* nothing else to do */
11288 } else if (abort_edit) {
11289 error = got_error(GOT_ERR_NOT_HISTEDIT);
11290 goto done;
11293 if (continue_edit) {
11294 char *path;
11296 if (!edit_in_progress) {
11297 error = got_error(GOT_ERR_NOT_HISTEDIT);
11298 goto done;
11301 error = got_worktree_get_histedit_script_path(&path, worktree);
11302 if (error)
11303 goto done;
11305 error = histedit_load_list(&histedit_cmds, path, repo);
11306 free(path);
11307 if (error)
11308 goto done;
11310 error = got_worktree_histedit_continue(&resume_commit_id,
11311 &tmp_branch, &branch, &base_commit_id, &fileindex,
11312 worktree, repo);
11313 if (error)
11314 goto done;
11316 error = got_ref_resolve(&head_commit_id, repo, branch);
11317 if (error)
11318 goto done;
11320 error = got_object_open_as_commit(&commit, repo,
11321 head_commit_id);
11322 if (error)
11323 goto done;
11324 parent_ids = got_object_commit_get_parent_ids(commit);
11325 pid = STAILQ_FIRST(parent_ids);
11326 if (pid == NULL) {
11327 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11328 goto done;
11330 error = collect_commits(&commits, head_commit_id, &pid->id,
11331 base_commit_id, got_worktree_get_path_prefix(worktree),
11332 GOT_ERR_HISTEDIT_PATH, repo);
11333 got_object_commit_close(commit);
11334 commit = NULL;
11335 if (error)
11336 goto done;
11337 } else {
11338 if (edit_in_progress) {
11339 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11340 goto done;
11343 error = got_ref_open(&branch, repo,
11344 got_worktree_get_head_ref_name(worktree), 0);
11345 if (error != NULL)
11346 goto done;
11348 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11349 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11350 "will not edit commit history of a branch outside "
11351 "the \"refs/heads/\" reference namespace");
11352 goto done;
11355 error = got_ref_resolve(&head_commit_id, repo, branch);
11356 got_ref_close(branch);
11357 branch = NULL;
11358 if (error)
11359 goto done;
11361 error = got_object_open_as_commit(&commit, repo,
11362 head_commit_id);
11363 if (error)
11364 goto done;
11365 parent_ids = got_object_commit_get_parent_ids(commit);
11366 pid = STAILQ_FIRST(parent_ids);
11367 if (pid == NULL) {
11368 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11369 goto done;
11371 error = collect_commits(&commits, head_commit_id, &pid->id,
11372 got_worktree_get_base_commit_id(worktree),
11373 got_worktree_get_path_prefix(worktree),
11374 GOT_ERR_HISTEDIT_PATH, repo);
11375 got_object_commit_close(commit);
11376 commit = NULL;
11377 if (error)
11378 goto done;
11380 if (STAILQ_EMPTY(&commits)) {
11381 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11382 goto done;
11385 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11386 &base_commit_id, &fileindex, worktree, repo);
11387 if (error)
11388 goto done;
11390 if (edit_script_path) {
11391 error = histedit_load_list(&histedit_cmds,
11392 edit_script_path, repo);
11393 if (error) {
11394 got_worktree_histedit_abort(worktree, fileindex,
11395 repo, branch, base_commit_id,
11396 abort_progress, &upa);
11397 print_merge_progress_stats(&upa);
11398 goto done;
11400 } else {
11401 const char *branch_name;
11402 branch_name = got_ref_get_symref_target(branch);
11403 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11404 branch_name += 11;
11405 error = histedit_edit_script(&histedit_cmds, &commits,
11406 branch_name, edit_logmsg_only, fold_only,
11407 edit_only, repo);
11408 if (error) {
11409 got_worktree_histedit_abort(worktree, fileindex,
11410 repo, branch, base_commit_id,
11411 abort_progress, &upa);
11412 print_merge_progress_stats(&upa);
11413 goto done;
11418 error = histedit_save_list(&histedit_cmds, worktree,
11419 repo);
11420 if (error) {
11421 got_worktree_histedit_abort(worktree, fileindex,
11422 repo, branch, base_commit_id,
11423 abort_progress, &upa);
11424 print_merge_progress_stats(&upa);
11425 goto done;
11430 error = histedit_check_script(&histedit_cmds, &commits, repo);
11431 if (error)
11432 goto done;
11434 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11435 if (resume_commit_id) {
11436 if (got_object_id_cmp(hle->commit_id,
11437 resume_commit_id) != 0)
11438 continue;
11440 resume_commit_id = NULL;
11441 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11442 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11443 error = histedit_skip_commit(hle, worktree,
11444 repo);
11445 if (error)
11446 goto done;
11447 } else {
11448 struct got_pathlist_head paths;
11449 int have_changes = 0;
11451 TAILQ_INIT(&paths);
11452 error = got_pathlist_append(&paths, "", NULL);
11453 if (error)
11454 goto done;
11455 error = got_worktree_status(worktree, &paths,
11456 repo, 0, check_local_changes, &have_changes,
11457 check_cancelled, NULL);
11458 got_pathlist_free(&paths);
11459 if (error) {
11460 if (error->code != GOT_ERR_CANCELLED)
11461 goto done;
11462 if (sigint_received || sigpipe_received)
11463 goto done;
11465 if (have_changes) {
11466 error = histedit_commit(NULL, worktree,
11467 fileindex, tmp_branch, hle, repo);
11468 if (error)
11469 goto done;
11470 } else {
11471 error = got_object_open_as_commit(
11472 &commit, repo, hle->commit_id);
11473 if (error)
11474 goto done;
11475 error = show_histedit_progress(commit,
11476 hle, NULL);
11477 got_object_commit_close(commit);
11478 commit = NULL;
11479 if (error)
11480 goto done;
11483 continue;
11486 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11487 error = histedit_skip_commit(hle, worktree, repo);
11488 if (error)
11489 goto done;
11490 continue;
11493 error = got_object_open_as_commit(&commit, repo,
11494 hle->commit_id);
11495 if (error)
11496 goto done;
11497 parent_ids = got_object_commit_get_parent_ids(commit);
11498 pid = STAILQ_FIRST(parent_ids);
11500 error = got_worktree_histedit_merge_files(&merged_paths,
11501 worktree, fileindex, &pid->id, hle->commit_id, repo,
11502 update_progress, &upa, check_cancelled, NULL);
11503 if (error)
11504 goto done;
11505 got_object_commit_close(commit);
11506 commit = NULL;
11508 print_merge_progress_stats(&upa);
11509 if (upa.conflicts > 0 || upa.missing > 0 ||
11510 upa.not_deleted > 0 || upa.unversioned > 0) {
11511 if (upa.conflicts > 0) {
11512 error = show_rebase_merge_conflict(
11513 hle->commit_id, repo);
11514 if (error)
11515 goto done;
11517 got_worktree_rebase_pathlist_free(&merged_paths);
11518 break;
11521 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11522 char *id_str;
11523 error = got_object_id_str(&id_str, hle->commit_id);
11524 if (error)
11525 goto done;
11526 printf("Stopping histedit for amending commit %s\n",
11527 id_str);
11528 free(id_str);
11529 got_worktree_rebase_pathlist_free(&merged_paths);
11530 error = got_worktree_histedit_postpone(worktree,
11531 fileindex);
11532 goto done;
11535 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11536 error = histedit_skip_commit(hle, worktree, repo);
11537 if (error)
11538 goto done;
11539 continue;
11542 error = histedit_commit(&merged_paths, worktree, fileindex,
11543 tmp_branch, hle, repo);
11544 got_worktree_rebase_pathlist_free(&merged_paths);
11545 if (error)
11546 goto done;
11549 if (upa.conflicts > 0 || upa.missing > 0 ||
11550 upa.not_deleted > 0 || upa.unversioned > 0) {
11551 error = got_worktree_histedit_postpone(worktree, fileindex);
11552 if (error)
11553 goto done;
11554 if (upa.conflicts > 0 && upa.missing == 0 &&
11555 upa.not_deleted == 0 && upa.unversioned == 0) {
11556 error = got_error_msg(GOT_ERR_CONFLICTS,
11557 "conflicts must be resolved before histedit "
11558 "can continue");
11559 } else if (upa.conflicts > 0) {
11560 error = got_error_msg(GOT_ERR_CONFLICTS,
11561 "conflicts must be resolved before histedit "
11562 "can continue; changes destined for some "
11563 "files were not yet merged and should be "
11564 "merged manually if required before the "
11565 "histedit operation is continued");
11566 } else {
11567 error = got_error_msg(GOT_ERR_CONFLICTS,
11568 "changes destined for some files were not "
11569 "yet merged and should be merged manually "
11570 "if required before the histedit operation "
11571 "is continued");
11573 } else
11574 error = histedit_complete(worktree, fileindex, tmp_branch,
11575 branch, repo);
11576 done:
11577 got_object_id_queue_free(&commits);
11578 histedit_free_list(&histedit_cmds);
11579 free(head_commit_id);
11580 free(base_commit_id);
11581 free(resume_commit_id);
11582 if (commit)
11583 got_object_commit_close(commit);
11584 if (branch)
11585 got_ref_close(branch);
11586 if (tmp_branch)
11587 got_ref_close(tmp_branch);
11588 if (worktree)
11589 got_worktree_close(worktree);
11590 if (repo) {
11591 const struct got_error *close_err = got_repo_close(repo);
11592 if (error == NULL)
11593 error = close_err;
11595 if (pack_fds) {
11596 const struct got_error *pack_err =
11597 got_repo_pack_fds_close(pack_fds);
11598 if (error == NULL)
11599 error = pack_err;
11601 return error;
11604 __dead static void
11605 usage_integrate(void)
11607 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11608 exit(1);
11611 static const struct got_error *
11612 cmd_integrate(int argc, char *argv[])
11614 const struct got_error *error = NULL;
11615 struct got_repository *repo = NULL;
11616 struct got_worktree *worktree = NULL;
11617 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11618 const char *branch_arg = NULL;
11619 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11620 struct got_fileindex *fileindex = NULL;
11621 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11622 int ch;
11623 struct got_update_progress_arg upa;
11624 int *pack_fds = NULL;
11626 while ((ch = getopt(argc, argv, "")) != -1) {
11627 switch (ch) {
11628 default:
11629 usage_integrate();
11630 /* NOTREACHED */
11634 argc -= optind;
11635 argv += optind;
11637 if (argc != 1)
11638 usage_integrate();
11639 branch_arg = argv[0];
11640 #ifndef PROFILE
11641 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11642 "unveil", NULL) == -1)
11643 err(1, "pledge");
11644 #endif
11645 cwd = getcwd(NULL, 0);
11646 if (cwd == NULL) {
11647 error = got_error_from_errno("getcwd");
11648 goto done;
11651 error = got_repo_pack_fds_open(&pack_fds);
11652 if (error != NULL)
11653 goto done;
11655 error = got_worktree_open(&worktree, cwd);
11656 if (error) {
11657 if (error->code == GOT_ERR_NOT_WORKTREE)
11658 error = wrap_not_worktree_error(error, "integrate",
11659 cwd);
11660 goto done;
11663 error = check_rebase_or_histedit_in_progress(worktree);
11664 if (error)
11665 goto done;
11667 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11668 NULL, pack_fds);
11669 if (error != NULL)
11670 goto done;
11672 error = apply_unveil(got_repo_get_path(repo), 0,
11673 got_worktree_get_root_path(worktree));
11674 if (error)
11675 goto done;
11677 error = check_merge_in_progress(worktree, repo);
11678 if (error)
11679 goto done;
11681 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11682 error = got_error_from_errno("asprintf");
11683 goto done;
11686 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11687 &base_branch_ref, worktree, refname, repo);
11688 if (error)
11689 goto done;
11691 refname = strdup(got_ref_get_name(branch_ref));
11692 if (refname == NULL) {
11693 error = got_error_from_errno("strdup");
11694 got_worktree_integrate_abort(worktree, fileindex, repo,
11695 branch_ref, base_branch_ref);
11696 goto done;
11698 base_refname = strdup(got_ref_get_name(base_branch_ref));
11699 if (base_refname == NULL) {
11700 error = got_error_from_errno("strdup");
11701 got_worktree_integrate_abort(worktree, fileindex, repo,
11702 branch_ref, base_branch_ref);
11703 goto done;
11706 error = got_ref_resolve(&commit_id, repo, branch_ref);
11707 if (error)
11708 goto done;
11710 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11711 if (error)
11712 goto done;
11714 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11715 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11716 "specified branch has already been integrated");
11717 got_worktree_integrate_abort(worktree, fileindex, repo,
11718 branch_ref, base_branch_ref);
11719 goto done;
11722 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11723 if (error) {
11724 if (error->code == GOT_ERR_ANCESTRY)
11725 error = got_error(GOT_ERR_REBASE_REQUIRED);
11726 got_worktree_integrate_abort(worktree, fileindex, repo,
11727 branch_ref, base_branch_ref);
11728 goto done;
11731 memset(&upa, 0, sizeof(upa));
11732 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11733 branch_ref, base_branch_ref, update_progress, &upa,
11734 check_cancelled, NULL);
11735 if (error)
11736 goto done;
11738 printf("Integrated %s into %s\n", refname, base_refname);
11739 print_update_progress_stats(&upa);
11740 done:
11741 if (repo) {
11742 const struct got_error *close_err = got_repo_close(repo);
11743 if (error == NULL)
11744 error = close_err;
11746 if (worktree)
11747 got_worktree_close(worktree);
11748 if (pack_fds) {
11749 const struct got_error *pack_err =
11750 got_repo_pack_fds_close(pack_fds);
11751 if (error == NULL)
11752 error = pack_err;
11754 free(cwd);
11755 free(base_commit_id);
11756 free(commit_id);
11757 free(refname);
11758 free(base_refname);
11759 return error;
11762 __dead static void
11763 usage_merge(void)
11765 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11766 getprogname());
11767 exit(1);
11770 static const struct got_error *
11771 cmd_merge(int argc, char *argv[])
11773 const struct got_error *error = NULL;
11774 struct got_worktree *worktree = NULL;
11775 struct got_repository *repo = NULL;
11776 struct got_fileindex *fileindex = NULL;
11777 char *cwd = NULL, *id_str = NULL, *author = NULL;
11778 struct got_reference *branch = NULL, *wt_branch = NULL;
11779 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11780 struct got_object_id *wt_branch_tip = NULL;
11781 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11782 int interrupt_merge = 0;
11783 struct got_update_progress_arg upa;
11784 struct got_object_id *merge_commit_id = NULL;
11785 char *branch_name = NULL;
11786 int *pack_fds = NULL;
11788 memset(&upa, 0, sizeof(upa));
11790 while ((ch = getopt(argc, argv, "acn")) != -1) {
11791 switch (ch) {
11792 case 'a':
11793 abort_merge = 1;
11794 break;
11795 case 'c':
11796 continue_merge = 1;
11797 break;
11798 case 'n':
11799 interrupt_merge = 1;
11800 break;
11801 default:
11802 usage_rebase();
11803 /* NOTREACHED */
11807 argc -= optind;
11808 argv += optind;
11810 #ifndef PROFILE
11811 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11812 "unveil", NULL) == -1)
11813 err(1, "pledge");
11814 #endif
11816 if (abort_merge && continue_merge)
11817 option_conflict('a', 'c');
11818 if (abort_merge || continue_merge) {
11819 if (argc != 0)
11820 usage_merge();
11821 } else if (argc != 1)
11822 usage_merge();
11824 cwd = getcwd(NULL, 0);
11825 if (cwd == NULL) {
11826 error = got_error_from_errno("getcwd");
11827 goto done;
11830 error = got_repo_pack_fds_open(&pack_fds);
11831 if (error != NULL)
11832 goto done;
11834 error = got_worktree_open(&worktree, cwd);
11835 if (error) {
11836 if (error->code == GOT_ERR_NOT_WORKTREE)
11837 error = wrap_not_worktree_error(error,
11838 "merge", cwd);
11839 goto done;
11842 error = got_repo_open(&repo,
11843 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11844 pack_fds);
11845 if (error != NULL)
11846 goto done;
11848 error = apply_unveil(got_repo_get_path(repo), 0,
11849 worktree ? got_worktree_get_root_path(worktree) : NULL);
11850 if (error)
11851 goto done;
11853 error = check_rebase_or_histedit_in_progress(worktree);
11854 if (error)
11855 goto done;
11857 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11858 repo);
11859 if (error)
11860 goto done;
11862 if (abort_merge) {
11863 if (!merge_in_progress) {
11864 error = got_error(GOT_ERR_NOT_MERGING);
11865 goto done;
11867 error = got_worktree_merge_continue(&branch_name,
11868 &branch_tip, &fileindex, worktree, repo);
11869 if (error)
11870 goto done;
11871 error = got_worktree_merge_abort(worktree, fileindex, repo,
11872 abort_progress, &upa);
11873 if (error)
11874 goto done;
11875 printf("Merge of %s aborted\n", branch_name);
11876 goto done; /* nothing else to do */
11879 error = get_author(&author, repo, worktree);
11880 if (error)
11881 goto done;
11883 if (continue_merge) {
11884 if (!merge_in_progress) {
11885 error = got_error(GOT_ERR_NOT_MERGING);
11886 goto done;
11888 error = got_worktree_merge_continue(&branch_name,
11889 &branch_tip, &fileindex, worktree, repo);
11890 if (error)
11891 goto done;
11892 } else {
11893 error = got_ref_open(&branch, repo, argv[0], 0);
11894 if (error != NULL)
11895 goto done;
11896 branch_name = strdup(got_ref_get_name(branch));
11897 if (branch_name == NULL) {
11898 error = got_error_from_errno("strdup");
11899 goto done;
11901 error = got_ref_resolve(&branch_tip, repo, branch);
11902 if (error)
11903 goto done;
11906 error = got_ref_open(&wt_branch, repo,
11907 got_worktree_get_head_ref_name(worktree), 0);
11908 if (error)
11909 goto done;
11910 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11911 if (error)
11912 goto done;
11913 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11914 wt_branch_tip, branch_tip, 0, repo,
11915 check_cancelled, NULL);
11916 if (error && error->code != GOT_ERR_ANCESTRY)
11917 goto done;
11919 if (!continue_merge) {
11920 error = check_path_prefix(wt_branch_tip, branch_tip,
11921 got_worktree_get_path_prefix(worktree),
11922 GOT_ERR_MERGE_PATH, repo);
11923 if (error)
11924 goto done;
11925 if (yca_id) {
11926 error = check_same_branch(wt_branch_tip, branch,
11927 yca_id, repo);
11928 if (error) {
11929 if (error->code != GOT_ERR_ANCESTRY)
11930 goto done;
11931 error = NULL;
11932 } else {
11933 static char msg[512];
11934 snprintf(msg, sizeof(msg),
11935 "cannot create a merge commit because "
11936 "%s is based on %s; %s can be integrated "
11937 "with 'got integrate' instead", branch_name,
11938 got_worktree_get_head_ref_name(worktree),
11939 branch_name);
11940 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11941 goto done;
11944 error = got_worktree_merge_prepare(&fileindex, worktree,
11945 branch, repo);
11946 if (error)
11947 goto done;
11949 error = got_worktree_merge_branch(worktree, fileindex,
11950 yca_id, branch_tip, repo, update_progress, &upa,
11951 check_cancelled, NULL);
11952 if (error)
11953 goto done;
11954 print_merge_progress_stats(&upa);
11955 if (!upa.did_something) {
11956 error = got_worktree_merge_abort(worktree, fileindex,
11957 repo, abort_progress, &upa);
11958 if (error)
11959 goto done;
11960 printf("Already up-to-date\n");
11961 goto done;
11965 if (interrupt_merge) {
11966 error = got_worktree_merge_postpone(worktree, fileindex);
11967 if (error)
11968 goto done;
11969 printf("Merge of %s interrupted on request\n", branch_name);
11970 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11971 upa.not_deleted > 0 || upa.unversioned > 0) {
11972 error = got_worktree_merge_postpone(worktree, fileindex);
11973 if (error)
11974 goto done;
11975 if (upa.conflicts > 0 && upa.missing == 0 &&
11976 upa.not_deleted == 0 && upa.unversioned == 0) {
11977 error = got_error_msg(GOT_ERR_CONFLICTS,
11978 "conflicts must be resolved before merging "
11979 "can continue");
11980 } else if (upa.conflicts > 0) {
11981 error = got_error_msg(GOT_ERR_CONFLICTS,
11982 "conflicts must be resolved before merging "
11983 "can continue; changes destined for some "
11984 "files were not yet merged and "
11985 "should be merged manually if required before the "
11986 "merge operation is continued");
11987 } else {
11988 error = got_error_msg(GOT_ERR_CONFLICTS,
11989 "changes destined for some "
11990 "files were not yet merged and should be "
11991 "merged manually if required before the "
11992 "merge operation is continued");
11994 goto done;
11995 } else {
11996 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11997 fileindex, author, NULL, 1, branch_tip, branch_name,
11998 repo, continue_merge ? print_status : NULL, NULL);
11999 if (error)
12000 goto done;
12001 error = got_worktree_merge_complete(worktree, fileindex, repo);
12002 if (error)
12003 goto done;
12004 error = got_object_id_str(&id_str, merge_commit_id);
12005 if (error)
12006 goto done;
12007 printf("Merged %s into %s: %s\n", branch_name,
12008 got_worktree_get_head_ref_name(worktree),
12009 id_str);
12012 done:
12013 free(id_str);
12014 free(merge_commit_id);
12015 free(author);
12016 free(branch_tip);
12017 free(branch_name);
12018 free(yca_id);
12019 if (branch)
12020 got_ref_close(branch);
12021 if (wt_branch)
12022 got_ref_close(wt_branch);
12023 if (worktree)
12024 got_worktree_close(worktree);
12025 if (repo) {
12026 const struct got_error *close_err = got_repo_close(repo);
12027 if (error == NULL)
12028 error = close_err;
12030 if (pack_fds) {
12031 const struct got_error *pack_err =
12032 got_repo_pack_fds_close(pack_fds);
12033 if (error == NULL)
12034 error = pack_err;
12036 return error;
12039 __dead static void
12040 usage_stage(void)
12042 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12043 "[-S] [file-path ...]\n",
12044 getprogname());
12045 exit(1);
12048 static const struct got_error *
12049 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12050 const char *path, struct got_object_id *blob_id,
12051 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12052 int dirfd, const char *de_name)
12054 const struct got_error *err = NULL;
12055 char *id_str = NULL;
12057 if (staged_status != GOT_STATUS_ADD &&
12058 staged_status != GOT_STATUS_MODIFY &&
12059 staged_status != GOT_STATUS_DELETE)
12060 return NULL;
12062 if (staged_status == GOT_STATUS_ADD ||
12063 staged_status == GOT_STATUS_MODIFY)
12064 err = got_object_id_str(&id_str, staged_blob_id);
12065 else
12066 err = got_object_id_str(&id_str, blob_id);
12067 if (err)
12068 return err;
12070 printf("%s %c %s\n", id_str, staged_status, path);
12071 free(id_str);
12072 return NULL;
12075 static const struct got_error *
12076 cmd_stage(int argc, char *argv[])
12078 const struct got_error *error = NULL;
12079 struct got_repository *repo = NULL;
12080 struct got_worktree *worktree = NULL;
12081 char *cwd = NULL;
12082 struct got_pathlist_head paths;
12083 struct got_pathlist_entry *pe;
12084 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12085 FILE *patch_script_file = NULL;
12086 const char *patch_script_path = NULL;
12087 struct choose_patch_arg cpa;
12088 int *pack_fds = NULL;
12090 TAILQ_INIT(&paths);
12092 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12093 switch (ch) {
12094 case 'l':
12095 list_stage = 1;
12096 break;
12097 case 'p':
12098 pflag = 1;
12099 break;
12100 case 'F':
12101 patch_script_path = optarg;
12102 break;
12103 case 'S':
12104 allow_bad_symlinks = 1;
12105 break;
12106 default:
12107 usage_stage();
12108 /* NOTREACHED */
12112 argc -= optind;
12113 argv += optind;
12115 #ifndef PROFILE
12116 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12117 "unveil", NULL) == -1)
12118 err(1, "pledge");
12119 #endif
12120 if (list_stage && (pflag || patch_script_path))
12121 errx(1, "-l option cannot be used with other options");
12122 if (patch_script_path && !pflag)
12123 errx(1, "-F option can only be used together with -p option");
12125 cwd = getcwd(NULL, 0);
12126 if (cwd == NULL) {
12127 error = got_error_from_errno("getcwd");
12128 goto done;
12131 error = got_repo_pack_fds_open(&pack_fds);
12132 if (error != NULL)
12133 goto done;
12135 error = got_worktree_open(&worktree, cwd);
12136 if (error) {
12137 if (error->code == GOT_ERR_NOT_WORKTREE)
12138 error = wrap_not_worktree_error(error, "stage", cwd);
12139 goto done;
12142 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12143 NULL, pack_fds);
12144 if (error != NULL)
12145 goto done;
12147 if (patch_script_path) {
12148 patch_script_file = fopen(patch_script_path, "re");
12149 if (patch_script_file == NULL) {
12150 error = got_error_from_errno2("fopen",
12151 patch_script_path);
12152 goto done;
12155 error = apply_unveil(got_repo_get_path(repo), 0,
12156 got_worktree_get_root_path(worktree));
12157 if (error)
12158 goto done;
12160 error = check_merge_in_progress(worktree, repo);
12161 if (error)
12162 goto done;
12164 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12165 if (error)
12166 goto done;
12168 if (list_stage)
12169 error = got_worktree_status(worktree, &paths, repo, 0,
12170 print_stage, NULL, check_cancelled, NULL);
12171 else {
12172 cpa.patch_script_file = patch_script_file;
12173 cpa.action = "stage";
12174 error = got_worktree_stage(worktree, &paths,
12175 pflag ? NULL : print_status, NULL,
12176 pflag ? choose_patch : NULL, &cpa,
12177 allow_bad_symlinks, repo);
12179 done:
12180 if (patch_script_file && fclose(patch_script_file) == EOF &&
12181 error == NULL)
12182 error = got_error_from_errno2("fclose", patch_script_path);
12183 if (repo) {
12184 const struct got_error *close_err = got_repo_close(repo);
12185 if (error == NULL)
12186 error = close_err;
12188 if (worktree)
12189 got_worktree_close(worktree);
12190 if (pack_fds) {
12191 const struct got_error *pack_err =
12192 got_repo_pack_fds_close(pack_fds);
12193 if (error == NULL)
12194 error = pack_err;
12196 TAILQ_FOREACH(pe, &paths, entry)
12197 free((char *)pe->path);
12198 got_pathlist_free(&paths);
12199 free(cwd);
12200 return error;
12203 __dead static void
12204 usage_unstage(void)
12206 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12207 "[file-path ...]\n",
12208 getprogname());
12209 exit(1);
12213 static const struct got_error *
12214 cmd_unstage(int argc, char *argv[])
12216 const struct got_error *error = NULL;
12217 struct got_repository *repo = NULL;
12218 struct got_worktree *worktree = NULL;
12219 char *cwd = NULL;
12220 struct got_pathlist_head paths;
12221 struct got_pathlist_entry *pe;
12222 int ch, pflag = 0;
12223 struct got_update_progress_arg upa;
12224 FILE *patch_script_file = NULL;
12225 const char *patch_script_path = NULL;
12226 struct choose_patch_arg cpa;
12227 int *pack_fds = NULL;
12229 TAILQ_INIT(&paths);
12231 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12232 switch (ch) {
12233 case 'p':
12234 pflag = 1;
12235 break;
12236 case 'F':
12237 patch_script_path = optarg;
12238 break;
12239 default:
12240 usage_unstage();
12241 /* NOTREACHED */
12245 argc -= optind;
12246 argv += optind;
12248 #ifndef PROFILE
12249 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12250 "unveil", NULL) == -1)
12251 err(1, "pledge");
12252 #endif
12253 if (patch_script_path && !pflag)
12254 errx(1, "-F option can only be used together with -p option");
12256 cwd = getcwd(NULL, 0);
12257 if (cwd == NULL) {
12258 error = got_error_from_errno("getcwd");
12259 goto done;
12262 error = got_repo_pack_fds_open(&pack_fds);
12263 if (error != NULL)
12264 goto done;
12266 error = got_worktree_open(&worktree, cwd);
12267 if (error) {
12268 if (error->code == GOT_ERR_NOT_WORKTREE)
12269 error = wrap_not_worktree_error(error, "unstage", cwd);
12270 goto done;
12273 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12274 NULL, pack_fds);
12275 if (error != NULL)
12276 goto done;
12278 if (patch_script_path) {
12279 patch_script_file = fopen(patch_script_path, "re");
12280 if (patch_script_file == NULL) {
12281 error = got_error_from_errno2("fopen",
12282 patch_script_path);
12283 goto done;
12287 error = apply_unveil(got_repo_get_path(repo), 0,
12288 got_worktree_get_root_path(worktree));
12289 if (error)
12290 goto done;
12292 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12293 if (error)
12294 goto done;
12296 cpa.patch_script_file = patch_script_file;
12297 cpa.action = "unstage";
12298 memset(&upa, 0, sizeof(upa));
12299 error = got_worktree_unstage(worktree, &paths, update_progress,
12300 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12301 if (!error)
12302 print_merge_progress_stats(&upa);
12303 done:
12304 if (patch_script_file && fclose(patch_script_file) == EOF &&
12305 error == NULL)
12306 error = got_error_from_errno2("fclose", patch_script_path);
12307 if (repo) {
12308 const struct got_error *close_err = got_repo_close(repo);
12309 if (error == NULL)
12310 error = close_err;
12312 if (worktree)
12313 got_worktree_close(worktree);
12314 if (pack_fds) {
12315 const struct got_error *pack_err =
12316 got_repo_pack_fds_close(pack_fds);
12317 if (error == NULL)
12318 error = pack_err;
12320 TAILQ_FOREACH(pe, &paths, entry)
12321 free((char *)pe->path);
12322 got_pathlist_free(&paths);
12323 free(cwd);
12324 return error;
12327 __dead static void
12328 usage_cat(void)
12330 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12331 "arg1 [arg2 ...]\n", getprogname());
12332 exit(1);
12335 static const struct got_error *
12336 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12338 const struct got_error *err;
12339 struct got_blob_object *blob;
12340 int fd = -1;
12342 fd = got_opentempfd();
12343 if (fd == -1)
12344 return got_error_from_errno("got_opentempfd");
12346 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12347 if (err)
12348 goto done;
12350 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12351 done:
12352 if (fd != -1 && close(fd) == -1 && err == NULL)
12353 err = got_error_from_errno("close");
12354 if (blob)
12355 got_object_blob_close(blob);
12356 return err;
12359 static const struct got_error *
12360 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12362 const struct got_error *err;
12363 struct got_tree_object *tree;
12364 int nentries, i;
12366 err = got_object_open_as_tree(&tree, repo, id);
12367 if (err)
12368 return err;
12370 nentries = got_object_tree_get_nentries(tree);
12371 for (i = 0; i < nentries; i++) {
12372 struct got_tree_entry *te;
12373 char *id_str;
12374 if (sigint_received || sigpipe_received)
12375 break;
12376 te = got_object_tree_get_entry(tree, i);
12377 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12378 if (err)
12379 break;
12380 fprintf(outfile, "%s %.7o %s\n", id_str,
12381 got_tree_entry_get_mode(te),
12382 got_tree_entry_get_name(te));
12383 free(id_str);
12386 got_object_tree_close(tree);
12387 return err;
12390 static void
12391 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
12393 long long h, m;
12394 char sign = '+';
12396 if (gmtoff < 0) {
12397 sign = '-';
12398 gmtoff = -gmtoff;
12401 h = (long long)gmtoff / 3600;
12402 m = ((long long)gmtoff - h*3600) / 60;
12403 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
12406 static const struct got_error *
12407 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12409 const struct got_error *err;
12410 struct got_commit_object *commit;
12411 const struct got_object_id_queue *parent_ids;
12412 struct got_object_qid *pid;
12413 char *id_str = NULL;
12414 const char *logmsg = NULL;
12415 char gmtoff[6];
12417 err = got_object_open_as_commit(&commit, repo, id);
12418 if (err)
12419 return err;
12421 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12422 if (err)
12423 goto done;
12425 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12426 parent_ids = got_object_commit_get_parent_ids(commit);
12427 fprintf(outfile, "numparents %d\n",
12428 got_object_commit_get_nparents(commit));
12429 STAILQ_FOREACH(pid, parent_ids, entry) {
12430 char *pid_str;
12431 err = got_object_id_str(&pid_str, &pid->id);
12432 if (err)
12433 goto done;
12434 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12435 free(pid_str);
12437 format_gmtoff(gmtoff, sizeof(gmtoff),
12438 got_object_commit_get_author_gmtoff(commit));
12439 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12440 got_object_commit_get_author(commit),
12441 (long long)got_object_commit_get_author_time(commit),
12442 gmtoff);
12444 format_gmtoff(gmtoff, sizeof(gmtoff),
12445 got_object_commit_get_committer_gmtoff(commit));
12446 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12447 got_object_commit_get_author(commit),
12448 (long long)got_object_commit_get_committer_time(commit),
12449 gmtoff);
12451 logmsg = got_object_commit_get_logmsg_raw(commit);
12452 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12453 fprintf(outfile, "%s", logmsg);
12454 done:
12455 free(id_str);
12456 got_object_commit_close(commit);
12457 return err;
12460 static const struct got_error *
12461 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12463 const struct got_error *err;
12464 struct got_tag_object *tag;
12465 char *id_str = NULL;
12466 const char *tagmsg = NULL;
12467 char gmtoff[6];
12469 err = got_object_open_as_tag(&tag, repo, id);
12470 if (err)
12471 return err;
12473 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12474 if (err)
12475 goto done;
12477 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12479 switch (got_object_tag_get_object_type(tag)) {
12480 case GOT_OBJ_TYPE_BLOB:
12481 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12482 GOT_OBJ_LABEL_BLOB);
12483 break;
12484 case GOT_OBJ_TYPE_TREE:
12485 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12486 GOT_OBJ_LABEL_TREE);
12487 break;
12488 case GOT_OBJ_TYPE_COMMIT:
12489 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12490 GOT_OBJ_LABEL_COMMIT);
12491 break;
12492 case GOT_OBJ_TYPE_TAG:
12493 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12494 GOT_OBJ_LABEL_TAG);
12495 break;
12496 default:
12497 break;
12500 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12501 got_object_tag_get_name(tag));
12503 format_gmtoff(gmtoff, sizeof(gmtoff),
12504 got_object_tag_get_tagger_gmtoff(tag));
12505 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12506 got_object_tag_get_tagger(tag),
12507 (long long)got_object_tag_get_tagger_time(tag),
12508 gmtoff);
12510 tagmsg = got_object_tag_get_message(tag);
12511 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12512 fprintf(outfile, "%s", tagmsg);
12513 done:
12514 free(id_str);
12515 got_object_tag_close(tag);
12516 return err;
12519 static const struct got_error *
12520 cmd_cat(int argc, char *argv[])
12522 const struct got_error *error;
12523 struct got_repository *repo = NULL;
12524 struct got_worktree *worktree = NULL;
12525 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12526 const char *commit_id_str = NULL;
12527 struct got_object_id *id = NULL, *commit_id = NULL;
12528 struct got_commit_object *commit = NULL;
12529 int ch, obj_type, i, force_path = 0;
12530 struct got_reflist_head refs;
12531 int *pack_fds = NULL;
12533 TAILQ_INIT(&refs);
12535 #ifndef PROFILE
12536 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12537 NULL) == -1)
12538 err(1, "pledge");
12539 #endif
12541 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12542 switch (ch) {
12543 case 'c':
12544 commit_id_str = optarg;
12545 break;
12546 case 'r':
12547 repo_path = realpath(optarg, NULL);
12548 if (repo_path == NULL)
12549 return got_error_from_errno2("realpath",
12550 optarg);
12551 got_path_strip_trailing_slashes(repo_path);
12552 break;
12553 case 'P':
12554 force_path = 1;
12555 break;
12556 default:
12557 usage_cat();
12558 /* NOTREACHED */
12562 argc -= optind;
12563 argv += optind;
12565 cwd = getcwd(NULL, 0);
12566 if (cwd == NULL) {
12567 error = got_error_from_errno("getcwd");
12568 goto done;
12571 error = got_repo_pack_fds_open(&pack_fds);
12572 if (error != NULL)
12573 goto done;
12575 if (repo_path == NULL) {
12576 error = got_worktree_open(&worktree, cwd);
12577 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12578 goto done;
12579 if (worktree) {
12580 repo_path = strdup(
12581 got_worktree_get_repo_path(worktree));
12582 if (repo_path == NULL) {
12583 error = got_error_from_errno("strdup");
12584 goto done;
12587 /* Release work tree lock. */
12588 got_worktree_close(worktree);
12589 worktree = NULL;
12593 if (repo_path == NULL) {
12594 repo_path = strdup(cwd);
12595 if (repo_path == NULL)
12596 return got_error_from_errno("strdup");
12599 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12600 free(repo_path);
12601 if (error != NULL)
12602 goto done;
12604 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12605 if (error)
12606 goto done;
12608 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12609 if (error)
12610 goto done;
12612 if (commit_id_str == NULL)
12613 commit_id_str = GOT_REF_HEAD;
12614 error = got_repo_match_object_id(&commit_id, NULL,
12615 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12616 if (error)
12617 goto done;
12619 error = got_object_open_as_commit(&commit, repo, commit_id);
12620 if (error)
12621 goto done;
12623 for (i = 0; i < argc; i++) {
12624 if (force_path) {
12625 error = got_object_id_by_path(&id, repo, commit,
12626 argv[i]);
12627 if (error)
12628 break;
12629 } else {
12630 error = got_repo_match_object_id(&id, &label, argv[i],
12631 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12632 repo);
12633 if (error) {
12634 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12635 error->code != GOT_ERR_NOT_REF)
12636 break;
12637 error = got_object_id_by_path(&id, repo,
12638 commit, argv[i]);
12639 if (error)
12640 break;
12644 error = got_object_get_type(&obj_type, repo, id);
12645 if (error)
12646 break;
12648 switch (obj_type) {
12649 case GOT_OBJ_TYPE_BLOB:
12650 error = cat_blob(id, repo, stdout);
12651 break;
12652 case GOT_OBJ_TYPE_TREE:
12653 error = cat_tree(id, repo, stdout);
12654 break;
12655 case GOT_OBJ_TYPE_COMMIT:
12656 error = cat_commit(id, repo, stdout);
12657 break;
12658 case GOT_OBJ_TYPE_TAG:
12659 error = cat_tag(id, repo, stdout);
12660 break;
12661 default:
12662 error = got_error(GOT_ERR_OBJ_TYPE);
12663 break;
12665 if (error)
12666 break;
12667 free(label);
12668 label = NULL;
12669 free(id);
12670 id = NULL;
12672 done:
12673 free(label);
12674 free(id);
12675 free(commit_id);
12676 if (commit)
12677 got_object_commit_close(commit);
12678 if (worktree)
12679 got_worktree_close(worktree);
12680 if (repo) {
12681 const struct got_error *close_err = got_repo_close(repo);
12682 if (error == NULL)
12683 error = close_err;
12685 if (pack_fds) {
12686 const struct got_error *pack_err =
12687 got_repo_pack_fds_close(pack_fds);
12688 if (error == NULL)
12689 error = pack_err;
12692 got_ref_list_free(&refs);
12693 return error;
12696 __dead static void
12697 usage_info(void)
12699 fprintf(stderr, "usage: %s info [path ...]\n",
12700 getprogname());
12701 exit(1);
12704 static const struct got_error *
12705 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12706 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12707 struct got_object_id *commit_id)
12709 const struct got_error *err = NULL;
12710 char *id_str = NULL;
12711 char datebuf[128];
12712 struct tm mytm, *tm;
12713 struct got_pathlist_head *paths = arg;
12714 struct got_pathlist_entry *pe;
12717 * Clear error indication from any of the path arguments which
12718 * would cause this file index entry to be displayed.
12720 TAILQ_FOREACH(pe, paths, entry) {
12721 if (got_path_cmp(path, pe->path, strlen(path),
12722 pe->path_len) == 0 ||
12723 got_path_is_child(path, pe->path, pe->path_len))
12724 pe->data = NULL; /* no error */
12727 printf(GOT_COMMIT_SEP_STR);
12728 if (S_ISLNK(mode))
12729 printf("symlink: %s\n", path);
12730 else if (S_ISREG(mode)) {
12731 printf("file: %s\n", path);
12732 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12733 } else if (S_ISDIR(mode))
12734 printf("directory: %s\n", path);
12735 else
12736 printf("something: %s\n", path);
12738 tm = localtime_r(&mtime, &mytm);
12739 if (tm == NULL)
12740 return NULL;
12741 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12742 return got_error(GOT_ERR_NO_SPACE);
12743 printf("timestamp: %s\n", datebuf);
12745 if (blob_id) {
12746 err = got_object_id_str(&id_str, blob_id);
12747 if (err)
12748 return err;
12749 printf("based on blob: %s\n", id_str);
12750 free(id_str);
12753 if (staged_blob_id) {
12754 err = got_object_id_str(&id_str, staged_blob_id);
12755 if (err)
12756 return err;
12757 printf("based on staged blob: %s\n", id_str);
12758 free(id_str);
12761 if (commit_id) {
12762 err = got_object_id_str(&id_str, commit_id);
12763 if (err)
12764 return err;
12765 printf("based on commit: %s\n", id_str);
12766 free(id_str);
12769 return NULL;
12772 static const struct got_error *
12773 cmd_info(int argc, char *argv[])
12775 const struct got_error *error = NULL;
12776 struct got_worktree *worktree = NULL;
12777 char *cwd = NULL, *id_str = NULL;
12778 struct got_pathlist_head paths;
12779 struct got_pathlist_entry *pe;
12780 char *uuidstr = NULL;
12781 int ch, show_files = 0;
12782 int *pack_fds = NULL;
12784 TAILQ_INIT(&paths);
12786 while ((ch = getopt(argc, argv, "")) != -1) {
12787 switch (ch) {
12788 default:
12789 usage_info();
12790 /* NOTREACHED */
12794 argc -= optind;
12795 argv += optind;
12797 #ifndef PROFILE
12798 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12799 NULL) == -1)
12800 err(1, "pledge");
12801 #endif
12802 cwd = getcwd(NULL, 0);
12803 if (cwd == NULL) {
12804 error = got_error_from_errno("getcwd");
12805 goto done;
12808 error = got_repo_pack_fds_open(&pack_fds);
12809 if (error != NULL)
12810 goto done;
12812 error = got_worktree_open(&worktree, cwd);
12813 if (error) {
12814 if (error->code == GOT_ERR_NOT_WORKTREE)
12815 error = wrap_not_worktree_error(error, "info", cwd);
12816 goto done;
12819 #ifndef PROFILE
12820 /* Remove "cpath" promise. */
12821 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12822 NULL) == -1)
12823 err(1, "pledge");
12824 #endif
12825 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12826 if (error)
12827 goto done;
12829 if (argc >= 1) {
12830 error = get_worktree_paths_from_argv(&paths, argc, argv,
12831 worktree);
12832 if (error)
12833 goto done;
12834 show_files = 1;
12837 error = got_object_id_str(&id_str,
12838 got_worktree_get_base_commit_id(worktree));
12839 if (error)
12840 goto done;
12842 error = got_worktree_get_uuid(&uuidstr, worktree);
12843 if (error)
12844 goto done;
12846 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12847 printf("work tree base commit: %s\n", id_str);
12848 printf("work tree path prefix: %s\n",
12849 got_worktree_get_path_prefix(worktree));
12850 printf("work tree branch reference: %s\n",
12851 got_worktree_get_head_ref_name(worktree));
12852 printf("work tree UUID: %s\n", uuidstr);
12853 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12855 if (show_files) {
12856 struct got_pathlist_entry *pe;
12857 TAILQ_FOREACH(pe, &paths, entry) {
12858 if (pe->path_len == 0)
12859 continue;
12861 * Assume this path will fail. This will be corrected
12862 * in print_path_info() in case the path does suceeed.
12864 pe->data = (void *)got_error_path(pe->path,
12865 GOT_ERR_BAD_PATH);
12867 error = got_worktree_path_info(worktree, &paths,
12868 print_path_info, &paths, check_cancelled, NULL);
12869 if (error)
12870 goto done;
12871 TAILQ_FOREACH(pe, &paths, entry) {
12872 if (pe->data != NULL) {
12873 error = pe->data; /* bad path */
12874 break;
12878 done:
12879 if (pack_fds) {
12880 const struct got_error *pack_err =
12881 got_repo_pack_fds_close(pack_fds);
12882 if (error == NULL)
12883 error = pack_err;
12885 TAILQ_FOREACH(pe, &paths, entry)
12886 free((char *)pe->path);
12887 got_pathlist_free(&paths);
12888 free(cwd);
12889 free(id_str);
12890 free(uuidstr);
12891 return error;