Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <locale.h>
28 #include <ctype.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <time.h>
36 #include <paths.h>
37 #include <regex.h>
38 #include <getopt.h>
40 #include "got_compat.h"
42 #include "got_version.h"
43 #include "got_error.h"
44 #include "got_object.h"
45 #include "got_reference.h"
46 #include "got_repository.h"
47 #include "got_path.h"
48 #include "got_cancel.h"
49 #include "got_worktree.h"
50 #include "got_diff.h"
51 #include "got_commit_graph.h"
52 #include "got_fetch.h"
53 #include "got_send.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_opentemp.h"
57 #include "got_gotconfig.h"
58 #include "got_dial.h"
59 #include "got_patch.h"
61 #ifndef nitems
62 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
63 #endif
65 static volatile sig_atomic_t sigint_received;
66 static volatile sig_atomic_t sigpipe_received;
68 static void
69 catch_sigint(int signo)
70 {
71 sigint_received = 1;
72 }
74 static void
75 catch_sigpipe(int signo)
76 {
77 sigpipe_received = 1;
78 }
81 struct got_cmd {
82 const char *cmd_name;
83 const struct got_error *(*cmd_main)(int, char *[]);
84 void (*cmd_usage)(void);
85 const char *cmd_alias;
86 };
88 __dead static void usage(int, int);
89 __dead static void usage_init(void);
90 __dead static void usage_import(void);
91 __dead static void usage_clone(void);
92 __dead static void usage_fetch(void);
93 __dead static void usage_checkout(void);
94 __dead static void usage_update(void);
95 __dead static void usage_log(void);
96 __dead static void usage_diff(void);
97 __dead static void usage_blame(void);
98 __dead static void usage_tree(void);
99 __dead static void usage_status(void);
100 __dead static void usage_ref(void);
101 __dead static void usage_branch(void);
102 __dead static void usage_tag(void);
103 __dead static void usage_add(void);
104 __dead static void usage_remove(void);
105 __dead static void usage_patch(void);
106 __dead static void usage_revert(void);
107 __dead static void usage_commit(void);
108 __dead static void usage_send(void);
109 __dead static void usage_cherrypick(void);
110 __dead static void usage_backout(void);
111 __dead static void usage_rebase(void);
112 __dead static void usage_histedit(void);
113 __dead static void usage_integrate(void);
114 __dead static void usage_merge(void);
115 __dead static void usage_stage(void);
116 __dead static void usage_unstage(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_init(int, char *[]);
121 static const struct got_error* cmd_import(int, char *[]);
122 static const struct got_error* cmd_clone(int, char *[]);
123 static const struct got_error* cmd_fetch(int, char *[]);
124 static const struct got_error* cmd_checkout(int, char *[]);
125 static const struct got_error* cmd_update(int, char *[]);
126 static const struct got_error* cmd_log(int, char *[]);
127 static const struct got_error* cmd_diff(int, char *[]);
128 static const struct got_error* cmd_blame(int, char *[]);
129 static const struct got_error* cmd_tree(int, char *[]);
130 static const struct got_error* cmd_status(int, char *[]);
131 static const struct got_error* cmd_ref(int, char *[]);
132 static const struct got_error* cmd_branch(int, char *[]);
133 static const struct got_error* cmd_tag(int, char *[]);
134 static const struct got_error* cmd_add(int, char *[]);
135 static const struct got_error* cmd_remove(int, char *[]);
136 static const struct got_error* cmd_patch(int, char *[]);
137 static const struct got_error* cmd_revert(int, char *[]);
138 static const struct got_error* cmd_commit(int, char *[]);
139 static const struct got_error* cmd_send(int, char *[]);
140 static const struct got_error* cmd_cherrypick(int, char *[]);
141 static const struct got_error* cmd_backout(int, char *[]);
142 static const struct got_error* cmd_rebase(int, char *[]);
143 static const struct got_error* cmd_histedit(int, char *[]);
144 static const struct got_error* cmd_integrate(int, char *[]);
145 static const struct got_error* cmd_merge(int, char *[]);
146 static const struct got_error* cmd_stage(int, char *[]);
147 static const struct got_error* cmd_unstage(int, char *[]);
148 static const struct got_error* cmd_cat(int, char *[]);
149 static const struct got_error* cmd_info(int, char *[]);
151 static const struct got_cmd got_commands[] = {
152 { "init", cmd_init, usage_init, "" },
153 { "import", cmd_import, usage_import, "im" },
154 { "clone", cmd_clone, usage_clone, "cl" },
155 { "fetch", cmd_fetch, usage_fetch, "fe" },
156 { "checkout", cmd_checkout, usage_checkout, "co" },
157 { "update", cmd_update, usage_update, "up" },
158 { "log", cmd_log, usage_log, "" },
159 { "diff", cmd_diff, usage_diff, "di" },
160 { "blame", cmd_blame, usage_blame, "bl" },
161 { "tree", cmd_tree, usage_tree, "tr" },
162 { "status", cmd_status, usage_status, "st" },
163 { "ref", cmd_ref, usage_ref, "" },
164 { "branch", cmd_branch, usage_branch, "br" },
165 { "tag", cmd_tag, usage_tag, "" },
166 { "add", cmd_add, usage_add, "" },
167 { "remove", cmd_remove, usage_remove, "rm" },
168 { "patch", cmd_patch, usage_patch, "pa" },
169 { "revert", cmd_revert, usage_revert, "rv" },
170 { "commit", cmd_commit, usage_commit, "ci" },
171 { "send", cmd_send, usage_send, "se" },
172 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
173 { "backout", cmd_backout, usage_backout, "bo" },
174 { "rebase", cmd_rebase, usage_rebase, "rb" },
175 { "histedit", cmd_histedit, usage_histedit, "he" },
176 { "integrate", cmd_integrate, usage_integrate,"ig" },
177 { "merge", cmd_merge, usage_merge, "mg" },
178 { "stage", cmd_stage, usage_stage, "sg" },
179 { "unstage", cmd_unstage, usage_unstage, "ug" },
180 { "cat", cmd_cat, usage_cat, "" },
181 { "info", cmd_info, usage_info, "" },
182 };
184 static void
185 list_commands(FILE *fp)
187 size_t i;
189 fprintf(fp, "commands:");
190 for (i = 0; i < nitems(got_commands); i++) {
191 const struct got_cmd *cmd = &got_commands[i];
192 fprintf(fp, " %s", cmd->cmd_name);
194 fputc('\n', fp);
197 __dead static void
198 option_conflict(char a, char b)
200 errx(1, "-%c and -%c options are mutually exclusive", a, b);
203 int
204 main(int argc, char *argv[])
206 const struct got_cmd *cmd;
207 size_t i;
208 int ch;
209 int hflag = 0, Vflag = 0;
210 static const struct option longopts[] = {
211 { "version", no_argument, NULL, 'V' },
212 { NULL, 0, NULL, 0 }
213 };
215 setlocale(LC_CTYPE, "");
217 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
218 switch (ch) {
219 case 'h':
220 hflag = 1;
221 break;
222 case 'V':
223 Vflag = 1;
224 break;
225 default:
226 usage(hflag, 1);
227 /* NOTREACHED */
231 argc -= optind;
232 argv += optind;
233 optind = 1;
234 optreset = 1;
236 if (Vflag) {
237 got_version_print_str();
238 return 0;
241 if (argc <= 0)
242 usage(hflag, hflag ? 0 : 1);
244 signal(SIGINT, catch_sigint);
245 signal(SIGPIPE, catch_sigpipe);
247 for (i = 0; i < nitems(got_commands); i++) {
248 const struct got_error *error;
250 cmd = &got_commands[i];
252 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
253 strcmp(cmd->cmd_alias, argv[0]) != 0)
254 continue;
256 if (hflag)
257 cmd->cmd_usage();
259 error = cmd->cmd_main(argc, argv);
260 if (error && error->code != GOT_ERR_CANCELLED &&
261 error->code != GOT_ERR_PRIVSEP_EXIT &&
262 !(sigpipe_received &&
263 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
264 !(sigint_received &&
265 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
266 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
267 return 1;
270 return 0;
273 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
274 list_commands(stderr);
275 return 1;
278 __dead static void
279 usage(int hflag, int status)
281 FILE *fp = (status == 0) ? stdout : stderr;
283 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
284 getprogname());
285 if (hflag)
286 list_commands(fp);
287 exit(status);
290 static const struct got_error *
291 get_editor(char **abspath)
293 const struct got_error *err = NULL;
294 const char *editor;
296 *abspath = NULL;
298 editor = getenv("VISUAL");
299 if (editor == NULL)
300 editor = getenv("EDITOR");
302 if (editor) {
303 err = got_path_find_prog(abspath, editor);
304 if (err)
305 return err;
308 if (*abspath == NULL) {
309 *abspath = strdup("/bin/ed");
310 if (*abspath == NULL)
311 return got_error_from_errno("strdup");
314 return NULL;
317 static const struct got_error *
318 apply_unveil(const char *repo_path, int repo_read_only,
319 const char *worktree_path)
321 const struct got_error *err;
323 #ifdef PROFILE
324 if (unveil("gmon.out", "rwc") != 0)
325 return got_error_from_errno2("unveil", "gmon.out");
326 #endif
327 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
328 return got_error_from_errno2("unveil", repo_path);
330 if (worktree_path && unveil(worktree_path, "rwc") != 0)
331 return got_error_from_errno2("unveil", worktree_path);
333 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
334 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
336 err = got_privsep_unveil_exec_helpers();
337 if (err != NULL)
338 return err;
340 if (unveil(NULL, NULL) != 0)
341 return got_error_from_errno("unveil");
343 return NULL;
346 __dead static void
347 usage_init(void)
349 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
350 exit(1);
353 static const struct got_error *
354 cmd_init(int argc, char *argv[])
356 const struct got_error *error = NULL;
357 char *repo_path = NULL;
358 int ch;
360 while ((ch = getopt(argc, argv, "")) != -1) {
361 switch (ch) {
362 default:
363 usage_init();
364 /* NOTREACHED */
368 argc -= optind;
369 argv += optind;
371 #ifndef PROFILE
372 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
373 err(1, "pledge");
374 #endif
375 if (argc != 1)
376 usage_init();
378 repo_path = strdup(argv[0]);
379 if (repo_path == NULL)
380 return got_error_from_errno("strdup");
382 got_path_strip_trailing_slashes(repo_path);
384 error = got_path_mkdir(repo_path);
385 if (error &&
386 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
387 goto done;
389 error = apply_unveil(repo_path, 0, NULL);
390 if (error)
391 goto done;
393 error = got_repo_init(repo_path);
394 done:
395 free(repo_path);
396 return error;
399 __dead static void
400 usage_import(void)
402 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
403 "[-r repository-path] [-I pattern] path\n", getprogname());
404 exit(1);
407 int
408 spawn_editor(const char *editor, const char *file)
410 pid_t pid;
411 sig_t sighup, sigint, sigquit;
412 int st = -1;
414 sighup = signal(SIGHUP, SIG_IGN);
415 sigint = signal(SIGINT, SIG_IGN);
416 sigquit = signal(SIGQUIT, SIG_IGN);
418 switch (pid = fork()) {
419 case -1:
420 goto doneediting;
421 case 0:
422 execl(editor, editor, file, (char *)NULL);
423 _exit(127);
426 while (waitpid(pid, &st, 0) == -1)
427 if (errno != EINTR)
428 break;
430 doneediting:
431 (void)signal(SIGHUP, sighup);
432 (void)signal(SIGINT, sigint);
433 (void)signal(SIGQUIT, sigquit);
435 if (!WIFEXITED(st)) {
436 errno = EINTR;
437 return -1;
440 return WEXITSTATUS(st);
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 char *line = NULL;
450 size_t linesize = 0;
451 ssize_t linelen;
452 struct stat st, st2;
453 FILE *fp = NULL;
454 size_t len, logmsg_len;
455 char *initial_content_stripped = NULL, *buf = NULL, *s;
457 *logmsg = NULL;
459 if (stat(logmsg_path, &st) == -1)
460 return got_error_from_errno2("stat", logmsg_path);
462 if (spawn_editor(editor, logmsg_path) == -1)
463 return got_error_from_errno("failed spawning editor");
465 if (stat(logmsg_path, &st2) == -1)
466 return got_error_from_errno("stat");
468 if (require_modification &&
469 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
470 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
471 "no changes made to commit message, aborting");
473 /*
474 * Set up a stripped version of the initial content without comments
475 * and blank lines. We need this in order to check if the message
476 * has in fact been edited.
477 */
478 initial_content_stripped = malloc(initial_content_len + 1);
479 if (initial_content_stripped == NULL)
480 return got_error_from_errno("malloc");
481 initial_content_stripped[0] = '\0';
483 buf = strdup(initial_content);
484 if (buf == NULL) {
485 err = got_error_from_errno("strdup");
486 goto done;
488 s = buf;
489 len = 0;
490 while ((line = strsep(&s, "\n")) != NULL) {
491 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
492 continue; /* remove comments and leading empty lines */
493 len = strlcat(initial_content_stripped, line,
494 initial_content_len + 1);
495 if (len >= initial_content_len + 1) {
496 err = got_error(GOT_ERR_NO_SPACE);
497 goto done;
500 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
501 initial_content_stripped[len - 1] = '\0';
502 len--;
505 logmsg_len = st2.st_size;
506 *logmsg = malloc(logmsg_len + 1);
507 if (*logmsg == NULL)
508 return got_error_from_errno("malloc");
509 (*logmsg)[0] = '\0';
511 fp = fopen(logmsg_path, "re");
512 if (fp == NULL) {
513 err = got_error_from_errno("fopen");
514 goto done;
517 len = 0;
518 while ((linelen = getline(&line, &linesize, fp)) != -1) {
519 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
520 continue; /* remove comments and leading empty lines */
521 len = strlcat(*logmsg, line, logmsg_len + 1);
522 if (len >= logmsg_len + 1) {
523 err = got_error(GOT_ERR_NO_SPACE);
524 goto done;
527 free(line);
528 if (ferror(fp)) {
529 err = got_ferror(fp, GOT_ERR_IO);
530 goto done;
532 while (len > 0 && (*logmsg)[len - 1] == '\n') {
533 (*logmsg)[len - 1] = '\0';
534 len--;
537 if (len == 0) {
538 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
539 "commit message cannot be empty, aborting");
540 goto done;
542 if (require_modification &&
543 strcmp(*logmsg, initial_content_stripped) == 0)
544 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
545 "no changes made to commit message, aborting");
546 done:
547 free(initial_content_stripped);
548 free(buf);
549 if (fp && fclose(fp) == EOF && err == NULL)
550 err = got_error_from_errno("fclose");
551 if (err) {
552 free(*logmsg);
553 *logmsg = NULL;
555 return err;
558 static const struct got_error *
559 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
560 const char *path_dir, const char *branch_name)
562 char *initial_content = NULL;
563 const struct got_error *err = NULL;
564 int initial_content_len;
565 int fd = -1;
567 initial_content_len = asprintf(&initial_content,
568 "\n# %s to be imported to branch %s\n", path_dir,
569 branch_name);
570 if (initial_content_len == -1)
571 return got_error_from_errno("asprintf");
573 err = got_opentemp_named_fd(logmsg_path, &fd,
574 GOT_TMPDIR_STR "/got-importmsg");
575 if (err)
576 goto done;
578 if (write(fd, initial_content, initial_content_len) == -1) {
579 err = got_error_from_errno2("write", *logmsg_path);
580 goto done;
583 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
584 initial_content_len, 1);
585 done:
586 if (fd != -1 && close(fd) == -1 && err == NULL)
587 err = got_error_from_errno2("close", *logmsg_path);
588 free(initial_content);
589 if (err) {
590 free(*logmsg_path);
591 *logmsg_path = NULL;
593 return err;
596 static const struct got_error *
597 import_progress(void *arg, const char *path)
599 printf("A %s\n", path);
600 return NULL;
603 static int
604 valid_author(const char *author)
606 /*
607 * Really dumb email address check; we're only doing this to
608 * avoid git's object parser breaking on commits we create.
609 */
610 while (*author && *author != '<')
611 author++;
612 if (*author != '<')
613 return 0;
614 while (*author && *author != '@')
615 author++;
616 if (*author != '@')
617 return 0;
618 while (*author && *author != '>')
619 author++;
620 return *author == '>';
623 static const struct got_error *
624 get_author(char **author, struct got_repository *repo,
625 struct got_worktree *worktree)
627 const struct got_error *err = NULL;
628 const char *got_author = NULL, *name, *email;
629 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
631 *author = NULL;
633 if (worktree)
634 worktree_conf = got_worktree_get_gotconfig(worktree);
635 repo_conf = got_repo_get_gotconfig(repo);
637 /*
638 * Priority of potential author information sources, from most
639 * significant to least significant:
640 * 1) work tree's .got/got.conf file
641 * 2) repository's got.conf file
642 * 3) repository's git config file
643 * 4) environment variables
644 * 5) global git config files (in user's home directory or /etc)
645 */
647 if (worktree_conf)
648 got_author = got_gotconfig_get_author(worktree_conf);
649 if (got_author == NULL)
650 got_author = got_gotconfig_get_author(repo_conf);
651 if (got_author == NULL) {
652 name = got_repo_get_gitconfig_author_name(repo);
653 email = got_repo_get_gitconfig_author_email(repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email) == -1)
656 return got_error_from_errno("asprintf");
657 return NULL;
660 got_author = getenv("GOT_AUTHOR");
661 if (got_author == NULL) {
662 name = got_repo_get_global_gitconfig_author_name(repo);
663 email = got_repo_get_global_gitconfig_author_email(
664 repo);
665 if (name && email) {
666 if (asprintf(author, "%s <%s>", name, email)
667 == -1)
668 return got_error_from_errno("asprintf");
669 return NULL;
671 /* TODO: Look up user in password database? */
672 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
676 *author = strdup(got_author);
677 if (*author == NULL)
678 return got_error_from_errno("strdup");
680 if (!valid_author(*author)) {
681 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
682 free(*author);
683 *author = NULL;
685 return err;
688 static const struct got_error *
689 get_gitconfig_path(char **gitconfig_path)
691 const char *homedir = getenv("HOME");
693 *gitconfig_path = NULL;
694 if (homedir) {
695 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
696 return got_error_from_errno("asprintf");
699 return NULL;
702 static const struct got_error *
703 cmd_import(int argc, char *argv[])
705 const struct got_error *error = NULL;
706 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
707 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
708 const char *branch_name = "main";
709 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
710 struct got_repository *repo = NULL;
711 struct got_reference *branch_ref = NULL, *head_ref = NULL;
712 struct got_object_id *new_commit_id = NULL;
713 int ch;
714 struct got_pathlist_head ignores;
715 struct got_pathlist_entry *pe;
716 int preserve_logmsg = 0;
718 TAILQ_INIT(&ignores);
720 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
721 switch (ch) {
722 case 'b':
723 branch_name = optarg;
724 break;
725 case 'm':
726 logmsg = strdup(optarg);
727 if (logmsg == NULL) {
728 error = got_error_from_errno("strdup");
729 goto done;
731 break;
732 case 'r':
733 repo_path = realpath(optarg, NULL);
734 if (repo_path == NULL) {
735 error = got_error_from_errno2("realpath",
736 optarg);
737 goto done;
739 break;
740 case 'I':
741 if (optarg[0] == '\0')
742 break;
743 error = got_pathlist_insert(&pe, &ignores, optarg,
744 NULL);
745 if (error)
746 goto done;
747 break;
748 default:
749 usage_import();
750 /* NOTREACHED */
754 argc -= optind;
755 argv += optind;
757 #ifndef PROFILE
758 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
759 "unveil",
760 NULL) == -1)
761 err(1, "pledge");
762 #endif
763 if (argc != 1)
764 usage_import();
766 if (repo_path == NULL) {
767 repo_path = getcwd(NULL, 0);
768 if (repo_path == NULL)
769 return got_error_from_errno("getcwd");
771 got_path_strip_trailing_slashes(repo_path);
772 error = get_gitconfig_path(&gitconfig_path);
773 if (error)
774 goto done;
775 error = got_repo_open(&repo, repo_path, gitconfig_path);
776 if (error)
777 goto done;
779 error = get_author(&author, repo, NULL);
780 if (error)
781 return error;
783 /*
784 * Don't let the user create a branch name with a leading '-'.
785 * While technically a valid reference name, this case is usually
786 * an unintended typo.
787 */
788 if (branch_name[0] == '-')
789 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
791 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
792 error = got_error_from_errno("asprintf");
793 goto done;
796 error = got_ref_open(&branch_ref, repo, refname, 0);
797 if (error) {
798 if (error->code != GOT_ERR_NOT_REF)
799 goto done;
800 } else {
801 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
802 "import target branch already exists");
803 goto done;
806 path_dir = realpath(argv[0], NULL);
807 if (path_dir == NULL) {
808 error = got_error_from_errno2("realpath", argv[0]);
809 goto done;
811 got_path_strip_trailing_slashes(path_dir);
813 /*
814 * unveil(2) traverses exec(2); if an editor is used we have
815 * to apply unveil after the log message has been written.
816 */
817 if (logmsg == NULL || strlen(logmsg) == 0) {
818 error = get_editor(&editor);
819 if (error)
820 goto done;
821 free(logmsg);
822 error = collect_import_msg(&logmsg, &logmsg_path, editor,
823 path_dir, refname);
824 if (error) {
825 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
826 logmsg_path != NULL)
827 preserve_logmsg = 1;
828 goto done;
832 if (unveil(path_dir, "r") != 0) {
833 error = got_error_from_errno2("unveil", path_dir);
834 if (logmsg_path)
835 preserve_logmsg = 1;
836 goto done;
839 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
840 if (error) {
841 if (logmsg_path)
842 preserve_logmsg = 1;
843 goto done;
846 error = got_repo_import(&new_commit_id, path_dir, logmsg,
847 author, &ignores, repo, import_progress, NULL);
848 if (error) {
849 if (logmsg_path)
850 preserve_logmsg = 1;
851 goto done;
854 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
855 if (error) {
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = got_ref_write(branch_ref, repo);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_object_id_str(&id_str, new_commit_id);
869 if (error) {
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
876 if (error) {
877 if (error->code != GOT_ERR_NOT_REF) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
884 branch_ref);
885 if (error) {
886 if (logmsg_path)
887 preserve_logmsg = 1;
888 goto done;
891 error = got_ref_write(head_ref, repo);
892 if (error) {
893 if (logmsg_path)
894 preserve_logmsg = 1;
895 goto done;
899 printf("Created branch %s with commit %s\n",
900 got_ref_get_name(branch_ref), id_str);
901 done:
902 if (preserve_logmsg) {
903 fprintf(stderr, "%s: log message preserved in %s\n",
904 getprogname(), logmsg_path);
905 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
906 error = got_error_from_errno2("unlink", logmsg_path);
907 free(logmsg);
908 free(logmsg_path);
909 free(repo_path);
910 free(editor);
911 free(refname);
912 free(new_commit_id);
913 free(id_str);
914 free(author);
915 free(gitconfig_path);
916 if (branch_ref)
917 got_ref_close(branch_ref);
918 if (head_ref)
919 got_ref_close(head_ref);
920 return error;
923 __dead static void
924 usage_clone(void)
926 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
927 "[-R reference] repository-url [directory]\n", getprogname());
928 exit(1);
931 struct got_fetch_progress_arg {
932 char last_scaled_size[FMT_SCALED_STRSIZE];
933 int last_p_indexed;
934 int last_p_resolved;
935 int verbosity;
937 struct got_repository *repo;
939 int create_configs;
940 int configs_created;
941 struct {
942 struct got_pathlist_head *symrefs;
943 struct got_pathlist_head *wanted_branches;
944 struct got_pathlist_head *wanted_refs;
945 const char *proto;
946 const char *host;
947 const char *port;
948 const char *remote_repo_path;
949 const char *git_url;
950 int fetch_all_branches;
951 int mirror_references;
952 } config_info;
953 };
955 /* XXX forward declaration */
956 static const struct got_error *
957 create_config_files(const char *proto, const char *host, const char *port,
958 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
959 int mirror_references, struct got_pathlist_head *symrefs,
960 struct got_pathlist_head *wanted_branches,
961 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
963 static const struct got_error *
964 fetch_progress(void *arg, const char *message, off_t packfile_size,
965 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
967 const struct got_error *err = NULL;
968 struct got_fetch_progress_arg *a = arg;
969 char scaled_size[FMT_SCALED_STRSIZE];
970 int p_indexed, p_resolved;
971 int print_size = 0, print_indexed = 0, print_resolved = 0;
973 /*
974 * In order to allow a failed clone to be resumed with 'got fetch'
975 * we try to create configuration files as soon as possible.
976 * Once the server has sent information about its default branch
977 * we have all required information.
978 */
979 if (a->create_configs && !a->configs_created &&
980 !TAILQ_EMPTY(a->config_info.symrefs)) {
981 err = create_config_files(a->config_info.proto,
982 a->config_info.host, a->config_info.port,
983 a->config_info.remote_repo_path,
984 a->config_info.git_url,
985 a->config_info.fetch_all_branches,
986 a->config_info.mirror_references,
987 a->config_info.symrefs,
988 a->config_info.wanted_branches,
989 a->config_info.wanted_refs, a->repo);
990 if (err)
991 return err;
992 a->configs_created = 1;
995 if (a->verbosity < 0)
996 return NULL;
998 if (message && message[0] != '\0') {
999 printf("\rserver: %s", message);
1000 fflush(stdout);
1001 return NULL;
1004 if (packfile_size > 0 || nobj_indexed > 0) {
1005 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1006 (a->last_scaled_size[0] == '\0' ||
1007 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1008 print_size = 1;
1009 if (strlcpy(a->last_scaled_size, scaled_size,
1010 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1011 return got_error(GOT_ERR_NO_SPACE);
1013 if (nobj_indexed > 0) {
1014 p_indexed = (nobj_indexed * 100) / nobj_total;
1015 if (p_indexed != a->last_p_indexed) {
1016 a->last_p_indexed = p_indexed;
1017 print_indexed = 1;
1018 print_size = 1;
1021 if (nobj_resolved > 0) {
1022 p_resolved = (nobj_resolved * 100) /
1023 (nobj_total - nobj_loose);
1024 if (p_resolved != a->last_p_resolved) {
1025 a->last_p_resolved = p_resolved;
1026 print_resolved = 1;
1027 print_indexed = 1;
1028 print_size = 1;
1033 if (print_size || print_indexed || print_resolved)
1034 printf("\r");
1035 if (print_size)
1036 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1037 if (print_indexed)
1038 printf("; indexing %d%%", p_indexed);
1039 if (print_resolved)
1040 printf("; resolving deltas %d%%", p_resolved);
1041 if (print_size || print_indexed || print_resolved)
1042 fflush(stdout);
1044 return NULL;
1047 static const struct got_error *
1048 create_symref(const char *refname, struct got_reference *target_ref,
1049 int verbosity, struct got_repository *repo)
1051 const struct got_error *err;
1052 struct got_reference *head_symref;
1054 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1055 if (err)
1056 return err;
1058 err = got_ref_write(head_symref, repo);
1059 if (err == NULL && verbosity > 0) {
1060 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1061 got_ref_get_name(target_ref));
1063 got_ref_close(head_symref);
1064 return err;
1067 static const struct got_error *
1068 list_remote_refs(struct got_pathlist_head *symrefs,
1069 struct got_pathlist_head *refs)
1071 const struct got_error *err;
1072 struct got_pathlist_entry *pe;
1074 TAILQ_FOREACH(pe, symrefs, entry) {
1075 const char *refname = pe->path;
1076 const char *targetref = pe->data;
1078 printf("%s: %s\n", refname, targetref);
1081 TAILQ_FOREACH(pe, refs, entry) {
1082 const char *refname = pe->path;
1083 struct got_object_id *id = pe->data;
1084 char *id_str;
1086 err = got_object_id_str(&id_str, id);
1087 if (err)
1088 return err;
1089 printf("%s: %s\n", refname, id_str);
1090 free(id_str);
1093 return NULL;
1096 static const struct got_error *
1097 create_ref(const char *refname, struct got_object_id *id,
1098 int verbosity, struct got_repository *repo)
1100 const struct got_error *err = NULL;
1101 struct got_reference *ref;
1102 char *id_str;
1104 err = got_object_id_str(&id_str, id);
1105 if (err)
1106 return err;
1108 err = got_ref_alloc(&ref, refname, id);
1109 if (err)
1110 goto done;
1112 err = got_ref_write(ref, repo);
1113 got_ref_close(ref);
1115 if (err == NULL && verbosity >= 0)
1116 printf("Created reference %s: %s\n", refname, id_str);
1117 done:
1118 free(id_str);
1119 return err;
1122 static int
1123 match_wanted_ref(const char *refname, const char *wanted_ref)
1125 if (strncmp(refname, "refs/", 5) != 0)
1126 return 0;
1127 refname += 5;
1130 * Prevent fetching of references that won't make any
1131 * sense outside of the remote repository's context.
1133 if (strncmp(refname, "got/", 4) == 0)
1134 return 0;
1135 if (strncmp(refname, "remotes/", 8) == 0)
1136 return 0;
1138 if (strncmp(wanted_ref, "refs/", 5) == 0)
1139 wanted_ref += 5;
1141 /* Allow prefix match. */
1142 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1143 return 1;
1145 /* Allow exact match. */
1146 return (strcmp(refname, wanted_ref) == 0);
1149 static int
1150 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1152 struct got_pathlist_entry *pe;
1154 TAILQ_FOREACH(pe, wanted_refs, entry) {
1155 if (match_wanted_ref(refname, pe->path))
1156 return 1;
1159 return 0;
1162 static const struct got_error *
1163 create_wanted_ref(const char *refname, struct got_object_id *id,
1164 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1166 const struct got_error *err;
1167 char *remote_refname;
1169 if (strncmp("refs/", refname, 5) == 0)
1170 refname += 5;
1172 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1173 remote_repo_name, refname) == -1)
1174 return got_error_from_errno("asprintf");
1176 err = create_ref(remote_refname, id, verbosity, repo);
1177 free(remote_refname);
1178 return err;
1181 static const struct got_error *
1182 create_gotconfig(const char *proto, const char *host, const char *port,
1183 const char *remote_repo_path, const char *default_branch,
1184 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1185 struct got_pathlist_head *wanted_refs, int mirror_references,
1186 struct got_repository *repo)
1188 const struct got_error *err = NULL;
1189 char *gotconfig_path = NULL;
1190 char *gotconfig = NULL;
1191 FILE *gotconfig_file = NULL;
1192 const char *branchname = NULL;
1193 char *branches = NULL, *refs = NULL;
1194 ssize_t n;
1196 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1197 struct got_pathlist_entry *pe;
1198 TAILQ_FOREACH(pe, wanted_branches, entry) {
1199 char *s;
1200 branchname = pe->path;
1201 if (strncmp(branchname, "refs/heads/", 11) == 0)
1202 branchname += 11;
1203 if (asprintf(&s, "%s\"%s\" ",
1204 branches ? branches : "", branchname) == -1) {
1205 err = got_error_from_errno("asprintf");
1206 goto done;
1208 free(branches);
1209 branches = s;
1211 } else if (!fetch_all_branches && default_branch) {
1212 branchname = default_branch;
1213 if (strncmp(branchname, "refs/heads/", 11) == 0)
1214 branchname += 11;
1215 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1216 err = got_error_from_errno("asprintf");
1217 goto done;
1220 if (!TAILQ_EMPTY(wanted_refs)) {
1221 struct got_pathlist_entry *pe;
1222 TAILQ_FOREACH(pe, wanted_refs, entry) {
1223 char *s;
1224 const char *refname = pe->path;
1225 if (strncmp(refname, "refs/", 5) == 0)
1226 branchname += 5;
1227 if (asprintf(&s, "%s\"%s\" ",
1228 refs ? refs : "", refname) == -1) {
1229 err = got_error_from_errno("asprintf");
1230 goto done;
1232 free(refs);
1233 refs = s;
1237 /* Create got.conf(5). */
1238 gotconfig_path = got_repo_get_path_gotconfig(repo);
1239 if (gotconfig_path == NULL) {
1240 err = got_error_from_errno("got_repo_get_path_gotconfig");
1241 goto done;
1243 gotconfig_file = fopen(gotconfig_path, "ae");
1244 if (gotconfig_file == NULL) {
1245 err = got_error_from_errno2("fopen", gotconfig_path);
1246 goto done;
1248 if (asprintf(&gotconfig,
1249 "remote \"%s\" {\n"
1250 "\tserver %s\n"
1251 "\tprotocol %s\n"
1252 "%s%s%s"
1253 "\trepository \"%s\"\n"
1254 "%s%s%s"
1255 "%s%s%s"
1256 "%s"
1257 "%s"
1258 "}\n",
1259 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1260 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1261 remote_repo_path, branches ? "\tbranch { " : "",
1262 branches ? branches : "", branches ? "}\n" : "",
1263 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1264 mirror_references ? "\tmirror-references yes\n" : "",
1265 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1269 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1270 if (n != strlen(gotconfig)) {
1271 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1272 goto done;
1275 done:
1276 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1277 err = got_error_from_errno2("fclose", gotconfig_path);
1278 free(gotconfig_path);
1279 free(branches);
1280 return err;
1283 static const struct got_error *
1284 create_gitconfig(const char *git_url, const char *default_branch,
1285 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1286 struct got_pathlist_head *wanted_refs, int mirror_references,
1287 struct got_repository *repo)
1289 const struct got_error *err = NULL;
1290 char *gitconfig_path = NULL;
1291 char *gitconfig = NULL;
1292 FILE *gitconfig_file = NULL;
1293 char *branches = NULL, *refs = NULL;
1294 const char *branchname;
1295 ssize_t n;
1297 /* Create a config file Git can understand. */
1298 gitconfig_path = got_repo_get_path_gitconfig(repo);
1299 if (gitconfig_path == NULL) {
1300 err = got_error_from_errno("got_repo_get_path_gitconfig");
1301 goto done;
1303 gitconfig_file = fopen(gitconfig_path, "ae");
1304 if (gitconfig_file == NULL) {
1305 err = got_error_from_errno2("fopen", gitconfig_path);
1306 goto done;
1308 if (fetch_all_branches) {
1309 if (mirror_references) {
1310 if (asprintf(&branches,
1311 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 } else if (asprintf(&branches,
1316 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1317 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1318 err = got_error_from_errno("asprintf");
1319 goto done;
1321 } else if (!TAILQ_EMPTY(wanted_branches)) {
1322 struct got_pathlist_entry *pe;
1323 TAILQ_FOREACH(pe, wanted_branches, entry) {
1324 char *s;
1325 branchname = pe->path;
1326 if (strncmp(branchname, "refs/heads/", 11) == 0)
1327 branchname += 11;
1328 if (mirror_references) {
1329 if (asprintf(&s,
1330 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1331 branches ? branches : "",
1332 branchname, branchname) == -1) {
1333 err = got_error_from_errno("asprintf");
1334 goto done;
1336 } else if (asprintf(&s,
1337 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1338 branches ? branches : "",
1339 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1340 branchname) == -1) {
1341 err = got_error_from_errno("asprintf");
1342 goto done;
1344 free(branches);
1345 branches = s;
1347 } else {
1349 * If the server specified a default branch, use just that one.
1350 * Otherwise fall back to fetching all branches on next fetch.
1352 if (default_branch) {
1353 branchname = default_branch;
1354 if (strncmp(branchname, "refs/heads/", 11) == 0)
1355 branchname += 11;
1356 } else
1357 branchname = "*"; /* fall back to all branches */
1358 if (mirror_references) {
1359 if (asprintf(&branches,
1360 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1361 branchname, branchname) == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1365 } else if (asprintf(&branches,
1366 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1367 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1368 branchname) == -1) {
1369 err = got_error_from_errno("asprintf");
1370 goto done;
1373 if (!TAILQ_EMPTY(wanted_refs)) {
1374 struct got_pathlist_entry *pe;
1375 TAILQ_FOREACH(pe, wanted_refs, entry) {
1376 char *s;
1377 const char *refname = pe->path;
1378 if (strncmp(refname, "refs/", 5) == 0)
1379 refname += 5;
1380 if (mirror_references) {
1381 if (asprintf(&s,
1382 "%s\tfetch = refs/%s:refs/%s\n",
1383 refs ? refs : "", refname, refname) == -1) {
1384 err = got_error_from_errno("asprintf");
1385 goto done;
1387 } else if (asprintf(&s,
1388 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1389 refs ? refs : "",
1390 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1391 refname) == -1) {
1392 err = got_error_from_errno("asprintf");
1393 goto done;
1395 free(refs);
1396 refs = s;
1400 if (asprintf(&gitconfig,
1401 "[remote \"%s\"]\n"
1402 "\turl = %s\n"
1403 "%s"
1404 "%s"
1405 "\tfetch = refs/tags/*:refs/tags/*\n",
1406 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1407 refs ? refs : "") == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1412 if (n != strlen(gitconfig)) {
1413 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1414 goto done;
1416 done:
1417 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1418 err = got_error_from_errno2("fclose", gitconfig_path);
1419 free(gitconfig_path);
1420 free(branches);
1421 return err;
1424 static const struct got_error *
1425 create_config_files(const char *proto, const char *host, const char *port,
1426 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1427 int mirror_references, struct got_pathlist_head *symrefs,
1428 struct got_pathlist_head *wanted_branches,
1429 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1431 const struct got_error *err = NULL;
1432 const char *default_branch = NULL;
1433 struct got_pathlist_entry *pe;
1436 * If we asked for a set of wanted branches then use the first
1437 * one of those.
1439 if (!TAILQ_EMPTY(wanted_branches)) {
1440 pe = TAILQ_FIRST(wanted_branches);
1441 default_branch = pe->path;
1442 } else {
1443 /* First HEAD ref listed by server is the default branch. */
1444 TAILQ_FOREACH(pe, symrefs, entry) {
1445 const char *refname = pe->path;
1446 const char *target = pe->data;
1448 if (strcmp(refname, GOT_REF_HEAD) != 0)
1449 continue;
1451 default_branch = target;
1452 break;
1456 /* Create got.conf(5). */
1457 err = create_gotconfig(proto, host, port, remote_repo_path,
1458 default_branch, fetch_all_branches, wanted_branches,
1459 wanted_refs, mirror_references, repo);
1460 if (err)
1461 return err;
1463 /* Create a config file Git can understand. */
1464 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1465 wanted_branches, wanted_refs, mirror_references, repo);
1468 static const struct got_error *
1469 cmd_clone(int argc, char *argv[])
1471 const struct got_error *error = NULL;
1472 const char *uri, *dirname;
1473 char *proto, *host, *port, *repo_name, *server_path;
1474 char *default_destdir = NULL, *id_str = NULL;
1475 const char *repo_path;
1476 struct got_repository *repo = NULL;
1477 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1478 struct got_pathlist_entry *pe;
1479 struct got_object_id *pack_hash = NULL;
1480 int ch, fetchfd = -1, fetchstatus;
1481 pid_t fetchpid = -1;
1482 struct got_fetch_progress_arg fpa;
1483 char *git_url = NULL;
1484 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1485 int list_refs_only = 0;
1487 TAILQ_INIT(&refs);
1488 TAILQ_INIT(&symrefs);
1489 TAILQ_INIT(&wanted_branches);
1490 TAILQ_INIT(&wanted_refs);
1492 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1493 switch (ch) {
1494 case 'a':
1495 fetch_all_branches = 1;
1496 break;
1497 case 'b':
1498 error = got_pathlist_append(&wanted_branches,
1499 optarg, NULL);
1500 if (error)
1501 return error;
1502 break;
1503 case 'l':
1504 list_refs_only = 1;
1505 break;
1506 case 'm':
1507 mirror_references = 1;
1508 break;
1509 case 'v':
1510 if (verbosity < 0)
1511 verbosity = 0;
1512 else if (verbosity < 3)
1513 verbosity++;
1514 break;
1515 case 'q':
1516 verbosity = -1;
1517 break;
1518 case 'R':
1519 error = got_pathlist_append(&wanted_refs,
1520 optarg, NULL);
1521 if (error)
1522 return error;
1523 break;
1524 default:
1525 usage_clone();
1526 break;
1529 argc -= optind;
1530 argv += optind;
1532 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1533 option_conflict('a', 'b');
1534 if (list_refs_only) {
1535 if (!TAILQ_EMPTY(&wanted_branches))
1536 option_conflict('l', 'b');
1537 if (fetch_all_branches)
1538 option_conflict('l', 'a');
1539 if (mirror_references)
1540 option_conflict('l', 'm');
1541 if (!TAILQ_EMPTY(&wanted_refs))
1542 option_conflict('l', 'R');
1545 uri = argv[0];
1547 if (argc == 1)
1548 dirname = NULL;
1549 else if (argc == 2)
1550 dirname = argv[1];
1551 else
1552 usage_clone();
1554 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1555 &repo_name, uri);
1556 if (error)
1557 goto done;
1559 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1560 host, port ? ":" : "", port ? port : "",
1561 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1562 error = got_error_from_errno("asprintf");
1563 goto done;
1566 if (strcmp(proto, "git") == 0) {
1567 #ifndef PROFILE
1568 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1569 "sendfd dns inet unveil", NULL) == -1)
1570 err(1, "pledge");
1571 #endif
1572 } else if (strcmp(proto, "git+ssh") == 0 ||
1573 strcmp(proto, "ssh") == 0) {
1574 #ifndef PROFILE
1575 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1576 "sendfd unveil", NULL) == -1)
1577 err(1, "pledge");
1578 #endif
1579 } else if (strcmp(proto, "http") == 0 ||
1580 strcmp(proto, "git+http") == 0) {
1581 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1582 goto done;
1583 } else {
1584 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1585 goto done;
1587 if (dirname == NULL) {
1588 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1589 error = got_error_from_errno("asprintf");
1590 goto done;
1592 repo_path = default_destdir;
1593 } else
1594 repo_path = dirname;
1596 if (!list_refs_only) {
1597 error = got_path_mkdir(repo_path);
1598 if (error &&
1599 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1600 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1601 goto done;
1602 if (!got_path_dir_is_empty(repo_path)) {
1603 error = got_error_path(repo_path,
1604 GOT_ERR_DIR_NOT_EMPTY);
1605 goto done;
1609 error = got_dial_apply_unveil(proto);
1610 if (error)
1611 goto done;
1613 error = apply_unveil(repo_path, 0, NULL);
1614 if (error)
1615 goto done;
1617 if (verbosity >= 0)
1618 printf("Connecting to %s%s%s\n", host,
1619 port ? ":" : "", port ? port : "");
1621 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1622 server_path, verbosity);
1623 if (error)
1624 goto done;
1626 if (!list_refs_only) {
1627 error = got_repo_init(repo_path);
1628 if (error)
1629 goto done;
1630 error = got_repo_open(&repo, repo_path, NULL);
1631 if (error)
1632 goto done;
1635 fpa.last_scaled_size[0] = '\0';
1636 fpa.last_p_indexed = -1;
1637 fpa.last_p_resolved = -1;
1638 fpa.verbosity = verbosity;
1639 fpa.create_configs = 1;
1640 fpa.configs_created = 0;
1641 fpa.repo = repo;
1642 fpa.config_info.symrefs = &symrefs;
1643 fpa.config_info.wanted_branches = &wanted_branches;
1644 fpa.config_info.wanted_refs = &wanted_refs;
1645 fpa.config_info.proto = proto;
1646 fpa.config_info.host = host;
1647 fpa.config_info.port = port;
1648 fpa.config_info.remote_repo_path = server_path;
1649 fpa.config_info.git_url = git_url;
1650 fpa.config_info.fetch_all_branches = fetch_all_branches;
1651 fpa.config_info.mirror_references = mirror_references;
1652 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1653 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1654 fetch_all_branches, &wanted_branches, &wanted_refs,
1655 list_refs_only, verbosity, fetchfd, repo,
1656 fetch_progress, &fpa);
1657 if (error)
1658 goto done;
1660 if (list_refs_only) {
1661 error = list_remote_refs(&symrefs, &refs);
1662 goto done;
1665 if (pack_hash == NULL) {
1666 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1667 "server sent an empty pack file");
1668 goto done;
1670 error = got_object_id_str(&id_str, pack_hash);
1671 if (error)
1672 goto done;
1673 if (verbosity >= 0)
1674 printf("\nFetched %s.pack\n", id_str);
1675 free(id_str);
1677 /* Set up references provided with the pack file. */
1678 TAILQ_FOREACH(pe, &refs, entry) {
1679 const char *refname = pe->path;
1680 struct got_object_id *id = pe->data;
1681 char *remote_refname;
1683 if (is_wanted_ref(&wanted_refs, refname) &&
1684 !mirror_references) {
1685 error = create_wanted_ref(refname, id,
1686 GOT_FETCH_DEFAULT_REMOTE_NAME,
1687 verbosity - 1, repo);
1688 if (error)
1689 goto done;
1690 continue;
1693 error = create_ref(refname, id, verbosity - 1, repo);
1694 if (error)
1695 goto done;
1697 if (mirror_references)
1698 continue;
1700 if (strncmp("refs/heads/", refname, 11) != 0)
1701 continue;
1703 if (asprintf(&remote_refname,
1704 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1705 refname + 11) == -1) {
1706 error = got_error_from_errno("asprintf");
1707 goto done;
1709 error = create_ref(remote_refname, id, verbosity - 1, repo);
1710 free(remote_refname);
1711 if (error)
1712 goto done;
1715 /* Set the HEAD reference if the server provided one. */
1716 TAILQ_FOREACH(pe, &symrefs, entry) {
1717 struct got_reference *target_ref;
1718 const char *refname = pe->path;
1719 const char *target = pe->data;
1720 char *remote_refname = NULL, *remote_target = NULL;
1722 if (strcmp(refname, GOT_REF_HEAD) != 0)
1723 continue;
1725 error = got_ref_open(&target_ref, repo, target, 0);
1726 if (error) {
1727 if (error->code == GOT_ERR_NOT_REF) {
1728 error = NULL;
1729 continue;
1731 goto done;
1734 error = create_symref(refname, target_ref, verbosity, repo);
1735 got_ref_close(target_ref);
1736 if (error)
1737 goto done;
1739 if (mirror_references)
1740 continue;
1742 if (strncmp("refs/heads/", target, 11) != 0)
1743 continue;
1745 if (asprintf(&remote_refname,
1746 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1747 refname) == -1) {
1748 error = got_error_from_errno("asprintf");
1749 goto done;
1751 if (asprintf(&remote_target,
1752 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1753 target + 11) == -1) {
1754 error = got_error_from_errno("asprintf");
1755 free(remote_refname);
1756 goto done;
1758 error = got_ref_open(&target_ref, repo, remote_target, 0);
1759 if (error) {
1760 free(remote_refname);
1761 free(remote_target);
1762 if (error->code == GOT_ERR_NOT_REF) {
1763 error = NULL;
1764 continue;
1766 goto done;
1768 error = create_symref(remote_refname, target_ref,
1769 verbosity - 1, repo);
1770 free(remote_refname);
1771 free(remote_target);
1772 got_ref_close(target_ref);
1773 if (error)
1774 goto done;
1776 if (pe == NULL) {
1778 * We failed to set the HEAD reference. If we asked for
1779 * a set of wanted branches use the first of one of those
1780 * which could be fetched instead.
1782 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1783 const char *target = pe->path;
1784 struct got_reference *target_ref;
1786 error = got_ref_open(&target_ref, repo, target, 0);
1787 if (error) {
1788 if (error->code == GOT_ERR_NOT_REF) {
1789 error = NULL;
1790 continue;
1792 goto done;
1795 error = create_symref(GOT_REF_HEAD, target_ref,
1796 verbosity, repo);
1797 got_ref_close(target_ref);
1798 if (error)
1799 goto done;
1800 break;
1804 if (verbosity >= 0)
1805 printf("Created %s repository '%s'\n",
1806 mirror_references ? "mirrored" : "cloned", repo_path);
1807 done:
1808 if (fetchpid > 0) {
1809 if (kill(fetchpid, SIGTERM) == -1)
1810 error = got_error_from_errno("kill");
1811 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1812 error = got_error_from_errno("waitpid");
1814 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1815 error = got_error_from_errno("close");
1816 if (repo) {
1817 const struct got_error *close_err = got_repo_close(repo);
1818 if (error == NULL)
1819 error = close_err;
1821 TAILQ_FOREACH(pe, &refs, entry) {
1822 free((void *)pe->path);
1823 free(pe->data);
1825 got_pathlist_free(&refs);
1826 TAILQ_FOREACH(pe, &symrefs, entry) {
1827 free((void *)pe->path);
1828 free(pe->data);
1830 got_pathlist_free(&symrefs);
1831 got_pathlist_free(&wanted_branches);
1832 got_pathlist_free(&wanted_refs);
1833 free(pack_hash);
1834 free(proto);
1835 free(host);
1836 free(port);
1837 free(server_path);
1838 free(repo_name);
1839 free(default_destdir);
1840 free(git_url);
1841 return error;
1844 static const struct got_error *
1845 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1846 int replace_tags, int verbosity, struct got_repository *repo)
1848 const struct got_error *err = NULL;
1849 char *new_id_str = NULL;
1850 struct got_object_id *old_id = NULL;
1852 err = got_object_id_str(&new_id_str, new_id);
1853 if (err)
1854 goto done;
1856 if (!replace_tags &&
1857 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1858 err = got_ref_resolve(&old_id, repo, ref);
1859 if (err)
1860 goto done;
1861 if (got_object_id_cmp(old_id, new_id) == 0)
1862 goto done;
1863 if (verbosity >= 0) {
1864 printf("Rejecting update of existing tag %s: %s\n",
1865 got_ref_get_name(ref), new_id_str);
1867 goto done;
1870 if (got_ref_is_symbolic(ref)) {
1871 if (verbosity >= 0) {
1872 printf("Replacing reference %s: %s\n",
1873 got_ref_get_name(ref),
1874 got_ref_get_symref_target(ref));
1876 err = got_ref_change_symref_to_ref(ref, new_id);
1877 if (err)
1878 goto done;
1879 err = got_ref_write(ref, repo);
1880 if (err)
1881 goto done;
1882 } else {
1883 err = got_ref_resolve(&old_id, repo, ref);
1884 if (err)
1885 goto done;
1886 if (got_object_id_cmp(old_id, new_id) == 0)
1887 goto done;
1889 err = got_ref_change_ref(ref, new_id);
1890 if (err)
1891 goto done;
1892 err = got_ref_write(ref, repo);
1893 if (err)
1894 goto done;
1897 if (verbosity >= 0)
1898 printf("Updated %s: %s\n", got_ref_get_name(ref),
1899 new_id_str);
1900 done:
1901 free(old_id);
1902 free(new_id_str);
1903 return err;
1906 static const struct got_error *
1907 update_symref(const char *refname, struct got_reference *target_ref,
1908 int verbosity, struct got_repository *repo)
1910 const struct got_error *err = NULL, *unlock_err;
1911 struct got_reference *symref;
1912 int symref_is_locked = 0;
1914 err = got_ref_open(&symref, repo, refname, 1);
1915 if (err) {
1916 if (err->code != GOT_ERR_NOT_REF)
1917 return err;
1918 err = got_ref_alloc_symref(&symref, refname, target_ref);
1919 if (err)
1920 goto done;
1922 err = got_ref_write(symref, repo);
1923 if (err)
1924 goto done;
1926 if (verbosity >= 0)
1927 printf("Created reference %s: %s\n",
1928 got_ref_get_name(symref),
1929 got_ref_get_symref_target(symref));
1930 } else {
1931 symref_is_locked = 1;
1933 if (strcmp(got_ref_get_symref_target(symref),
1934 got_ref_get_name(target_ref)) == 0)
1935 goto done;
1937 err = got_ref_change_symref(symref,
1938 got_ref_get_name(target_ref));
1939 if (err)
1940 goto done;
1942 err = got_ref_write(symref, repo);
1943 if (err)
1944 goto done;
1946 if (verbosity >= 0)
1947 printf("Updated %s: %s\n", got_ref_get_name(symref),
1948 got_ref_get_symref_target(symref));
1951 done:
1952 if (symref_is_locked) {
1953 unlock_err = got_ref_unlock(symref);
1954 if (unlock_err && err == NULL)
1955 err = unlock_err;
1957 got_ref_close(symref);
1958 return err;
1961 __dead static void
1962 usage_fetch(void)
1964 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1965 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1966 "[remote-repository-name]\n",
1967 getprogname());
1968 exit(1);
1971 static const struct got_error *
1972 delete_missing_ref(struct got_reference *ref,
1973 int verbosity, struct got_repository *repo)
1975 const struct got_error *err = NULL;
1976 struct got_object_id *id = NULL;
1977 char *id_str = NULL;
1979 if (got_ref_is_symbolic(ref)) {
1980 err = got_ref_delete(ref, repo);
1981 if (err)
1982 return err;
1983 if (verbosity >= 0) {
1984 printf("Deleted %s: %s\n",
1985 got_ref_get_name(ref),
1986 got_ref_get_symref_target(ref));
1988 } else {
1989 err = got_ref_resolve(&id, repo, ref);
1990 if (err)
1991 return err;
1992 err = got_object_id_str(&id_str, id);
1993 if (err)
1994 goto done;
1996 err = got_ref_delete(ref, repo);
1997 if (err)
1998 goto done;
1999 if (verbosity >= 0) {
2000 printf("Deleted %s: %s\n",
2001 got_ref_get_name(ref), id_str);
2004 done:
2005 free(id);
2006 free(id_str);
2007 return NULL;
2010 static const struct got_error *
2011 delete_missing_refs(struct got_pathlist_head *their_refs,
2012 struct got_pathlist_head *their_symrefs,
2013 const struct got_remote_repo *remote,
2014 int verbosity, struct got_repository *repo)
2016 const struct got_error *err = NULL, *unlock_err;
2017 struct got_reflist_head my_refs;
2018 struct got_reflist_entry *re;
2019 struct got_pathlist_entry *pe;
2020 char *remote_namespace = NULL;
2021 char *local_refname = NULL;
2023 TAILQ_INIT(&my_refs);
2025 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2026 == -1)
2027 return got_error_from_errno("asprintf");
2029 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2030 if (err)
2031 goto done;
2033 TAILQ_FOREACH(re, &my_refs, entry) {
2034 const char *refname = got_ref_get_name(re->ref);
2035 const char *their_refname;
2037 if (remote->mirror_references) {
2038 their_refname = refname;
2039 } else {
2040 if (strncmp(refname, remote_namespace,
2041 strlen(remote_namespace)) == 0) {
2042 if (strcmp(refname + strlen(remote_namespace),
2043 GOT_REF_HEAD) == 0)
2044 continue;
2045 if (asprintf(&local_refname, "refs/heads/%s",
2046 refname + strlen(remote_namespace)) == -1) {
2047 err = got_error_from_errno("asprintf");
2048 goto done;
2050 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2051 continue;
2053 their_refname = local_refname;
2056 TAILQ_FOREACH(pe, their_refs, entry) {
2057 if (strcmp(their_refname, pe->path) == 0)
2058 break;
2060 if (pe != NULL)
2061 continue;
2063 TAILQ_FOREACH(pe, their_symrefs, entry) {
2064 if (strcmp(their_refname, pe->path) == 0)
2065 break;
2067 if (pe != NULL)
2068 continue;
2070 err = delete_missing_ref(re->ref, verbosity, repo);
2071 if (err)
2072 break;
2074 if (local_refname) {
2075 struct got_reference *ref;
2076 err = got_ref_open(&ref, repo, local_refname, 1);
2077 if (err) {
2078 if (err->code != GOT_ERR_NOT_REF)
2079 break;
2080 free(local_refname);
2081 local_refname = NULL;
2082 continue;
2084 err = delete_missing_ref(ref, verbosity, repo);
2085 if (err)
2086 break;
2087 unlock_err = got_ref_unlock(ref);
2088 got_ref_close(ref);
2089 if (unlock_err && err == NULL) {
2090 err = unlock_err;
2091 break;
2094 free(local_refname);
2095 local_refname = NULL;
2098 done:
2099 free(remote_namespace);
2100 free(local_refname);
2101 return err;
2104 static const struct got_error *
2105 update_wanted_ref(const char *refname, struct got_object_id *id,
2106 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2108 const struct got_error *err, *unlock_err;
2109 char *remote_refname;
2110 struct got_reference *ref;
2112 if (strncmp("refs/", refname, 5) == 0)
2113 refname += 5;
2115 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2116 remote_repo_name, refname) == -1)
2117 return got_error_from_errno("asprintf");
2119 err = got_ref_open(&ref, repo, remote_refname, 1);
2120 if (err) {
2121 if (err->code != GOT_ERR_NOT_REF)
2122 goto done;
2123 err = create_ref(remote_refname, id, verbosity, repo);
2124 } else {
2125 err = update_ref(ref, id, 0, verbosity, repo);
2126 unlock_err = got_ref_unlock(ref);
2127 if (unlock_err && err == NULL)
2128 err = unlock_err;
2129 got_ref_close(ref);
2131 done:
2132 free(remote_refname);
2133 return err;
2136 static const struct got_error *
2137 delete_ref(struct got_repository *repo, struct got_reference *ref)
2139 const struct got_error *err = NULL;
2140 struct got_object_id *id = NULL;
2141 char *id_str = NULL;
2142 const char *target;
2144 if (got_ref_is_symbolic(ref)) {
2145 target = got_ref_get_symref_target(ref);
2146 } else {
2147 err = got_ref_resolve(&id, repo, ref);
2148 if (err)
2149 goto done;
2150 err = got_object_id_str(&id_str, id);
2151 if (err)
2152 goto done;
2153 target = id_str;
2156 err = got_ref_delete(ref, repo);
2157 if (err)
2158 goto done;
2160 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2161 done:
2162 free(id);
2163 free(id_str);
2164 return err;
2167 static const struct got_error *
2168 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2170 const struct got_error *err = NULL;
2171 struct got_reflist_head refs;
2172 struct got_reflist_entry *re;
2173 char *prefix;
2175 TAILQ_INIT(&refs);
2177 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2178 err = got_error_from_errno("asprintf");
2179 goto done;
2181 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2182 if (err)
2183 goto done;
2185 TAILQ_FOREACH(re, &refs, entry)
2186 delete_ref(repo, re->ref);
2187 done:
2188 got_ref_list_free(&refs);
2189 return err;
2192 static const struct got_error *
2193 cmd_fetch(int argc, char *argv[])
2195 const struct got_error *error = NULL, *unlock_err;
2196 char *cwd = NULL, *repo_path = NULL;
2197 const char *remote_name;
2198 char *proto = NULL, *host = NULL, *port = NULL;
2199 char *repo_name = NULL, *server_path = NULL;
2200 const struct got_remote_repo *remotes, *remote = NULL;
2201 int nremotes;
2202 char *id_str = NULL;
2203 struct got_repository *repo = NULL;
2204 struct got_worktree *worktree = NULL;
2205 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2206 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2207 struct got_pathlist_entry *pe;
2208 struct got_object_id *pack_hash = NULL;
2209 int i, ch, fetchfd = -1, fetchstatus;
2210 pid_t fetchpid = -1;
2211 struct got_fetch_progress_arg fpa;
2212 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2213 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2215 TAILQ_INIT(&refs);
2216 TAILQ_INIT(&symrefs);
2217 TAILQ_INIT(&wanted_branches);
2218 TAILQ_INIT(&wanted_refs);
2220 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2221 switch (ch) {
2222 case 'a':
2223 fetch_all_branches = 1;
2224 break;
2225 case 'b':
2226 error = got_pathlist_append(&wanted_branches,
2227 optarg, NULL);
2228 if (error)
2229 return error;
2230 break;
2231 case 'd':
2232 delete_refs = 1;
2233 break;
2234 case 'l':
2235 list_refs_only = 1;
2236 break;
2237 case 'r':
2238 repo_path = realpath(optarg, NULL);
2239 if (repo_path == NULL)
2240 return got_error_from_errno2("realpath",
2241 optarg);
2242 got_path_strip_trailing_slashes(repo_path);
2243 break;
2244 case 't':
2245 replace_tags = 1;
2246 break;
2247 case 'v':
2248 if (verbosity < 0)
2249 verbosity = 0;
2250 else if (verbosity < 3)
2251 verbosity++;
2252 break;
2253 case 'q':
2254 verbosity = -1;
2255 break;
2256 case 'R':
2257 error = got_pathlist_append(&wanted_refs,
2258 optarg, NULL);
2259 if (error)
2260 return error;
2261 break;
2262 case 'X':
2263 delete_remote = 1;
2264 break;
2265 default:
2266 usage_fetch();
2267 break;
2270 argc -= optind;
2271 argv += optind;
2273 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2274 option_conflict('a', 'b');
2275 if (list_refs_only) {
2276 if (!TAILQ_EMPTY(&wanted_branches))
2277 option_conflict('l', 'b');
2278 if (fetch_all_branches)
2279 option_conflict('l', 'a');
2280 if (delete_refs)
2281 option_conflict('l', 'd');
2282 if (delete_remote)
2283 option_conflict('l', 'X');
2285 if (delete_remote) {
2286 if (fetch_all_branches)
2287 option_conflict('X', 'a');
2288 if (!TAILQ_EMPTY(&wanted_branches))
2289 option_conflict('X', 'b');
2290 if (delete_refs)
2291 option_conflict('X', 'd');
2292 if (replace_tags)
2293 option_conflict('X', 't');
2294 if (!TAILQ_EMPTY(&wanted_refs))
2295 option_conflict('X', 'R');
2298 if (argc == 0) {
2299 if (delete_remote)
2300 errx(1, "-X option requires a remote name");
2301 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2302 } else if (argc == 1)
2303 remote_name = argv[0];
2304 else
2305 usage_fetch();
2307 cwd = getcwd(NULL, 0);
2308 if (cwd == NULL) {
2309 error = got_error_from_errno("getcwd");
2310 goto done;
2313 if (repo_path == NULL) {
2314 error = got_worktree_open(&worktree, cwd);
2315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2316 goto done;
2317 else
2318 error = NULL;
2319 if (worktree) {
2320 repo_path =
2321 strdup(got_worktree_get_repo_path(worktree));
2322 if (repo_path == NULL)
2323 error = got_error_from_errno("strdup");
2324 if (error)
2325 goto done;
2326 } else {
2327 repo_path = strdup(cwd);
2328 if (repo_path == NULL) {
2329 error = got_error_from_errno("strdup");
2330 goto done;
2335 error = got_repo_open(&repo, repo_path, NULL);
2336 if (error)
2337 goto done;
2339 if (delete_remote) {
2340 error = delete_refs_for_remote(repo, remote_name);
2341 goto done; /* nothing else to do */
2344 if (worktree) {
2345 worktree_conf = got_worktree_get_gotconfig(worktree);
2346 if (worktree_conf) {
2347 got_gotconfig_get_remotes(&nremotes, &remotes,
2348 worktree_conf);
2349 for (i = 0; i < nremotes; i++) {
2350 if (strcmp(remotes[i].name, remote_name) == 0) {
2351 remote = &remotes[i];
2352 break;
2357 if (remote == NULL) {
2358 repo_conf = got_repo_get_gotconfig(repo);
2359 if (repo_conf) {
2360 got_gotconfig_get_remotes(&nremotes, &remotes,
2361 repo_conf);
2362 for (i = 0; i < nremotes; i++) {
2363 if (strcmp(remotes[i].name, remote_name) == 0) {
2364 remote = &remotes[i];
2365 break;
2370 if (remote == NULL) {
2371 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2372 for (i = 0; i < nremotes; i++) {
2373 if (strcmp(remotes[i].name, remote_name) == 0) {
2374 remote = &remotes[i];
2375 break;
2379 if (remote == NULL) {
2380 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2381 goto done;
2384 if (TAILQ_EMPTY(&wanted_branches)) {
2385 if (!fetch_all_branches)
2386 fetch_all_branches = remote->fetch_all_branches;
2387 for (i = 0; i < remote->nfetch_branches; i++) {
2388 got_pathlist_append(&wanted_branches,
2389 remote->fetch_branches[i], NULL);
2392 if (TAILQ_EMPTY(&wanted_refs)) {
2393 for (i = 0; i < remote->nfetch_refs; i++) {
2394 got_pathlist_append(&wanted_refs,
2395 remote->fetch_refs[i], NULL);
2399 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2400 &repo_name, remote->fetch_url);
2401 if (error)
2402 goto done;
2404 if (strcmp(proto, "git") == 0) {
2405 #ifndef PROFILE
2406 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2407 "sendfd dns inet unveil", NULL) == -1)
2408 err(1, "pledge");
2409 #endif
2410 } else if (strcmp(proto, "git+ssh") == 0 ||
2411 strcmp(proto, "ssh") == 0) {
2412 #ifndef PROFILE
2413 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2414 "sendfd unveil", NULL) == -1)
2415 err(1, "pledge");
2416 #endif
2417 } else if (strcmp(proto, "http") == 0 ||
2418 strcmp(proto, "git+http") == 0) {
2419 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2420 goto done;
2421 } else {
2422 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2423 goto done;
2426 error = got_dial_apply_unveil(proto);
2427 if (error)
2428 goto done;
2430 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2431 if (error)
2432 goto done;
2434 if (verbosity >= 0)
2435 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2436 port ? ":" : "", port ? port : "");
2438 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2439 server_path, verbosity);
2440 if (error)
2441 goto done;
2443 fpa.last_scaled_size[0] = '\0';
2444 fpa.last_p_indexed = -1;
2445 fpa.last_p_resolved = -1;
2446 fpa.verbosity = verbosity;
2447 fpa.repo = repo;
2448 fpa.create_configs = 0;
2449 fpa.configs_created = 0;
2450 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2451 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2452 remote->mirror_references, fetch_all_branches, &wanted_branches,
2453 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2454 fetch_progress, &fpa);
2455 if (error)
2456 goto done;
2458 if (list_refs_only) {
2459 error = list_remote_refs(&symrefs, &refs);
2460 goto done;
2463 if (pack_hash == NULL) {
2464 if (verbosity >= 0)
2465 printf("Already up-to-date\n");
2466 } else if (verbosity >= 0) {
2467 error = got_object_id_str(&id_str, pack_hash);
2468 if (error)
2469 goto done;
2470 printf("\nFetched %s.pack\n", id_str);
2471 free(id_str);
2472 id_str = NULL;
2475 /* Update references provided with the pack file. */
2476 TAILQ_FOREACH(pe, &refs, entry) {
2477 const char *refname = pe->path;
2478 struct got_object_id *id = pe->data;
2479 struct got_reference *ref;
2480 char *remote_refname;
2482 if (is_wanted_ref(&wanted_refs, refname) &&
2483 !remote->mirror_references) {
2484 error = update_wanted_ref(refname, id,
2485 remote->name, verbosity, repo);
2486 if (error)
2487 goto done;
2488 continue;
2491 if (remote->mirror_references ||
2492 strncmp("refs/tags/", refname, 10) == 0) {
2493 error = got_ref_open(&ref, repo, refname, 1);
2494 if (error) {
2495 if (error->code != GOT_ERR_NOT_REF)
2496 goto done;
2497 error = create_ref(refname, id, verbosity,
2498 repo);
2499 if (error)
2500 goto done;
2501 } else {
2502 error = update_ref(ref, id, replace_tags,
2503 verbosity, repo);
2504 unlock_err = got_ref_unlock(ref);
2505 if (unlock_err && error == NULL)
2506 error = unlock_err;
2507 got_ref_close(ref);
2508 if (error)
2509 goto done;
2511 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2512 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2513 remote_name, refname + 11) == -1) {
2514 error = got_error_from_errno("asprintf");
2515 goto done;
2518 error = got_ref_open(&ref, repo, remote_refname, 1);
2519 if (error) {
2520 if (error->code != GOT_ERR_NOT_REF)
2521 goto done;
2522 error = create_ref(remote_refname, id,
2523 verbosity, repo);
2524 if (error)
2525 goto done;
2526 } else {
2527 error = update_ref(ref, id, replace_tags,
2528 verbosity, repo);
2529 unlock_err = got_ref_unlock(ref);
2530 if (unlock_err && error == NULL)
2531 error = unlock_err;
2532 got_ref_close(ref);
2533 if (error)
2534 goto done;
2537 /* Also create a local branch if none exists yet. */
2538 error = got_ref_open(&ref, repo, refname, 1);
2539 if (error) {
2540 if (error->code != GOT_ERR_NOT_REF)
2541 goto done;
2542 error = create_ref(refname, id, verbosity,
2543 repo);
2544 if (error)
2545 goto done;
2546 } else {
2547 unlock_err = got_ref_unlock(ref);
2548 if (unlock_err && error == NULL)
2549 error = unlock_err;
2550 got_ref_close(ref);
2554 if (delete_refs) {
2555 error = delete_missing_refs(&refs, &symrefs, remote,
2556 verbosity, repo);
2557 if (error)
2558 goto done;
2561 if (!remote->mirror_references) {
2562 /* Update remote HEAD reference if the server provided one. */
2563 TAILQ_FOREACH(pe, &symrefs, entry) {
2564 struct got_reference *target_ref;
2565 const char *refname = pe->path;
2566 const char *target = pe->data;
2567 char *remote_refname = NULL, *remote_target = NULL;
2569 if (strcmp(refname, GOT_REF_HEAD) != 0)
2570 continue;
2572 if (strncmp("refs/heads/", target, 11) != 0)
2573 continue;
2575 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2576 remote->name, refname) == -1) {
2577 error = got_error_from_errno("asprintf");
2578 goto done;
2580 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2581 remote->name, target + 11) == -1) {
2582 error = got_error_from_errno("asprintf");
2583 free(remote_refname);
2584 goto done;
2587 error = got_ref_open(&target_ref, repo, remote_target,
2588 0);
2589 if (error) {
2590 free(remote_refname);
2591 free(remote_target);
2592 if (error->code == GOT_ERR_NOT_REF) {
2593 error = NULL;
2594 continue;
2596 goto done;
2598 error = update_symref(remote_refname, target_ref,
2599 verbosity, repo);
2600 free(remote_refname);
2601 free(remote_target);
2602 got_ref_close(target_ref);
2603 if (error)
2604 goto done;
2607 done:
2608 if (fetchpid > 0) {
2609 if (kill(fetchpid, SIGTERM) == -1)
2610 error = got_error_from_errno("kill");
2611 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2612 error = got_error_from_errno("waitpid");
2614 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2615 error = got_error_from_errno("close");
2616 if (repo) {
2617 const struct got_error *close_err = got_repo_close(repo);
2618 if (error == NULL)
2619 error = close_err;
2621 if (worktree)
2622 got_worktree_close(worktree);
2623 TAILQ_FOREACH(pe, &refs, entry) {
2624 free((void *)pe->path);
2625 free(pe->data);
2627 got_pathlist_free(&refs);
2628 TAILQ_FOREACH(pe, &symrefs, entry) {
2629 free((void *)pe->path);
2630 free(pe->data);
2632 got_pathlist_free(&symrefs);
2633 got_pathlist_free(&wanted_branches);
2634 got_pathlist_free(&wanted_refs);
2635 free(id_str);
2636 free(cwd);
2637 free(repo_path);
2638 free(pack_hash);
2639 free(proto);
2640 free(host);
2641 free(port);
2642 free(server_path);
2643 free(repo_name);
2644 return error;
2648 __dead static void
2649 usage_checkout(void)
2651 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2652 "[-p prefix] [-q] repository-path [worktree-path]\n",
2653 getprogname());
2654 exit(1);
2657 static void
2658 show_worktree_base_ref_warning(void)
2660 fprintf(stderr, "%s: warning: could not create a reference "
2661 "to the work tree's base commit; the commit could be "
2662 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2663 "repository writable and running 'got update' will prevent this\n",
2664 getprogname());
2667 struct got_checkout_progress_arg {
2668 const char *worktree_path;
2669 int had_base_commit_ref_error;
2670 int verbosity;
2673 static const struct got_error *
2674 checkout_progress(void *arg, unsigned char status, const char *path)
2676 struct got_checkout_progress_arg *a = arg;
2678 /* Base commit bump happens silently. */
2679 if (status == GOT_STATUS_BUMP_BASE)
2680 return NULL;
2682 if (status == GOT_STATUS_BASE_REF_ERR) {
2683 a->had_base_commit_ref_error = 1;
2684 return NULL;
2687 while (path[0] == '/')
2688 path++;
2690 if (a->verbosity >= 0)
2691 printf("%c %s/%s\n", status, a->worktree_path, path);
2693 return NULL;
2696 static const struct got_error *
2697 check_cancelled(void *arg)
2699 if (sigint_received || sigpipe_received)
2700 return got_error(GOT_ERR_CANCELLED);
2701 return NULL;
2704 static const struct got_error *
2705 check_linear_ancestry(struct got_object_id *commit_id,
2706 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2707 struct got_repository *repo)
2709 const struct got_error *err = NULL;
2710 struct got_object_id *yca_id;
2712 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2713 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2714 if (err)
2715 return err;
2717 if (yca_id == NULL)
2718 return got_error(GOT_ERR_ANCESTRY);
2721 * Require a straight line of history between the target commit
2722 * and the work tree's base commit.
2724 * Non-linear situations such as this require a rebase:
2726 * (commit) D F (base_commit)
2727 * \ /
2728 * C E
2729 * \ /
2730 * B (yca)
2731 * |
2732 * A
2734 * 'got update' only handles linear cases:
2735 * Update forwards in time: A (base/yca) - B - C - D (commit)
2736 * Update backwards in time: D (base) - C - B - A (commit/yca)
2738 if (allow_forwards_in_time_only) {
2739 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2740 return got_error(GOT_ERR_ANCESTRY);
2741 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2742 got_object_id_cmp(base_commit_id, yca_id) != 0)
2743 return got_error(GOT_ERR_ANCESTRY);
2745 free(yca_id);
2746 return NULL;
2749 static const struct got_error *
2750 check_same_branch(struct got_object_id *commit_id,
2751 struct got_reference *head_ref, struct got_object_id *yca_id,
2752 struct got_repository *repo)
2754 const struct got_error *err = NULL;
2755 struct got_commit_graph *graph = NULL;
2756 struct got_object_id *head_commit_id = NULL;
2757 int is_same_branch = 0;
2759 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2760 if (err)
2761 goto done;
2763 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2764 is_same_branch = 1;
2765 goto done;
2767 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2768 is_same_branch = 1;
2769 goto done;
2772 err = got_commit_graph_open(&graph, "/", 1);
2773 if (err)
2774 goto done;
2776 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2777 check_cancelled, NULL);
2778 if (err)
2779 goto done;
2781 for (;;) {
2782 struct got_object_id *id;
2783 err = got_commit_graph_iter_next(&id, graph, repo,
2784 check_cancelled, NULL);
2785 if (err) {
2786 if (err->code == GOT_ERR_ITER_COMPLETED)
2787 err = NULL;
2788 break;
2791 if (id) {
2792 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2793 break;
2794 if (got_object_id_cmp(id, commit_id) == 0) {
2795 is_same_branch = 1;
2796 break;
2800 done:
2801 if (graph)
2802 got_commit_graph_close(graph);
2803 free(head_commit_id);
2804 if (!err && !is_same_branch)
2805 err = got_error(GOT_ERR_ANCESTRY);
2806 return err;
2809 static const struct got_error *
2810 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2812 static char msg[512];
2813 const char *branch_name;
2815 if (got_ref_is_symbolic(ref))
2816 branch_name = got_ref_get_symref_target(ref);
2817 else
2818 branch_name = got_ref_get_name(ref);
2820 if (strncmp("refs/heads/", branch_name, 11) == 0)
2821 branch_name += 11;
2823 snprintf(msg, sizeof(msg),
2824 "target commit is not contained in branch '%s'; "
2825 "the branch to use must be specified with -b; "
2826 "if necessary a new branch can be created for "
2827 "this commit with 'got branch -c %s BRANCH_NAME'",
2828 branch_name, commit_id_str);
2830 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2833 static const struct got_error *
2834 cmd_checkout(int argc, char *argv[])
2836 const struct got_error *error = NULL;
2837 struct got_repository *repo = NULL;
2838 struct got_reference *head_ref = NULL, *ref = NULL;
2839 struct got_worktree *worktree = NULL;
2840 char *repo_path = NULL;
2841 char *worktree_path = NULL;
2842 const char *path_prefix = "";
2843 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2844 char *commit_id_str = NULL;
2845 struct got_object_id *commit_id = NULL;
2846 char *cwd = NULL;
2847 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2848 struct got_pathlist_head paths;
2849 struct got_checkout_progress_arg cpa;
2851 TAILQ_INIT(&paths);
2853 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2854 switch (ch) {
2855 case 'b':
2856 branch_name = optarg;
2857 break;
2858 case 'c':
2859 commit_id_str = strdup(optarg);
2860 if (commit_id_str == NULL)
2861 return got_error_from_errno("strdup");
2862 break;
2863 case 'E':
2864 allow_nonempty = 1;
2865 break;
2866 case 'p':
2867 path_prefix = optarg;
2868 break;
2869 case 'q':
2870 verbosity = -1;
2871 break;
2872 default:
2873 usage_checkout();
2874 /* NOTREACHED */
2878 argc -= optind;
2879 argv += optind;
2881 #ifndef PROFILE
2882 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2883 "unveil", NULL) == -1)
2884 err(1, "pledge");
2885 #endif
2886 if (argc == 1) {
2887 char *base, *dotgit;
2888 const char *path;
2889 repo_path = realpath(argv[0], NULL);
2890 if (repo_path == NULL)
2891 return got_error_from_errno2("realpath", argv[0]);
2892 cwd = getcwd(NULL, 0);
2893 if (cwd == NULL) {
2894 error = got_error_from_errno("getcwd");
2895 goto done;
2897 if (path_prefix[0])
2898 path = path_prefix;
2899 else
2900 path = repo_path;
2901 error = got_path_basename(&base, path);
2902 if (error)
2903 goto done;
2904 dotgit = strstr(base, ".git");
2905 if (dotgit)
2906 *dotgit = '\0';
2907 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2908 error = got_error_from_errno("asprintf");
2909 free(base);
2910 goto done;
2912 free(base);
2913 } else if (argc == 2) {
2914 repo_path = realpath(argv[0], NULL);
2915 if (repo_path == NULL) {
2916 error = got_error_from_errno2("realpath", argv[0]);
2917 goto done;
2919 worktree_path = realpath(argv[1], NULL);
2920 if (worktree_path == NULL) {
2921 if (errno != ENOENT) {
2922 error = got_error_from_errno2("realpath",
2923 argv[1]);
2924 goto done;
2926 worktree_path = strdup(argv[1]);
2927 if (worktree_path == NULL) {
2928 error = got_error_from_errno("strdup");
2929 goto done;
2932 } else
2933 usage_checkout();
2935 got_path_strip_trailing_slashes(repo_path);
2936 got_path_strip_trailing_slashes(worktree_path);
2938 error = got_repo_open(&repo, repo_path, NULL);
2939 if (error != NULL)
2940 goto done;
2942 /* Pre-create work tree path for unveil(2) */
2943 error = got_path_mkdir(worktree_path);
2944 if (error) {
2945 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2946 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2947 goto done;
2948 if (!allow_nonempty &&
2949 !got_path_dir_is_empty(worktree_path)) {
2950 error = got_error_path(worktree_path,
2951 GOT_ERR_DIR_NOT_EMPTY);
2952 goto done;
2956 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2957 if (error)
2958 goto done;
2960 error = got_ref_open(&head_ref, repo, branch_name, 0);
2961 if (error != NULL)
2962 goto done;
2964 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2965 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2966 goto done;
2968 error = got_worktree_open(&worktree, worktree_path);
2969 if (error != NULL)
2970 goto done;
2972 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2973 path_prefix);
2974 if (error != NULL)
2975 goto done;
2976 if (!same_path_prefix) {
2977 error = got_error(GOT_ERR_PATH_PREFIX);
2978 goto done;
2981 if (commit_id_str) {
2982 struct got_reflist_head refs;
2983 TAILQ_INIT(&refs);
2984 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2985 NULL);
2986 if (error)
2987 goto done;
2988 error = got_repo_match_object_id(&commit_id, NULL,
2989 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2990 got_ref_list_free(&refs);
2991 if (error)
2992 goto done;
2993 error = check_linear_ancestry(commit_id,
2994 got_worktree_get_base_commit_id(worktree), 0, repo);
2995 if (error != NULL) {
2996 if (error->code == GOT_ERR_ANCESTRY) {
2997 error = checkout_ancestry_error(
2998 head_ref, commit_id_str);
3000 goto done;
3002 error = check_same_branch(commit_id, head_ref, NULL, repo);
3003 if (error) {
3004 if (error->code == GOT_ERR_ANCESTRY) {
3005 error = checkout_ancestry_error(
3006 head_ref, commit_id_str);
3008 goto done;
3010 error = got_worktree_set_base_commit_id(worktree, repo,
3011 commit_id);
3012 if (error)
3013 goto done;
3014 /* Expand potentially abbreviated commit ID string. */
3015 free(commit_id_str);
3016 error = got_object_id_str(&commit_id_str, commit_id);
3017 if (error)
3018 goto done;
3019 } else {
3020 commit_id = got_object_id_dup(
3021 got_worktree_get_base_commit_id(worktree));
3022 if (commit_id == NULL) {
3023 error = got_error_from_errno("got_object_id_dup");
3024 goto done;
3026 error = got_object_id_str(&commit_id_str, commit_id);
3027 if (error)
3028 goto done;
3031 error = got_pathlist_append(&paths, "", NULL);
3032 if (error)
3033 goto done;
3034 cpa.worktree_path = worktree_path;
3035 cpa.had_base_commit_ref_error = 0;
3036 cpa.verbosity = verbosity;
3037 error = got_worktree_checkout_files(worktree, &paths, repo,
3038 checkout_progress, &cpa, check_cancelled, NULL);
3039 if (error != NULL)
3040 goto done;
3042 if (got_ref_is_symbolic(head_ref)) {
3043 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3044 if (error)
3045 goto done;
3046 refname = got_ref_get_name(ref);
3047 } else
3048 refname = got_ref_get_name(head_ref);
3049 printf("Checked out %s: %s\n", refname, commit_id_str);
3050 printf("Now shut up and hack\n");
3051 if (cpa.had_base_commit_ref_error)
3052 show_worktree_base_ref_warning();
3053 done:
3054 if (head_ref)
3055 got_ref_close(head_ref);
3056 if (ref)
3057 got_ref_close(ref);
3058 got_pathlist_free(&paths);
3059 free(commit_id_str);
3060 free(commit_id);
3061 free(repo_path);
3062 free(worktree_path);
3063 free(cwd);
3064 return error;
3067 struct got_update_progress_arg {
3068 int did_something;
3069 int conflicts;
3070 int obstructed;
3071 int not_updated;
3072 int missing;
3073 int not_deleted;
3074 int unversioned;
3075 int verbosity;
3078 void
3079 print_update_progress_stats(struct got_update_progress_arg *upa)
3081 if (!upa->did_something)
3082 return;
3084 if (upa->conflicts > 0)
3085 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3086 if (upa->obstructed > 0)
3087 printf("File paths obstructed by a non-regular file: %d\n",
3088 upa->obstructed);
3089 if (upa->not_updated > 0)
3090 printf("Files not updated because of existing merge "
3091 "conflicts: %d\n", upa->not_updated);
3095 * The meaning of some status codes differs between merge-style operations and
3096 * update operations. For example, the ! status code means "file was missing"
3097 * if changes were merged into the work tree, and "missing file was restored"
3098 * if the work tree was updated. This function should be used by any operation
3099 * which merges changes into the work tree without updating the work tree.
3101 void
3102 print_merge_progress_stats(struct got_update_progress_arg *upa)
3104 if (!upa->did_something)
3105 return;
3107 if (upa->conflicts > 0)
3108 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3109 if (upa->obstructed > 0)
3110 printf("File paths obstructed by a non-regular file: %d\n",
3111 upa->obstructed);
3112 if (upa->missing > 0)
3113 printf("Files which had incoming changes but could not be "
3114 "found in the work tree: %d\n", upa->missing);
3115 if (upa->not_deleted > 0)
3116 printf("Files not deleted due to differences in deleted "
3117 "content: %d\n", upa->not_deleted);
3118 if (upa->unversioned > 0)
3119 printf("Files not merged because an unversioned file was "
3120 "found in the work tree: %d\n", upa->unversioned);
3123 __dead static void
3124 usage_update(void)
3126 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3127 "[path ...]\n",
3128 getprogname());
3129 exit(1);
3132 static const struct got_error *
3133 update_progress(void *arg, unsigned char status, const char *path)
3135 struct got_update_progress_arg *upa = arg;
3137 if (status == GOT_STATUS_EXISTS ||
3138 status == GOT_STATUS_BASE_REF_ERR)
3139 return NULL;
3141 upa->did_something = 1;
3143 /* Base commit bump happens silently. */
3144 if (status == GOT_STATUS_BUMP_BASE)
3145 return NULL;
3147 if (status == GOT_STATUS_CONFLICT)
3148 upa->conflicts++;
3149 if (status == GOT_STATUS_OBSTRUCTED)
3150 upa->obstructed++;
3151 if (status == GOT_STATUS_CANNOT_UPDATE)
3152 upa->not_updated++;
3153 if (status == GOT_STATUS_MISSING)
3154 upa->missing++;
3155 if (status == GOT_STATUS_CANNOT_DELETE)
3156 upa->not_deleted++;
3157 if (status == GOT_STATUS_UNVERSIONED)
3158 upa->unversioned++;
3160 while (path[0] == '/')
3161 path++;
3162 if (upa->verbosity >= 0)
3163 printf("%c %s\n", status, path);
3165 return NULL;
3168 static const struct got_error *
3169 switch_head_ref(struct got_reference *head_ref,
3170 struct got_object_id *commit_id, struct got_worktree *worktree,
3171 struct got_repository *repo)
3173 const struct got_error *err = NULL;
3174 char *base_id_str;
3175 int ref_has_moved = 0;
3177 /* Trivial case: switching between two different references. */
3178 if (strcmp(got_ref_get_name(head_ref),
3179 got_worktree_get_head_ref_name(worktree)) != 0) {
3180 printf("Switching work tree from %s to %s\n",
3181 got_worktree_get_head_ref_name(worktree),
3182 got_ref_get_name(head_ref));
3183 return got_worktree_set_head_ref(worktree, head_ref);
3186 err = check_linear_ancestry(commit_id,
3187 got_worktree_get_base_commit_id(worktree), 0, repo);
3188 if (err) {
3189 if (err->code != GOT_ERR_ANCESTRY)
3190 return err;
3191 ref_has_moved = 1;
3193 if (!ref_has_moved)
3194 return NULL;
3196 /* Switching to a rebased branch with the same reference name. */
3197 err = got_object_id_str(&base_id_str,
3198 got_worktree_get_base_commit_id(worktree));
3199 if (err)
3200 return err;
3201 printf("Reference %s now points at a different branch\n",
3202 got_worktree_get_head_ref_name(worktree));
3203 printf("Switching work tree from %s to %s\n", base_id_str,
3204 got_worktree_get_head_ref_name(worktree));
3205 return NULL;
3208 static const struct got_error *
3209 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3211 const struct got_error *err;
3212 int in_progress;
3214 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3215 if (err)
3216 return err;
3217 if (in_progress)
3218 return got_error(GOT_ERR_REBASING);
3220 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3221 if (err)
3222 return err;
3223 if (in_progress)
3224 return got_error(GOT_ERR_HISTEDIT_BUSY);
3226 return NULL;
3229 static const struct got_error *
3230 check_merge_in_progress(struct got_worktree *worktree,
3231 struct got_repository *repo)
3233 const struct got_error *err;
3234 int in_progress;
3236 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3237 if (err)
3238 return err;
3239 if (in_progress)
3240 return got_error(GOT_ERR_MERGE_BUSY);
3242 return NULL;
3245 static const struct got_error *
3246 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3247 char *argv[], struct got_worktree *worktree)
3249 const struct got_error *err = NULL;
3250 char *path;
3251 struct got_pathlist_entry *new;
3252 int i;
3254 if (argc == 0) {
3255 path = strdup("");
3256 if (path == NULL)
3257 return got_error_from_errno("strdup");
3258 return got_pathlist_append(paths, path, NULL);
3261 for (i = 0; i < argc; i++) {
3262 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3263 if (err)
3264 break;
3265 err = got_pathlist_insert(&new, paths, path, NULL);
3266 if (err || new == NULL /* duplicate */) {
3267 free(path);
3268 if (err)
3269 break;
3273 return err;
3276 static const struct got_error *
3277 wrap_not_worktree_error(const struct got_error *orig_err,
3278 const char *cmdname, const char *path)
3280 const struct got_error *err;
3281 struct got_repository *repo;
3282 static char msg[512];
3284 err = got_repo_open(&repo, path, NULL);
3285 if (err)
3286 return orig_err;
3288 snprintf(msg, sizeof(msg),
3289 "'got %s' needs a work tree in addition to a git repository\n"
3290 "Work trees can be checked out from this Git repository with "
3291 "'got checkout'.\n"
3292 "The got(1) manual page contains more information.", cmdname);
3293 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3294 got_repo_close(repo);
3295 return err;
3298 static const struct got_error *
3299 cmd_update(int argc, char *argv[])
3301 const struct got_error *error = NULL;
3302 struct got_repository *repo = NULL;
3303 struct got_worktree *worktree = NULL;
3304 char *worktree_path = NULL;
3305 struct got_object_id *commit_id = NULL;
3306 char *commit_id_str = NULL;
3307 const char *branch_name = NULL;
3308 struct got_reference *head_ref = NULL;
3309 struct got_pathlist_head paths;
3310 struct got_pathlist_entry *pe;
3311 int ch, verbosity = 0;
3312 struct got_update_progress_arg upa;
3314 TAILQ_INIT(&paths);
3316 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3317 switch (ch) {
3318 case 'b':
3319 branch_name = optarg;
3320 break;
3321 case 'c':
3322 commit_id_str = strdup(optarg);
3323 if (commit_id_str == NULL)
3324 return got_error_from_errno("strdup");
3325 break;
3326 case 'q':
3327 verbosity = -1;
3328 break;
3329 default:
3330 usage_update();
3331 /* NOTREACHED */
3335 argc -= optind;
3336 argv += optind;
3338 #ifndef PROFILE
3339 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3340 "unveil", NULL) == -1)
3341 err(1, "pledge");
3342 #endif
3343 worktree_path = getcwd(NULL, 0);
3344 if (worktree_path == NULL) {
3345 error = got_error_from_errno("getcwd");
3346 goto done;
3348 error = got_worktree_open(&worktree, worktree_path);
3349 if (error) {
3350 if (error->code == GOT_ERR_NOT_WORKTREE)
3351 error = wrap_not_worktree_error(error, "update",
3352 worktree_path);
3353 goto done;
3356 error = check_rebase_or_histedit_in_progress(worktree);
3357 if (error)
3358 goto done;
3360 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3361 NULL);
3362 if (error != NULL)
3363 goto done;
3365 error = apply_unveil(got_repo_get_path(repo), 0,
3366 got_worktree_get_root_path(worktree));
3367 if (error)
3368 goto done;
3370 error = check_merge_in_progress(worktree, repo);
3371 if (error)
3372 goto done;
3374 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3375 if (error)
3376 goto done;
3378 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3379 got_worktree_get_head_ref_name(worktree), 0);
3380 if (error != NULL)
3381 goto done;
3382 if (commit_id_str == NULL) {
3383 error = got_ref_resolve(&commit_id, repo, head_ref);
3384 if (error != NULL)
3385 goto done;
3386 error = got_object_id_str(&commit_id_str, commit_id);
3387 if (error != NULL)
3388 goto done;
3389 } else {
3390 struct got_reflist_head refs;
3391 TAILQ_INIT(&refs);
3392 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3393 NULL);
3394 if (error)
3395 goto done;
3396 error = got_repo_match_object_id(&commit_id, NULL,
3397 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3398 got_ref_list_free(&refs);
3399 free(commit_id_str);
3400 commit_id_str = NULL;
3401 if (error)
3402 goto done;
3403 error = got_object_id_str(&commit_id_str, commit_id);
3404 if (error)
3405 goto done;
3408 if (branch_name) {
3409 struct got_object_id *head_commit_id;
3410 TAILQ_FOREACH(pe, &paths, entry) {
3411 if (pe->path_len == 0)
3412 continue;
3413 error = got_error_msg(GOT_ERR_BAD_PATH,
3414 "switching between branches requires that "
3415 "the entire work tree gets updated");
3416 goto done;
3418 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3419 if (error)
3420 goto done;
3421 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3422 repo);
3423 free(head_commit_id);
3424 if (error != NULL)
3425 goto done;
3426 error = check_same_branch(commit_id, head_ref, NULL, repo);
3427 if (error)
3428 goto done;
3429 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3430 if (error)
3431 goto done;
3432 } else {
3433 error = check_linear_ancestry(commit_id,
3434 got_worktree_get_base_commit_id(worktree), 0, repo);
3435 if (error != NULL) {
3436 if (error->code == GOT_ERR_ANCESTRY)
3437 error = got_error(GOT_ERR_BRANCH_MOVED);
3438 goto done;
3440 error = check_same_branch(commit_id, head_ref, NULL, repo);
3441 if (error)
3442 goto done;
3445 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3446 commit_id) != 0) {
3447 error = got_worktree_set_base_commit_id(worktree, repo,
3448 commit_id);
3449 if (error)
3450 goto done;
3453 memset(&upa, 0, sizeof(upa));
3454 upa.verbosity = verbosity;
3455 error = got_worktree_checkout_files(worktree, &paths, repo,
3456 update_progress, &upa, check_cancelled, NULL);
3457 if (error != NULL)
3458 goto done;
3460 if (upa.did_something) {
3461 printf("Updated to %s: %s\n",
3462 got_worktree_get_head_ref_name(worktree), commit_id_str);
3463 } else
3464 printf("Already up-to-date\n");
3465 print_update_progress_stats(&upa);
3466 done:
3467 free(worktree_path);
3468 TAILQ_FOREACH(pe, &paths, entry)
3469 free((char *)pe->path);
3470 got_pathlist_free(&paths);
3471 free(commit_id);
3472 free(commit_id_str);
3473 return error;
3476 static const struct got_error *
3477 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3478 const char *path, int diff_context, int ignore_whitespace,
3479 int force_text_diff, struct got_repository *repo)
3481 const struct got_error *err = NULL;
3482 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3483 FILE *f1 = NULL, *f2 = NULL;
3485 if (blob_id1) {
3486 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3487 if (err)
3488 goto done;
3489 f1 = got_opentemp();
3490 if (f1 == NULL) {
3491 err = got_error_from_errno("got_opentemp");
3492 goto done;
3496 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3497 if (err)
3498 goto done;
3500 f2 = got_opentemp();
3501 if (f2 == NULL) {
3502 err = got_error_from_errno("got_opentemp");
3503 goto done;
3506 while (path[0] == '/')
3507 path++;
3508 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3509 diff_context, ignore_whitespace, force_text_diff, stdout);
3510 done:
3511 if (blob1)
3512 got_object_blob_close(blob1);
3513 got_object_blob_close(blob2);
3514 if (f1 && fclose(f1) == EOF && err == NULL)
3515 err = got_error_from_errno("fclose");
3516 if (f2 && fclose(f2) == EOF && err == NULL)
3517 err = got_error_from_errno("fclose");
3518 return err;
3521 static const struct got_error *
3522 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3523 const char *path, int diff_context, int ignore_whitespace,
3524 int force_text_diff, struct got_repository *repo)
3526 const struct got_error *err = NULL;
3527 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3528 struct got_diff_blob_output_unidiff_arg arg;
3529 FILE *f1 = NULL, *f2 = NULL;
3531 if (tree_id1) {
3532 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3533 if (err)
3534 goto done;
3535 f1 = got_opentemp();
3536 if (f1 == NULL) {
3537 err = got_error_from_errno("got_opentemp");
3538 goto done;
3542 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3543 if (err)
3544 goto done;
3546 f2 = got_opentemp();
3547 if (f2 == NULL) {
3548 err = got_error_from_errno("got_opentemp");
3549 goto done;
3552 arg.diff_context = diff_context;
3553 arg.ignore_whitespace = ignore_whitespace;
3554 arg.force_text_diff = force_text_diff;
3555 arg.outfile = stdout;
3556 arg.line_offsets = NULL;
3557 arg.nlines = 0;
3558 while (path[0] == '/')
3559 path++;
3560 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3561 got_diff_blob_output_unidiff, &arg, 1);
3562 done:
3563 if (tree1)
3564 got_object_tree_close(tree1);
3565 if (tree2)
3566 got_object_tree_close(tree2);
3567 if (f1 && fclose(f1) == EOF && err == NULL)
3568 err = got_error_from_errno("fclose");
3569 if (f2 && fclose(f2) == EOF && err == NULL)
3570 err = got_error_from_errno("fclose");
3571 return err;
3574 static const struct got_error *
3575 get_changed_paths(struct got_pathlist_head *paths,
3576 struct got_commit_object *commit, struct got_repository *repo)
3578 const struct got_error *err = NULL;
3579 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3580 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3581 struct got_object_qid *qid;
3583 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3584 if (qid != NULL) {
3585 struct got_commit_object *pcommit;
3586 err = got_object_open_as_commit(&pcommit, repo,
3587 &qid->id);
3588 if (err)
3589 return err;
3591 tree_id1 = got_object_id_dup(
3592 got_object_commit_get_tree_id(pcommit));
3593 if (tree_id1 == NULL) {
3594 got_object_commit_close(pcommit);
3595 return got_error_from_errno("got_object_id_dup");
3597 got_object_commit_close(pcommit);
3601 if (tree_id1) {
3602 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3603 if (err)
3604 goto done;
3607 tree_id2 = got_object_commit_get_tree_id(commit);
3608 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3609 if (err)
3610 goto done;
3612 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3613 got_diff_tree_collect_changed_paths, paths, 0);
3614 done:
3615 if (tree1)
3616 got_object_tree_close(tree1);
3617 if (tree2)
3618 got_object_tree_close(tree2);
3619 free(tree_id1);
3620 return err;
3623 static const struct got_error *
3624 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3625 const char *path, int diff_context, struct got_repository *repo)
3627 const struct got_error *err = NULL;
3628 struct got_commit_object *pcommit = NULL;
3629 char *id_str1 = NULL, *id_str2 = NULL;
3630 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3631 struct got_object_qid *qid;
3633 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3634 if (qid != NULL) {
3635 err = got_object_open_as_commit(&pcommit, repo,
3636 &qid->id);
3637 if (err)
3638 return err;
3641 if (path && path[0] != '\0') {
3642 int obj_type;
3643 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3644 if (err)
3645 goto done;
3646 err = got_object_id_str(&id_str2, obj_id2);
3647 if (err) {
3648 free(obj_id2);
3649 goto done;
3651 if (pcommit) {
3652 err = got_object_id_by_path(&obj_id1, repo,
3653 pcommit, path);
3654 if (err) {
3655 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3656 free(obj_id2);
3657 goto done;
3659 } else {
3660 err = got_object_id_str(&id_str1, obj_id1);
3661 if (err) {
3662 free(obj_id2);
3663 goto done;
3667 err = got_object_get_type(&obj_type, repo, obj_id2);
3668 if (err) {
3669 free(obj_id2);
3670 goto done;
3672 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3673 switch (obj_type) {
3674 case GOT_OBJ_TYPE_BLOB:
3675 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3676 0, 0, repo);
3677 break;
3678 case GOT_OBJ_TYPE_TREE:
3679 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3680 0, 0, repo);
3681 break;
3682 default:
3683 err = got_error(GOT_ERR_OBJ_TYPE);
3684 break;
3686 free(obj_id1);
3687 free(obj_id2);
3688 } else {
3689 obj_id2 = got_object_commit_get_tree_id(commit);
3690 err = got_object_id_str(&id_str2, obj_id2);
3691 if (err)
3692 goto done;
3693 if (pcommit) {
3694 obj_id1 = got_object_commit_get_tree_id(pcommit);
3695 err = got_object_id_str(&id_str1, obj_id1);
3696 if (err)
3697 goto done;
3699 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3700 id_str2);
3701 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3702 repo);
3704 done:
3705 free(id_str1);
3706 free(id_str2);
3707 if (pcommit)
3708 got_object_commit_close(pcommit);
3709 return err;
3712 static char *
3713 get_datestr(time_t *time, char *datebuf)
3715 struct tm mytm, *tm;
3716 char *p, *s;
3718 tm = gmtime_r(time, &mytm);
3719 if (tm == NULL)
3720 return NULL;
3721 s = asctime_r(tm, datebuf);
3722 if (s == NULL)
3723 return NULL;
3724 p = strchr(s, '\n');
3725 if (p)
3726 *p = '\0';
3727 return s;
3730 static const struct got_error *
3731 match_logmsg(int *have_match, struct got_object_id *id,
3732 struct got_commit_object *commit, regex_t *regex)
3734 const struct got_error *err = NULL;
3735 regmatch_t regmatch;
3736 char *id_str = NULL, *logmsg = NULL;
3738 *have_match = 0;
3740 err = got_object_id_str(&id_str, id);
3741 if (err)
3742 return err;
3744 err = got_object_commit_get_logmsg(&logmsg, commit);
3745 if (err)
3746 goto done;
3748 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3749 *have_match = 1;
3750 done:
3751 free(id_str);
3752 free(logmsg);
3753 return err;
3756 static void
3757 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3758 regex_t *regex)
3760 regmatch_t regmatch;
3761 struct got_pathlist_entry *pe;
3763 *have_match = 0;
3765 TAILQ_FOREACH(pe, changed_paths, entry) {
3766 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3767 *have_match = 1;
3768 break;
3773 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3775 static const struct got_error*
3776 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3777 struct got_object_id *id, struct got_repository *repo)
3779 static const struct got_error *err = NULL;
3780 struct got_reflist_entry *re;
3781 char *s;
3782 const char *name;
3784 *refs_str = NULL;
3786 TAILQ_FOREACH(re, refs, entry) {
3787 struct got_tag_object *tag = NULL;
3788 struct got_object_id *ref_id;
3789 int cmp;
3791 name = got_ref_get_name(re->ref);
3792 if (strcmp(name, GOT_REF_HEAD) == 0)
3793 continue;
3794 if (strncmp(name, "refs/", 5) == 0)
3795 name += 5;
3796 if (strncmp(name, "got/", 4) == 0)
3797 continue;
3798 if (strncmp(name, "heads/", 6) == 0)
3799 name += 6;
3800 if (strncmp(name, "remotes/", 8) == 0) {
3801 name += 8;
3802 s = strstr(name, "/" GOT_REF_HEAD);
3803 if (s != NULL && s[strlen(s)] == '\0')
3804 continue;
3806 err = got_ref_resolve(&ref_id, repo, re->ref);
3807 if (err)
3808 break;
3809 if (strncmp(name, "tags/", 5) == 0) {
3810 err = got_object_open_as_tag(&tag, repo, ref_id);
3811 if (err) {
3812 if (err->code != GOT_ERR_OBJ_TYPE) {
3813 free(ref_id);
3814 break;
3816 /* Ref points at something other than a tag. */
3817 err = NULL;
3818 tag = NULL;
3821 cmp = got_object_id_cmp(tag ?
3822 got_object_tag_get_object_id(tag) : ref_id, id);
3823 free(ref_id);
3824 if (tag)
3825 got_object_tag_close(tag);
3826 if (cmp != 0)
3827 continue;
3828 s = *refs_str;
3829 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3830 s ? ", " : "", name) == -1) {
3831 err = got_error_from_errno("asprintf");
3832 free(s);
3833 *refs_str = NULL;
3834 break;
3836 free(s);
3839 return err;
3842 static const struct got_error *
3843 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3844 struct got_repository *repo, const char *path,
3845 struct got_pathlist_head *changed_paths, int show_patch,
3846 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3847 const char *custom_refs_str)
3849 const struct got_error *err = NULL;
3850 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3851 char datebuf[26];
3852 time_t committer_time;
3853 const char *author, *committer;
3854 char *refs_str = NULL;
3856 err = got_object_id_str(&id_str, id);
3857 if (err)
3858 return err;
3860 if (custom_refs_str == NULL) {
3861 struct got_reflist_head *refs;
3862 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3863 if (refs) {
3864 err = build_refs_str(&refs_str, refs, id, repo);
3865 if (err)
3866 goto done;
3870 printf(GOT_COMMIT_SEP_STR);
3871 if (custom_refs_str)
3872 printf("commit %s (%s)\n", id_str, custom_refs_str);
3873 else
3874 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3875 refs_str ? refs_str : "", refs_str ? ")" : "");
3876 free(id_str);
3877 id_str = NULL;
3878 free(refs_str);
3879 refs_str = NULL;
3880 printf("from: %s\n", got_object_commit_get_author(commit));
3881 committer_time = got_object_commit_get_committer_time(commit);
3882 datestr = get_datestr(&committer_time, datebuf);
3883 if (datestr)
3884 printf("date: %s UTC\n", datestr);
3885 author = got_object_commit_get_author(commit);
3886 committer = got_object_commit_get_committer(commit);
3887 if (strcmp(author, committer) != 0)
3888 printf("via: %s\n", committer);
3889 if (got_object_commit_get_nparents(commit) > 1) {
3890 const struct got_object_id_queue *parent_ids;
3891 struct got_object_qid *qid;
3892 int n = 1;
3893 parent_ids = got_object_commit_get_parent_ids(commit);
3894 STAILQ_FOREACH(qid, parent_ids, entry) {
3895 err = got_object_id_str(&id_str, &qid->id);
3896 if (err)
3897 goto done;
3898 printf("parent %d: %s\n", n++, id_str);
3899 free(id_str);
3900 id_str = NULL;
3904 err = got_object_commit_get_logmsg(&logmsg0, commit);
3905 if (err)
3906 goto done;
3908 logmsg = logmsg0;
3909 do {
3910 line = strsep(&logmsg, "\n");
3911 if (line)
3912 printf(" %s\n", line);
3913 } while (line);
3914 free(logmsg0);
3916 if (changed_paths) {
3917 struct got_pathlist_entry *pe;
3918 TAILQ_FOREACH(pe, changed_paths, entry) {
3919 struct got_diff_changed_path *cp = pe->data;
3920 printf(" %c %s\n", cp->status, pe->path);
3922 printf("\n");
3924 if (show_patch) {
3925 err = print_patch(commit, id, path, diff_context, repo);
3926 if (err == 0)
3927 printf("\n");
3930 if (fflush(stdout) != 0 && err == NULL)
3931 err = got_error_from_errno("fflush");
3932 done:
3933 free(id_str);
3934 free(refs_str);
3935 return err;
3938 static const struct got_error *
3939 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3940 struct got_repository *repo, const char *path, int show_changed_paths,
3941 int show_patch, const char *search_pattern, int diff_context, int limit,
3942 int log_branches, int reverse_display_order,
3943 struct got_reflist_object_id_map *refs_idmap)
3945 const struct got_error *err;
3946 struct got_commit_graph *graph;
3947 regex_t regex;
3948 int have_match;
3949 struct got_object_id_queue reversed_commits;
3950 struct got_object_qid *qid;
3951 struct got_commit_object *commit;
3952 struct got_pathlist_head changed_paths;
3953 struct got_pathlist_entry *pe;
3955 STAILQ_INIT(&reversed_commits);
3956 TAILQ_INIT(&changed_paths);
3958 if (search_pattern && regcomp(&regex, search_pattern,
3959 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3960 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3962 err = got_commit_graph_open(&graph, path, !log_branches);
3963 if (err)
3964 return err;
3965 err = got_commit_graph_iter_start(graph, root_id, repo,
3966 check_cancelled, NULL);
3967 if (err)
3968 goto done;
3969 for (;;) {
3970 struct got_object_id *id;
3972 if (sigint_received || sigpipe_received)
3973 break;
3975 err = got_commit_graph_iter_next(&id, graph, repo,
3976 check_cancelled, NULL);
3977 if (err) {
3978 if (err->code == GOT_ERR_ITER_COMPLETED)
3979 err = NULL;
3980 break;
3982 if (id == NULL)
3983 break;
3985 err = got_object_open_as_commit(&commit, repo, id);
3986 if (err)
3987 break;
3989 if (show_changed_paths && !reverse_display_order) {
3990 err = get_changed_paths(&changed_paths, commit, repo);
3991 if (err)
3992 break;
3995 if (search_pattern) {
3996 err = match_logmsg(&have_match, id, commit, &regex);
3997 if (err) {
3998 got_object_commit_close(commit);
3999 break;
4001 if (have_match == 0 && show_changed_paths)
4002 match_changed_paths(&have_match,
4003 &changed_paths, &regex);
4004 if (have_match == 0) {
4005 got_object_commit_close(commit);
4006 TAILQ_FOREACH(pe, &changed_paths, entry) {
4007 free((char *)pe->path);
4008 free(pe->data);
4010 got_pathlist_free(&changed_paths);
4011 continue;
4015 if (reverse_display_order) {
4016 err = got_object_qid_alloc(&qid, id);
4017 if (err)
4018 break;
4019 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4020 got_object_commit_close(commit);
4021 } else {
4022 err = print_commit(commit, id, repo, path,
4023 show_changed_paths ? &changed_paths : NULL,
4024 show_patch, diff_context, refs_idmap, NULL);
4025 got_object_commit_close(commit);
4026 if (err)
4027 break;
4029 if ((limit && --limit == 0) ||
4030 (end_id && got_object_id_cmp(id, end_id) == 0))
4031 break;
4033 TAILQ_FOREACH(pe, &changed_paths, entry) {
4034 free((char *)pe->path);
4035 free(pe->data);
4037 got_pathlist_free(&changed_paths);
4039 if (reverse_display_order) {
4040 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4041 err = got_object_open_as_commit(&commit, repo,
4042 &qid->id);
4043 if (err)
4044 break;
4045 if (show_changed_paths) {
4046 err = get_changed_paths(&changed_paths,
4047 commit, repo);
4048 if (err)
4049 break;
4051 err = print_commit(commit, &qid->id, repo, path,
4052 show_changed_paths ? &changed_paths : NULL,
4053 show_patch, diff_context, refs_idmap, NULL);
4054 got_object_commit_close(commit);
4055 if (err)
4056 break;
4057 TAILQ_FOREACH(pe, &changed_paths, entry) {
4058 free((char *)pe->path);
4059 free(pe->data);
4061 got_pathlist_free(&changed_paths);
4064 done:
4065 while (!STAILQ_EMPTY(&reversed_commits)) {
4066 qid = STAILQ_FIRST(&reversed_commits);
4067 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4068 got_object_qid_free(qid);
4070 TAILQ_FOREACH(pe, &changed_paths, entry) {
4071 free((char *)pe->path);
4072 free(pe->data);
4074 got_pathlist_free(&changed_paths);
4075 if (search_pattern)
4076 regfree(&regex);
4077 got_commit_graph_close(graph);
4078 return err;
4081 __dead static void
4082 usage_log(void)
4084 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4085 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4086 "[-R] [path]\n", getprogname());
4087 exit(1);
4090 static int
4091 get_default_log_limit(void)
4093 const char *got_default_log_limit;
4094 long long n;
4095 const char *errstr;
4097 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4098 if (got_default_log_limit == NULL)
4099 return 0;
4100 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4101 if (errstr != NULL)
4102 return 0;
4103 return n;
4106 static const struct got_error *
4107 cmd_log(int argc, char *argv[])
4109 const struct got_error *error;
4110 struct got_repository *repo = NULL;
4111 struct got_worktree *worktree = NULL;
4112 struct got_object_id *start_id = NULL, *end_id = NULL;
4113 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4114 const char *start_commit = NULL, *end_commit = NULL;
4115 const char *search_pattern = NULL;
4116 int diff_context = -1, ch;
4117 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4118 int reverse_display_order = 0;
4119 const char *errstr;
4120 struct got_reflist_head refs;
4121 struct got_reflist_object_id_map *refs_idmap = NULL;
4123 TAILQ_INIT(&refs);
4125 #ifndef PROFILE
4126 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4127 NULL)
4128 == -1)
4129 err(1, "pledge");
4130 #endif
4132 limit = get_default_log_limit();
4134 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4135 switch (ch) {
4136 case 'p':
4137 show_patch = 1;
4138 break;
4139 case 'P':
4140 show_changed_paths = 1;
4141 break;
4142 case 'c':
4143 start_commit = optarg;
4144 break;
4145 case 'C':
4146 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4147 &errstr);
4148 if (errstr != NULL)
4149 errx(1, "number of context lines is %s: %s",
4150 errstr, optarg);
4151 break;
4152 case 'l':
4153 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4154 if (errstr != NULL)
4155 errx(1, "number of commits is %s: %s",
4156 errstr, optarg);
4157 break;
4158 case 'b':
4159 log_branches = 1;
4160 break;
4161 case 'r':
4162 repo_path = realpath(optarg, NULL);
4163 if (repo_path == NULL)
4164 return got_error_from_errno2("realpath",
4165 optarg);
4166 got_path_strip_trailing_slashes(repo_path);
4167 break;
4168 case 'R':
4169 reverse_display_order = 1;
4170 break;
4171 case 's':
4172 search_pattern = optarg;
4173 break;
4174 case 'x':
4175 end_commit = optarg;
4176 break;
4177 default:
4178 usage_log();
4179 /* NOTREACHED */
4183 argc -= optind;
4184 argv += optind;
4186 if (diff_context == -1)
4187 diff_context = 3;
4188 else if (!show_patch)
4189 errx(1, "-C requires -p");
4191 cwd = getcwd(NULL, 0);
4192 if (cwd == NULL) {
4193 error = got_error_from_errno("getcwd");
4194 goto done;
4197 if (repo_path == NULL) {
4198 error = got_worktree_open(&worktree, cwd);
4199 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4200 goto done;
4201 error = NULL;
4204 if (argc == 1) {
4205 if (worktree) {
4206 error = got_worktree_resolve_path(&path, worktree,
4207 argv[0]);
4208 if (error)
4209 goto done;
4210 } else {
4211 path = strdup(argv[0]);
4212 if (path == NULL) {
4213 error = got_error_from_errno("strdup");
4214 goto done;
4217 } else if (argc != 0)
4218 usage_log();
4220 if (repo_path == NULL) {
4221 repo_path = worktree ?
4222 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4224 if (repo_path == NULL) {
4225 error = got_error_from_errno("strdup");
4226 goto done;
4229 error = got_repo_open(&repo, repo_path, NULL);
4230 if (error != NULL)
4231 goto done;
4233 error = apply_unveil(got_repo_get_path(repo), 1,
4234 worktree ? got_worktree_get_root_path(worktree) : NULL);
4235 if (error)
4236 goto done;
4238 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4239 if (error)
4240 goto done;
4242 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4243 if (error)
4244 goto done;
4246 if (start_commit == NULL) {
4247 struct got_reference *head_ref;
4248 struct got_commit_object *commit = NULL;
4249 error = got_ref_open(&head_ref, repo,
4250 worktree ? got_worktree_get_head_ref_name(worktree)
4251 : GOT_REF_HEAD, 0);
4252 if (error != NULL)
4253 goto done;
4254 error = got_ref_resolve(&start_id, repo, head_ref);
4255 got_ref_close(head_ref);
4256 if (error != NULL)
4257 goto done;
4258 error = got_object_open_as_commit(&commit, repo,
4259 start_id);
4260 if (error != NULL)
4261 goto done;
4262 got_object_commit_close(commit);
4263 } else {
4264 error = got_repo_match_object_id(&start_id, NULL,
4265 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4266 if (error != NULL)
4267 goto done;
4269 if (end_commit != NULL) {
4270 error = got_repo_match_object_id(&end_id, NULL,
4271 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4272 if (error != NULL)
4273 goto done;
4276 if (worktree) {
4278 * If a path was specified on the command line it was resolved
4279 * to a path in the work tree above. Prepend the work tree's
4280 * path prefix to obtain the corresponding in-repository path.
4282 if (path) {
4283 const char *prefix;
4284 prefix = got_worktree_get_path_prefix(worktree);
4285 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4286 (path[0] != '\0') ? "/" : "", path) == -1) {
4287 error = got_error_from_errno("asprintf");
4288 goto done;
4291 } else
4292 error = got_repo_map_path(&in_repo_path, repo,
4293 path ? path : "");
4294 if (error != NULL)
4295 goto done;
4296 if (in_repo_path) {
4297 free(path);
4298 path = in_repo_path;
4301 if (worktree) {
4302 /* Release work tree lock. */
4303 got_worktree_close(worktree);
4304 worktree = NULL;
4307 error = print_commits(start_id, end_id, repo, path ? path : "",
4308 show_changed_paths, show_patch, search_pattern, diff_context,
4309 limit, log_branches, reverse_display_order, refs_idmap);
4310 done:
4311 free(path);
4312 free(repo_path);
4313 free(cwd);
4314 if (worktree)
4315 got_worktree_close(worktree);
4316 if (repo) {
4317 const struct got_error *close_err = got_repo_close(repo);
4318 if (error == NULL)
4319 error = close_err;
4321 if (refs_idmap)
4322 got_reflist_object_id_map_free(refs_idmap);
4323 got_ref_list_free(&refs);
4324 return error;
4327 __dead static void
4328 usage_diff(void)
4330 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4331 "[-r repository-path] [-s] [-w] [-P] "
4332 "[object1 object2 | path ...]\n", getprogname());
4333 exit(1);
4336 struct print_diff_arg {
4337 struct got_repository *repo;
4338 struct got_worktree *worktree;
4339 int diff_context;
4340 const char *id_str;
4341 int header_shown;
4342 int diff_staged;
4343 int ignore_whitespace;
4344 int force_text_diff;
4348 * Create a file which contains the target path of a symlink so we can feed
4349 * it as content to the diff engine.
4351 static const struct got_error *
4352 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4353 const char *abspath)
4355 const struct got_error *err = NULL;
4356 char target_path[PATH_MAX];
4357 ssize_t target_len, outlen;
4359 *fd = -1;
4361 if (dirfd != -1) {
4362 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4363 if (target_len == -1)
4364 return got_error_from_errno2("readlinkat", abspath);
4365 } else {
4366 target_len = readlink(abspath, target_path, PATH_MAX);
4367 if (target_len == -1)
4368 return got_error_from_errno2("readlink", abspath);
4371 *fd = got_opentempfd();
4372 if (*fd == -1)
4373 return got_error_from_errno("got_opentempfd");
4375 outlen = write(*fd, target_path, target_len);
4376 if (outlen == -1) {
4377 err = got_error_from_errno("got_opentempfd");
4378 goto done;
4381 if (lseek(*fd, 0, SEEK_SET) == -1) {
4382 err = got_error_from_errno2("lseek", abspath);
4383 goto done;
4385 done:
4386 if (err) {
4387 close(*fd);
4388 *fd = -1;
4390 return err;
4393 static const struct got_error *
4394 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4395 const char *path, struct got_object_id *blob_id,
4396 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4397 int dirfd, const char *de_name)
4399 struct print_diff_arg *a = arg;
4400 const struct got_error *err = NULL;
4401 struct got_blob_object *blob1 = NULL;
4402 int fd = -1;
4403 FILE *f1 = NULL, *f2 = NULL;
4404 char *abspath = NULL, *label1 = NULL;
4405 struct stat sb;
4406 off_t size1 = 0;
4408 if (a->diff_staged) {
4409 if (staged_status != GOT_STATUS_MODIFY &&
4410 staged_status != GOT_STATUS_ADD &&
4411 staged_status != GOT_STATUS_DELETE)
4412 return NULL;
4413 } else {
4414 if (staged_status == GOT_STATUS_DELETE)
4415 return NULL;
4416 if (status == GOT_STATUS_NONEXISTENT)
4417 return got_error_set_errno(ENOENT, path);
4418 if (status != GOT_STATUS_MODIFY &&
4419 status != GOT_STATUS_ADD &&
4420 status != GOT_STATUS_DELETE &&
4421 status != GOT_STATUS_CONFLICT)
4422 return NULL;
4425 if (!a->header_shown) {
4426 printf("diff %s %s%s\n", a->id_str,
4427 got_worktree_get_root_path(a->worktree),
4428 a->diff_staged ? " (staged changes)" : "");
4429 a->header_shown = 1;
4432 if (a->diff_staged) {
4433 const char *label1 = NULL, *label2 = NULL;
4434 switch (staged_status) {
4435 case GOT_STATUS_MODIFY:
4436 label1 = path;
4437 label2 = path;
4438 break;
4439 case GOT_STATUS_ADD:
4440 label2 = path;
4441 break;
4442 case GOT_STATUS_DELETE:
4443 label1 = path;
4444 break;
4445 default:
4446 return got_error(GOT_ERR_FILE_STATUS);
4448 f1 = got_opentemp();
4449 if (f1 == NULL) {
4450 err = got_error_from_errno("got_opentemp");
4451 goto done;
4453 f2 = got_opentemp();
4454 if (f2 == NULL) {
4455 err = got_error_from_errno("got_opentemp");
4456 goto done;
4458 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4459 blob_id, staged_blob_id, label1, label2, a->diff_context,
4460 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4461 goto done;
4464 if (staged_status == GOT_STATUS_ADD ||
4465 staged_status == GOT_STATUS_MODIFY) {
4466 char *id_str;
4467 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4468 8192);
4469 if (err)
4470 goto done;
4471 err = got_object_id_str(&id_str, staged_blob_id);
4472 if (err)
4473 goto done;
4474 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4475 err = got_error_from_errno("asprintf");
4476 free(id_str);
4477 goto done;
4479 free(id_str);
4480 } else if (status != GOT_STATUS_ADD) {
4481 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4482 if (err)
4483 goto done;
4486 if (status != GOT_STATUS_DELETE) {
4487 if (asprintf(&abspath, "%s/%s",
4488 got_worktree_get_root_path(a->worktree), path) == -1) {
4489 err = got_error_from_errno("asprintf");
4490 goto done;
4493 if (dirfd != -1) {
4494 fd = openat(dirfd, de_name,
4495 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4496 if (fd == -1) {
4497 if (!got_err_open_nofollow_on_symlink()) {
4498 err = got_error_from_errno2("openat",
4499 abspath);
4500 goto done;
4502 err = get_symlink_target_file(&fd, dirfd,
4503 de_name, abspath);
4504 if (err)
4505 goto done;
4507 } else {
4508 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4509 if (fd == -1) {
4510 if (!got_err_open_nofollow_on_symlink()) {
4511 err = got_error_from_errno2("open",
4512 abspath);
4513 goto done;
4515 err = get_symlink_target_file(&fd, dirfd,
4516 de_name, abspath);
4517 if (err)
4518 goto done;
4521 if (fstat(fd, &sb) == -1) {
4522 err = got_error_from_errno2("fstat", abspath);
4523 goto done;
4525 f2 = fdopen(fd, "r");
4526 if (f2 == NULL) {
4527 err = got_error_from_errno2("fdopen", abspath);
4528 goto done;
4530 fd = -1;
4531 } else
4532 sb.st_size = 0;
4534 if (blob1) {
4535 f1 = got_opentemp();
4536 if (f1 == NULL) {
4537 err = got_error_from_errno("got_opentemp");
4538 goto done;
4540 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4541 blob1);
4542 if (err)
4543 goto done;
4546 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4547 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4548 stdout);
4549 done:
4550 if (blob1)
4551 got_object_blob_close(blob1);
4552 if (f1 && fclose(f1) == EOF && err == NULL)
4553 err = got_error_from_errno("fclose");
4554 if (f2 && fclose(f2) == EOF && err == NULL)
4555 err = got_error_from_errno("fclose");
4556 if (fd != -1 && close(fd) == -1 && err == NULL)
4557 err = got_error_from_errno("close");
4558 free(abspath);
4559 return err;
4562 static const struct got_error *
4563 cmd_diff(int argc, char *argv[])
4565 const struct got_error *error;
4566 struct got_repository *repo = NULL;
4567 struct got_worktree *worktree = NULL;
4568 char *cwd = NULL, *repo_path = NULL;
4569 const char *commit_args[2] = { NULL, NULL };
4570 int ncommit_args = 0;
4571 struct got_object_id *ids[2] = { NULL, NULL };
4572 char *labels[2] = { NULL, NULL };
4573 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4574 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4575 int force_text_diff = 0, force_path = 0, rflag = 0;
4576 const char *errstr;
4577 struct got_reflist_head refs;
4578 struct got_pathlist_head paths;
4579 struct got_pathlist_entry *pe;
4580 FILE *f1 = NULL, *f2 = NULL;
4582 TAILQ_INIT(&refs);
4583 TAILQ_INIT(&paths);
4585 #ifndef PROFILE
4586 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4587 NULL) == -1)
4588 err(1, "pledge");
4589 #endif
4591 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4592 switch (ch) {
4593 case 'a':
4594 force_text_diff = 1;
4595 break;
4596 case 'c':
4597 if (ncommit_args >= 2)
4598 errx(1, "too many -c options used");
4599 commit_args[ncommit_args++] = optarg;
4600 break;
4601 case 'C':
4602 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4603 &errstr);
4604 if (errstr != NULL)
4605 errx(1, "number of context lines is %s: %s",
4606 errstr, optarg);
4607 break;
4608 case 'r':
4609 repo_path = realpath(optarg, NULL);
4610 if (repo_path == NULL)
4611 return got_error_from_errno2("realpath",
4612 optarg);
4613 got_path_strip_trailing_slashes(repo_path);
4614 rflag = 1;
4615 break;
4616 case 's':
4617 diff_staged = 1;
4618 break;
4619 case 'w':
4620 ignore_whitespace = 1;
4621 break;
4622 case 'P':
4623 force_path = 1;
4624 break;
4625 default:
4626 usage_diff();
4627 /* NOTREACHED */
4631 argc -= optind;
4632 argv += optind;
4634 cwd = getcwd(NULL, 0);
4635 if (cwd == NULL) {
4636 error = got_error_from_errno("getcwd");
4637 goto done;
4640 if (repo_path == NULL) {
4641 error = got_worktree_open(&worktree, cwd);
4642 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4643 goto done;
4644 else
4645 error = NULL;
4646 if (worktree) {
4647 repo_path =
4648 strdup(got_worktree_get_repo_path(worktree));
4649 if (repo_path == NULL) {
4650 error = got_error_from_errno("strdup");
4651 goto done;
4653 } else {
4654 repo_path = strdup(cwd);
4655 if (repo_path == NULL) {
4656 error = got_error_from_errno("strdup");
4657 goto done;
4662 error = got_repo_open(&repo, repo_path, NULL);
4663 free(repo_path);
4664 if (error != NULL)
4665 goto done;
4667 if (rflag || worktree == NULL || ncommit_args > 0) {
4668 if (force_path) {
4669 error = got_error_msg(GOT_ERR_NOT_IMPL,
4670 "-P option can only be used when diffing "
4671 "a work tree");
4672 goto done;
4674 if (diff_staged) {
4675 error = got_error_msg(GOT_ERR_NOT_IMPL,
4676 "-s option can only be used when diffing "
4677 "a work tree");
4678 goto done;
4682 error = apply_unveil(got_repo_get_path(repo), 1,
4683 worktree ? got_worktree_get_root_path(worktree) : NULL);
4684 if (error)
4685 goto done;
4687 if ((!force_path && argc == 2) || ncommit_args > 0) {
4688 int obj_type = (ncommit_args > 0 ?
4689 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4690 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4691 NULL);
4692 if (error)
4693 goto done;
4694 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4695 const char *arg;
4696 if (ncommit_args > 0)
4697 arg = commit_args[i];
4698 else
4699 arg = argv[i];
4700 error = got_repo_match_object_id(&ids[i], &labels[i],
4701 arg, obj_type, &refs, repo);
4702 if (error) {
4703 if (error->code != GOT_ERR_NOT_REF &&
4704 error->code != GOT_ERR_NO_OBJ)
4705 goto done;
4706 if (ncommit_args > 0)
4707 goto done;
4708 error = NULL;
4709 break;
4714 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4715 struct print_diff_arg arg;
4716 char *id_str;
4718 if (worktree == NULL) {
4719 if (argc == 2 && ids[0] == NULL) {
4720 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4721 goto done;
4722 } else if (argc == 2 && ids[1] == NULL) {
4723 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4724 goto done;
4725 } else if (argc > 0) {
4726 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4727 "%s", "specified paths cannot be resolved");
4728 goto done;
4729 } else {
4730 error = got_error(GOT_ERR_NOT_WORKTREE);
4731 goto done;
4735 error = get_worktree_paths_from_argv(&paths, argc, argv,
4736 worktree);
4737 if (error)
4738 goto done;
4740 error = got_object_id_str(&id_str,
4741 got_worktree_get_base_commit_id(worktree));
4742 if (error)
4743 goto done;
4744 arg.repo = repo;
4745 arg.worktree = worktree;
4746 arg.diff_context = diff_context;
4747 arg.id_str = id_str;
4748 arg.header_shown = 0;
4749 arg.diff_staged = diff_staged;
4750 arg.ignore_whitespace = ignore_whitespace;
4751 arg.force_text_diff = force_text_diff;
4753 error = got_worktree_status(worktree, &paths, repo, 0,
4754 print_diff, &arg, check_cancelled, NULL);
4755 free(id_str);
4756 goto done;
4759 if (ncommit_args == 1) {
4760 struct got_commit_object *commit;
4761 error = got_object_open_as_commit(&commit, repo, ids[0]);
4762 if (error)
4763 goto done;
4765 labels[1] = labels[0];
4766 ids[1] = ids[0];
4767 if (got_object_commit_get_nparents(commit) > 0) {
4768 const struct got_object_id_queue *pids;
4769 struct got_object_qid *pid;
4770 pids = got_object_commit_get_parent_ids(commit);
4771 pid = STAILQ_FIRST(pids);
4772 ids[0] = got_object_id_dup(&pid->id);
4773 if (ids[0] == NULL) {
4774 error = got_error_from_errno(
4775 "got_object_id_dup");
4776 got_object_commit_close(commit);
4777 goto done;
4779 error = got_object_id_str(&labels[0], ids[0]);
4780 if (error) {
4781 got_object_commit_close(commit);
4782 goto done;
4784 } else {
4785 ids[0] = NULL;
4786 labels[0] = strdup("/dev/null");
4787 if (labels[0] == NULL) {
4788 error = got_error_from_errno("strdup");
4789 got_object_commit_close(commit);
4790 goto done;
4794 got_object_commit_close(commit);
4797 if (ncommit_args == 0 && argc > 2) {
4798 error = got_error_msg(GOT_ERR_BAD_PATH,
4799 "path arguments cannot be used when diffing two objects");
4800 goto done;
4803 if (ids[0]) {
4804 error = got_object_get_type(&type1, repo, ids[0]);
4805 if (error)
4806 goto done;
4809 error = got_object_get_type(&type2, repo, ids[1]);
4810 if (error)
4811 goto done;
4812 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4813 error = got_error(GOT_ERR_OBJ_TYPE);
4814 goto done;
4816 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4817 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4818 "path arguments cannot be used when diffing blobs");
4819 goto done;
4822 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4823 char *in_repo_path;
4824 struct got_pathlist_entry *new;
4825 if (worktree) {
4826 const char *prefix;
4827 char *p;
4828 error = got_worktree_resolve_path(&p, worktree,
4829 argv[i]);
4830 if (error)
4831 goto done;
4832 prefix = got_worktree_get_path_prefix(worktree);
4833 while (prefix[0] == '/')
4834 prefix++;
4835 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4836 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4837 p) == -1) {
4838 error = got_error_from_errno("asprintf");
4839 free(p);
4840 goto done;
4842 free(p);
4843 } else {
4844 char *mapped_path, *s;
4845 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4846 if (error)
4847 goto done;
4848 s = mapped_path;
4849 while (s[0] == '/')
4850 s++;
4851 in_repo_path = strdup(s);
4852 if (in_repo_path == NULL) {
4853 error = got_error_from_errno("asprintf");
4854 free(mapped_path);
4855 goto done;
4857 free(mapped_path);
4860 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4861 if (error || new == NULL /* duplicate */)
4862 free(in_repo_path);
4863 if (error)
4864 goto done;
4867 if (worktree) {
4868 /* Release work tree lock. */
4869 got_worktree_close(worktree);
4870 worktree = NULL;
4873 f1 = got_opentemp();
4874 if (f1 == NULL) {
4875 error = got_error_from_errno("got_opentemp");
4876 goto done;
4879 f2 = got_opentemp();
4880 if (f2 == NULL) {
4881 error = got_error_from_errno("got_opentemp");
4882 goto done;
4885 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4886 case GOT_OBJ_TYPE_BLOB:
4887 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4888 ids[0], ids[1], NULL, NULL, diff_context,
4889 ignore_whitespace, force_text_diff, repo, stdout);
4890 break;
4891 case GOT_OBJ_TYPE_TREE:
4892 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
4893 ids[0], ids[1], &paths, "", "", diff_context,
4894 ignore_whitespace, force_text_diff, repo, stdout);
4895 break;
4896 case GOT_OBJ_TYPE_COMMIT:
4897 printf("diff %s %s\n", labels[0], labels[1]);
4898 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4899 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
4900 force_text_diff, repo, stdout);
4901 break;
4902 default:
4903 error = got_error(GOT_ERR_OBJ_TYPE);
4905 done:
4906 free(labels[0]);
4907 free(labels[1]);
4908 free(ids[0]);
4909 free(ids[1]);
4910 if (worktree)
4911 got_worktree_close(worktree);
4912 if (repo) {
4913 const struct got_error *close_err = got_repo_close(repo);
4914 if (error == NULL)
4915 error = close_err;
4917 TAILQ_FOREACH(pe, &paths, entry)
4918 free((char *)pe->path);
4919 got_pathlist_free(&paths);
4920 got_ref_list_free(&refs);
4921 if (f1 && fclose(f1) == EOF && error == NULL)
4922 error = got_error_from_errno("fclose");
4923 if (f2 && fclose(f2) == EOF && error == NULL)
4924 error = got_error_from_errno("fclose");
4925 return error;
4928 __dead static void
4929 usage_blame(void)
4931 fprintf(stderr,
4932 "usage: %s blame [-c commit] [-r repository-path] path\n",
4933 getprogname());
4934 exit(1);
4937 struct blame_line {
4938 int annotated;
4939 char *id_str;
4940 char *committer;
4941 char datebuf[11]; /* YYYY-MM-DD + NUL */
4944 struct blame_cb_args {
4945 struct blame_line *lines;
4946 int nlines;
4947 int nlines_prec;
4948 int lineno_cur;
4949 off_t *line_offsets;
4950 FILE *f;
4951 struct got_repository *repo;
4954 static const struct got_error *
4955 blame_cb(void *arg, int nlines, int lineno,
4956 struct got_commit_object *commit, struct got_object_id *id)
4958 const struct got_error *err = NULL;
4959 struct blame_cb_args *a = arg;
4960 struct blame_line *bline;
4961 char *line = NULL;
4962 size_t linesize = 0;
4963 off_t offset;
4964 struct tm tm;
4965 time_t committer_time;
4967 if (nlines != a->nlines ||
4968 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4969 return got_error(GOT_ERR_RANGE);
4971 if (sigint_received)
4972 return got_error(GOT_ERR_ITER_COMPLETED);
4974 if (lineno == -1)
4975 return NULL; /* no change in this commit */
4977 /* Annotate this line. */
4978 bline = &a->lines[lineno - 1];
4979 if (bline->annotated)
4980 return NULL;
4981 err = got_object_id_str(&bline->id_str, id);
4982 if (err)
4983 return err;
4985 bline->committer = strdup(got_object_commit_get_committer(commit));
4986 if (bline->committer == NULL) {
4987 err = got_error_from_errno("strdup");
4988 goto done;
4991 committer_time = got_object_commit_get_committer_time(commit);
4992 if (gmtime_r(&committer_time, &tm) == NULL)
4993 return got_error_from_errno("gmtime_r");
4994 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4995 &tm) == 0) {
4996 err = got_error(GOT_ERR_NO_SPACE);
4997 goto done;
4999 bline->annotated = 1;
5001 /* Print lines annotated so far. */
5002 bline = &a->lines[a->lineno_cur - 1];
5003 if (!bline->annotated)
5004 goto done;
5006 offset = a->line_offsets[a->lineno_cur - 1];
5007 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5008 err = got_error_from_errno("fseeko");
5009 goto done;
5012 while (bline->annotated) {
5013 char *smallerthan, *at, *nl, *committer;
5014 size_t len;
5016 if (getline(&line, &linesize, a->f) == -1) {
5017 if (ferror(a->f))
5018 err = got_error_from_errno("getline");
5019 break;
5022 committer = bline->committer;
5023 smallerthan = strchr(committer, '<');
5024 if (smallerthan && smallerthan[1] != '\0')
5025 committer = smallerthan + 1;
5026 at = strchr(committer, '@');
5027 if (at)
5028 *at = '\0';
5029 len = strlen(committer);
5030 if (len >= 9)
5031 committer[8] = '\0';
5033 nl = strchr(line, '\n');
5034 if (nl)
5035 *nl = '\0';
5036 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5037 bline->id_str, bline->datebuf, committer, line);
5039 a->lineno_cur++;
5040 bline = &a->lines[a->lineno_cur - 1];
5042 done:
5043 free(line);
5044 return err;
5047 static const struct got_error *
5048 cmd_blame(int argc, char *argv[])
5050 const struct got_error *error;
5051 struct got_repository *repo = NULL;
5052 struct got_worktree *worktree = NULL;
5053 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5054 char *link_target = NULL;
5055 struct got_object_id *obj_id = NULL;
5056 struct got_object_id *commit_id = NULL;
5057 struct got_commit_object *commit = NULL;
5058 struct got_blob_object *blob = NULL;
5059 char *commit_id_str = NULL;
5060 struct blame_cb_args bca;
5061 int ch, obj_type, i;
5062 off_t filesize;
5064 memset(&bca, 0, sizeof(bca));
5066 #ifndef PROFILE
5067 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5068 NULL) == -1)
5069 err(1, "pledge");
5070 #endif
5072 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5073 switch (ch) {
5074 case 'c':
5075 commit_id_str = optarg;
5076 break;
5077 case 'r':
5078 repo_path = realpath(optarg, NULL);
5079 if (repo_path == NULL)
5080 return got_error_from_errno2("realpath",
5081 optarg);
5082 got_path_strip_trailing_slashes(repo_path);
5083 break;
5084 default:
5085 usage_blame();
5086 /* NOTREACHED */
5090 argc -= optind;
5091 argv += optind;
5093 if (argc == 1)
5094 path = argv[0];
5095 else
5096 usage_blame();
5098 cwd = getcwd(NULL, 0);
5099 if (cwd == NULL) {
5100 error = got_error_from_errno("getcwd");
5101 goto done;
5103 if (repo_path == NULL) {
5104 error = got_worktree_open(&worktree, cwd);
5105 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5106 goto done;
5107 else
5108 error = NULL;
5109 if (worktree) {
5110 repo_path =
5111 strdup(got_worktree_get_repo_path(worktree));
5112 if (repo_path == NULL) {
5113 error = got_error_from_errno("strdup");
5114 if (error)
5115 goto done;
5117 } else {
5118 repo_path = strdup(cwd);
5119 if (repo_path == NULL) {
5120 error = got_error_from_errno("strdup");
5121 goto done;
5126 error = got_repo_open(&repo, repo_path, NULL);
5127 if (error != NULL)
5128 goto done;
5130 if (worktree) {
5131 const char *prefix = got_worktree_get_path_prefix(worktree);
5132 char *p;
5134 error = got_worktree_resolve_path(&p, worktree, path);
5135 if (error)
5136 goto done;
5137 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5138 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5139 p) == -1) {
5140 error = got_error_from_errno("asprintf");
5141 free(p);
5142 goto done;
5144 free(p);
5145 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5146 } else {
5147 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5148 if (error)
5149 goto done;
5150 error = got_repo_map_path(&in_repo_path, repo, path);
5152 if (error)
5153 goto done;
5155 if (commit_id_str == NULL) {
5156 struct got_reference *head_ref;
5157 error = got_ref_open(&head_ref, repo, worktree ?
5158 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5159 if (error != NULL)
5160 goto done;
5161 error = got_ref_resolve(&commit_id, repo, head_ref);
5162 got_ref_close(head_ref);
5163 if (error != NULL)
5164 goto done;
5165 } else {
5166 struct got_reflist_head refs;
5167 TAILQ_INIT(&refs);
5168 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5169 NULL);
5170 if (error)
5171 goto done;
5172 error = got_repo_match_object_id(&commit_id, NULL,
5173 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5174 got_ref_list_free(&refs);
5175 if (error)
5176 goto done;
5179 if (worktree) {
5180 /* Release work tree lock. */
5181 got_worktree_close(worktree);
5182 worktree = NULL;
5185 error = got_object_open_as_commit(&commit, repo, commit_id);
5186 if (error)
5187 goto done;
5189 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5190 commit, repo);
5191 if (error)
5192 goto done;
5194 error = got_object_id_by_path(&obj_id, repo, commit,
5195 link_target ? link_target : in_repo_path);
5196 if (error)
5197 goto done;
5199 error = got_object_get_type(&obj_type, repo, obj_id);
5200 if (error)
5201 goto done;
5203 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5204 error = got_error_path(link_target ? link_target : in_repo_path,
5205 GOT_ERR_OBJ_TYPE);
5206 goto done;
5209 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5210 if (error)
5211 goto done;
5212 bca.f = got_opentemp();
5213 if (bca.f == NULL) {
5214 error = got_error_from_errno("got_opentemp");
5215 goto done;
5217 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5218 &bca.line_offsets, bca.f, blob);
5219 if (error || bca.nlines == 0)
5220 goto done;
5222 /* Don't include \n at EOF in the blame line count. */
5223 if (bca.line_offsets[bca.nlines - 1] == filesize)
5224 bca.nlines--;
5226 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5227 if (bca.lines == NULL) {
5228 error = got_error_from_errno("calloc");
5229 goto done;
5231 bca.lineno_cur = 1;
5232 bca.nlines_prec = 0;
5233 i = bca.nlines;
5234 while (i > 0) {
5235 i /= 10;
5236 bca.nlines_prec++;
5238 bca.repo = repo;
5240 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5241 repo, blame_cb, &bca, check_cancelled, NULL);
5242 done:
5243 free(in_repo_path);
5244 free(link_target);
5245 free(repo_path);
5246 free(cwd);
5247 free(commit_id);
5248 free(obj_id);
5249 if (commit)
5250 got_object_commit_close(commit);
5251 if (blob)
5252 got_object_blob_close(blob);
5253 if (worktree)
5254 got_worktree_close(worktree);
5255 if (repo) {
5256 const struct got_error *close_err = got_repo_close(repo);
5257 if (error == NULL)
5258 error = close_err;
5260 if (bca.lines) {
5261 for (i = 0; i < bca.nlines; i++) {
5262 struct blame_line *bline = &bca.lines[i];
5263 free(bline->id_str);
5264 free(bline->committer);
5266 free(bca.lines);
5268 free(bca.line_offsets);
5269 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5270 error = got_error_from_errno("fclose");
5271 return error;
5274 __dead static void
5275 usage_tree(void)
5277 fprintf(stderr,
5278 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5279 getprogname());
5280 exit(1);
5283 static const struct got_error *
5284 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5285 const char *root_path, struct got_repository *repo)
5287 const struct got_error *err = NULL;
5288 int is_root_path = (strcmp(path, root_path) == 0);
5289 const char *modestr = "";
5290 mode_t mode = got_tree_entry_get_mode(te);
5291 char *link_target = NULL;
5293 path += strlen(root_path);
5294 while (path[0] == '/')
5295 path++;
5297 if (got_object_tree_entry_is_submodule(te))
5298 modestr = "$";
5299 else if (S_ISLNK(mode)) {
5300 int i;
5302 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5303 if (err)
5304 return err;
5305 for (i = 0; i < strlen(link_target); i++) {
5306 if (!isprint((unsigned char)link_target[i]))
5307 link_target[i] = '?';
5310 modestr = "@";
5312 else if (S_ISDIR(mode))
5313 modestr = "/";
5314 else if (mode & S_IXUSR)
5315 modestr = "*";
5317 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5318 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5319 link_target ? " -> ": "", link_target ? link_target : "");
5321 free(link_target);
5322 return NULL;
5325 static const struct got_error *
5326 print_tree(const char *path, struct got_commit_object *commit,
5327 int show_ids, int recurse, const char *root_path,
5328 struct got_repository *repo)
5330 const struct got_error *err = NULL;
5331 struct got_object_id *tree_id = NULL;
5332 struct got_tree_object *tree = NULL;
5333 int nentries, i;
5335 err = got_object_id_by_path(&tree_id, repo, commit, path);
5336 if (err)
5337 goto done;
5339 err = got_object_open_as_tree(&tree, repo, tree_id);
5340 if (err)
5341 goto done;
5342 nentries = got_object_tree_get_nentries(tree);
5343 for (i = 0; i < nentries; i++) {
5344 struct got_tree_entry *te;
5345 char *id = NULL;
5347 if (sigint_received || sigpipe_received)
5348 break;
5350 te = got_object_tree_get_entry(tree, i);
5351 if (show_ids) {
5352 char *id_str;
5353 err = got_object_id_str(&id_str,
5354 got_tree_entry_get_id(te));
5355 if (err)
5356 goto done;
5357 if (asprintf(&id, "%s ", id_str) == -1) {
5358 err = got_error_from_errno("asprintf");
5359 free(id_str);
5360 goto done;
5362 free(id_str);
5364 err = print_entry(te, id, path, root_path, repo);
5365 free(id);
5366 if (err)
5367 goto done;
5369 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5370 char *child_path;
5371 if (asprintf(&child_path, "%s%s%s", path,
5372 path[0] == '/' && path[1] == '\0' ? "" : "/",
5373 got_tree_entry_get_name(te)) == -1) {
5374 err = got_error_from_errno("asprintf");
5375 goto done;
5377 err = print_tree(child_path, commit, show_ids, 1,
5378 root_path, repo);
5379 free(child_path);
5380 if (err)
5381 goto done;
5384 done:
5385 if (tree)
5386 got_object_tree_close(tree);
5387 free(tree_id);
5388 return err;
5391 static const struct got_error *
5392 cmd_tree(int argc, char *argv[])
5394 const struct got_error *error;
5395 struct got_repository *repo = NULL;
5396 struct got_worktree *worktree = NULL;
5397 const char *path, *refname = NULL;
5398 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5399 struct got_object_id *commit_id = NULL;
5400 struct got_commit_object *commit = NULL;
5401 char *commit_id_str = NULL;
5402 int show_ids = 0, recurse = 0;
5403 int ch;
5405 #ifndef PROFILE
5406 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5407 NULL) == -1)
5408 err(1, "pledge");
5409 #endif
5411 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5412 switch (ch) {
5413 case 'c':
5414 commit_id_str = optarg;
5415 break;
5416 case 'r':
5417 repo_path = realpath(optarg, NULL);
5418 if (repo_path == NULL)
5419 return got_error_from_errno2("realpath",
5420 optarg);
5421 got_path_strip_trailing_slashes(repo_path);
5422 break;
5423 case 'i':
5424 show_ids = 1;
5425 break;
5426 case 'R':
5427 recurse = 1;
5428 break;
5429 default:
5430 usage_tree();
5431 /* NOTREACHED */
5435 argc -= optind;
5436 argv += optind;
5438 if (argc == 1)
5439 path = argv[0];
5440 else if (argc > 1)
5441 usage_tree();
5442 else
5443 path = NULL;
5445 cwd = getcwd(NULL, 0);
5446 if (cwd == NULL) {
5447 error = got_error_from_errno("getcwd");
5448 goto done;
5450 if (repo_path == NULL) {
5451 error = got_worktree_open(&worktree, cwd);
5452 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5453 goto done;
5454 else
5455 error = NULL;
5456 if (worktree) {
5457 repo_path =
5458 strdup(got_worktree_get_repo_path(worktree));
5459 if (repo_path == NULL)
5460 error = got_error_from_errno("strdup");
5461 if (error)
5462 goto done;
5463 } else {
5464 repo_path = strdup(cwd);
5465 if (repo_path == NULL) {
5466 error = got_error_from_errno("strdup");
5467 goto done;
5472 error = got_repo_open(&repo, repo_path, NULL);
5473 if (error != NULL)
5474 goto done;
5476 if (worktree) {
5477 const char *prefix = got_worktree_get_path_prefix(worktree);
5478 char *p;
5480 if (path == NULL)
5481 path = "";
5482 error = got_worktree_resolve_path(&p, worktree, path);
5483 if (error)
5484 goto done;
5485 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5486 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5487 p) == -1) {
5488 error = got_error_from_errno("asprintf");
5489 free(p);
5490 goto done;
5492 free(p);
5493 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5494 if (error)
5495 goto done;
5496 } else {
5497 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5498 if (error)
5499 goto done;
5500 if (path == NULL)
5501 path = "/";
5502 error = got_repo_map_path(&in_repo_path, repo, path);
5503 if (error != NULL)
5504 goto done;
5507 if (commit_id_str == NULL) {
5508 struct got_reference *head_ref;
5509 if (worktree)
5510 refname = got_worktree_get_head_ref_name(worktree);
5511 else
5512 refname = GOT_REF_HEAD;
5513 error = got_ref_open(&head_ref, repo, refname, 0);
5514 if (error != NULL)
5515 goto done;
5516 error = got_ref_resolve(&commit_id, repo, head_ref);
5517 got_ref_close(head_ref);
5518 if (error != NULL)
5519 goto done;
5520 } else {
5521 struct got_reflist_head refs;
5522 TAILQ_INIT(&refs);
5523 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5524 NULL);
5525 if (error)
5526 goto done;
5527 error = got_repo_match_object_id(&commit_id, NULL,
5528 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5529 got_ref_list_free(&refs);
5530 if (error)
5531 goto done;
5534 if (worktree) {
5535 /* Release work tree lock. */
5536 got_worktree_close(worktree);
5537 worktree = NULL;
5540 error = got_object_open_as_commit(&commit, repo, commit_id);
5541 if (error)
5542 goto done;
5544 error = print_tree(in_repo_path, commit, show_ids, recurse,
5545 in_repo_path, repo);
5546 done:
5547 free(in_repo_path);
5548 free(repo_path);
5549 free(cwd);
5550 free(commit_id);
5551 if (commit)
5552 got_object_commit_close(commit);
5553 if (worktree)
5554 got_worktree_close(worktree);
5555 if (repo) {
5556 const struct got_error *close_err = got_repo_close(repo);
5557 if (error == NULL)
5558 error = close_err;
5560 return error;
5563 __dead static void
5564 usage_status(void)
5566 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5567 "[-S status-codes] [path ...]\n", getprogname());
5568 exit(1);
5571 struct got_status_arg {
5572 char *status_codes;
5573 int suppress;
5576 static const struct got_error *
5577 print_status(void *arg, unsigned char status, unsigned char staged_status,
5578 const char *path, struct got_object_id *blob_id,
5579 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5580 int dirfd, const char *de_name)
5582 struct got_status_arg *st = arg;
5584 if (status == staged_status && (status == GOT_STATUS_DELETE))
5585 status = GOT_STATUS_NO_CHANGE;
5586 if (st != NULL && st->status_codes) {
5587 size_t ncodes = strlen(st->status_codes);
5588 int i, j = 0;
5590 for (i = 0; i < ncodes ; i++) {
5591 if (st->suppress) {
5592 if (status == st->status_codes[i] ||
5593 staged_status == st->status_codes[i]) {
5594 j++;
5595 continue;
5597 } else {
5598 if (status == st->status_codes[i] ||
5599 staged_status == st->status_codes[i])
5600 break;
5604 if (st->suppress && j == 0)
5605 goto print;
5607 if (i == ncodes)
5608 return NULL;
5610 print:
5611 printf("%c%c %s\n", status, staged_status, path);
5612 return NULL;
5615 static const struct got_error *
5616 cmd_status(int argc, char *argv[])
5618 const struct got_error *error = NULL;
5619 struct got_repository *repo = NULL;
5620 struct got_worktree *worktree = NULL;
5621 struct got_status_arg st;
5622 char *cwd = NULL;
5623 struct got_pathlist_head paths;
5624 struct got_pathlist_entry *pe;
5625 int ch, i, no_ignores = 0;
5627 TAILQ_INIT(&paths);
5629 memset(&st, 0, sizeof(st));
5630 st.status_codes = NULL;
5631 st.suppress = 0;
5633 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5634 switch (ch) {
5635 case 'I':
5636 no_ignores = 1;
5637 break;
5638 case 'S':
5639 if (st.status_codes != NULL && st.suppress == 0)
5640 option_conflict('S', 's');
5641 st.suppress = 1;
5642 /* fallthrough */
5643 case 's':
5644 for (i = 0; i < strlen(optarg); i++) {
5645 switch (optarg[i]) {
5646 case GOT_STATUS_MODIFY:
5647 case GOT_STATUS_ADD:
5648 case GOT_STATUS_DELETE:
5649 case GOT_STATUS_CONFLICT:
5650 case GOT_STATUS_MISSING:
5651 case GOT_STATUS_OBSTRUCTED:
5652 case GOT_STATUS_UNVERSIONED:
5653 case GOT_STATUS_MODE_CHANGE:
5654 case GOT_STATUS_NONEXISTENT:
5655 break;
5656 default:
5657 errx(1, "invalid status code '%c'",
5658 optarg[i]);
5661 if (ch == 's' && st.suppress)
5662 option_conflict('s', 'S');
5663 st.status_codes = optarg;
5664 break;
5665 default:
5666 usage_status();
5667 /* NOTREACHED */
5671 argc -= optind;
5672 argv += optind;
5674 #ifndef PROFILE
5675 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5676 NULL) == -1)
5677 err(1, "pledge");
5678 #endif
5679 cwd = getcwd(NULL, 0);
5680 if (cwd == NULL) {
5681 error = got_error_from_errno("getcwd");
5682 goto done;
5685 error = got_worktree_open(&worktree, cwd);
5686 if (error) {
5687 if (error->code == GOT_ERR_NOT_WORKTREE)
5688 error = wrap_not_worktree_error(error, "status", cwd);
5689 goto done;
5692 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5693 NULL);
5694 if (error != NULL)
5695 goto done;
5697 error = apply_unveil(got_repo_get_path(repo), 1,
5698 got_worktree_get_root_path(worktree));
5699 if (error)
5700 goto done;
5702 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5703 if (error)
5704 goto done;
5706 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5707 print_status, &st, check_cancelled, NULL);
5708 done:
5709 TAILQ_FOREACH(pe, &paths, entry)
5710 free((char *)pe->path);
5711 got_pathlist_free(&paths);
5712 free(cwd);
5713 return error;
5716 __dead static void
5717 usage_ref(void)
5719 fprintf(stderr,
5720 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5721 "[-s reference] [-d] [name]\n",
5722 getprogname());
5723 exit(1);
5726 static const struct got_error *
5727 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5729 static const struct got_error *err = NULL;
5730 struct got_reflist_head refs;
5731 struct got_reflist_entry *re;
5733 TAILQ_INIT(&refs);
5734 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5735 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5736 repo);
5737 if (err)
5738 return err;
5740 TAILQ_FOREACH(re, &refs, entry) {
5741 char *refstr;
5742 refstr = got_ref_to_str(re->ref);
5743 if (refstr == NULL) {
5744 err = got_error_from_errno("got_ref_to_str");
5745 break;
5747 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5748 free(refstr);
5751 got_ref_list_free(&refs);
5752 return err;
5755 static const struct got_error *
5756 delete_ref_by_name(struct got_repository *repo, const char *refname)
5758 const struct got_error *err;
5759 struct got_reference *ref;
5761 err = got_ref_open(&ref, repo, refname, 0);
5762 if (err)
5763 return err;
5765 err = delete_ref(repo, ref);
5766 got_ref_close(ref);
5767 return err;
5770 static const struct got_error *
5771 add_ref(struct got_repository *repo, const char *refname, const char *target)
5773 const struct got_error *err = NULL;
5774 struct got_object_id *id = NULL;
5775 struct got_reference *ref = NULL;
5776 struct got_reflist_head refs;
5779 * Don't let the user create a reference name with a leading '-'.
5780 * While technically a valid reference name, this case is usually
5781 * an unintended typo.
5783 if (refname[0] == '-')
5784 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5786 TAILQ_INIT(&refs);
5787 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5788 if (err)
5789 goto done;
5790 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5791 &refs, repo);
5792 got_ref_list_free(&refs);
5793 if (err)
5794 goto done;
5796 err = got_ref_alloc(&ref, refname, id);
5797 if (err)
5798 goto done;
5800 err = got_ref_write(ref, repo);
5801 done:
5802 if (ref)
5803 got_ref_close(ref);
5804 free(id);
5805 return err;
5808 static const struct got_error *
5809 add_symref(struct got_repository *repo, const char *refname, const char *target)
5811 const struct got_error *err = NULL;
5812 struct got_reference *ref = NULL;
5813 struct got_reference *target_ref = NULL;
5816 * Don't let the user create a reference name with a leading '-'.
5817 * While technically a valid reference name, this case is usually
5818 * an unintended typo.
5820 if (refname[0] == '-')
5821 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5823 err = got_ref_open(&target_ref, repo, target, 0);
5824 if (err)
5825 return err;
5827 err = got_ref_alloc_symref(&ref, refname, target_ref);
5828 if (err)
5829 goto done;
5831 err = got_ref_write(ref, repo);
5832 done:
5833 if (target_ref)
5834 got_ref_close(target_ref);
5835 if (ref)
5836 got_ref_close(ref);
5837 return err;
5840 static const struct got_error *
5841 cmd_ref(int argc, char *argv[])
5843 const struct got_error *error = NULL;
5844 struct got_repository *repo = NULL;
5845 struct got_worktree *worktree = NULL;
5846 char *cwd = NULL, *repo_path = NULL;
5847 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5848 const char *obj_arg = NULL, *symref_target= NULL;
5849 char *refname = NULL;
5851 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5852 switch (ch) {
5853 case 'c':
5854 obj_arg = optarg;
5855 break;
5856 case 'd':
5857 do_delete = 1;
5858 break;
5859 case 'r':
5860 repo_path = realpath(optarg, NULL);
5861 if (repo_path == NULL)
5862 return got_error_from_errno2("realpath",
5863 optarg);
5864 got_path_strip_trailing_slashes(repo_path);
5865 break;
5866 case 'l':
5867 do_list = 1;
5868 break;
5869 case 's':
5870 symref_target = optarg;
5871 break;
5872 case 't':
5873 sort_by_time = 1;
5874 break;
5875 default:
5876 usage_ref();
5877 /* NOTREACHED */
5881 if (obj_arg && do_list)
5882 option_conflict('c', 'l');
5883 if (obj_arg && do_delete)
5884 option_conflict('c', 'd');
5885 if (obj_arg && symref_target)
5886 option_conflict('c', 's');
5887 if (symref_target && do_delete)
5888 option_conflict('s', 'd');
5889 if (symref_target && do_list)
5890 option_conflict('s', 'l');
5891 if (do_delete && do_list)
5892 option_conflict('d', 'l');
5893 if (sort_by_time && !do_list)
5894 errx(1, "-t option requires -l option");
5896 argc -= optind;
5897 argv += optind;
5899 if (do_list) {
5900 if (argc != 0 && argc != 1)
5901 usage_ref();
5902 if (argc == 1) {
5903 refname = strdup(argv[0]);
5904 if (refname == NULL) {
5905 error = got_error_from_errno("strdup");
5906 goto done;
5909 } else {
5910 if (argc != 1)
5911 usage_ref();
5912 refname = strdup(argv[0]);
5913 if (refname == NULL) {
5914 error = got_error_from_errno("strdup");
5915 goto done;
5919 if (refname)
5920 got_path_strip_trailing_slashes(refname);
5922 #ifndef PROFILE
5923 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5924 "sendfd unveil", NULL) == -1)
5925 err(1, "pledge");
5926 #endif
5927 cwd = getcwd(NULL, 0);
5928 if (cwd == NULL) {
5929 error = got_error_from_errno("getcwd");
5930 goto done;
5933 if (repo_path == NULL) {
5934 error = got_worktree_open(&worktree, cwd);
5935 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5936 goto done;
5937 else
5938 error = NULL;
5939 if (worktree) {
5940 repo_path =
5941 strdup(got_worktree_get_repo_path(worktree));
5942 if (repo_path == NULL)
5943 error = got_error_from_errno("strdup");
5944 if (error)
5945 goto done;
5946 } else {
5947 repo_path = strdup(cwd);
5948 if (repo_path == NULL) {
5949 error = got_error_from_errno("strdup");
5950 goto done;
5955 error = got_repo_open(&repo, repo_path, NULL);
5956 if (error != NULL)
5957 goto done;
5959 #ifndef PROFILE
5960 if (do_list) {
5961 /* Remove "cpath" promise. */
5962 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5963 NULL) == -1)
5964 err(1, "pledge");
5966 #endif
5968 error = apply_unveil(got_repo_get_path(repo), do_list,
5969 worktree ? got_worktree_get_root_path(worktree) : NULL);
5970 if (error)
5971 goto done;
5973 if (do_list)
5974 error = list_refs(repo, refname, sort_by_time);
5975 else if (do_delete)
5976 error = delete_ref_by_name(repo, refname);
5977 else if (symref_target)
5978 error = add_symref(repo, refname, symref_target);
5979 else {
5980 if (obj_arg == NULL)
5981 usage_ref();
5982 error = add_ref(repo, refname, obj_arg);
5984 done:
5985 free(refname);
5986 if (repo) {
5987 const struct got_error *close_err = got_repo_close(repo);
5988 if (error == NULL)
5989 error = close_err;
5991 if (worktree)
5992 got_worktree_close(worktree);
5993 free(cwd);
5994 free(repo_path);
5995 return error;
5998 __dead static void
5999 usage_branch(void)
6001 fprintf(stderr,
6002 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6003 "[-n] [name]\n", getprogname());
6004 exit(1);
6007 static const struct got_error *
6008 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6009 struct got_reference *ref)
6011 const struct got_error *err = NULL;
6012 const char *refname, *marker = " ";
6013 char *refstr;
6015 refname = got_ref_get_name(ref);
6016 if (worktree && strcmp(refname,
6017 got_worktree_get_head_ref_name(worktree)) == 0) {
6018 struct got_object_id *id = NULL;
6020 err = got_ref_resolve(&id, repo, ref);
6021 if (err)
6022 return err;
6023 if (got_object_id_cmp(id,
6024 got_worktree_get_base_commit_id(worktree)) == 0)
6025 marker = "* ";
6026 else
6027 marker = "~ ";
6028 free(id);
6031 if (strncmp(refname, "refs/heads/", 11) == 0)
6032 refname += 11;
6033 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6034 refname += 18;
6035 if (strncmp(refname, "refs/remotes/", 13) == 0)
6036 refname += 13;
6038 refstr = got_ref_to_str(ref);
6039 if (refstr == NULL)
6040 return got_error_from_errno("got_ref_to_str");
6042 printf("%s%s: %s\n", marker, refname, refstr);
6043 free(refstr);
6044 return NULL;
6047 static const struct got_error *
6048 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6050 const char *refname;
6052 if (worktree == NULL)
6053 return got_error(GOT_ERR_NOT_WORKTREE);
6055 refname = got_worktree_get_head_ref_name(worktree);
6057 if (strncmp(refname, "refs/heads/", 11) == 0)
6058 refname += 11;
6059 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6060 refname += 18;
6062 printf("%s\n", refname);
6064 return NULL;
6067 static const struct got_error *
6068 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6069 int sort_by_time)
6071 static const struct got_error *err = NULL;
6072 struct got_reflist_head refs;
6073 struct got_reflist_entry *re;
6074 struct got_reference *temp_ref = NULL;
6075 int rebase_in_progress, histedit_in_progress;
6077 TAILQ_INIT(&refs);
6079 if (worktree) {
6080 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6081 worktree);
6082 if (err)
6083 return err;
6085 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6086 worktree);
6087 if (err)
6088 return err;
6090 if (rebase_in_progress || histedit_in_progress) {
6091 err = got_ref_open(&temp_ref, repo,
6092 got_worktree_get_head_ref_name(worktree), 0);
6093 if (err)
6094 return err;
6095 list_branch(repo, worktree, temp_ref);
6096 got_ref_close(temp_ref);
6100 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6101 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6102 repo);
6103 if (err)
6104 return err;
6106 TAILQ_FOREACH(re, &refs, entry)
6107 list_branch(repo, worktree, re->ref);
6109 got_ref_list_free(&refs);
6111 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6112 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6113 repo);
6114 if (err)
6115 return err;
6117 TAILQ_FOREACH(re, &refs, entry)
6118 list_branch(repo, worktree, re->ref);
6120 got_ref_list_free(&refs);
6122 return NULL;
6125 static const struct got_error *
6126 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6127 const char *branch_name)
6129 const struct got_error *err = NULL;
6130 struct got_reference *ref = NULL;
6131 char *refname, *remote_refname = NULL;
6133 if (strncmp(branch_name, "refs/", 5) == 0)
6134 branch_name += 5;
6135 if (strncmp(branch_name, "heads/", 6) == 0)
6136 branch_name += 6;
6137 else if (strncmp(branch_name, "remotes/", 8) == 0)
6138 branch_name += 8;
6140 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6141 return got_error_from_errno("asprintf");
6143 if (asprintf(&remote_refname, "refs/remotes/%s",
6144 branch_name) == -1) {
6145 err = got_error_from_errno("asprintf");
6146 goto done;
6149 err = got_ref_open(&ref, repo, refname, 0);
6150 if (err) {
6151 const struct got_error *err2;
6152 if (err->code != GOT_ERR_NOT_REF)
6153 goto done;
6155 * Keep 'err' intact such that if neither branch exists
6156 * we report "refs/heads" rather than "refs/remotes" in
6157 * our error message.
6159 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6160 if (err2)
6161 goto done;
6162 err = NULL;
6165 if (worktree &&
6166 strcmp(got_worktree_get_head_ref_name(worktree),
6167 got_ref_get_name(ref)) == 0) {
6168 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6169 "will not delete this work tree's current branch");
6170 goto done;
6173 err = delete_ref(repo, ref);
6174 done:
6175 if (ref)
6176 got_ref_close(ref);
6177 free(refname);
6178 free(remote_refname);
6179 return err;
6182 static const struct got_error *
6183 add_branch(struct got_repository *repo, const char *branch_name,
6184 struct got_object_id *base_commit_id)
6186 const struct got_error *err = NULL;
6187 struct got_reference *ref = NULL;
6188 char *base_refname = NULL, *refname = NULL;
6191 * Don't let the user create a branch name with a leading '-'.
6192 * While technically a valid reference name, this case is usually
6193 * an unintended typo.
6195 if (branch_name[0] == '-')
6196 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6198 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6199 branch_name += 11;
6201 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6202 err = got_error_from_errno("asprintf");
6203 goto done;
6206 err = got_ref_open(&ref, repo, refname, 0);
6207 if (err == NULL) {
6208 err = got_error(GOT_ERR_BRANCH_EXISTS);
6209 goto done;
6210 } else if (err->code != GOT_ERR_NOT_REF)
6211 goto done;
6213 err = got_ref_alloc(&ref, refname, base_commit_id);
6214 if (err)
6215 goto done;
6217 err = got_ref_write(ref, repo);
6218 done:
6219 if (ref)
6220 got_ref_close(ref);
6221 free(base_refname);
6222 free(refname);
6223 return err;
6226 static const struct got_error *
6227 cmd_branch(int argc, char *argv[])
6229 const struct got_error *error = NULL;
6230 struct got_repository *repo = NULL;
6231 struct got_worktree *worktree = NULL;
6232 char *cwd = NULL, *repo_path = NULL;
6233 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6234 const char *delref = NULL, *commit_id_arg = NULL;
6235 struct got_reference *ref = NULL;
6236 struct got_pathlist_head paths;
6237 struct got_pathlist_entry *pe;
6238 struct got_object_id *commit_id = NULL;
6239 char *commit_id_str = NULL;
6241 TAILQ_INIT(&paths);
6243 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6244 switch (ch) {
6245 case 'c':
6246 commit_id_arg = optarg;
6247 break;
6248 case 'd':
6249 delref = optarg;
6250 break;
6251 case 'r':
6252 repo_path = realpath(optarg, NULL);
6253 if (repo_path == NULL)
6254 return got_error_from_errno2("realpath",
6255 optarg);
6256 got_path_strip_trailing_slashes(repo_path);
6257 break;
6258 case 'l':
6259 do_list = 1;
6260 break;
6261 case 'n':
6262 do_update = 0;
6263 break;
6264 case 't':
6265 sort_by_time = 1;
6266 break;
6267 default:
6268 usage_branch();
6269 /* NOTREACHED */
6273 if (do_list && delref)
6274 option_conflict('l', 'd');
6275 if (sort_by_time && !do_list)
6276 errx(1, "-t option requires -l option");
6278 argc -= optind;
6279 argv += optind;
6281 if (!do_list && !delref && argc == 0)
6282 do_show = 1;
6284 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6285 errx(1, "-c option can only be used when creating a branch");
6287 if (do_list || delref) {
6288 if (argc > 0)
6289 usage_branch();
6290 } else if (!do_show && argc != 1)
6291 usage_branch();
6293 #ifndef PROFILE
6294 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6295 "sendfd unveil", NULL) == -1)
6296 err(1, "pledge");
6297 #endif
6298 cwd = getcwd(NULL, 0);
6299 if (cwd == NULL) {
6300 error = got_error_from_errno("getcwd");
6301 goto done;
6304 if (repo_path == NULL) {
6305 error = got_worktree_open(&worktree, cwd);
6306 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6307 goto done;
6308 else
6309 error = NULL;
6310 if (worktree) {
6311 repo_path =
6312 strdup(got_worktree_get_repo_path(worktree));
6313 if (repo_path == NULL)
6314 error = got_error_from_errno("strdup");
6315 if (error)
6316 goto done;
6317 } else {
6318 repo_path = strdup(cwd);
6319 if (repo_path == NULL) {
6320 error = got_error_from_errno("strdup");
6321 goto done;
6326 error = got_repo_open(&repo, repo_path, NULL);
6327 if (error != NULL)
6328 goto done;
6330 #ifndef PROFILE
6331 if (do_list || do_show) {
6332 /* Remove "cpath" promise. */
6333 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6334 NULL) == -1)
6335 err(1, "pledge");
6337 #endif
6339 error = apply_unveil(got_repo_get_path(repo), do_list,
6340 worktree ? got_worktree_get_root_path(worktree) : NULL);
6341 if (error)
6342 goto done;
6344 if (do_show)
6345 error = show_current_branch(repo, worktree);
6346 else if (do_list)
6347 error = list_branches(repo, worktree, sort_by_time);
6348 else if (delref)
6349 error = delete_branch(repo, worktree, delref);
6350 else {
6351 struct got_reflist_head refs;
6352 TAILQ_INIT(&refs);
6353 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6354 NULL);
6355 if (error)
6356 goto done;
6357 if (commit_id_arg == NULL)
6358 commit_id_arg = worktree ?
6359 got_worktree_get_head_ref_name(worktree) :
6360 GOT_REF_HEAD;
6361 error = got_repo_match_object_id(&commit_id, NULL,
6362 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6363 got_ref_list_free(&refs);
6364 if (error)
6365 goto done;
6366 error = add_branch(repo, argv[0], commit_id);
6367 if (error)
6368 goto done;
6369 if (worktree && do_update) {
6370 struct got_update_progress_arg upa;
6371 char *branch_refname = NULL;
6373 error = got_object_id_str(&commit_id_str, commit_id);
6374 if (error)
6375 goto done;
6376 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6377 worktree);
6378 if (error)
6379 goto done;
6380 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6381 == -1) {
6382 error = got_error_from_errno("asprintf");
6383 goto done;
6385 error = got_ref_open(&ref, repo, branch_refname, 0);
6386 free(branch_refname);
6387 if (error)
6388 goto done;
6389 error = switch_head_ref(ref, commit_id, worktree,
6390 repo);
6391 if (error)
6392 goto done;
6393 error = got_worktree_set_base_commit_id(worktree, repo,
6394 commit_id);
6395 if (error)
6396 goto done;
6397 memset(&upa, 0, sizeof(upa));
6398 error = got_worktree_checkout_files(worktree, &paths,
6399 repo, update_progress, &upa, check_cancelled,
6400 NULL);
6401 if (error)
6402 goto done;
6403 if (upa.did_something) {
6404 printf("Updated to %s: %s\n",
6405 got_worktree_get_head_ref_name(worktree),
6406 commit_id_str);
6408 print_update_progress_stats(&upa);
6411 done:
6412 if (ref)
6413 got_ref_close(ref);
6414 if (repo) {
6415 const struct got_error *close_err = got_repo_close(repo);
6416 if (error == NULL)
6417 error = close_err;
6419 if (worktree)
6420 got_worktree_close(worktree);
6421 free(cwd);
6422 free(repo_path);
6423 free(commit_id);
6424 free(commit_id_str);
6425 TAILQ_FOREACH(pe, &paths, entry)
6426 free((char *)pe->path);
6427 got_pathlist_free(&paths);
6428 return error;
6432 __dead static void
6433 usage_tag(void)
6435 fprintf(stderr,
6436 "usage: %s tag [-c commit] [-r repository] [-l] "
6437 "[-m message] name\n", getprogname());
6438 exit(1);
6441 #if 0
6442 static const struct got_error *
6443 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6445 const struct got_error *err = NULL;
6446 struct got_reflist_entry *re, *se, *new;
6447 struct got_object_id *re_id, *se_id;
6448 struct got_tag_object *re_tag, *se_tag;
6449 time_t re_time, se_time;
6451 STAILQ_FOREACH(re, tags, entry) {
6452 se = STAILQ_FIRST(sorted);
6453 if (se == NULL) {
6454 err = got_reflist_entry_dup(&new, re);
6455 if (err)
6456 return err;
6457 STAILQ_INSERT_HEAD(sorted, new, entry);
6458 continue;
6459 } else {
6460 err = got_ref_resolve(&re_id, repo, re->ref);
6461 if (err)
6462 break;
6463 err = got_object_open_as_tag(&re_tag, repo, re_id);
6464 free(re_id);
6465 if (err)
6466 break;
6467 re_time = got_object_tag_get_tagger_time(re_tag);
6468 got_object_tag_close(re_tag);
6471 while (se) {
6472 err = got_ref_resolve(&se_id, repo, re->ref);
6473 if (err)
6474 break;
6475 err = got_object_open_as_tag(&se_tag, repo, se_id);
6476 free(se_id);
6477 if (err)
6478 break;
6479 se_time = got_object_tag_get_tagger_time(se_tag);
6480 got_object_tag_close(se_tag);
6482 if (se_time > re_time) {
6483 err = got_reflist_entry_dup(&new, re);
6484 if (err)
6485 return err;
6486 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6487 break;
6489 se = STAILQ_NEXT(se, entry);
6490 continue;
6493 done:
6494 return err;
6496 #endif
6498 static const struct got_error *
6499 list_tags(struct got_repository *repo)
6501 static const struct got_error *err = NULL;
6502 struct got_reflist_head refs;
6503 struct got_reflist_entry *re;
6505 TAILQ_INIT(&refs);
6507 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6508 if (err)
6509 return err;
6511 TAILQ_FOREACH(re, &refs, entry) {
6512 const char *refname;
6513 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6514 char datebuf[26];
6515 const char *tagger;
6516 time_t tagger_time;
6517 struct got_object_id *id;
6518 struct got_tag_object *tag;
6519 struct got_commit_object *commit = NULL;
6521 refname = got_ref_get_name(re->ref);
6522 if (strncmp(refname, "refs/tags/", 10) != 0)
6523 continue;
6524 refname += 10;
6525 refstr = got_ref_to_str(re->ref);
6526 if (refstr == NULL) {
6527 err = got_error_from_errno("got_ref_to_str");
6528 break;
6530 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6531 free(refstr);
6533 err = got_ref_resolve(&id, repo, re->ref);
6534 if (err)
6535 break;
6536 err = got_object_open_as_tag(&tag, repo, id);
6537 if (err) {
6538 if (err->code != GOT_ERR_OBJ_TYPE) {
6539 free(id);
6540 break;
6542 /* "lightweight" tag */
6543 err = got_object_open_as_commit(&commit, repo, id);
6544 if (err) {
6545 free(id);
6546 break;
6548 tagger = got_object_commit_get_committer(commit);
6549 tagger_time =
6550 got_object_commit_get_committer_time(commit);
6551 err = got_object_id_str(&id_str, id);
6552 free(id);
6553 if (err)
6554 break;
6555 } else {
6556 free(id);
6557 tagger = got_object_tag_get_tagger(tag);
6558 tagger_time = got_object_tag_get_tagger_time(tag);
6559 err = got_object_id_str(&id_str,
6560 got_object_tag_get_object_id(tag));
6561 if (err)
6562 break;
6564 printf("from: %s\n", tagger);
6565 datestr = get_datestr(&tagger_time, datebuf);
6566 if (datestr)
6567 printf("date: %s UTC\n", datestr);
6568 if (commit)
6569 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6570 else {
6571 switch (got_object_tag_get_object_type(tag)) {
6572 case GOT_OBJ_TYPE_BLOB:
6573 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6574 id_str);
6575 break;
6576 case GOT_OBJ_TYPE_TREE:
6577 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6578 id_str);
6579 break;
6580 case GOT_OBJ_TYPE_COMMIT:
6581 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6582 id_str);
6583 break;
6584 case GOT_OBJ_TYPE_TAG:
6585 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6586 id_str);
6587 break;
6588 default:
6589 break;
6592 free(id_str);
6593 if (commit) {
6594 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6595 if (err)
6596 break;
6597 got_object_commit_close(commit);
6598 } else {
6599 tagmsg0 = strdup(got_object_tag_get_message(tag));
6600 got_object_tag_close(tag);
6601 if (tagmsg0 == NULL) {
6602 err = got_error_from_errno("strdup");
6603 break;
6607 tagmsg = tagmsg0;
6608 do {
6609 line = strsep(&tagmsg, "\n");
6610 if (line)
6611 printf(" %s\n", line);
6612 } while (line);
6613 free(tagmsg0);
6616 got_ref_list_free(&refs);
6617 return NULL;
6620 static const struct got_error *
6621 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6622 const char *tag_name, const char *repo_path)
6624 const struct got_error *err = NULL;
6625 char *template = NULL, *initial_content = NULL;
6626 char *editor = NULL;
6627 int initial_content_len;
6628 int fd = -1;
6630 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6631 err = got_error_from_errno("asprintf");
6632 goto done;
6635 initial_content_len = asprintf(&initial_content,
6636 "\n# tagging commit %s as %s\n",
6637 commit_id_str, tag_name);
6638 if (initial_content_len == -1) {
6639 err = got_error_from_errno("asprintf");
6640 goto done;
6643 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6644 if (err)
6645 goto done;
6647 if (write(fd, initial_content, initial_content_len) == -1) {
6648 err = got_error_from_errno2("write", *tagmsg_path);
6649 goto done;
6652 err = get_editor(&editor);
6653 if (err)
6654 goto done;
6655 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6656 initial_content_len, 1);
6657 done:
6658 free(initial_content);
6659 free(template);
6660 free(editor);
6662 if (fd != -1 && close(fd) == -1 && err == NULL)
6663 err = got_error_from_errno2("close", *tagmsg_path);
6665 /* Editor is done; we can now apply unveil(2) */
6666 if (err == NULL)
6667 err = apply_unveil(repo_path, 0, NULL);
6668 if (err) {
6669 free(*tagmsg);
6670 *tagmsg = NULL;
6672 return err;
6675 static const struct got_error *
6676 add_tag(struct got_repository *repo, const char *tagger,
6677 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6679 const struct got_error *err = NULL;
6680 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6681 char *label = NULL, *commit_id_str = NULL;
6682 struct got_reference *ref = NULL;
6683 char *refname = NULL, *tagmsg = NULL;
6684 char *tagmsg_path = NULL, *tag_id_str = NULL;
6685 int preserve_tagmsg = 0;
6686 struct got_reflist_head refs;
6688 TAILQ_INIT(&refs);
6691 * Don't let the user create a tag name with a leading '-'.
6692 * While technically a valid reference name, this case is usually
6693 * an unintended typo.
6695 if (tag_name[0] == '-')
6696 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6698 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6699 if (err)
6700 goto done;
6702 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6703 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6704 if (err)
6705 goto done;
6707 err = got_object_id_str(&commit_id_str, commit_id);
6708 if (err)
6709 goto done;
6711 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6712 refname = strdup(tag_name);
6713 if (refname == NULL) {
6714 err = got_error_from_errno("strdup");
6715 goto done;
6717 tag_name += 10;
6718 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6719 err = got_error_from_errno("asprintf");
6720 goto done;
6723 err = got_ref_open(&ref, repo, refname, 0);
6724 if (err == NULL) {
6725 err = got_error(GOT_ERR_TAG_EXISTS);
6726 goto done;
6727 } else if (err->code != GOT_ERR_NOT_REF)
6728 goto done;
6730 if (tagmsg_arg == NULL) {
6731 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6732 tag_name, got_repo_get_path(repo));
6733 if (err) {
6734 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6735 tagmsg_path != NULL)
6736 preserve_tagmsg = 1;
6737 goto done;
6741 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6742 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6743 if (err) {
6744 if (tagmsg_path)
6745 preserve_tagmsg = 1;
6746 goto done;
6749 err = got_ref_alloc(&ref, refname, tag_id);
6750 if (err) {
6751 if (tagmsg_path)
6752 preserve_tagmsg = 1;
6753 goto done;
6756 err = got_ref_write(ref, repo);
6757 if (err) {
6758 if (tagmsg_path)
6759 preserve_tagmsg = 1;
6760 goto done;
6763 err = got_object_id_str(&tag_id_str, tag_id);
6764 if (err) {
6765 if (tagmsg_path)
6766 preserve_tagmsg = 1;
6767 goto done;
6769 printf("Created tag %s\n", tag_id_str);
6770 done:
6771 if (preserve_tagmsg) {
6772 fprintf(stderr, "%s: tag message preserved in %s\n",
6773 getprogname(), tagmsg_path);
6774 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6775 err = got_error_from_errno2("unlink", tagmsg_path);
6776 free(tag_id_str);
6777 if (ref)
6778 got_ref_close(ref);
6779 free(commit_id);
6780 free(commit_id_str);
6781 free(refname);
6782 free(tagmsg);
6783 free(tagmsg_path);
6784 got_ref_list_free(&refs);
6785 return err;
6788 static const struct got_error *
6789 cmd_tag(int argc, char *argv[])
6791 const struct got_error *error = NULL;
6792 struct got_repository *repo = NULL;
6793 struct got_worktree *worktree = NULL;
6794 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6795 char *gitconfig_path = NULL, *tagger = NULL;
6796 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6797 int ch, do_list = 0;
6799 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6800 switch (ch) {
6801 case 'c':
6802 commit_id_arg = optarg;
6803 break;
6804 case 'm':
6805 tagmsg = optarg;
6806 break;
6807 case 'r':
6808 repo_path = realpath(optarg, NULL);
6809 if (repo_path == NULL)
6810 return got_error_from_errno2("realpath",
6811 optarg);
6812 got_path_strip_trailing_slashes(repo_path);
6813 break;
6814 case 'l':
6815 do_list = 1;
6816 break;
6817 default:
6818 usage_tag();
6819 /* NOTREACHED */
6823 argc -= optind;
6824 argv += optind;
6826 if (do_list) {
6827 if (commit_id_arg != NULL)
6828 errx(1,
6829 "-c option can only be used when creating a tag");
6830 if (tagmsg)
6831 option_conflict('l', 'm');
6832 if (argc > 0)
6833 usage_tag();
6834 } else if (argc != 1)
6835 usage_tag();
6837 tag_name = argv[0];
6839 #ifndef PROFILE
6840 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6841 "sendfd unveil", NULL) == -1)
6842 err(1, "pledge");
6843 #endif
6844 cwd = getcwd(NULL, 0);
6845 if (cwd == NULL) {
6846 error = got_error_from_errno("getcwd");
6847 goto done;
6850 if (repo_path == NULL) {
6851 error = got_worktree_open(&worktree, cwd);
6852 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6853 goto done;
6854 else
6855 error = NULL;
6856 if (worktree) {
6857 repo_path =
6858 strdup(got_worktree_get_repo_path(worktree));
6859 if (repo_path == NULL)
6860 error = got_error_from_errno("strdup");
6861 if (error)
6862 goto done;
6863 } else {
6864 repo_path = strdup(cwd);
6865 if (repo_path == NULL) {
6866 error = got_error_from_errno("strdup");
6867 goto done;
6872 if (do_list) {
6873 if (worktree) {
6874 /* Release work tree lock. */
6875 got_worktree_close(worktree);
6876 worktree = NULL;
6878 error = got_repo_open(&repo, repo_path, NULL);
6879 if (error != NULL)
6880 goto done;
6881 #ifndef PROFILE
6882 /* Remove "cpath" promise. */
6883 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6884 NULL) == -1)
6885 err(1, "pledge");
6886 #endif
6887 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6888 if (error)
6889 goto done;
6890 error = list_tags(repo);
6891 } else {
6892 error = get_gitconfig_path(&gitconfig_path);
6893 if (error)
6894 goto done;
6895 error = got_repo_open(&repo, repo_path, gitconfig_path);
6896 if (error != NULL)
6897 goto done;
6899 error = get_author(&tagger, repo, worktree);
6900 if (error)
6901 goto done;
6902 if (worktree) {
6903 /* Release work tree lock. */
6904 got_worktree_close(worktree);
6905 worktree = NULL;
6908 if (tagmsg) {
6909 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6910 if (error)
6911 goto done;
6914 if (commit_id_arg == NULL) {
6915 struct got_reference *head_ref;
6916 struct got_object_id *commit_id;
6917 error = got_ref_open(&head_ref, repo,
6918 worktree ? got_worktree_get_head_ref_name(worktree)
6919 : GOT_REF_HEAD, 0);
6920 if (error)
6921 goto done;
6922 error = got_ref_resolve(&commit_id, repo, head_ref);
6923 got_ref_close(head_ref);
6924 if (error)
6925 goto done;
6926 error = got_object_id_str(&commit_id_str, commit_id);
6927 free(commit_id);
6928 if (error)
6929 goto done;
6932 error = add_tag(repo, tagger, tag_name,
6933 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6935 done:
6936 if (repo) {
6937 const struct got_error *close_err = got_repo_close(repo);
6938 if (error == NULL)
6939 error = close_err;
6941 if (worktree)
6942 got_worktree_close(worktree);
6943 free(cwd);
6944 free(repo_path);
6945 free(gitconfig_path);
6946 free(commit_id_str);
6947 free(tagger);
6948 return error;
6951 __dead static void
6952 usage_add(void)
6954 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6955 getprogname());
6956 exit(1);
6959 static const struct got_error *
6960 add_progress(void *arg, unsigned char status, const char *path)
6962 while (path[0] == '/')
6963 path++;
6964 printf("%c %s\n", status, path);
6965 return NULL;
6968 static const struct got_error *
6969 cmd_add(int argc, char *argv[])
6971 const struct got_error *error = NULL;
6972 struct got_repository *repo = NULL;
6973 struct got_worktree *worktree = NULL;
6974 char *cwd = NULL;
6975 struct got_pathlist_head paths;
6976 struct got_pathlist_entry *pe;
6977 int ch, can_recurse = 0, no_ignores = 0;
6979 TAILQ_INIT(&paths);
6981 while ((ch = getopt(argc, argv, "IR")) != -1) {
6982 switch (ch) {
6983 case 'I':
6984 no_ignores = 1;
6985 break;
6986 case 'R':
6987 can_recurse = 1;
6988 break;
6989 default:
6990 usage_add();
6991 /* NOTREACHED */
6995 argc -= optind;
6996 argv += optind;
6998 #ifndef PROFILE
6999 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7000 NULL) == -1)
7001 err(1, "pledge");
7002 #endif
7003 if (argc < 1)
7004 usage_add();
7006 cwd = getcwd(NULL, 0);
7007 if (cwd == NULL) {
7008 error = got_error_from_errno("getcwd");
7009 goto done;
7012 error = got_worktree_open(&worktree, cwd);
7013 if (error) {
7014 if (error->code == GOT_ERR_NOT_WORKTREE)
7015 error = wrap_not_worktree_error(error, "add", cwd);
7016 goto done;
7019 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7020 NULL);
7021 if (error != NULL)
7022 goto done;
7024 error = apply_unveil(got_repo_get_path(repo), 1,
7025 got_worktree_get_root_path(worktree));
7026 if (error)
7027 goto done;
7029 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7030 if (error)
7031 goto done;
7033 if (!can_recurse) {
7034 char *ondisk_path;
7035 struct stat sb;
7036 TAILQ_FOREACH(pe, &paths, entry) {
7037 if (asprintf(&ondisk_path, "%s/%s",
7038 got_worktree_get_root_path(worktree),
7039 pe->path) == -1) {
7040 error = got_error_from_errno("asprintf");
7041 goto done;
7043 if (lstat(ondisk_path, &sb) == -1) {
7044 if (errno == ENOENT) {
7045 free(ondisk_path);
7046 continue;
7048 error = got_error_from_errno2("lstat",
7049 ondisk_path);
7050 free(ondisk_path);
7051 goto done;
7053 free(ondisk_path);
7054 if (S_ISDIR(sb.st_mode)) {
7055 error = got_error_msg(GOT_ERR_BAD_PATH,
7056 "adding directories requires -R option");
7057 goto done;
7062 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7063 NULL, repo, no_ignores);
7064 done:
7065 if (repo) {
7066 const struct got_error *close_err = got_repo_close(repo);
7067 if (error == NULL)
7068 error = close_err;
7070 if (worktree)
7071 got_worktree_close(worktree);
7072 TAILQ_FOREACH(pe, &paths, entry)
7073 free((char *)pe->path);
7074 got_pathlist_free(&paths);
7075 free(cwd);
7076 return error;
7079 __dead static void
7080 usage_remove(void)
7082 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7083 "path ...\n", getprogname());
7084 exit(1);
7087 static const struct got_error *
7088 print_remove_status(void *arg, unsigned char status,
7089 unsigned char staged_status, const char *path)
7091 while (path[0] == '/')
7092 path++;
7093 if (status == GOT_STATUS_NONEXISTENT)
7094 return NULL;
7095 if (status == staged_status && (status == GOT_STATUS_DELETE))
7096 status = GOT_STATUS_NO_CHANGE;
7097 printf("%c%c %s\n", status, staged_status, path);
7098 return NULL;
7101 static const struct got_error *
7102 cmd_remove(int argc, char *argv[])
7104 const struct got_error *error = NULL;
7105 struct got_worktree *worktree = NULL;
7106 struct got_repository *repo = NULL;
7107 const char *status_codes = NULL;
7108 char *cwd = NULL;
7109 struct got_pathlist_head paths;
7110 struct got_pathlist_entry *pe;
7111 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7112 int ignore_missing_paths = 0;
7114 TAILQ_INIT(&paths);
7116 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7117 switch (ch) {
7118 case 'f':
7119 delete_local_mods = 1;
7120 ignore_missing_paths = 1;
7121 break;
7122 case 'k':
7123 keep_on_disk = 1;
7124 break;
7125 case 'R':
7126 can_recurse = 1;
7127 break;
7128 case 's':
7129 for (i = 0; i < strlen(optarg); i++) {
7130 switch (optarg[i]) {
7131 case GOT_STATUS_MODIFY:
7132 delete_local_mods = 1;
7133 break;
7134 case GOT_STATUS_MISSING:
7135 ignore_missing_paths = 1;
7136 break;
7137 default:
7138 errx(1, "invalid status code '%c'",
7139 optarg[i]);
7142 status_codes = optarg;
7143 break;
7144 default:
7145 usage_remove();
7146 /* NOTREACHED */
7150 argc -= optind;
7151 argv += optind;
7153 #ifndef PROFILE
7154 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7155 NULL) == -1)
7156 err(1, "pledge");
7157 #endif
7158 if (argc < 1)
7159 usage_remove();
7161 cwd = getcwd(NULL, 0);
7162 if (cwd == NULL) {
7163 error = got_error_from_errno("getcwd");
7164 goto done;
7166 error = got_worktree_open(&worktree, cwd);
7167 if (error) {
7168 if (error->code == GOT_ERR_NOT_WORKTREE)
7169 error = wrap_not_worktree_error(error, "remove", cwd);
7170 goto done;
7173 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7174 NULL);
7175 if (error)
7176 goto done;
7178 error = apply_unveil(got_repo_get_path(repo), 1,
7179 got_worktree_get_root_path(worktree));
7180 if (error)
7181 goto done;
7183 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7184 if (error)
7185 goto done;
7187 if (!can_recurse) {
7188 char *ondisk_path;
7189 struct stat sb;
7190 TAILQ_FOREACH(pe, &paths, entry) {
7191 if (asprintf(&ondisk_path, "%s/%s",
7192 got_worktree_get_root_path(worktree),
7193 pe->path) == -1) {
7194 error = got_error_from_errno("asprintf");
7195 goto done;
7197 if (lstat(ondisk_path, &sb) == -1) {
7198 if (errno == ENOENT) {
7199 free(ondisk_path);
7200 continue;
7202 error = got_error_from_errno2("lstat",
7203 ondisk_path);
7204 free(ondisk_path);
7205 goto done;
7207 free(ondisk_path);
7208 if (S_ISDIR(sb.st_mode)) {
7209 error = got_error_msg(GOT_ERR_BAD_PATH,
7210 "removing directories requires -R option");
7211 goto done;
7216 error = got_worktree_schedule_delete(worktree, &paths,
7217 delete_local_mods, status_codes, print_remove_status, NULL,
7218 repo, keep_on_disk, ignore_missing_paths);
7219 done:
7220 if (repo) {
7221 const struct got_error *close_err = got_repo_close(repo);
7222 if (error == NULL)
7223 error = close_err;
7225 if (worktree)
7226 got_worktree_close(worktree);
7227 TAILQ_FOREACH(pe, &paths, entry)
7228 free((char *)pe->path);
7229 got_pathlist_free(&paths);
7230 free(cwd);
7231 return error;
7234 __dead static void
7235 usage_patch(void)
7237 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7238 "[-R] [patchfile]\n", getprogname());
7239 exit(1);
7242 static const struct got_error *
7243 patch_from_stdin(int *patchfd)
7245 const struct got_error *err = NULL;
7246 ssize_t r;
7247 char *path, buf[BUFSIZ];
7248 sig_t sighup, sigint, sigquit;
7250 err = got_opentemp_named_fd(&path, patchfd,
7251 GOT_TMPDIR_STR "/got-patch");
7252 if (err)
7253 return err;
7254 unlink(path);
7255 free(path);
7257 sighup = signal(SIGHUP, SIG_DFL);
7258 sigint = signal(SIGINT, SIG_DFL);
7259 sigquit = signal(SIGQUIT, SIG_DFL);
7261 for (;;) {
7262 r = read(0, buf, sizeof(buf));
7263 if (r == -1) {
7264 err = got_error_from_errno("read");
7265 break;
7267 if (r == 0)
7268 break;
7269 if (write(*patchfd, buf, r) == -1) {
7270 err = got_error_from_errno("write");
7271 break;
7275 signal(SIGHUP, sighup);
7276 signal(SIGINT, sigint);
7277 signal(SIGQUIT, sigquit);
7279 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7280 err = got_error_from_errno("lseek");
7282 if (err != NULL) {
7283 close(*patchfd);
7284 *patchfd = -1;
7287 return err;
7290 static const struct got_error *
7291 patch_progress(void *arg, const char *old, const char *new,
7292 unsigned char status, const struct got_error *error, long old_from,
7293 long old_lines, long new_from, long new_lines, long offset,
7294 const struct got_error *hunk_err)
7296 const char *path = new == NULL ? old : new;
7298 while (*path == '/')
7299 path++;
7301 if (status != 0)
7302 printf("%c %s\n", status, path);
7304 if (error != NULL)
7305 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7307 if (offset != 0 || hunk_err != NULL) {
7308 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7309 old_lines, new_from, new_lines);
7310 if (hunk_err != NULL)
7311 printf("%s\n", hunk_err->msg);
7312 else
7313 printf("applied with offset %ld\n", offset);
7316 return NULL;
7319 static const struct got_error *
7320 cmd_patch(int argc, char *argv[])
7322 const struct got_error *error = NULL, *close_error = NULL;
7323 struct got_worktree *worktree = NULL;
7324 struct got_repository *repo = NULL;
7325 const char *errstr;
7326 char *cwd = NULL;
7327 int ch, nop = 0, strip = -1, reverse = 0;
7328 int patchfd;
7330 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7331 switch (ch) {
7332 case 'n':
7333 nop = 1;
7334 break;
7335 case 'p':
7336 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7337 if (errstr != NULL)
7338 errx(1, "pathname strip count is %s: %s",
7339 errstr, optarg);
7340 break;
7341 case 'R':
7342 reverse = 1;
7343 break;
7344 default:
7345 usage_patch();
7346 /* NOTREACHED */
7350 argc -= optind;
7351 argv += optind;
7353 if (argc == 0) {
7354 error = patch_from_stdin(&patchfd);
7355 if (error)
7356 return error;
7357 } else if (argc == 1) {
7358 patchfd = open(argv[0], O_RDONLY);
7359 if (patchfd == -1) {
7360 error = got_error_from_errno2("open", argv[0]);
7361 return error;
7363 } else
7364 usage_patch();
7366 if ((cwd = getcwd(NULL, 0)) == NULL) {
7367 error = got_error_from_errno("getcwd");
7368 goto done;
7371 error = got_worktree_open(&worktree, cwd);
7372 if (error != NULL)
7373 goto done;
7375 const char *repo_path = got_worktree_get_repo_path(worktree);
7376 error = got_repo_open(&repo, repo_path, NULL);
7377 if (error != NULL)
7378 goto done;
7380 error = apply_unveil(got_repo_get_path(repo), 0,
7381 got_worktree_get_root_path(worktree));
7382 if (error != NULL)
7383 goto done;
7385 #ifndef PROFILE
7386 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7387 NULL) == -1)
7388 err(1, "pledge");
7389 #endif
7391 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7392 &patch_progress, NULL, check_cancelled, NULL);
7394 done:
7395 if (repo) {
7396 close_error = got_repo_close(repo);
7397 if (error == NULL)
7398 error = close_error;
7400 if (worktree != NULL) {
7401 close_error = got_worktree_close(worktree);
7402 if (error == NULL)
7403 error = close_error;
7405 free(cwd);
7406 return error;
7409 __dead static void
7410 usage_revert(void)
7412 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7413 "path ...\n", getprogname());
7414 exit(1);
7417 static const struct got_error *
7418 revert_progress(void *arg, unsigned char status, const char *path)
7420 if (status == GOT_STATUS_UNVERSIONED)
7421 return NULL;
7423 while (path[0] == '/')
7424 path++;
7425 printf("%c %s\n", status, path);
7426 return NULL;
7429 struct choose_patch_arg {
7430 FILE *patch_script_file;
7431 const char *action;
7434 static const struct got_error *
7435 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7436 int nchanges, const char *action)
7438 char *line = NULL;
7439 size_t linesize = 0;
7440 ssize_t linelen;
7442 switch (status) {
7443 case GOT_STATUS_ADD:
7444 printf("A %s\n%s this addition? [y/n] ", path, action);
7445 break;
7446 case GOT_STATUS_DELETE:
7447 printf("D %s\n%s this deletion? [y/n] ", path, action);
7448 break;
7449 case GOT_STATUS_MODIFY:
7450 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7451 return got_error_from_errno("fseek");
7452 printf(GOT_COMMIT_SEP_STR);
7453 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7454 printf("%s", line);
7455 if (ferror(patch_file))
7456 return got_error_from_errno("getline");
7457 printf(GOT_COMMIT_SEP_STR);
7458 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7459 path, n, nchanges, action);
7460 break;
7461 default:
7462 return got_error_path(path, GOT_ERR_FILE_STATUS);
7465 return NULL;
7468 static const struct got_error *
7469 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7470 FILE *patch_file, int n, int nchanges)
7472 const struct got_error *err = NULL;
7473 char *line = NULL;
7474 size_t linesize = 0;
7475 ssize_t linelen;
7476 int resp = ' ';
7477 struct choose_patch_arg *a = arg;
7479 *choice = GOT_PATCH_CHOICE_NONE;
7481 if (a->patch_script_file) {
7482 char *nl;
7483 err = show_change(status, path, patch_file, n, nchanges,
7484 a->action);
7485 if (err)
7486 return err;
7487 linelen = getline(&line, &linesize, a->patch_script_file);
7488 if (linelen == -1) {
7489 if (ferror(a->patch_script_file))
7490 return got_error_from_errno("getline");
7491 return NULL;
7493 nl = strchr(line, '\n');
7494 if (nl)
7495 *nl = '\0';
7496 if (strcmp(line, "y") == 0) {
7497 *choice = GOT_PATCH_CHOICE_YES;
7498 printf("y\n");
7499 } else if (strcmp(line, "n") == 0) {
7500 *choice = GOT_PATCH_CHOICE_NO;
7501 printf("n\n");
7502 } else if (strcmp(line, "q") == 0 &&
7503 status == GOT_STATUS_MODIFY) {
7504 *choice = GOT_PATCH_CHOICE_QUIT;
7505 printf("q\n");
7506 } else
7507 printf("invalid response '%s'\n", line);
7508 free(line);
7509 return NULL;
7512 while (resp != 'y' && resp != 'n' && resp != 'q') {
7513 err = show_change(status, path, patch_file, n, nchanges,
7514 a->action);
7515 if (err)
7516 return err;
7517 resp = getchar();
7518 if (resp == '\n')
7519 resp = getchar();
7520 if (status == GOT_STATUS_MODIFY) {
7521 if (resp != 'y' && resp != 'n' && resp != 'q') {
7522 printf("invalid response '%c'\n", resp);
7523 resp = ' ';
7525 } else if (resp != 'y' && resp != 'n') {
7526 printf("invalid response '%c'\n", resp);
7527 resp = ' ';
7531 if (resp == 'y')
7532 *choice = GOT_PATCH_CHOICE_YES;
7533 else if (resp == 'n')
7534 *choice = GOT_PATCH_CHOICE_NO;
7535 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7536 *choice = GOT_PATCH_CHOICE_QUIT;
7538 return NULL;
7541 static const struct got_error *
7542 cmd_revert(int argc, char *argv[])
7544 const struct got_error *error = NULL;
7545 struct got_worktree *worktree = NULL;
7546 struct got_repository *repo = NULL;
7547 char *cwd = NULL, *path = NULL;
7548 struct got_pathlist_head paths;
7549 struct got_pathlist_entry *pe;
7550 int ch, can_recurse = 0, pflag = 0;
7551 FILE *patch_script_file = NULL;
7552 const char *patch_script_path = NULL;
7553 struct choose_patch_arg cpa;
7555 TAILQ_INIT(&paths);
7557 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7558 switch (ch) {
7559 case 'p':
7560 pflag = 1;
7561 break;
7562 case 'F':
7563 patch_script_path = optarg;
7564 break;
7565 case 'R':
7566 can_recurse = 1;
7567 break;
7568 default:
7569 usage_revert();
7570 /* NOTREACHED */
7574 argc -= optind;
7575 argv += optind;
7577 #ifndef PROFILE
7578 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7579 "unveil", NULL) == -1)
7580 err(1, "pledge");
7581 #endif
7582 if (argc < 1)
7583 usage_revert();
7584 if (patch_script_path && !pflag)
7585 errx(1, "-F option can only be used together with -p option");
7587 cwd = getcwd(NULL, 0);
7588 if (cwd == NULL) {
7589 error = got_error_from_errno("getcwd");
7590 goto done;
7592 error = got_worktree_open(&worktree, cwd);
7593 if (error) {
7594 if (error->code == GOT_ERR_NOT_WORKTREE)
7595 error = wrap_not_worktree_error(error, "revert", cwd);
7596 goto done;
7599 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7600 NULL);
7601 if (error != NULL)
7602 goto done;
7604 if (patch_script_path) {
7605 patch_script_file = fopen(patch_script_path, "re");
7606 if (patch_script_file == NULL) {
7607 error = got_error_from_errno2("fopen",
7608 patch_script_path);
7609 goto done;
7612 error = apply_unveil(got_repo_get_path(repo), 1,
7613 got_worktree_get_root_path(worktree));
7614 if (error)
7615 goto done;
7617 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7618 if (error)
7619 goto done;
7621 if (!can_recurse) {
7622 char *ondisk_path;
7623 struct stat sb;
7624 TAILQ_FOREACH(pe, &paths, entry) {
7625 if (asprintf(&ondisk_path, "%s/%s",
7626 got_worktree_get_root_path(worktree),
7627 pe->path) == -1) {
7628 error = got_error_from_errno("asprintf");
7629 goto done;
7631 if (lstat(ondisk_path, &sb) == -1) {
7632 if (errno == ENOENT) {
7633 free(ondisk_path);
7634 continue;
7636 error = got_error_from_errno2("lstat",
7637 ondisk_path);
7638 free(ondisk_path);
7639 goto done;
7641 free(ondisk_path);
7642 if (S_ISDIR(sb.st_mode)) {
7643 error = got_error_msg(GOT_ERR_BAD_PATH,
7644 "reverting directories requires -R option");
7645 goto done;
7650 cpa.patch_script_file = patch_script_file;
7651 cpa.action = "revert";
7652 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7653 pflag ? choose_patch : NULL, &cpa, repo);
7654 done:
7655 if (patch_script_file && fclose(patch_script_file) == EOF &&
7656 error == NULL)
7657 error = got_error_from_errno2("fclose", patch_script_path);
7658 if (repo) {
7659 const struct got_error *close_err = got_repo_close(repo);
7660 if (error == NULL)
7661 error = close_err;
7663 if (worktree)
7664 got_worktree_close(worktree);
7665 free(path);
7666 free(cwd);
7667 return error;
7670 __dead static void
7671 usage_commit(void)
7673 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7674 "[path ...]\n", getprogname());
7675 exit(1);
7678 struct collect_commit_logmsg_arg {
7679 const char *cmdline_log;
7680 const char *prepared_log;
7681 int non_interactive;
7682 const char *editor;
7683 const char *worktree_path;
7684 const char *branch_name;
7685 const char *repo_path;
7686 char *logmsg_path;
7690 static const struct got_error *
7691 read_prepared_logmsg(char **logmsg, const char *path)
7693 const struct got_error *err = NULL;
7694 FILE *f = NULL;
7695 struct stat sb;
7696 size_t r;
7698 *logmsg = NULL;
7699 memset(&sb, 0, sizeof(sb));
7701 f = fopen(path, "re");
7702 if (f == NULL)
7703 return got_error_from_errno2("fopen", path);
7705 if (fstat(fileno(f), &sb) == -1) {
7706 err = got_error_from_errno2("fstat", path);
7707 goto done;
7709 if (sb.st_size == 0) {
7710 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7711 goto done;
7714 *logmsg = malloc(sb.st_size + 1);
7715 if (*logmsg == NULL) {
7716 err = got_error_from_errno("malloc");
7717 goto done;
7720 r = fread(*logmsg, 1, sb.st_size, f);
7721 if (r != sb.st_size) {
7722 if (ferror(f))
7723 err = got_error_from_errno2("fread", path);
7724 else
7725 err = got_error(GOT_ERR_IO);
7726 goto done;
7728 (*logmsg)[sb.st_size] = '\0';
7729 done:
7730 if (fclose(f) == EOF && err == NULL)
7731 err = got_error_from_errno2("fclose", path);
7732 if (err) {
7733 free(*logmsg);
7734 *logmsg = NULL;
7736 return err;
7740 static const struct got_error *
7741 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7742 void *arg)
7744 char *initial_content = NULL;
7745 struct got_pathlist_entry *pe;
7746 const struct got_error *err = NULL;
7747 char *template = NULL;
7748 struct collect_commit_logmsg_arg *a = arg;
7749 int initial_content_len;
7750 int fd = -1;
7751 size_t len;
7753 /* if a message was specified on the command line, just use it */
7754 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7755 len = strlen(a->cmdline_log) + 1;
7756 *logmsg = malloc(len + 1);
7757 if (*logmsg == NULL)
7758 return got_error_from_errno("malloc");
7759 strlcpy(*logmsg, a->cmdline_log, len);
7760 return NULL;
7761 } else if (a->prepared_log != NULL && a->non_interactive)
7762 return read_prepared_logmsg(logmsg, a->prepared_log);
7764 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7765 return got_error_from_errno("asprintf");
7767 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7768 if (err)
7769 goto done;
7771 if (a->prepared_log) {
7772 char *msg;
7773 err = read_prepared_logmsg(&msg, a->prepared_log);
7774 if (err)
7775 goto done;
7776 if (write(fd, msg, strlen(msg)) == -1) {
7777 err = got_error_from_errno2("write", a->logmsg_path);
7778 free(msg);
7779 goto done;
7781 free(msg);
7784 initial_content_len = asprintf(&initial_content,
7785 "\n# changes to be committed on branch %s:\n",
7786 a->branch_name);
7787 if (initial_content_len == -1) {
7788 err = got_error_from_errno("asprintf");
7789 goto done;
7792 if (write(fd, initial_content, initial_content_len) == -1) {
7793 err = got_error_from_errno2("write", a->logmsg_path);
7794 goto done;
7797 TAILQ_FOREACH(pe, commitable_paths, entry) {
7798 struct got_commitable *ct = pe->data;
7799 dprintf(fd, "# %c %s\n",
7800 got_commitable_get_status(ct),
7801 got_commitable_get_path(ct));
7804 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7805 initial_content_len, a->prepared_log ? 0 : 1);
7806 done:
7807 free(initial_content);
7808 free(template);
7810 if (fd != -1 && close(fd) == -1 && err == NULL)
7811 err = got_error_from_errno2("close", a->logmsg_path);
7813 /* Editor is done; we can now apply unveil(2) */
7814 if (err == NULL)
7815 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7816 if (err) {
7817 free(*logmsg);
7818 *logmsg = NULL;
7820 return err;
7823 static const struct got_error *
7824 cmd_commit(int argc, char *argv[])
7826 const struct got_error *error = NULL;
7827 struct got_worktree *worktree = NULL;
7828 struct got_repository *repo = NULL;
7829 char *cwd = NULL, *id_str = NULL;
7830 struct got_object_id *id = NULL;
7831 const char *logmsg = NULL;
7832 char *prepared_logmsg = NULL;
7833 struct collect_commit_logmsg_arg cl_arg;
7834 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7835 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7836 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7837 struct got_pathlist_head paths;
7839 TAILQ_INIT(&paths);
7840 cl_arg.logmsg_path = NULL;
7842 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7843 switch (ch) {
7844 case 'F':
7845 if (logmsg != NULL)
7846 option_conflict('F', 'm');
7847 prepared_logmsg = realpath(optarg, NULL);
7848 if (prepared_logmsg == NULL)
7849 return got_error_from_errno2("realpath",
7850 optarg);
7851 break;
7852 case 'm':
7853 if (prepared_logmsg)
7854 option_conflict('m', 'F');
7855 logmsg = optarg;
7856 break;
7857 case 'N':
7858 non_interactive = 1;
7859 break;
7860 case 'S':
7861 allow_bad_symlinks = 1;
7862 break;
7863 default:
7864 usage_commit();
7865 /* NOTREACHED */
7869 argc -= optind;
7870 argv += optind;
7872 #ifndef PROFILE
7873 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7874 "unveil", NULL) == -1)
7875 err(1, "pledge");
7876 #endif
7877 cwd = getcwd(NULL, 0);
7878 if (cwd == NULL) {
7879 error = got_error_from_errno("getcwd");
7880 goto done;
7882 error = got_worktree_open(&worktree, cwd);
7883 if (error) {
7884 if (error->code == GOT_ERR_NOT_WORKTREE)
7885 error = wrap_not_worktree_error(error, "commit", cwd);
7886 goto done;
7889 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7890 if (error)
7891 goto done;
7892 if (rebase_in_progress) {
7893 error = got_error(GOT_ERR_REBASING);
7894 goto done;
7897 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7898 worktree);
7899 if (error)
7900 goto done;
7902 error = get_gitconfig_path(&gitconfig_path);
7903 if (error)
7904 goto done;
7905 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7906 gitconfig_path);
7907 if (error != NULL)
7908 goto done;
7910 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7911 if (error)
7912 goto done;
7913 if (merge_in_progress) {
7914 error = got_error(GOT_ERR_MERGE_BUSY);
7915 goto done;
7918 error = get_author(&author, repo, worktree);
7919 if (error)
7920 return error;
7923 * unveil(2) traverses exec(2); if an editor is used we have
7924 * to apply unveil after the log message has been written.
7926 if (logmsg == NULL || strlen(logmsg) == 0)
7927 error = get_editor(&editor);
7928 else
7929 error = apply_unveil(got_repo_get_path(repo), 0,
7930 got_worktree_get_root_path(worktree));
7931 if (error)
7932 goto done;
7934 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7935 if (error)
7936 goto done;
7938 cl_arg.editor = editor;
7939 cl_arg.cmdline_log = logmsg;
7940 cl_arg.prepared_log = prepared_logmsg;
7941 cl_arg.non_interactive = non_interactive;
7942 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7943 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7944 if (!histedit_in_progress) {
7945 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7946 error = got_error(GOT_ERR_COMMIT_BRANCH);
7947 goto done;
7949 cl_arg.branch_name += 11;
7951 cl_arg.repo_path = got_repo_get_path(repo);
7952 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7953 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7954 print_status, NULL, repo);
7955 if (error) {
7956 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7957 cl_arg.logmsg_path != NULL)
7958 preserve_logmsg = 1;
7959 goto done;
7962 error = got_object_id_str(&id_str, id);
7963 if (error)
7964 goto done;
7965 printf("Created commit %s\n", id_str);
7966 done:
7967 if (preserve_logmsg) {
7968 fprintf(stderr, "%s: log message preserved in %s\n",
7969 getprogname(), cl_arg.logmsg_path);
7970 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7971 error == NULL)
7972 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7973 free(cl_arg.logmsg_path);
7974 if (repo) {
7975 const struct got_error *close_err = got_repo_close(repo);
7976 if (error == NULL)
7977 error = close_err;
7979 if (worktree)
7980 got_worktree_close(worktree);
7981 free(cwd);
7982 free(id_str);
7983 free(gitconfig_path);
7984 free(editor);
7985 free(author);
7986 free(prepared_logmsg);
7987 return error;
7990 __dead static void
7991 usage_send(void)
7993 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7994 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7995 "[remote-repository]\n", getprogname());
7996 exit(1);
7999 static void
8000 print_load_info(int print_colored, int print_found, int print_trees,
8001 int ncolored, int nfound, int ntrees)
8003 if (print_colored) {
8004 printf("%d commit%s colored", ncolored,
8005 ncolored == 1 ? "" : "s");
8007 if (print_found) {
8008 printf("%s%d object%s found",
8009 ncolored > 0 ? "; " : "",
8010 nfound, nfound == 1 ? "" : "s");
8012 if (print_trees) {
8013 printf("; %d tree%s scanned", ntrees,
8014 ntrees == 1 ? "" : "s");
8018 struct got_send_progress_arg {
8019 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8020 int verbosity;
8021 int last_ncolored;
8022 int last_nfound;
8023 int last_ntrees;
8024 int loading_done;
8025 int last_ncommits;
8026 int last_nobj_total;
8027 int last_p_deltify;
8028 int last_p_written;
8029 int last_p_sent;
8030 int printed_something;
8031 int sent_something;
8032 struct got_pathlist_head *delete_branches;
8035 static const struct got_error *
8036 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8037 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8038 int nobj_written, off_t bytes_sent, const char *refname, int success)
8040 struct got_send_progress_arg *a = arg;
8041 char scaled_packsize[FMT_SCALED_STRSIZE];
8042 char scaled_sent[FMT_SCALED_STRSIZE];
8043 int p_deltify = 0, p_written = 0, p_sent = 0;
8044 int print_colored = 0, print_found = 0, print_trees = 0;
8045 int print_searching = 0, print_total = 0;
8046 int print_deltify = 0, print_written = 0, print_sent = 0;
8048 if (a->verbosity < 0)
8049 return NULL;
8051 if (refname) {
8052 const char *status = success ? "accepted" : "rejected";
8054 if (success) {
8055 struct got_pathlist_entry *pe;
8056 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8057 const char *branchname = pe->path;
8058 if (got_path_cmp(branchname, refname,
8059 strlen(branchname), strlen(refname)) == 0) {
8060 status = "deleted";
8061 a->sent_something = 1;
8062 break;
8067 if (a->printed_something)
8068 putchar('\n');
8069 printf("Server has %s %s", status, refname);
8070 a->printed_something = 1;
8071 return NULL;
8074 if (a->last_ncolored != ncolored) {
8075 print_colored = 1;
8076 a->last_ncolored = ncolored;
8079 if (a->last_nfound != nfound) {
8080 print_colored = 1;
8081 print_found = 1;
8082 a->last_nfound = nfound;
8085 if (a->last_ntrees != ntrees) {
8086 print_colored = 1;
8087 print_found = 1;
8088 print_trees = 1;
8089 a->last_ntrees = ntrees;
8092 if ((print_colored || print_found || print_trees) &&
8093 !a->loading_done) {
8094 printf("\r");
8095 print_load_info(print_colored, print_found, print_trees,
8096 ncolored, nfound, ntrees);
8097 a->printed_something = 1;
8098 fflush(stdout);
8099 return NULL;
8100 } else if (!a->loading_done) {
8101 printf("\r");
8102 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8103 printf("\n");
8104 a->loading_done = 1;
8107 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8108 return got_error_from_errno("fmt_scaled");
8109 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8110 return got_error_from_errno("fmt_scaled");
8112 if (a->last_ncommits != ncommits) {
8113 print_searching = 1;
8114 a->last_ncommits = ncommits;
8117 if (a->last_nobj_total != nobj_total) {
8118 print_searching = 1;
8119 print_total = 1;
8120 a->last_nobj_total = nobj_total;
8123 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8124 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8125 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8126 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8127 return got_error(GOT_ERR_NO_SPACE);
8130 if (nobj_deltify > 0 || nobj_written > 0) {
8131 if (nobj_deltify > 0) {
8132 p_deltify = (nobj_deltify * 100) / nobj_total;
8133 if (p_deltify != a->last_p_deltify) {
8134 a->last_p_deltify = p_deltify;
8135 print_searching = 1;
8136 print_total = 1;
8137 print_deltify = 1;
8140 if (nobj_written > 0) {
8141 p_written = (nobj_written * 100) / nobj_total;
8142 if (p_written != a->last_p_written) {
8143 a->last_p_written = p_written;
8144 print_searching = 1;
8145 print_total = 1;
8146 print_deltify = 1;
8147 print_written = 1;
8152 if (bytes_sent > 0) {
8153 p_sent = (bytes_sent * 100) / packfile_size;
8154 if (p_sent != a->last_p_sent) {
8155 a->last_p_sent = p_sent;
8156 print_searching = 1;
8157 print_total = 1;
8158 print_deltify = 1;
8159 print_written = 1;
8160 print_sent = 1;
8162 a->sent_something = 1;
8165 if (print_searching || print_total || print_deltify || print_written ||
8166 print_sent)
8167 printf("\r");
8168 if (print_searching)
8169 printf("packing %d reference%s", ncommits,
8170 ncommits == 1 ? "" : "s");
8171 if (print_total)
8172 printf("; %d object%s", nobj_total,
8173 nobj_total == 1 ? "" : "s");
8174 if (print_deltify)
8175 printf("; deltify: %d%%", p_deltify);
8176 if (print_sent)
8177 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8178 scaled_packsize, p_sent);
8179 else if (print_written)
8180 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8181 scaled_packsize, p_written);
8182 if (print_searching || print_total || print_deltify ||
8183 print_written || print_sent) {
8184 a->printed_something = 1;
8185 fflush(stdout);
8187 return NULL;
8190 static const struct got_error *
8191 cmd_send(int argc, char *argv[])
8193 const struct got_error *error = NULL;
8194 char *cwd = NULL, *repo_path = NULL;
8195 const char *remote_name;
8196 char *proto = NULL, *host = NULL, *port = NULL;
8197 char *repo_name = NULL, *server_path = NULL;
8198 const struct got_remote_repo *remotes, *remote = NULL;
8199 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8200 struct got_repository *repo = NULL;
8201 struct got_worktree *worktree = NULL;
8202 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8203 struct got_pathlist_head branches;
8204 struct got_pathlist_head tags;
8205 struct got_reflist_head all_branches;
8206 struct got_reflist_head all_tags;
8207 struct got_pathlist_head delete_args;
8208 struct got_pathlist_head delete_branches;
8209 struct got_reflist_entry *re;
8210 struct got_pathlist_entry *pe;
8211 int i, ch, sendfd = -1, sendstatus;
8212 pid_t sendpid = -1;
8213 struct got_send_progress_arg spa;
8214 int verbosity = 0, overwrite_refs = 0;
8215 int send_all_branches = 0, send_all_tags = 0;
8216 struct got_reference *ref = NULL;
8218 TAILQ_INIT(&branches);
8219 TAILQ_INIT(&tags);
8220 TAILQ_INIT(&all_branches);
8221 TAILQ_INIT(&all_tags);
8222 TAILQ_INIT(&delete_args);
8223 TAILQ_INIT(&delete_branches);
8225 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8226 switch (ch) {
8227 case 'a':
8228 send_all_branches = 1;
8229 break;
8230 case 'b':
8231 error = got_pathlist_append(&branches, optarg, NULL);
8232 if (error)
8233 return error;
8234 nbranches++;
8235 break;
8236 case 'd':
8237 error = got_pathlist_append(&delete_args, optarg, NULL);
8238 if (error)
8239 return error;
8240 break;
8241 case 'f':
8242 overwrite_refs = 1;
8243 break;
8244 case 'r':
8245 repo_path = realpath(optarg, NULL);
8246 if (repo_path == NULL)
8247 return got_error_from_errno2("realpath",
8248 optarg);
8249 got_path_strip_trailing_slashes(repo_path);
8250 break;
8251 case 't':
8252 error = got_pathlist_append(&tags, optarg, NULL);
8253 if (error)
8254 return error;
8255 ntags++;
8256 break;
8257 case 'T':
8258 send_all_tags = 1;
8259 break;
8260 case 'v':
8261 if (verbosity < 0)
8262 verbosity = 0;
8263 else if (verbosity < 3)
8264 verbosity++;
8265 break;
8266 case 'q':
8267 verbosity = -1;
8268 break;
8269 default:
8270 usage_send();
8271 /* NOTREACHED */
8274 argc -= optind;
8275 argv += optind;
8277 if (send_all_branches && !TAILQ_EMPTY(&branches))
8278 option_conflict('a', 'b');
8279 if (send_all_tags && !TAILQ_EMPTY(&tags))
8280 option_conflict('T', 't');
8283 if (argc == 0)
8284 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8285 else if (argc == 1)
8286 remote_name = argv[0];
8287 else
8288 usage_send();
8290 cwd = getcwd(NULL, 0);
8291 if (cwd == NULL) {
8292 error = got_error_from_errno("getcwd");
8293 goto done;
8296 if (repo_path == NULL) {
8297 error = got_worktree_open(&worktree, cwd);
8298 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8299 goto done;
8300 else
8301 error = NULL;
8302 if (worktree) {
8303 repo_path =
8304 strdup(got_worktree_get_repo_path(worktree));
8305 if (repo_path == NULL)
8306 error = got_error_from_errno("strdup");
8307 if (error)
8308 goto done;
8309 } else {
8310 repo_path = strdup(cwd);
8311 if (repo_path == NULL) {
8312 error = got_error_from_errno("strdup");
8313 goto done;
8318 error = got_repo_open(&repo, repo_path, NULL);
8319 if (error)
8320 goto done;
8322 if (worktree) {
8323 worktree_conf = got_worktree_get_gotconfig(worktree);
8324 if (worktree_conf) {
8325 got_gotconfig_get_remotes(&nremotes, &remotes,
8326 worktree_conf);
8327 for (i = 0; i < nremotes; i++) {
8328 if (strcmp(remotes[i].name, remote_name) == 0) {
8329 remote = &remotes[i];
8330 break;
8335 if (remote == NULL) {
8336 repo_conf = got_repo_get_gotconfig(repo);
8337 if (repo_conf) {
8338 got_gotconfig_get_remotes(&nremotes, &remotes,
8339 repo_conf);
8340 for (i = 0; i < nremotes; i++) {
8341 if (strcmp(remotes[i].name, remote_name) == 0) {
8342 remote = &remotes[i];
8343 break;
8348 if (remote == NULL) {
8349 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8350 for (i = 0; i < nremotes; i++) {
8351 if (strcmp(remotes[i].name, remote_name) == 0) {
8352 remote = &remotes[i];
8353 break;
8357 if (remote == NULL) {
8358 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8359 goto done;
8362 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8363 &repo_name, remote->send_url);
8364 if (error)
8365 goto done;
8367 if (strcmp(proto, "git") == 0) {
8368 #ifndef PROFILE
8369 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8370 "sendfd dns inet unveil", NULL) == -1)
8371 err(1, "pledge");
8372 #endif
8373 } else if (strcmp(proto, "git+ssh") == 0 ||
8374 strcmp(proto, "ssh") == 0) {
8375 #ifndef PROFILE
8376 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8377 "sendfd unveil", NULL) == -1)
8378 err(1, "pledge");
8379 #endif
8380 } else if (strcmp(proto, "http") == 0 ||
8381 strcmp(proto, "git+http") == 0) {
8382 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8383 goto done;
8384 } else {
8385 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8386 goto done;
8389 error = got_dial_apply_unveil(proto);
8390 if (error)
8391 goto done;
8393 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8394 if (error)
8395 goto done;
8397 if (send_all_branches) {
8398 error = got_ref_list(&all_branches, repo, "refs/heads",
8399 got_ref_cmp_by_name, NULL);
8400 if (error)
8401 goto done;
8402 TAILQ_FOREACH(re, &all_branches, entry) {
8403 const char *branchname = got_ref_get_name(re->ref);
8404 error = got_pathlist_append(&branches,
8405 branchname, NULL);
8406 if (error)
8407 goto done;
8408 nbranches++;
8410 } else if (nbranches == 0) {
8411 for (i = 0; i < remote->nsend_branches; i++) {
8412 got_pathlist_append(&branches,
8413 remote->send_branches[i], NULL);
8417 if (send_all_tags) {
8418 error = got_ref_list(&all_tags, repo, "refs/tags",
8419 got_ref_cmp_by_name, NULL);
8420 if (error)
8421 goto done;
8422 TAILQ_FOREACH(re, &all_tags, entry) {
8423 const char *tagname = got_ref_get_name(re->ref);
8424 error = got_pathlist_append(&tags,
8425 tagname, NULL);
8426 if (error)
8427 goto done;
8428 ntags++;
8433 * To prevent accidents only branches in refs/heads/ can be deleted
8434 * with 'got send -d'.
8435 * Deleting anything else requires local repository access or Git.
8437 TAILQ_FOREACH(pe, &delete_args, entry) {
8438 const char *branchname = pe->path;
8439 char *s;
8440 struct got_pathlist_entry *new;
8441 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8442 s = strdup(branchname);
8443 if (s == NULL) {
8444 error = got_error_from_errno("strdup");
8445 goto done;
8447 } else {
8448 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8449 error = got_error_from_errno("asprintf");
8450 goto done;
8453 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8454 if (error || new == NULL /* duplicate */)
8455 free(s);
8456 if (error)
8457 goto done;
8458 ndelete_branches++;
8461 if (nbranches == 0 && ndelete_branches == 0) {
8462 struct got_reference *head_ref;
8463 if (worktree)
8464 error = got_ref_open(&head_ref, repo,
8465 got_worktree_get_head_ref_name(worktree), 0);
8466 else
8467 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8468 if (error)
8469 goto done;
8470 if (got_ref_is_symbolic(head_ref)) {
8471 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8472 got_ref_close(head_ref);
8473 if (error)
8474 goto done;
8475 } else
8476 ref = head_ref;
8477 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8478 NULL);
8479 if (error)
8480 goto done;
8481 nbranches++;
8484 if (verbosity >= 0)
8485 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8486 port ? ":" : "", port ? port : "");
8488 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8489 server_path, verbosity);
8490 if (error)
8491 goto done;
8493 memset(&spa, 0, sizeof(spa));
8494 spa.last_scaled_packsize[0] = '\0';
8495 spa.last_p_deltify = -1;
8496 spa.last_p_written = -1;
8497 spa.verbosity = verbosity;
8498 spa.delete_branches = &delete_branches;
8499 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8500 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8501 check_cancelled, NULL);
8502 if (spa.printed_something)
8503 putchar('\n');
8504 if (error)
8505 goto done;
8506 if (!spa.sent_something && verbosity >= 0)
8507 printf("Already up-to-date\n");
8508 done:
8509 if (sendpid > 0) {
8510 if (kill(sendpid, SIGTERM) == -1)
8511 error = got_error_from_errno("kill");
8512 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8513 error = got_error_from_errno("waitpid");
8515 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8516 error = got_error_from_errno("close");
8517 if (repo) {
8518 const struct got_error *close_err = got_repo_close(repo);
8519 if (error == NULL)
8520 error = close_err;
8522 if (worktree)
8523 got_worktree_close(worktree);
8524 if (ref)
8525 got_ref_close(ref);
8526 got_pathlist_free(&branches);
8527 got_pathlist_free(&tags);
8528 got_ref_list_free(&all_branches);
8529 got_ref_list_free(&all_tags);
8530 got_pathlist_free(&delete_args);
8531 TAILQ_FOREACH(pe, &delete_branches, entry)
8532 free((char *)pe->path);
8533 got_pathlist_free(&delete_branches);
8534 free(cwd);
8535 free(repo_path);
8536 free(proto);
8537 free(host);
8538 free(port);
8539 free(server_path);
8540 free(repo_name);
8541 return error;
8544 __dead static void
8545 usage_cherrypick(void)
8547 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8548 exit(1);
8551 static const struct got_error *
8552 cmd_cherrypick(int argc, char *argv[])
8554 const struct got_error *error = NULL;
8555 struct got_worktree *worktree = NULL;
8556 struct got_repository *repo = NULL;
8557 char *cwd = NULL, *commit_id_str = NULL;
8558 struct got_object_id *commit_id = NULL;
8559 struct got_commit_object *commit = NULL;
8560 struct got_object_qid *pid;
8561 int ch;
8562 struct got_update_progress_arg upa;
8564 while ((ch = getopt(argc, argv, "")) != -1) {
8565 switch (ch) {
8566 default:
8567 usage_cherrypick();
8568 /* NOTREACHED */
8572 argc -= optind;
8573 argv += optind;
8575 #ifndef PROFILE
8576 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8577 "unveil", NULL) == -1)
8578 err(1, "pledge");
8579 #endif
8580 if (argc != 1)
8581 usage_cherrypick();
8583 cwd = getcwd(NULL, 0);
8584 if (cwd == NULL) {
8585 error = got_error_from_errno("getcwd");
8586 goto done;
8588 error = got_worktree_open(&worktree, cwd);
8589 if (error) {
8590 if (error->code == GOT_ERR_NOT_WORKTREE)
8591 error = wrap_not_worktree_error(error, "cherrypick",
8592 cwd);
8593 goto done;
8596 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8597 NULL);
8598 if (error != NULL)
8599 goto done;
8601 error = apply_unveil(got_repo_get_path(repo), 0,
8602 got_worktree_get_root_path(worktree));
8603 if (error)
8604 goto done;
8606 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8607 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8608 if (error)
8609 goto done;
8610 error = got_object_id_str(&commit_id_str, commit_id);
8611 if (error)
8612 goto done;
8614 error = got_object_open_as_commit(&commit, repo, commit_id);
8615 if (error)
8616 goto done;
8617 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8618 memset(&upa, 0, sizeof(upa));
8619 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8620 commit_id, repo, update_progress, &upa, check_cancelled,
8621 NULL);
8622 if (error != NULL)
8623 goto done;
8625 if (upa.did_something)
8626 printf("Merged commit %s\n", commit_id_str);
8627 print_merge_progress_stats(&upa);
8628 done:
8629 if (commit)
8630 got_object_commit_close(commit);
8631 free(commit_id_str);
8632 if (worktree)
8633 got_worktree_close(worktree);
8634 if (repo) {
8635 const struct got_error *close_err = got_repo_close(repo);
8636 if (error == NULL)
8637 error = close_err;
8639 return error;
8642 __dead static void
8643 usage_backout(void)
8645 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8646 exit(1);
8649 static const struct got_error *
8650 cmd_backout(int argc, char *argv[])
8652 const struct got_error *error = NULL;
8653 struct got_worktree *worktree = NULL;
8654 struct got_repository *repo = NULL;
8655 char *cwd = NULL, *commit_id_str = NULL;
8656 struct got_object_id *commit_id = NULL;
8657 struct got_commit_object *commit = NULL;
8658 struct got_object_qid *pid;
8659 int ch;
8660 struct got_update_progress_arg upa;
8662 while ((ch = getopt(argc, argv, "")) != -1) {
8663 switch (ch) {
8664 default:
8665 usage_backout();
8666 /* NOTREACHED */
8670 argc -= optind;
8671 argv += optind;
8673 #ifndef PROFILE
8674 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8675 "unveil", NULL) == -1)
8676 err(1, "pledge");
8677 #endif
8678 if (argc != 1)
8679 usage_backout();
8681 cwd = getcwd(NULL, 0);
8682 if (cwd == NULL) {
8683 error = got_error_from_errno("getcwd");
8684 goto done;
8686 error = got_worktree_open(&worktree, cwd);
8687 if (error) {
8688 if (error->code == GOT_ERR_NOT_WORKTREE)
8689 error = wrap_not_worktree_error(error, "backout", cwd);
8690 goto done;
8693 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8694 NULL);
8695 if (error != NULL)
8696 goto done;
8698 error = apply_unveil(got_repo_get_path(repo), 0,
8699 got_worktree_get_root_path(worktree));
8700 if (error)
8701 goto done;
8703 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8704 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8705 if (error)
8706 goto done;
8707 error = got_object_id_str(&commit_id_str, commit_id);
8708 if (error)
8709 goto done;
8711 error = got_object_open_as_commit(&commit, repo, commit_id);
8712 if (error)
8713 goto done;
8714 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8715 if (pid == NULL) {
8716 error = got_error(GOT_ERR_ROOT_COMMIT);
8717 goto done;
8720 memset(&upa, 0, sizeof(upa));
8721 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8722 repo, update_progress, &upa, check_cancelled, NULL);
8723 if (error != NULL)
8724 goto done;
8726 if (upa.did_something)
8727 printf("Backed out commit %s\n", commit_id_str);
8728 print_merge_progress_stats(&upa);
8729 done:
8730 if (commit)
8731 got_object_commit_close(commit);
8732 free(commit_id_str);
8733 if (worktree)
8734 got_worktree_close(worktree);
8735 if (repo) {
8736 const struct got_error *close_err = got_repo_close(repo);
8737 if (error == NULL)
8738 error = close_err;
8740 return error;
8743 __dead static void
8744 usage_rebase(void)
8746 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8747 getprogname());
8748 exit(1);
8751 void
8752 trim_logmsg(char *logmsg, int limit)
8754 char *nl;
8755 size_t len;
8757 len = strlen(logmsg);
8758 if (len > limit)
8759 len = limit;
8760 logmsg[len] = '\0';
8761 nl = strchr(logmsg, '\n');
8762 if (nl)
8763 *nl = '\0';
8766 static const struct got_error *
8767 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8769 const struct got_error *err;
8770 char *logmsg0 = NULL;
8771 const char *s;
8773 err = got_object_commit_get_logmsg(&logmsg0, commit);
8774 if (err)
8775 return err;
8777 s = logmsg0;
8778 while (isspace((unsigned char)s[0]))
8779 s++;
8781 *logmsg = strdup(s);
8782 if (*logmsg == NULL) {
8783 err = got_error_from_errno("strdup");
8784 goto done;
8787 trim_logmsg(*logmsg, limit);
8788 done:
8789 free(logmsg0);
8790 return err;
8793 static const struct got_error *
8794 show_rebase_merge_conflict(struct got_object_id *id,
8795 struct got_repository *repo)
8797 const struct got_error *err;
8798 struct got_commit_object *commit = NULL;
8799 char *id_str = NULL, *logmsg = NULL;
8801 err = got_object_open_as_commit(&commit, repo, id);
8802 if (err)
8803 return err;
8805 err = got_object_id_str(&id_str, id);
8806 if (err)
8807 goto done;
8809 id_str[12] = '\0';
8811 err = get_short_logmsg(&logmsg, 42, commit);
8812 if (err)
8813 goto done;
8815 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8816 done:
8817 free(id_str);
8818 got_object_commit_close(commit);
8819 free(logmsg);
8820 return err;
8823 static const struct got_error *
8824 show_rebase_progress(struct got_commit_object *commit,
8825 struct got_object_id *old_id, struct got_object_id *new_id)
8827 const struct got_error *err;
8828 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8830 err = got_object_id_str(&old_id_str, old_id);
8831 if (err)
8832 goto done;
8834 if (new_id) {
8835 err = got_object_id_str(&new_id_str, new_id);
8836 if (err)
8837 goto done;
8840 old_id_str[12] = '\0';
8841 if (new_id_str)
8842 new_id_str[12] = '\0';
8844 err = get_short_logmsg(&logmsg, 42, commit);
8845 if (err)
8846 goto done;
8848 printf("%s -> %s: %s\n", old_id_str,
8849 new_id_str ? new_id_str : "no-op change", logmsg);
8850 done:
8851 free(old_id_str);
8852 free(new_id_str);
8853 free(logmsg);
8854 return err;
8857 static const struct got_error *
8858 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8859 struct got_reference *branch, struct got_reference *new_base_branch,
8860 struct got_reference *tmp_branch, struct got_repository *repo,
8861 int create_backup)
8863 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8864 return got_worktree_rebase_complete(worktree, fileindex,
8865 new_base_branch, tmp_branch, branch, repo, create_backup);
8868 static const struct got_error *
8869 rebase_commit(struct got_pathlist_head *merged_paths,
8870 struct got_worktree *worktree, struct got_fileindex *fileindex,
8871 struct got_reference *tmp_branch,
8872 struct got_object_id *commit_id, struct got_repository *repo)
8874 const struct got_error *error;
8875 struct got_commit_object *commit;
8876 struct got_object_id *new_commit_id;
8878 error = got_object_open_as_commit(&commit, repo, commit_id);
8879 if (error)
8880 return error;
8882 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8883 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8884 if (error) {
8885 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8886 goto done;
8887 error = show_rebase_progress(commit, commit_id, NULL);
8888 } else {
8889 error = show_rebase_progress(commit, commit_id, new_commit_id);
8890 free(new_commit_id);
8892 done:
8893 got_object_commit_close(commit);
8894 return error;
8897 struct check_path_prefix_arg {
8898 const char *path_prefix;
8899 size_t len;
8900 int errcode;
8903 static const struct got_error *
8904 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8905 struct got_blob_object *blob2, FILE *f1, FILE *f2,
8906 struct got_object_id *id1, struct got_object_id *id2,
8907 const char *path1, const char *path2,
8908 mode_t mode1, mode_t mode2, struct got_repository *repo)
8910 struct check_path_prefix_arg *a = arg;
8912 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8913 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8914 return got_error(a->errcode);
8916 return NULL;
8919 static const struct got_error *
8920 check_path_prefix(struct got_object_id *parent_id,
8921 struct got_object_id *commit_id, const char *path_prefix,
8922 int errcode, struct got_repository *repo)
8924 const struct got_error *err;
8925 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8926 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8927 struct check_path_prefix_arg cpp_arg;
8929 if (got_path_is_root_dir(path_prefix))
8930 return NULL;
8932 err = got_object_open_as_commit(&commit, repo, commit_id);
8933 if (err)
8934 goto done;
8936 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8937 if (err)
8938 goto done;
8940 err = got_object_open_as_tree(&tree1, repo,
8941 got_object_commit_get_tree_id(parent_commit));
8942 if (err)
8943 goto done;
8945 err = got_object_open_as_tree(&tree2, repo,
8946 got_object_commit_get_tree_id(commit));
8947 if (err)
8948 goto done;
8950 cpp_arg.path_prefix = path_prefix;
8951 while (cpp_arg.path_prefix[0] == '/')
8952 cpp_arg.path_prefix++;
8953 cpp_arg.len = strlen(cpp_arg.path_prefix);
8954 cpp_arg.errcode = errcode;
8955 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
8956 check_path_prefix_in_diff, &cpp_arg, 0);
8957 done:
8958 if (tree1)
8959 got_object_tree_close(tree1);
8960 if (tree2)
8961 got_object_tree_close(tree2);
8962 if (commit)
8963 got_object_commit_close(commit);
8964 if (parent_commit)
8965 got_object_commit_close(parent_commit);
8966 return err;
8969 static const struct got_error *
8970 collect_commits(struct got_object_id_queue *commits,
8971 struct got_object_id *initial_commit_id,
8972 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8973 const char *path_prefix, int path_prefix_errcode,
8974 struct got_repository *repo)
8976 const struct got_error *err = NULL;
8977 struct got_commit_graph *graph = NULL;
8978 struct got_object_id *parent_id = NULL;
8979 struct got_object_qid *qid;
8980 struct got_object_id *commit_id = initial_commit_id;
8982 err = got_commit_graph_open(&graph, "/", 1);
8983 if (err)
8984 return err;
8986 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8987 check_cancelled, NULL);
8988 if (err)
8989 goto done;
8990 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8991 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8992 check_cancelled, NULL);
8993 if (err) {
8994 if (err->code == GOT_ERR_ITER_COMPLETED) {
8995 err = got_error_msg(GOT_ERR_ANCESTRY,
8996 "ran out of commits to rebase before "
8997 "youngest common ancestor commit has "
8998 "been reached?!?");
9000 goto done;
9001 } else {
9002 err = check_path_prefix(parent_id, commit_id,
9003 path_prefix, path_prefix_errcode, repo);
9004 if (err)
9005 goto done;
9007 err = got_object_qid_alloc(&qid, commit_id);
9008 if (err)
9009 goto done;
9010 STAILQ_INSERT_HEAD(commits, qid, entry);
9011 commit_id = parent_id;
9014 done:
9015 got_commit_graph_close(graph);
9016 return err;
9019 static const struct got_error *
9020 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9022 const struct got_error *err = NULL;
9023 time_t committer_time;
9024 struct tm tm;
9025 char datebuf[11]; /* YYYY-MM-DD + NUL */
9026 char *author0 = NULL, *author, *smallerthan;
9027 char *logmsg0 = NULL, *logmsg, *newline;
9029 committer_time = got_object_commit_get_committer_time(commit);
9030 if (gmtime_r(&committer_time, &tm) == NULL)
9031 return got_error_from_errno("gmtime_r");
9032 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9033 return got_error(GOT_ERR_NO_SPACE);
9035 author0 = strdup(got_object_commit_get_author(commit));
9036 if (author0 == NULL)
9037 return got_error_from_errno("strdup");
9038 author = author0;
9039 smallerthan = strchr(author, '<');
9040 if (smallerthan && smallerthan[1] != '\0')
9041 author = smallerthan + 1;
9042 author[strcspn(author, "@>")] = '\0';
9044 err = got_object_commit_get_logmsg(&logmsg0, commit);
9045 if (err)
9046 goto done;
9047 logmsg = logmsg0;
9048 while (*logmsg == '\n')
9049 logmsg++;
9050 newline = strchr(logmsg, '\n');
9051 if (newline)
9052 *newline = '\0';
9054 if (asprintf(brief_str, "%s %s %s",
9055 datebuf, author, logmsg) == -1)
9056 err = got_error_from_errno("asprintf");
9057 done:
9058 free(author0);
9059 free(logmsg0);
9060 return err;
9063 static const struct got_error *
9064 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9065 struct got_repository *repo)
9067 const struct got_error *err;
9068 char *id_str;
9070 err = got_object_id_str(&id_str, id);
9071 if (err)
9072 return err;
9074 err = got_ref_delete(ref, repo);
9075 if (err)
9076 goto done;
9078 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9079 done:
9080 free(id_str);
9081 return err;
9084 static const struct got_error *
9085 print_backup_ref(const char *branch_name, const char *new_id_str,
9086 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9087 struct got_reflist_object_id_map *refs_idmap,
9088 struct got_repository *repo)
9090 const struct got_error *err = NULL;
9091 struct got_reflist_head *refs;
9092 char *refs_str = NULL;
9093 struct got_object_id *new_commit_id = NULL;
9094 struct got_commit_object *new_commit = NULL;
9095 char *new_commit_brief_str = NULL;
9096 struct got_object_id *yca_id = NULL;
9097 struct got_commit_object *yca_commit = NULL;
9098 char *yca_id_str = NULL, *yca_brief_str = NULL;
9099 char *custom_refs_str;
9101 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9102 return got_error_from_errno("asprintf");
9104 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9105 0, 0, refs_idmap, custom_refs_str);
9106 if (err)
9107 goto done;
9109 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9110 if (err)
9111 goto done;
9113 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9114 if (refs) {
9115 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9116 if (err)
9117 goto done;
9120 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9121 if (err)
9122 goto done;
9124 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9125 if (err)
9126 goto done;
9128 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9129 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9130 if (err)
9131 goto done;
9133 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9134 refs_str ? " (" : "", refs_str ? refs_str : "",
9135 refs_str ? ")" : "", new_commit_brief_str);
9136 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9137 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9138 free(refs_str);
9139 refs_str = NULL;
9141 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9142 if (err)
9143 goto done;
9145 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9146 if (err)
9147 goto done;
9149 err = got_object_id_str(&yca_id_str, yca_id);
9150 if (err)
9151 goto done;
9153 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9154 if (refs) {
9155 err = build_refs_str(&refs_str, refs, yca_id, repo);
9156 if (err)
9157 goto done;
9159 printf("history forked at %s%s%s%s\n %s\n",
9160 yca_id_str,
9161 refs_str ? " (" : "", refs_str ? refs_str : "",
9162 refs_str ? ")" : "", yca_brief_str);
9164 done:
9165 free(custom_refs_str);
9166 free(new_commit_id);
9167 free(refs_str);
9168 free(yca_id);
9169 free(yca_id_str);
9170 free(yca_brief_str);
9171 if (new_commit)
9172 got_object_commit_close(new_commit);
9173 if (yca_commit)
9174 got_object_commit_close(yca_commit);
9176 return NULL;
9179 static const struct got_error *
9180 process_backup_refs(const char *backup_ref_prefix,
9181 const char *wanted_branch_name,
9182 int delete, struct got_repository *repo)
9184 const struct got_error *err;
9185 struct got_reflist_head refs, backup_refs;
9186 struct got_reflist_entry *re;
9187 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9188 struct got_object_id *old_commit_id = NULL;
9189 char *branch_name = NULL;
9190 struct got_commit_object *old_commit = NULL;
9191 struct got_reflist_object_id_map *refs_idmap = NULL;
9192 int wanted_branch_found = 0;
9194 TAILQ_INIT(&refs);
9195 TAILQ_INIT(&backup_refs);
9197 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9198 if (err)
9199 return err;
9201 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9202 if (err)
9203 goto done;
9205 if (wanted_branch_name) {
9206 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9207 wanted_branch_name += 11;
9210 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9211 got_ref_cmp_by_commit_timestamp_descending, repo);
9212 if (err)
9213 goto done;
9215 TAILQ_FOREACH(re, &backup_refs, entry) {
9216 const char *refname = got_ref_get_name(re->ref);
9217 char *slash;
9219 err = check_cancelled(NULL);
9220 if (err)
9221 break;
9223 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9224 if (err)
9225 break;
9227 err = got_object_open_as_commit(&old_commit, repo,
9228 old_commit_id);
9229 if (err)
9230 break;
9232 if (strncmp(backup_ref_prefix, refname,
9233 backup_ref_prefix_len) == 0)
9234 refname += backup_ref_prefix_len;
9236 while (refname[0] == '/')
9237 refname++;
9239 branch_name = strdup(refname);
9240 if (branch_name == NULL) {
9241 err = got_error_from_errno("strdup");
9242 break;
9244 slash = strrchr(branch_name, '/');
9245 if (slash) {
9246 *slash = '\0';
9247 refname += strlen(branch_name) + 1;
9250 if (wanted_branch_name == NULL ||
9251 strcmp(wanted_branch_name, branch_name) == 0) {
9252 wanted_branch_found = 1;
9253 if (delete) {
9254 err = delete_backup_ref(re->ref,
9255 old_commit_id, repo);
9256 } else {
9257 err = print_backup_ref(branch_name, refname,
9258 old_commit_id, old_commit, refs_idmap,
9259 repo);
9261 if (err)
9262 break;
9265 free(old_commit_id);
9266 old_commit_id = NULL;
9267 free(branch_name);
9268 branch_name = NULL;
9269 got_object_commit_close(old_commit);
9270 old_commit = NULL;
9273 if (wanted_branch_name && !wanted_branch_found) {
9274 err = got_error_fmt(GOT_ERR_NOT_REF,
9275 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9277 done:
9278 if (refs_idmap)
9279 got_reflist_object_id_map_free(refs_idmap);
9280 got_ref_list_free(&refs);
9281 got_ref_list_free(&backup_refs);
9282 free(old_commit_id);
9283 free(branch_name);
9284 if (old_commit)
9285 got_object_commit_close(old_commit);
9286 return err;
9289 static const struct got_error *
9290 abort_progress(void *arg, unsigned char status, const char *path)
9293 * Unversioned files should not clutter progress output when
9294 * an operation is aborted.
9296 if (status == GOT_STATUS_UNVERSIONED)
9297 return NULL;
9299 return update_progress(arg, status, path);
9302 static const struct got_error *
9303 cmd_rebase(int argc, char *argv[])
9305 const struct got_error *error = NULL;
9306 struct got_worktree *worktree = NULL;
9307 struct got_repository *repo = NULL;
9308 struct got_fileindex *fileindex = NULL;
9309 char *cwd = NULL;
9310 struct got_reference *branch = NULL;
9311 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9312 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9313 struct got_object_id *resume_commit_id = NULL;
9314 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9315 struct got_commit_object *commit = NULL;
9316 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9317 int histedit_in_progress = 0, merge_in_progress = 0;
9318 int create_backup = 1, list_backups = 0, delete_backups = 0;
9319 struct got_object_id_queue commits;
9320 struct got_pathlist_head merged_paths;
9321 const struct got_object_id_queue *parent_ids;
9322 struct got_object_qid *qid, *pid;
9323 struct got_update_progress_arg upa;
9325 STAILQ_INIT(&commits);
9326 TAILQ_INIT(&merged_paths);
9327 memset(&upa, 0, sizeof(upa));
9329 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9330 switch (ch) {
9331 case 'a':
9332 abort_rebase = 1;
9333 break;
9334 case 'c':
9335 continue_rebase = 1;
9336 break;
9337 case 'l':
9338 list_backups = 1;
9339 break;
9340 case 'X':
9341 delete_backups = 1;
9342 break;
9343 default:
9344 usage_rebase();
9345 /* NOTREACHED */
9349 argc -= optind;
9350 argv += optind;
9352 #ifndef PROFILE
9353 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9354 "unveil", NULL) == -1)
9355 err(1, "pledge");
9356 #endif
9357 if (list_backups) {
9358 if (abort_rebase)
9359 option_conflict('l', 'a');
9360 if (continue_rebase)
9361 option_conflict('l', 'c');
9362 if (delete_backups)
9363 option_conflict('l', 'X');
9364 if (argc != 0 && argc != 1)
9365 usage_rebase();
9366 } else if (delete_backups) {
9367 if (abort_rebase)
9368 option_conflict('X', 'a');
9369 if (continue_rebase)
9370 option_conflict('X', 'c');
9371 if (list_backups)
9372 option_conflict('l', 'X');
9373 if (argc != 0 && argc != 1)
9374 usage_rebase();
9375 } else {
9376 if (abort_rebase && continue_rebase)
9377 usage_rebase();
9378 else if (abort_rebase || continue_rebase) {
9379 if (argc != 0)
9380 usage_rebase();
9381 } else if (argc != 1)
9382 usage_rebase();
9385 cwd = getcwd(NULL, 0);
9386 if (cwd == NULL) {
9387 error = got_error_from_errno("getcwd");
9388 goto done;
9390 error = got_worktree_open(&worktree, cwd);
9391 if (error) {
9392 if (list_backups || delete_backups) {
9393 if (error->code != GOT_ERR_NOT_WORKTREE)
9394 goto done;
9395 } else {
9396 if (error->code == GOT_ERR_NOT_WORKTREE)
9397 error = wrap_not_worktree_error(error,
9398 "rebase", cwd);
9399 goto done;
9403 error = got_repo_open(&repo,
9404 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9405 if (error != NULL)
9406 goto done;
9408 error = apply_unveil(got_repo_get_path(repo), 0,
9409 worktree ? got_worktree_get_root_path(worktree) : NULL);
9410 if (error)
9411 goto done;
9413 if (list_backups || delete_backups) {
9414 error = process_backup_refs(
9415 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9416 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9417 goto done; /* nothing else to do */
9420 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9421 worktree);
9422 if (error)
9423 goto done;
9424 if (histedit_in_progress) {
9425 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9426 goto done;
9429 error = got_worktree_merge_in_progress(&merge_in_progress,
9430 worktree, repo);
9431 if (error)
9432 goto done;
9433 if (merge_in_progress) {
9434 error = got_error(GOT_ERR_MERGE_BUSY);
9435 goto done;
9438 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9439 if (error)
9440 goto done;
9442 if (abort_rebase) {
9443 if (!rebase_in_progress) {
9444 error = got_error(GOT_ERR_NOT_REBASING);
9445 goto done;
9447 error = got_worktree_rebase_continue(&resume_commit_id,
9448 &new_base_branch, &tmp_branch, &branch, &fileindex,
9449 worktree, repo);
9450 if (error)
9451 goto done;
9452 printf("Switching work tree to %s\n",
9453 got_ref_get_symref_target(new_base_branch));
9454 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9455 new_base_branch, abort_progress, &upa);
9456 if (error)
9457 goto done;
9458 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9459 print_merge_progress_stats(&upa);
9460 goto done; /* nothing else to do */
9463 if (continue_rebase) {
9464 if (!rebase_in_progress) {
9465 error = got_error(GOT_ERR_NOT_REBASING);
9466 goto done;
9468 error = got_worktree_rebase_continue(&resume_commit_id,
9469 &new_base_branch, &tmp_branch, &branch, &fileindex,
9470 worktree, repo);
9471 if (error)
9472 goto done;
9474 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9475 resume_commit_id, repo);
9476 if (error)
9477 goto done;
9479 yca_id = got_object_id_dup(resume_commit_id);
9480 if (yca_id == NULL) {
9481 error = got_error_from_errno("got_object_id_dup");
9482 goto done;
9484 } else {
9485 error = got_ref_open(&branch, repo, argv[0], 0);
9486 if (error != NULL)
9487 goto done;
9490 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9491 if (error)
9492 goto done;
9494 if (!continue_rebase) {
9495 struct got_object_id *base_commit_id;
9497 base_commit_id = got_worktree_get_base_commit_id(worktree);
9498 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9499 base_commit_id, branch_head_commit_id, 1, repo,
9500 check_cancelled, NULL);
9501 if (error)
9502 goto done;
9503 if (yca_id == NULL) {
9504 error = got_error_msg(GOT_ERR_ANCESTRY,
9505 "specified branch shares no common ancestry "
9506 "with work tree's branch");
9507 goto done;
9510 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9511 if (error) {
9512 if (error->code != GOT_ERR_ANCESTRY)
9513 goto done;
9514 error = NULL;
9515 } else {
9516 struct got_pathlist_head paths;
9517 printf("%s is already based on %s\n",
9518 got_ref_get_name(branch),
9519 got_worktree_get_head_ref_name(worktree));
9520 error = switch_head_ref(branch, branch_head_commit_id,
9521 worktree, repo);
9522 if (error)
9523 goto done;
9524 error = got_worktree_set_base_commit_id(worktree, repo,
9525 branch_head_commit_id);
9526 if (error)
9527 goto done;
9528 TAILQ_INIT(&paths);
9529 error = got_pathlist_append(&paths, "", NULL);
9530 if (error)
9531 goto done;
9532 error = got_worktree_checkout_files(worktree,
9533 &paths, repo, update_progress, &upa,
9534 check_cancelled, NULL);
9535 got_pathlist_free(&paths);
9536 if (error)
9537 goto done;
9538 if (upa.did_something) {
9539 char *id_str;
9540 error = got_object_id_str(&id_str,
9541 branch_head_commit_id);
9542 if (error)
9543 goto done;
9544 printf("Updated to %s: %s\n",
9545 got_worktree_get_head_ref_name(worktree),
9546 id_str);
9547 free(id_str);
9548 } else
9549 printf("Already up-to-date\n");
9550 print_update_progress_stats(&upa);
9551 goto done;
9555 commit_id = branch_head_commit_id;
9556 error = got_object_open_as_commit(&commit, repo, commit_id);
9557 if (error)
9558 goto done;
9560 parent_ids = got_object_commit_get_parent_ids(commit);
9561 pid = STAILQ_FIRST(parent_ids);
9562 if (pid == NULL) {
9563 error = got_error(GOT_ERR_EMPTY_REBASE);
9564 goto done;
9566 error = collect_commits(&commits, commit_id, &pid->id,
9567 yca_id, got_worktree_get_path_prefix(worktree),
9568 GOT_ERR_REBASE_PATH, repo);
9569 got_object_commit_close(commit);
9570 commit = NULL;
9571 if (error)
9572 goto done;
9574 if (!continue_rebase) {
9575 error = got_worktree_rebase_prepare(&new_base_branch,
9576 &tmp_branch, &fileindex, worktree, branch, repo);
9577 if (error)
9578 goto done;
9581 if (STAILQ_EMPTY(&commits)) {
9582 if (continue_rebase) {
9583 error = rebase_complete(worktree, fileindex,
9584 branch, new_base_branch, tmp_branch, repo,
9585 create_backup);
9586 goto done;
9587 } else {
9588 /* Fast-forward the reference of the branch. */
9589 struct got_object_id *new_head_commit_id;
9590 char *id_str;
9591 error = got_ref_resolve(&new_head_commit_id, repo,
9592 new_base_branch);
9593 if (error)
9594 goto done;
9595 error = got_object_id_str(&id_str, new_head_commit_id);
9596 printf("Forwarding %s to commit %s\n",
9597 got_ref_get_name(branch), id_str);
9598 free(id_str);
9599 error = got_ref_change_ref(branch,
9600 new_head_commit_id);
9601 if (error)
9602 goto done;
9603 /* No backup needed since objects did not change. */
9604 create_backup = 0;
9608 pid = NULL;
9609 STAILQ_FOREACH(qid, &commits, entry) {
9611 commit_id = &qid->id;
9612 parent_id = pid ? &pid->id : yca_id;
9613 pid = qid;
9615 memset(&upa, 0, sizeof(upa));
9616 error = got_worktree_rebase_merge_files(&merged_paths,
9617 worktree, fileindex, parent_id, commit_id, repo,
9618 update_progress, &upa, check_cancelled, NULL);
9619 if (error)
9620 goto done;
9622 print_merge_progress_stats(&upa);
9623 if (upa.conflicts > 0 || upa.missing > 0 ||
9624 upa.not_deleted > 0 || upa.unversioned > 0) {
9625 if (upa.conflicts > 0) {
9626 error = show_rebase_merge_conflict(&qid->id,
9627 repo);
9628 if (error)
9629 goto done;
9631 got_worktree_rebase_pathlist_free(&merged_paths);
9632 break;
9635 error = rebase_commit(&merged_paths, worktree, fileindex,
9636 tmp_branch, commit_id, repo);
9637 got_worktree_rebase_pathlist_free(&merged_paths);
9638 if (error)
9639 goto done;
9642 if (upa.conflicts > 0 || upa.missing > 0 ||
9643 upa.not_deleted > 0 || upa.unversioned > 0) {
9644 error = got_worktree_rebase_postpone(worktree, fileindex);
9645 if (error)
9646 goto done;
9647 if (upa.conflicts > 0 && upa.missing == 0 &&
9648 upa.not_deleted == 0 && upa.unversioned == 0) {
9649 error = got_error_msg(GOT_ERR_CONFLICTS,
9650 "conflicts must be resolved before rebasing "
9651 "can continue");
9652 } else if (upa.conflicts > 0) {
9653 error = got_error_msg(GOT_ERR_CONFLICTS,
9654 "conflicts must be resolved before rebasing "
9655 "can continue; changes destined for some "
9656 "files were not yet merged and should be "
9657 "merged manually if required before the "
9658 "rebase operation is continued");
9659 } else {
9660 error = got_error_msg(GOT_ERR_CONFLICTS,
9661 "changes destined for some files were not "
9662 "yet merged and should be merged manually "
9663 "if required before the rebase operation "
9664 "is continued");
9666 } else
9667 error = rebase_complete(worktree, fileindex, branch,
9668 new_base_branch, tmp_branch, repo, create_backup);
9669 done:
9670 got_object_id_queue_free(&commits);
9671 free(branch_head_commit_id);
9672 free(resume_commit_id);
9673 free(yca_id);
9674 if (commit)
9675 got_object_commit_close(commit);
9676 if (branch)
9677 got_ref_close(branch);
9678 if (new_base_branch)
9679 got_ref_close(new_base_branch);
9680 if (tmp_branch)
9681 got_ref_close(tmp_branch);
9682 if (worktree)
9683 got_worktree_close(worktree);
9684 if (repo) {
9685 const struct got_error *close_err = got_repo_close(repo);
9686 if (error == NULL)
9687 error = close_err;
9689 return error;
9692 __dead static void
9693 usage_histedit(void)
9695 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9696 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9697 getprogname());
9698 exit(1);
9701 #define GOT_HISTEDIT_PICK 'p'
9702 #define GOT_HISTEDIT_EDIT 'e'
9703 #define GOT_HISTEDIT_FOLD 'f'
9704 #define GOT_HISTEDIT_DROP 'd'
9705 #define GOT_HISTEDIT_MESG 'm'
9707 static const struct got_histedit_cmd {
9708 unsigned char code;
9709 const char *name;
9710 const char *desc;
9711 } got_histedit_cmds[] = {
9712 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9713 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9714 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9715 "be used" },
9716 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9717 { GOT_HISTEDIT_MESG, "mesg",
9718 "single-line log message for commit above (open editor if empty)" },
9721 struct got_histedit_list_entry {
9722 TAILQ_ENTRY(got_histedit_list_entry) entry;
9723 struct got_object_id *commit_id;
9724 const struct got_histedit_cmd *cmd;
9725 char *logmsg;
9727 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9729 static const struct got_error *
9730 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9731 FILE *f, struct got_repository *repo)
9733 const struct got_error *err = NULL;
9734 char *logmsg = NULL, *id_str = NULL;
9735 struct got_commit_object *commit = NULL;
9736 int n;
9738 err = got_object_open_as_commit(&commit, repo, commit_id);
9739 if (err)
9740 goto done;
9742 err = get_short_logmsg(&logmsg, 34, commit);
9743 if (err)
9744 goto done;
9746 err = got_object_id_str(&id_str, commit_id);
9747 if (err)
9748 goto done;
9750 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9751 if (n < 0)
9752 err = got_ferror(f, GOT_ERR_IO);
9753 done:
9754 if (commit)
9755 got_object_commit_close(commit);
9756 free(id_str);
9757 free(logmsg);
9758 return err;
9761 static const struct got_error *
9762 histedit_write_commit_list(struct got_object_id_queue *commits,
9763 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9764 struct got_repository *repo)
9766 const struct got_error *err = NULL;
9767 struct got_object_qid *qid;
9768 const char *histedit_cmd = NULL;
9770 if (STAILQ_EMPTY(commits))
9771 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9773 STAILQ_FOREACH(qid, commits, entry) {
9774 histedit_cmd = got_histedit_cmds[0].name;
9775 if (edit_only)
9776 histedit_cmd = "edit";
9777 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9778 histedit_cmd = "fold";
9779 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9780 if (err)
9781 break;
9782 if (edit_logmsg_only) {
9783 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9784 if (n < 0) {
9785 err = got_ferror(f, GOT_ERR_IO);
9786 break;
9791 return err;
9794 static const struct got_error *
9795 write_cmd_list(FILE *f, const char *branch_name,
9796 struct got_object_id_queue *commits)
9798 const struct got_error *err = NULL;
9799 size_t i;
9800 int n;
9801 char *id_str;
9802 struct got_object_qid *qid;
9804 qid = STAILQ_FIRST(commits);
9805 err = got_object_id_str(&id_str, &qid->id);
9806 if (err)
9807 return err;
9809 n = fprintf(f,
9810 "# Editing the history of branch '%s' starting at\n"
9811 "# commit %s\n"
9812 "# Commits will be processed in order from top to "
9813 "bottom of this file.\n", branch_name, id_str);
9814 if (n < 0) {
9815 err = got_ferror(f, GOT_ERR_IO);
9816 goto done;
9819 n = fprintf(f, "# Available histedit commands:\n");
9820 if (n < 0) {
9821 err = got_ferror(f, GOT_ERR_IO);
9822 goto done;
9825 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9826 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9827 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9828 cmd->desc);
9829 if (n < 0) {
9830 err = got_ferror(f, GOT_ERR_IO);
9831 break;
9834 done:
9835 free(id_str);
9836 return err;
9839 static const struct got_error *
9840 histedit_syntax_error(int lineno)
9842 static char msg[42];
9843 int ret;
9845 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9846 lineno);
9847 if (ret == -1 || ret >= sizeof(msg))
9848 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9850 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9853 static const struct got_error *
9854 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9855 char *logmsg, struct got_repository *repo)
9857 const struct got_error *err;
9858 struct got_commit_object *folded_commit = NULL;
9859 char *id_str, *folded_logmsg = NULL;
9861 err = got_object_id_str(&id_str, hle->commit_id);
9862 if (err)
9863 return err;
9865 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9866 if (err)
9867 goto done;
9869 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9870 if (err)
9871 goto done;
9872 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9873 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9874 folded_logmsg) == -1) {
9875 err = got_error_from_errno("asprintf");
9877 done:
9878 if (folded_commit)
9879 got_object_commit_close(folded_commit);
9880 free(id_str);
9881 free(folded_logmsg);
9882 return err;
9885 static struct got_histedit_list_entry *
9886 get_folded_commits(struct got_histedit_list_entry *hle)
9888 struct got_histedit_list_entry *prev, *folded = NULL;
9890 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9891 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9892 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9893 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9894 folded = prev;
9895 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9898 return folded;
9901 static const struct got_error *
9902 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9903 struct got_repository *repo)
9905 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9906 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9907 const struct got_error *err = NULL;
9908 struct got_commit_object *commit = NULL;
9909 int logmsg_len;
9910 int fd;
9911 struct got_histedit_list_entry *folded = NULL;
9913 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9914 if (err)
9915 return err;
9917 folded = get_folded_commits(hle);
9918 if (folded) {
9919 while (folded != hle) {
9920 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9921 folded = TAILQ_NEXT(folded, entry);
9922 continue;
9924 err = append_folded_commit_msg(&new_msg, folded,
9925 logmsg, repo);
9926 if (err)
9927 goto done;
9928 free(logmsg);
9929 logmsg = new_msg;
9930 folded = TAILQ_NEXT(folded, entry);
9934 err = got_object_id_str(&id_str, hle->commit_id);
9935 if (err)
9936 goto done;
9937 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9938 if (err)
9939 goto done;
9940 logmsg_len = asprintf(&new_msg,
9941 "%s\n# original log message of commit %s: %s",
9942 logmsg ? logmsg : "", id_str, orig_logmsg);
9943 if (logmsg_len == -1) {
9944 err = got_error_from_errno("asprintf");
9945 goto done;
9947 free(logmsg);
9948 logmsg = new_msg;
9950 err = got_object_id_str(&id_str, hle->commit_id);
9951 if (err)
9952 goto done;
9954 err = got_opentemp_named_fd(&logmsg_path, &fd,
9955 GOT_TMPDIR_STR "/got-logmsg");
9956 if (err)
9957 goto done;
9959 write(fd, logmsg, logmsg_len);
9960 close(fd);
9962 err = get_editor(&editor);
9963 if (err)
9964 goto done;
9966 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9967 logmsg_len, 0);
9968 if (err) {
9969 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9970 goto done;
9971 err = NULL;
9972 hle->logmsg = strdup(new_msg);
9973 if (hle->logmsg == NULL)
9974 err = got_error_from_errno("strdup");
9976 done:
9977 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9978 err = got_error_from_errno2("unlink", logmsg_path);
9979 free(logmsg_path);
9980 free(logmsg);
9981 free(orig_logmsg);
9982 free(editor);
9983 if (commit)
9984 got_object_commit_close(commit);
9985 return err;
9988 static const struct got_error *
9989 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9990 FILE *f, struct got_repository *repo)
9992 const struct got_error *err = NULL;
9993 char *line = NULL, *p, *end;
9994 size_t i, size;
9995 ssize_t len;
9996 int lineno = 0;
9997 const struct got_histedit_cmd *cmd;
9998 struct got_object_id *commit_id = NULL;
9999 struct got_histedit_list_entry *hle = NULL;
10001 for (;;) {
10002 len = getline(&line, &size, f);
10003 if (len == -1) {
10004 const struct got_error *getline_err;
10005 if (feof(f))
10006 break;
10007 getline_err = got_error_from_errno("getline");
10008 err = got_ferror(f, getline_err->code);
10009 break;
10011 lineno++;
10012 p = line;
10013 while (isspace((unsigned char)p[0]))
10014 p++;
10015 if (p[0] == '#' || p[0] == '\0') {
10016 free(line);
10017 line = NULL;
10018 continue;
10020 cmd = NULL;
10021 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10022 cmd = &got_histedit_cmds[i];
10023 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10024 isspace((unsigned char)p[strlen(cmd->name)])) {
10025 p += strlen(cmd->name);
10026 break;
10028 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10029 p++;
10030 break;
10033 if (i == nitems(got_histedit_cmds)) {
10034 err = histedit_syntax_error(lineno);
10035 break;
10037 while (isspace((unsigned char)p[0]))
10038 p++;
10039 if (cmd->code == GOT_HISTEDIT_MESG) {
10040 if (hle == NULL || hle->logmsg != NULL) {
10041 err = got_error(GOT_ERR_HISTEDIT_CMD);
10042 break;
10044 if (p[0] == '\0') {
10045 err = histedit_edit_logmsg(hle, repo);
10046 if (err)
10047 break;
10048 } else {
10049 hle->logmsg = strdup(p);
10050 if (hle->logmsg == NULL) {
10051 err = got_error_from_errno("strdup");
10052 break;
10055 free(line);
10056 line = NULL;
10057 continue;
10058 } else {
10059 end = p;
10060 while (end[0] && !isspace((unsigned char)end[0]))
10061 end++;
10062 *end = '\0';
10064 err = got_object_resolve_id_str(&commit_id, repo, p);
10065 if (err) {
10066 /* override error code */
10067 err = histedit_syntax_error(lineno);
10068 break;
10071 hle = malloc(sizeof(*hle));
10072 if (hle == NULL) {
10073 err = got_error_from_errno("malloc");
10074 break;
10076 hle->cmd = cmd;
10077 hle->commit_id = commit_id;
10078 hle->logmsg = NULL;
10079 commit_id = NULL;
10080 free(line);
10081 line = NULL;
10082 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10085 free(line);
10086 free(commit_id);
10087 return err;
10090 static const struct got_error *
10091 histedit_check_script(struct got_histedit_list *histedit_cmds,
10092 struct got_object_id_queue *commits, struct got_repository *repo)
10094 const struct got_error *err = NULL;
10095 struct got_object_qid *qid;
10096 struct got_histedit_list_entry *hle;
10097 static char msg[92];
10098 char *id_str;
10100 if (TAILQ_EMPTY(histedit_cmds))
10101 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10102 "histedit script contains no commands");
10103 if (STAILQ_EMPTY(commits))
10104 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10106 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10107 struct got_histedit_list_entry *hle2;
10108 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10109 if (hle == hle2)
10110 continue;
10111 if (got_object_id_cmp(hle->commit_id,
10112 hle2->commit_id) != 0)
10113 continue;
10114 err = got_object_id_str(&id_str, hle->commit_id);
10115 if (err)
10116 return err;
10117 snprintf(msg, sizeof(msg), "commit %s is listed "
10118 "more than once in histedit script", id_str);
10119 free(id_str);
10120 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10124 STAILQ_FOREACH(qid, commits, entry) {
10125 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10126 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10127 break;
10129 if (hle == NULL) {
10130 err = got_object_id_str(&id_str, &qid->id);
10131 if (err)
10132 return err;
10133 snprintf(msg, sizeof(msg),
10134 "commit %s missing from histedit script", id_str);
10135 free(id_str);
10136 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10140 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10141 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10142 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10143 "last commit in histedit script cannot be folded");
10145 return NULL;
10148 static const struct got_error *
10149 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10150 const char *path, struct got_object_id_queue *commits,
10151 struct got_repository *repo)
10153 const struct got_error *err = NULL;
10154 char *editor;
10155 FILE *f = NULL;
10157 err = get_editor(&editor);
10158 if (err)
10159 return err;
10161 if (spawn_editor(editor, path) == -1) {
10162 err = got_error_from_errno("failed spawning editor");
10163 goto done;
10166 f = fopen(path, "re");
10167 if (f == NULL) {
10168 err = got_error_from_errno("fopen");
10169 goto done;
10171 err = histedit_parse_list(histedit_cmds, f, repo);
10172 if (err)
10173 goto done;
10175 err = histedit_check_script(histedit_cmds, commits, repo);
10176 done:
10177 if (f && fclose(f) == EOF && err == NULL)
10178 err = got_error_from_errno("fclose");
10179 free(editor);
10180 return err;
10183 static const struct got_error *
10184 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10185 struct got_object_id_queue *, const char *, const char *,
10186 struct got_repository *);
10188 static const struct got_error *
10189 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10190 struct got_object_id_queue *commits, const char *branch_name,
10191 int edit_logmsg_only, int fold_only, int edit_only,
10192 struct got_repository *repo)
10194 const struct got_error *err;
10195 FILE *f = NULL;
10196 char *path = NULL;
10198 err = got_opentemp_named(&path, &f, "got-histedit");
10199 if (err)
10200 return err;
10202 err = write_cmd_list(f, branch_name, commits);
10203 if (err)
10204 goto done;
10206 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10207 fold_only, edit_only, repo);
10208 if (err)
10209 goto done;
10211 if (edit_logmsg_only || fold_only || edit_only) {
10212 rewind(f);
10213 err = histedit_parse_list(histedit_cmds, f, repo);
10214 } else {
10215 if (fclose(f) == EOF) {
10216 err = got_error_from_errno("fclose");
10217 goto done;
10219 f = NULL;
10220 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10221 if (err) {
10222 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10223 err->code != GOT_ERR_HISTEDIT_CMD)
10224 goto done;
10225 err = histedit_edit_list_retry(histedit_cmds, err,
10226 commits, path, branch_name, repo);
10229 done:
10230 if (f && fclose(f) == EOF && err == NULL)
10231 err = got_error_from_errno("fclose");
10232 if (path && unlink(path) != 0 && err == NULL)
10233 err = got_error_from_errno2("unlink", path);
10234 free(path);
10235 return err;
10238 static const struct got_error *
10239 histedit_save_list(struct got_histedit_list *histedit_cmds,
10240 struct got_worktree *worktree, struct got_repository *repo)
10242 const struct got_error *err = NULL;
10243 char *path = NULL;
10244 FILE *f = NULL;
10245 struct got_histedit_list_entry *hle;
10246 struct got_commit_object *commit = NULL;
10248 err = got_worktree_get_histedit_script_path(&path, worktree);
10249 if (err)
10250 return err;
10252 f = fopen(path, "we");
10253 if (f == NULL) {
10254 err = got_error_from_errno2("fopen", path);
10255 goto done;
10257 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10258 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10259 repo);
10260 if (err)
10261 break;
10263 if (hle->logmsg) {
10264 int n = fprintf(f, "%c %s\n",
10265 GOT_HISTEDIT_MESG, hle->logmsg);
10266 if (n < 0) {
10267 err = got_ferror(f, GOT_ERR_IO);
10268 break;
10272 done:
10273 if (f && fclose(f) == EOF && err == NULL)
10274 err = got_error_from_errno("fclose");
10275 free(path);
10276 if (commit)
10277 got_object_commit_close(commit);
10278 return err;
10281 void
10282 histedit_free_list(struct got_histedit_list *histedit_cmds)
10284 struct got_histedit_list_entry *hle;
10286 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10287 TAILQ_REMOVE(histedit_cmds, hle, entry);
10288 free(hle);
10292 static const struct got_error *
10293 histedit_load_list(struct got_histedit_list *histedit_cmds,
10294 const char *path, struct got_repository *repo)
10296 const struct got_error *err = NULL;
10297 FILE *f = NULL;
10299 f = fopen(path, "re");
10300 if (f == NULL) {
10301 err = got_error_from_errno2("fopen", path);
10302 goto done;
10305 err = histedit_parse_list(histedit_cmds, f, repo);
10306 done:
10307 if (f && fclose(f) == EOF && err == NULL)
10308 err = got_error_from_errno("fclose");
10309 return err;
10312 static const struct got_error *
10313 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10314 const struct got_error *edit_err, struct got_object_id_queue *commits,
10315 const char *path, const char *branch_name, struct got_repository *repo)
10317 const struct got_error *err = NULL, *prev_err = edit_err;
10318 int resp = ' ';
10320 while (resp != 'c' && resp != 'r' && resp != 'a') {
10321 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10322 "or (a)bort: ", getprogname(), prev_err->msg);
10323 resp = getchar();
10324 if (resp == '\n')
10325 resp = getchar();
10326 if (resp == 'c') {
10327 histedit_free_list(histedit_cmds);
10328 err = histedit_run_editor(histedit_cmds, path, commits,
10329 repo);
10330 if (err) {
10331 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10332 err->code != GOT_ERR_HISTEDIT_CMD)
10333 break;
10334 prev_err = err;
10335 resp = ' ';
10336 continue;
10338 break;
10339 } else if (resp == 'r') {
10340 histedit_free_list(histedit_cmds);
10341 err = histedit_edit_script(histedit_cmds,
10342 commits, branch_name, 0, 0, 0, repo);
10343 if (err) {
10344 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10345 err->code != GOT_ERR_HISTEDIT_CMD)
10346 break;
10347 prev_err = err;
10348 resp = ' ';
10349 continue;
10351 break;
10352 } else if (resp == 'a') {
10353 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10354 break;
10355 } else
10356 printf("invalid response '%c'\n", resp);
10359 return err;
10362 static const struct got_error *
10363 histedit_complete(struct got_worktree *worktree,
10364 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10365 struct got_reference *branch, struct got_repository *repo)
10367 printf("Switching work tree to %s\n",
10368 got_ref_get_symref_target(branch));
10369 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10370 branch, repo);
10373 static const struct got_error *
10374 show_histedit_progress(struct got_commit_object *commit,
10375 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10377 const struct got_error *err;
10378 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10380 err = got_object_id_str(&old_id_str, hle->commit_id);
10381 if (err)
10382 goto done;
10384 if (new_id) {
10385 err = got_object_id_str(&new_id_str, new_id);
10386 if (err)
10387 goto done;
10390 old_id_str[12] = '\0';
10391 if (new_id_str)
10392 new_id_str[12] = '\0';
10394 if (hle->logmsg) {
10395 logmsg = strdup(hle->logmsg);
10396 if (logmsg == NULL) {
10397 err = got_error_from_errno("strdup");
10398 goto done;
10400 trim_logmsg(logmsg, 42);
10401 } else {
10402 err = get_short_logmsg(&logmsg, 42, commit);
10403 if (err)
10404 goto done;
10407 switch (hle->cmd->code) {
10408 case GOT_HISTEDIT_PICK:
10409 case GOT_HISTEDIT_EDIT:
10410 printf("%s -> %s: %s\n", old_id_str,
10411 new_id_str ? new_id_str : "no-op change", logmsg);
10412 break;
10413 case GOT_HISTEDIT_DROP:
10414 case GOT_HISTEDIT_FOLD:
10415 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10416 logmsg);
10417 break;
10418 default:
10419 break;
10421 done:
10422 free(old_id_str);
10423 free(new_id_str);
10424 return err;
10427 static const struct got_error *
10428 histedit_commit(struct got_pathlist_head *merged_paths,
10429 struct got_worktree *worktree, struct got_fileindex *fileindex,
10430 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10431 struct got_repository *repo)
10433 const struct got_error *err;
10434 struct got_commit_object *commit;
10435 struct got_object_id *new_commit_id;
10437 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10438 && hle->logmsg == NULL) {
10439 err = histedit_edit_logmsg(hle, repo);
10440 if (err)
10441 return err;
10444 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10445 if (err)
10446 return err;
10448 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10449 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10450 hle->logmsg, repo);
10451 if (err) {
10452 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10453 goto done;
10454 err = show_histedit_progress(commit, hle, NULL);
10455 } else {
10456 err = show_histedit_progress(commit, hle, new_commit_id);
10457 free(new_commit_id);
10459 done:
10460 got_object_commit_close(commit);
10461 return err;
10464 static const struct got_error *
10465 histedit_skip_commit(struct got_histedit_list_entry *hle,
10466 struct got_worktree *worktree, struct got_repository *repo)
10468 const struct got_error *error;
10469 struct got_commit_object *commit;
10471 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10472 repo);
10473 if (error)
10474 return error;
10476 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10477 if (error)
10478 return error;
10480 error = show_histedit_progress(commit, hle, NULL);
10481 got_object_commit_close(commit);
10482 return error;
10485 static const struct got_error *
10486 check_local_changes(void *arg, unsigned char status,
10487 unsigned char staged_status, const char *path,
10488 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10489 struct got_object_id *commit_id, int dirfd, const char *de_name)
10491 int *have_local_changes = arg;
10493 switch (status) {
10494 case GOT_STATUS_ADD:
10495 case GOT_STATUS_DELETE:
10496 case GOT_STATUS_MODIFY:
10497 case GOT_STATUS_CONFLICT:
10498 *have_local_changes = 1;
10499 return got_error(GOT_ERR_CANCELLED);
10500 default:
10501 break;
10504 switch (staged_status) {
10505 case GOT_STATUS_ADD:
10506 case GOT_STATUS_DELETE:
10507 case GOT_STATUS_MODIFY:
10508 *have_local_changes = 1;
10509 return got_error(GOT_ERR_CANCELLED);
10510 default:
10511 break;
10514 return NULL;
10517 static const struct got_error *
10518 cmd_histedit(int argc, char *argv[])
10520 const struct got_error *error = NULL;
10521 struct got_worktree *worktree = NULL;
10522 struct got_fileindex *fileindex = NULL;
10523 struct got_repository *repo = NULL;
10524 char *cwd = NULL;
10525 struct got_reference *branch = NULL;
10526 struct got_reference *tmp_branch = NULL;
10527 struct got_object_id *resume_commit_id = NULL;
10528 struct got_object_id *base_commit_id = NULL;
10529 struct got_object_id *head_commit_id = NULL;
10530 struct got_commit_object *commit = NULL;
10531 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10532 struct got_update_progress_arg upa;
10533 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10534 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10535 int list_backups = 0, delete_backups = 0;
10536 const char *edit_script_path = NULL;
10537 struct got_object_id_queue commits;
10538 struct got_pathlist_head merged_paths;
10539 const struct got_object_id_queue *parent_ids;
10540 struct got_object_qid *pid;
10541 struct got_histedit_list histedit_cmds;
10542 struct got_histedit_list_entry *hle;
10544 STAILQ_INIT(&commits);
10545 TAILQ_INIT(&histedit_cmds);
10546 TAILQ_INIT(&merged_paths);
10547 memset(&upa, 0, sizeof(upa));
10549 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10550 switch (ch) {
10551 case 'a':
10552 abort_edit = 1;
10553 break;
10554 case 'c':
10555 continue_edit = 1;
10556 break;
10557 case 'e':
10558 edit_only = 1;
10559 break;
10560 case 'f':
10561 fold_only = 1;
10562 break;
10563 case 'F':
10564 edit_script_path = optarg;
10565 break;
10566 case 'm':
10567 edit_logmsg_only = 1;
10568 break;
10569 case 'l':
10570 list_backups = 1;
10571 break;
10572 case 'X':
10573 delete_backups = 1;
10574 break;
10575 default:
10576 usage_histedit();
10577 /* NOTREACHED */
10581 argc -= optind;
10582 argv += optind;
10584 #ifndef PROFILE
10585 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10586 "unveil", NULL) == -1)
10587 err(1, "pledge");
10588 #endif
10589 if (abort_edit && continue_edit)
10590 option_conflict('a', 'c');
10591 if (edit_script_path && edit_logmsg_only)
10592 option_conflict('F', 'm');
10593 if (abort_edit && edit_logmsg_only)
10594 option_conflict('a', 'm');
10595 if (continue_edit && edit_logmsg_only)
10596 option_conflict('c', 'm');
10597 if (abort_edit && fold_only)
10598 option_conflict('a', 'f');
10599 if (continue_edit && fold_only)
10600 option_conflict('c', 'f');
10601 if (fold_only && edit_logmsg_only)
10602 option_conflict('f', 'm');
10603 if (edit_script_path && fold_only)
10604 option_conflict('F', 'f');
10605 if (abort_edit && edit_only)
10606 option_conflict('a', 'e');
10607 if (continue_edit && edit_only)
10608 option_conflict('c', 'e');
10609 if (edit_only && edit_logmsg_only)
10610 option_conflict('e', 'm');
10611 if (edit_script_path && edit_only)
10612 option_conflict('F', 'e');
10613 if (list_backups) {
10614 if (abort_edit)
10615 option_conflict('l', 'a');
10616 if (continue_edit)
10617 option_conflict('l', 'c');
10618 if (edit_script_path)
10619 option_conflict('l', 'F');
10620 if (edit_logmsg_only)
10621 option_conflict('l', 'm');
10622 if (fold_only)
10623 option_conflict('l', 'f');
10624 if (edit_only)
10625 option_conflict('l', 'e');
10626 if (delete_backups)
10627 option_conflict('l', 'X');
10628 if (argc != 0 && argc != 1)
10629 usage_histedit();
10630 } else if (delete_backups) {
10631 if (abort_edit)
10632 option_conflict('X', 'a');
10633 if (continue_edit)
10634 option_conflict('X', 'c');
10635 if (edit_script_path)
10636 option_conflict('X', 'F');
10637 if (edit_logmsg_only)
10638 option_conflict('X', 'm');
10639 if (fold_only)
10640 option_conflict('X', 'f');
10641 if (edit_only)
10642 option_conflict('X', 'e');
10643 if (list_backups)
10644 option_conflict('X', 'l');
10645 if (argc != 0 && argc != 1)
10646 usage_histedit();
10647 } else if (argc != 0)
10648 usage_histedit();
10651 * This command cannot apply unveil(2) in all cases because the
10652 * user may choose to run an editor to edit the histedit script
10653 * and to edit individual commit log messages.
10654 * unveil(2) traverses exec(2); if an editor is used we have to
10655 * apply unveil after edit script and log messages have been written.
10656 * XXX TODO: Make use of unveil(2) where possible.
10659 cwd = getcwd(NULL, 0);
10660 if (cwd == NULL) {
10661 error = got_error_from_errno("getcwd");
10662 goto done;
10664 error = got_worktree_open(&worktree, cwd);
10665 if (error) {
10666 if (list_backups || delete_backups) {
10667 if (error->code != GOT_ERR_NOT_WORKTREE)
10668 goto done;
10669 } else {
10670 if (error->code == GOT_ERR_NOT_WORKTREE)
10671 error = wrap_not_worktree_error(error,
10672 "histedit", cwd);
10673 goto done;
10677 if (list_backups || delete_backups) {
10678 error = got_repo_open(&repo,
10679 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10680 NULL);
10681 if (error != NULL)
10682 goto done;
10683 error = apply_unveil(got_repo_get_path(repo), 0,
10684 worktree ? got_worktree_get_root_path(worktree) : NULL);
10685 if (error)
10686 goto done;
10687 error = process_backup_refs(
10688 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10689 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10690 goto done; /* nothing else to do */
10693 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10694 NULL);
10695 if (error != NULL)
10696 goto done;
10698 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10699 if (error)
10700 goto done;
10701 if (rebase_in_progress) {
10702 error = got_error(GOT_ERR_REBASING);
10703 goto done;
10706 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10707 repo);
10708 if (error)
10709 goto done;
10710 if (merge_in_progress) {
10711 error = got_error(GOT_ERR_MERGE_BUSY);
10712 goto done;
10715 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10716 if (error)
10717 goto done;
10719 if (edit_in_progress && edit_logmsg_only) {
10720 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10721 "histedit operation is in progress in this "
10722 "work tree and must be continued or aborted "
10723 "before the -m option can be used");
10724 goto done;
10726 if (edit_in_progress && fold_only) {
10727 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10728 "histedit operation is in progress in this "
10729 "work tree and must be continued or aborted "
10730 "before the -f option can be used");
10731 goto done;
10733 if (edit_in_progress && edit_only) {
10734 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10735 "histedit operation is in progress in this "
10736 "work tree and must be continued or aborted "
10737 "before the -e option can be used");
10738 goto done;
10741 if (edit_in_progress && abort_edit) {
10742 error = got_worktree_histedit_continue(&resume_commit_id,
10743 &tmp_branch, &branch, &base_commit_id, &fileindex,
10744 worktree, repo);
10745 if (error)
10746 goto done;
10747 printf("Switching work tree to %s\n",
10748 got_ref_get_symref_target(branch));
10749 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10750 branch, base_commit_id, abort_progress, &upa);
10751 if (error)
10752 goto done;
10753 printf("Histedit of %s aborted\n",
10754 got_ref_get_symref_target(branch));
10755 print_merge_progress_stats(&upa);
10756 goto done; /* nothing else to do */
10757 } else if (abort_edit) {
10758 error = got_error(GOT_ERR_NOT_HISTEDIT);
10759 goto done;
10762 if (continue_edit) {
10763 char *path;
10765 if (!edit_in_progress) {
10766 error = got_error(GOT_ERR_NOT_HISTEDIT);
10767 goto done;
10770 error = got_worktree_get_histedit_script_path(&path, worktree);
10771 if (error)
10772 goto done;
10774 error = histedit_load_list(&histedit_cmds, path, repo);
10775 free(path);
10776 if (error)
10777 goto done;
10779 error = got_worktree_histedit_continue(&resume_commit_id,
10780 &tmp_branch, &branch, &base_commit_id, &fileindex,
10781 worktree, repo);
10782 if (error)
10783 goto done;
10785 error = got_ref_resolve(&head_commit_id, repo, branch);
10786 if (error)
10787 goto done;
10789 error = got_object_open_as_commit(&commit, repo,
10790 head_commit_id);
10791 if (error)
10792 goto done;
10793 parent_ids = got_object_commit_get_parent_ids(commit);
10794 pid = STAILQ_FIRST(parent_ids);
10795 if (pid == NULL) {
10796 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10797 goto done;
10799 error = collect_commits(&commits, head_commit_id, &pid->id,
10800 base_commit_id, got_worktree_get_path_prefix(worktree),
10801 GOT_ERR_HISTEDIT_PATH, repo);
10802 got_object_commit_close(commit);
10803 commit = NULL;
10804 if (error)
10805 goto done;
10806 } else {
10807 if (edit_in_progress) {
10808 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10809 goto done;
10812 error = got_ref_open(&branch, repo,
10813 got_worktree_get_head_ref_name(worktree), 0);
10814 if (error != NULL)
10815 goto done;
10817 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10818 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10819 "will not edit commit history of a branch outside "
10820 "the \"refs/heads/\" reference namespace");
10821 goto done;
10824 error = got_ref_resolve(&head_commit_id, repo, branch);
10825 got_ref_close(branch);
10826 branch = NULL;
10827 if (error)
10828 goto done;
10830 error = got_object_open_as_commit(&commit, repo,
10831 head_commit_id);
10832 if (error)
10833 goto done;
10834 parent_ids = got_object_commit_get_parent_ids(commit);
10835 pid = STAILQ_FIRST(parent_ids);
10836 if (pid == NULL) {
10837 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10838 goto done;
10840 error = collect_commits(&commits, head_commit_id, &pid->id,
10841 got_worktree_get_base_commit_id(worktree),
10842 got_worktree_get_path_prefix(worktree),
10843 GOT_ERR_HISTEDIT_PATH, repo);
10844 got_object_commit_close(commit);
10845 commit = NULL;
10846 if (error)
10847 goto done;
10849 if (STAILQ_EMPTY(&commits)) {
10850 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10851 goto done;
10854 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10855 &base_commit_id, &fileindex, worktree, repo);
10856 if (error)
10857 goto done;
10859 if (edit_script_path) {
10860 error = histedit_load_list(&histedit_cmds,
10861 edit_script_path, repo);
10862 if (error) {
10863 got_worktree_histedit_abort(worktree, fileindex,
10864 repo, branch, base_commit_id,
10865 abort_progress, &upa);
10866 print_merge_progress_stats(&upa);
10867 goto done;
10869 } else {
10870 const char *branch_name;
10871 branch_name = got_ref_get_symref_target(branch);
10872 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10873 branch_name += 11;
10874 error = histedit_edit_script(&histedit_cmds, &commits,
10875 branch_name, edit_logmsg_only, fold_only,
10876 edit_only, repo);
10877 if (error) {
10878 got_worktree_histedit_abort(worktree, fileindex,
10879 repo, branch, base_commit_id,
10880 abort_progress, &upa);
10881 print_merge_progress_stats(&upa);
10882 goto done;
10887 error = histedit_save_list(&histedit_cmds, worktree,
10888 repo);
10889 if (error) {
10890 got_worktree_histedit_abort(worktree, fileindex,
10891 repo, branch, base_commit_id,
10892 abort_progress, &upa);
10893 print_merge_progress_stats(&upa);
10894 goto done;
10899 error = histedit_check_script(&histedit_cmds, &commits, repo);
10900 if (error)
10901 goto done;
10903 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10904 if (resume_commit_id) {
10905 if (got_object_id_cmp(hle->commit_id,
10906 resume_commit_id) != 0)
10907 continue;
10909 resume_commit_id = NULL;
10910 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10911 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10912 error = histedit_skip_commit(hle, worktree,
10913 repo);
10914 if (error)
10915 goto done;
10916 } else {
10917 struct got_pathlist_head paths;
10918 int have_changes = 0;
10920 TAILQ_INIT(&paths);
10921 error = got_pathlist_append(&paths, "", NULL);
10922 if (error)
10923 goto done;
10924 error = got_worktree_status(worktree, &paths,
10925 repo, 0, check_local_changes, &have_changes,
10926 check_cancelled, NULL);
10927 got_pathlist_free(&paths);
10928 if (error) {
10929 if (error->code != GOT_ERR_CANCELLED)
10930 goto done;
10931 if (sigint_received || sigpipe_received)
10932 goto done;
10934 if (have_changes) {
10935 error = histedit_commit(NULL, worktree,
10936 fileindex, tmp_branch, hle, repo);
10937 if (error)
10938 goto done;
10939 } else {
10940 error = got_object_open_as_commit(
10941 &commit, repo, hle->commit_id);
10942 if (error)
10943 goto done;
10944 error = show_histedit_progress(commit,
10945 hle, NULL);
10946 got_object_commit_close(commit);
10947 commit = NULL;
10948 if (error)
10949 goto done;
10952 continue;
10955 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10956 error = histedit_skip_commit(hle, worktree, repo);
10957 if (error)
10958 goto done;
10959 continue;
10962 error = got_object_open_as_commit(&commit, repo,
10963 hle->commit_id);
10964 if (error)
10965 goto done;
10966 parent_ids = got_object_commit_get_parent_ids(commit);
10967 pid = STAILQ_FIRST(parent_ids);
10969 error = got_worktree_histedit_merge_files(&merged_paths,
10970 worktree, fileindex, &pid->id, hle->commit_id, repo,
10971 update_progress, &upa, check_cancelled, NULL);
10972 if (error)
10973 goto done;
10974 got_object_commit_close(commit);
10975 commit = NULL;
10977 print_merge_progress_stats(&upa);
10978 if (upa.conflicts > 0 || upa.missing > 0 ||
10979 upa.not_deleted > 0 || upa.unversioned > 0) {
10980 if (upa.conflicts > 0) {
10981 error = show_rebase_merge_conflict(
10982 hle->commit_id, repo);
10983 if (error)
10984 goto done;
10986 got_worktree_rebase_pathlist_free(&merged_paths);
10987 break;
10990 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10991 char *id_str;
10992 error = got_object_id_str(&id_str, hle->commit_id);
10993 if (error)
10994 goto done;
10995 printf("Stopping histedit for amending commit %s\n",
10996 id_str);
10997 free(id_str);
10998 got_worktree_rebase_pathlist_free(&merged_paths);
10999 error = got_worktree_histedit_postpone(worktree,
11000 fileindex);
11001 goto done;
11004 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11005 error = histedit_skip_commit(hle, worktree, repo);
11006 if (error)
11007 goto done;
11008 continue;
11011 error = histedit_commit(&merged_paths, worktree, fileindex,
11012 tmp_branch, hle, repo);
11013 got_worktree_rebase_pathlist_free(&merged_paths);
11014 if (error)
11015 goto done;
11018 if (upa.conflicts > 0 || upa.missing > 0 ||
11019 upa.not_deleted > 0 || upa.unversioned > 0) {
11020 error = got_worktree_histedit_postpone(worktree, fileindex);
11021 if (error)
11022 goto done;
11023 if (upa.conflicts > 0 && upa.missing == 0 &&
11024 upa.not_deleted == 0 && upa.unversioned == 0) {
11025 error = got_error_msg(GOT_ERR_CONFLICTS,
11026 "conflicts must be resolved before histedit "
11027 "can continue");
11028 } else if (upa.conflicts > 0) {
11029 error = got_error_msg(GOT_ERR_CONFLICTS,
11030 "conflicts must be resolved before histedit "
11031 "can continue; changes destined for some "
11032 "files were not yet merged and should be "
11033 "merged manually if required before the "
11034 "histedit operation is continued");
11035 } else {
11036 error = got_error_msg(GOT_ERR_CONFLICTS,
11037 "changes destined for some files were not "
11038 "yet merged and should be merged manually "
11039 "if required before the histedit operation "
11040 "is continued");
11042 } else
11043 error = histedit_complete(worktree, fileindex, tmp_branch,
11044 branch, repo);
11045 done:
11046 got_object_id_queue_free(&commits);
11047 histedit_free_list(&histedit_cmds);
11048 free(head_commit_id);
11049 free(base_commit_id);
11050 free(resume_commit_id);
11051 if (commit)
11052 got_object_commit_close(commit);
11053 if (branch)
11054 got_ref_close(branch);
11055 if (tmp_branch)
11056 got_ref_close(tmp_branch);
11057 if (worktree)
11058 got_worktree_close(worktree);
11059 if (repo) {
11060 const struct got_error *close_err = got_repo_close(repo);
11061 if (error == NULL)
11062 error = close_err;
11064 return error;
11067 __dead static void
11068 usage_integrate(void)
11070 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11071 exit(1);
11074 static const struct got_error *
11075 cmd_integrate(int argc, char *argv[])
11077 const struct got_error *error = NULL;
11078 struct got_repository *repo = NULL;
11079 struct got_worktree *worktree = NULL;
11080 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11081 const char *branch_arg = NULL;
11082 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11083 struct got_fileindex *fileindex = NULL;
11084 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11085 int ch;
11086 struct got_update_progress_arg upa;
11088 while ((ch = getopt(argc, argv, "")) != -1) {
11089 switch (ch) {
11090 default:
11091 usage_integrate();
11092 /* NOTREACHED */
11096 argc -= optind;
11097 argv += optind;
11099 if (argc != 1)
11100 usage_integrate();
11101 branch_arg = argv[0];
11102 #ifndef PROFILE
11103 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11104 "unveil", NULL) == -1)
11105 err(1, "pledge");
11106 #endif
11107 cwd = getcwd(NULL, 0);
11108 if (cwd == NULL) {
11109 error = got_error_from_errno("getcwd");
11110 goto done;
11113 error = got_worktree_open(&worktree, cwd);
11114 if (error) {
11115 if (error->code == GOT_ERR_NOT_WORKTREE)
11116 error = wrap_not_worktree_error(error, "integrate",
11117 cwd);
11118 goto done;
11121 error = check_rebase_or_histedit_in_progress(worktree);
11122 if (error)
11123 goto done;
11125 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11126 NULL);
11127 if (error != NULL)
11128 goto done;
11130 error = apply_unveil(got_repo_get_path(repo), 0,
11131 got_worktree_get_root_path(worktree));
11132 if (error)
11133 goto done;
11135 error = check_merge_in_progress(worktree, repo);
11136 if (error)
11137 goto done;
11139 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11140 error = got_error_from_errno("asprintf");
11141 goto done;
11144 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11145 &base_branch_ref, worktree, refname, repo);
11146 if (error)
11147 goto done;
11149 refname = strdup(got_ref_get_name(branch_ref));
11150 if (refname == NULL) {
11151 error = got_error_from_errno("strdup");
11152 got_worktree_integrate_abort(worktree, fileindex, repo,
11153 branch_ref, base_branch_ref);
11154 goto done;
11156 base_refname = strdup(got_ref_get_name(base_branch_ref));
11157 if (base_refname == NULL) {
11158 error = got_error_from_errno("strdup");
11159 got_worktree_integrate_abort(worktree, fileindex, repo,
11160 branch_ref, base_branch_ref);
11161 goto done;
11164 error = got_ref_resolve(&commit_id, repo, branch_ref);
11165 if (error)
11166 goto done;
11168 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11169 if (error)
11170 goto done;
11172 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11173 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11174 "specified branch has already been integrated");
11175 got_worktree_integrate_abort(worktree, fileindex, repo,
11176 branch_ref, base_branch_ref);
11177 goto done;
11180 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11181 if (error) {
11182 if (error->code == GOT_ERR_ANCESTRY)
11183 error = got_error(GOT_ERR_REBASE_REQUIRED);
11184 got_worktree_integrate_abort(worktree, fileindex, repo,
11185 branch_ref, base_branch_ref);
11186 goto done;
11189 memset(&upa, 0, sizeof(upa));
11190 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11191 branch_ref, base_branch_ref, update_progress, &upa,
11192 check_cancelled, NULL);
11193 if (error)
11194 goto done;
11196 printf("Integrated %s into %s\n", refname, base_refname);
11197 print_update_progress_stats(&upa);
11198 done:
11199 if (repo) {
11200 const struct got_error *close_err = got_repo_close(repo);
11201 if (error == NULL)
11202 error = close_err;
11204 if (worktree)
11205 got_worktree_close(worktree);
11206 free(cwd);
11207 free(base_commit_id);
11208 free(commit_id);
11209 free(refname);
11210 free(base_refname);
11211 return error;
11214 __dead static void
11215 usage_merge(void)
11217 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11218 getprogname());
11219 exit(1);
11222 static const struct got_error *
11223 cmd_merge(int argc, char *argv[])
11225 const struct got_error *error = NULL;
11226 struct got_worktree *worktree = NULL;
11227 struct got_repository *repo = NULL;
11228 struct got_fileindex *fileindex = NULL;
11229 char *cwd = NULL, *id_str = NULL, *author = NULL;
11230 struct got_reference *branch = NULL, *wt_branch = NULL;
11231 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11232 struct got_object_id *wt_branch_tip = NULL;
11233 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11234 int interrupt_merge = 0;
11235 struct got_update_progress_arg upa;
11236 struct got_object_id *merge_commit_id = NULL;
11237 char *branch_name = NULL;
11239 memset(&upa, 0, sizeof(upa));
11241 while ((ch = getopt(argc, argv, "acn")) != -1) {
11242 switch (ch) {
11243 case 'a':
11244 abort_merge = 1;
11245 break;
11246 case 'c':
11247 continue_merge = 1;
11248 break;
11249 case 'n':
11250 interrupt_merge = 1;
11251 break;
11252 default:
11253 usage_rebase();
11254 /* NOTREACHED */
11258 argc -= optind;
11259 argv += optind;
11261 #ifndef PROFILE
11262 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11263 "unveil", NULL) == -1)
11264 err(1, "pledge");
11265 #endif
11267 if (abort_merge && continue_merge)
11268 option_conflict('a', 'c');
11269 if (abort_merge || continue_merge) {
11270 if (argc != 0)
11271 usage_merge();
11272 } else if (argc != 1)
11273 usage_merge();
11275 cwd = getcwd(NULL, 0);
11276 if (cwd == NULL) {
11277 error = got_error_from_errno("getcwd");
11278 goto done;
11281 error = got_worktree_open(&worktree, cwd);
11282 if (error) {
11283 if (error->code == GOT_ERR_NOT_WORKTREE)
11284 error = wrap_not_worktree_error(error,
11285 "merge", cwd);
11286 goto done;
11289 error = got_repo_open(&repo,
11290 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11291 if (error != NULL)
11292 goto done;
11294 error = apply_unveil(got_repo_get_path(repo), 0,
11295 worktree ? got_worktree_get_root_path(worktree) : NULL);
11296 if (error)
11297 goto done;
11299 error = check_rebase_or_histedit_in_progress(worktree);
11300 if (error)
11301 goto done;
11303 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11304 repo);
11305 if (error)
11306 goto done;
11308 if (abort_merge) {
11309 if (!merge_in_progress) {
11310 error = got_error(GOT_ERR_NOT_MERGING);
11311 goto done;
11313 error = got_worktree_merge_continue(&branch_name,
11314 &branch_tip, &fileindex, worktree, repo);
11315 if (error)
11316 goto done;
11317 error = got_worktree_merge_abort(worktree, fileindex, repo,
11318 abort_progress, &upa);
11319 if (error)
11320 goto done;
11321 printf("Merge of %s aborted\n", branch_name);
11322 goto done; /* nothing else to do */
11325 error = get_author(&author, repo, worktree);
11326 if (error)
11327 goto done;
11329 if (continue_merge) {
11330 if (!merge_in_progress) {
11331 error = got_error(GOT_ERR_NOT_MERGING);
11332 goto done;
11334 error = got_worktree_merge_continue(&branch_name,
11335 &branch_tip, &fileindex, worktree, repo);
11336 if (error)
11337 goto done;
11338 } else {
11339 error = got_ref_open(&branch, repo, argv[0], 0);
11340 if (error != NULL)
11341 goto done;
11342 branch_name = strdup(got_ref_get_name(branch));
11343 if (branch_name == NULL) {
11344 error = got_error_from_errno("strdup");
11345 goto done;
11347 error = got_ref_resolve(&branch_tip, repo, branch);
11348 if (error)
11349 goto done;
11352 error = got_ref_open(&wt_branch, repo,
11353 got_worktree_get_head_ref_name(worktree), 0);
11354 if (error)
11355 goto done;
11356 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11357 if (error)
11358 goto done;
11359 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11360 wt_branch_tip, branch_tip, 0, repo,
11361 check_cancelled, NULL);
11362 if (error && error->code != GOT_ERR_ANCESTRY)
11363 goto done;
11365 if (!continue_merge) {
11366 error = check_path_prefix(wt_branch_tip, branch_tip,
11367 got_worktree_get_path_prefix(worktree),
11368 GOT_ERR_MERGE_PATH, repo);
11369 if (error)
11370 goto done;
11371 if (yca_id) {
11372 error = check_same_branch(wt_branch_tip, branch,
11373 yca_id, repo);
11374 if (error) {
11375 if (error->code != GOT_ERR_ANCESTRY)
11376 goto done;
11377 error = NULL;
11378 } else {
11379 static char msg[512];
11380 snprintf(msg, sizeof(msg),
11381 "cannot create a merge commit because "
11382 "%s is based on %s; %s can be integrated "
11383 "with 'got integrate' instead", branch_name,
11384 got_worktree_get_head_ref_name(worktree),
11385 branch_name);
11386 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11387 goto done;
11390 error = got_worktree_merge_prepare(&fileindex, worktree,
11391 branch, repo);
11392 if (error)
11393 goto done;
11395 error = got_worktree_merge_branch(worktree, fileindex,
11396 yca_id, branch_tip, repo, update_progress, &upa,
11397 check_cancelled, NULL);
11398 if (error)
11399 goto done;
11400 print_merge_progress_stats(&upa);
11401 if (!upa.did_something) {
11402 error = got_worktree_merge_abort(worktree, fileindex,
11403 repo, abort_progress, &upa);
11404 if (error)
11405 goto done;
11406 printf("Already up-to-date\n");
11407 goto done;
11411 if (interrupt_merge) {
11412 error = got_worktree_merge_postpone(worktree, fileindex);
11413 if (error)
11414 goto done;
11415 printf("Merge of %s interrupted on request\n", branch_name);
11416 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11417 upa.not_deleted > 0 || upa.unversioned > 0) {
11418 error = got_worktree_merge_postpone(worktree, fileindex);
11419 if (error)
11420 goto done;
11421 if (upa.conflicts > 0 && upa.missing == 0 &&
11422 upa.not_deleted == 0 && upa.unversioned == 0) {
11423 error = got_error_msg(GOT_ERR_CONFLICTS,
11424 "conflicts must be resolved before merging "
11425 "can continue");
11426 } else if (upa.conflicts > 0) {
11427 error = got_error_msg(GOT_ERR_CONFLICTS,
11428 "conflicts must be resolved before merging "
11429 "can continue; changes destined for some "
11430 "files were not yet merged and "
11431 "should be merged manually if required before the "
11432 "merge operation is continued");
11433 } else {
11434 error = got_error_msg(GOT_ERR_CONFLICTS,
11435 "changes destined for some "
11436 "files were not yet merged and should be "
11437 "merged manually if required before the "
11438 "merge operation is continued");
11440 goto done;
11441 } else {
11442 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11443 fileindex, author, NULL, 1, branch_tip, branch_name,
11444 repo, continue_merge ? print_status : NULL, NULL);
11445 if (error)
11446 goto done;
11447 error = got_worktree_merge_complete(worktree, fileindex, repo);
11448 if (error)
11449 goto done;
11450 error = got_object_id_str(&id_str, merge_commit_id);
11451 if (error)
11452 goto done;
11453 printf("Merged %s into %s: %s\n", branch_name,
11454 got_worktree_get_head_ref_name(worktree),
11455 id_str);
11458 done:
11459 free(id_str);
11460 free(merge_commit_id);
11461 free(author);
11462 free(branch_tip);
11463 free(branch_name);
11464 free(yca_id);
11465 if (branch)
11466 got_ref_close(branch);
11467 if (wt_branch)
11468 got_ref_close(wt_branch);
11469 if (worktree)
11470 got_worktree_close(worktree);
11471 if (repo) {
11472 const struct got_error *close_err = got_repo_close(repo);
11473 if (error == NULL)
11474 error = close_err;
11476 return error;
11479 __dead static void
11480 usage_stage(void)
11482 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11483 "[-S] [file-path ...]\n",
11484 getprogname());
11485 exit(1);
11488 static const struct got_error *
11489 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11490 const char *path, struct got_object_id *blob_id,
11491 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11492 int dirfd, const char *de_name)
11494 const struct got_error *err = NULL;
11495 char *id_str = NULL;
11497 if (staged_status != GOT_STATUS_ADD &&
11498 staged_status != GOT_STATUS_MODIFY &&
11499 staged_status != GOT_STATUS_DELETE)
11500 return NULL;
11502 if (staged_status == GOT_STATUS_ADD ||
11503 staged_status == GOT_STATUS_MODIFY)
11504 err = got_object_id_str(&id_str, staged_blob_id);
11505 else
11506 err = got_object_id_str(&id_str, blob_id);
11507 if (err)
11508 return err;
11510 printf("%s %c %s\n", id_str, staged_status, path);
11511 free(id_str);
11512 return NULL;
11515 static const struct got_error *
11516 cmd_stage(int argc, char *argv[])
11518 const struct got_error *error = NULL;
11519 struct got_repository *repo = NULL;
11520 struct got_worktree *worktree = NULL;
11521 char *cwd = NULL;
11522 struct got_pathlist_head paths;
11523 struct got_pathlist_entry *pe;
11524 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11525 FILE *patch_script_file = NULL;
11526 const char *patch_script_path = NULL;
11527 struct choose_patch_arg cpa;
11529 TAILQ_INIT(&paths);
11531 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11532 switch (ch) {
11533 case 'l':
11534 list_stage = 1;
11535 break;
11536 case 'p':
11537 pflag = 1;
11538 break;
11539 case 'F':
11540 patch_script_path = optarg;
11541 break;
11542 case 'S':
11543 allow_bad_symlinks = 1;
11544 break;
11545 default:
11546 usage_stage();
11547 /* NOTREACHED */
11551 argc -= optind;
11552 argv += optind;
11554 #ifndef PROFILE
11555 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11556 "unveil", NULL) == -1)
11557 err(1, "pledge");
11558 #endif
11559 if (list_stage && (pflag || patch_script_path))
11560 errx(1, "-l option cannot be used with other options");
11561 if (patch_script_path && !pflag)
11562 errx(1, "-F option can only be used together with -p option");
11564 cwd = getcwd(NULL, 0);
11565 if (cwd == NULL) {
11566 error = got_error_from_errno("getcwd");
11567 goto done;
11570 error = got_worktree_open(&worktree, cwd);
11571 if (error) {
11572 if (error->code == GOT_ERR_NOT_WORKTREE)
11573 error = wrap_not_worktree_error(error, "stage", cwd);
11574 goto done;
11577 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11578 NULL);
11579 if (error != NULL)
11580 goto done;
11582 if (patch_script_path) {
11583 patch_script_file = fopen(patch_script_path, "re");
11584 if (patch_script_file == NULL) {
11585 error = got_error_from_errno2("fopen",
11586 patch_script_path);
11587 goto done;
11590 error = apply_unveil(got_repo_get_path(repo), 0,
11591 got_worktree_get_root_path(worktree));
11592 if (error)
11593 goto done;
11595 error = check_merge_in_progress(worktree, repo);
11596 if (error)
11597 goto done;
11599 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11600 if (error)
11601 goto done;
11603 if (list_stage)
11604 error = got_worktree_status(worktree, &paths, repo, 0,
11605 print_stage, NULL, check_cancelled, NULL);
11606 else {
11607 cpa.patch_script_file = patch_script_file;
11608 cpa.action = "stage";
11609 error = got_worktree_stage(worktree, &paths,
11610 pflag ? NULL : print_status, NULL,
11611 pflag ? choose_patch : NULL, &cpa,
11612 allow_bad_symlinks, repo);
11614 done:
11615 if (patch_script_file && fclose(patch_script_file) == EOF &&
11616 error == NULL)
11617 error = got_error_from_errno2("fclose", patch_script_path);
11618 if (repo) {
11619 const struct got_error *close_err = got_repo_close(repo);
11620 if (error == NULL)
11621 error = close_err;
11623 if (worktree)
11624 got_worktree_close(worktree);
11625 TAILQ_FOREACH(pe, &paths, entry)
11626 free((char *)pe->path);
11627 got_pathlist_free(&paths);
11628 free(cwd);
11629 return error;
11632 __dead static void
11633 usage_unstage(void)
11635 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11636 "[file-path ...]\n",
11637 getprogname());
11638 exit(1);
11642 static const struct got_error *
11643 cmd_unstage(int argc, char *argv[])
11645 const struct got_error *error = NULL;
11646 struct got_repository *repo = NULL;
11647 struct got_worktree *worktree = NULL;
11648 char *cwd = NULL;
11649 struct got_pathlist_head paths;
11650 struct got_pathlist_entry *pe;
11651 int ch, pflag = 0;
11652 struct got_update_progress_arg upa;
11653 FILE *patch_script_file = NULL;
11654 const char *patch_script_path = NULL;
11655 struct choose_patch_arg cpa;
11657 TAILQ_INIT(&paths);
11659 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11660 switch (ch) {
11661 case 'p':
11662 pflag = 1;
11663 break;
11664 case 'F':
11665 patch_script_path = optarg;
11666 break;
11667 default:
11668 usage_unstage();
11669 /* NOTREACHED */
11673 argc -= optind;
11674 argv += optind;
11676 #ifndef PROFILE
11677 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11678 "unveil", NULL) == -1)
11679 err(1, "pledge");
11680 #endif
11681 if (patch_script_path && !pflag)
11682 errx(1, "-F option can only be used together with -p option");
11684 cwd = getcwd(NULL, 0);
11685 if (cwd == NULL) {
11686 error = got_error_from_errno("getcwd");
11687 goto done;
11690 error = got_worktree_open(&worktree, cwd);
11691 if (error) {
11692 if (error->code == GOT_ERR_NOT_WORKTREE)
11693 error = wrap_not_worktree_error(error, "unstage", cwd);
11694 goto done;
11697 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11698 NULL);
11699 if (error != NULL)
11700 goto done;
11702 if (patch_script_path) {
11703 patch_script_file = fopen(patch_script_path, "re");
11704 if (patch_script_file == NULL) {
11705 error = got_error_from_errno2("fopen",
11706 patch_script_path);
11707 goto done;
11711 error = apply_unveil(got_repo_get_path(repo), 0,
11712 got_worktree_get_root_path(worktree));
11713 if (error)
11714 goto done;
11716 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11717 if (error)
11718 goto done;
11720 cpa.patch_script_file = patch_script_file;
11721 cpa.action = "unstage";
11722 memset(&upa, 0, sizeof(upa));
11723 error = got_worktree_unstage(worktree, &paths, update_progress,
11724 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11725 if (!error)
11726 print_merge_progress_stats(&upa);
11727 done:
11728 if (patch_script_file && fclose(patch_script_file) == EOF &&
11729 error == NULL)
11730 error = got_error_from_errno2("fclose", patch_script_path);
11731 if (repo) {
11732 const struct got_error *close_err = got_repo_close(repo);
11733 if (error == NULL)
11734 error = close_err;
11736 if (worktree)
11737 got_worktree_close(worktree);
11738 TAILQ_FOREACH(pe, &paths, entry)
11739 free((char *)pe->path);
11740 got_pathlist_free(&paths);
11741 free(cwd);
11742 return error;
11745 __dead static void
11746 usage_cat(void)
11748 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11749 "arg1 [arg2 ...]\n", getprogname());
11750 exit(1);
11753 static const struct got_error *
11754 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11756 const struct got_error *err;
11757 struct got_blob_object *blob;
11759 err = got_object_open_as_blob(&blob, repo, id, 8192);
11760 if (err)
11761 return err;
11763 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11764 got_object_blob_close(blob);
11765 return err;
11768 static const struct got_error *
11769 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11771 const struct got_error *err;
11772 struct got_tree_object *tree;
11773 int nentries, i;
11775 err = got_object_open_as_tree(&tree, repo, id);
11776 if (err)
11777 return err;
11779 nentries = got_object_tree_get_nentries(tree);
11780 for (i = 0; i < nentries; i++) {
11781 struct got_tree_entry *te;
11782 char *id_str;
11783 if (sigint_received || sigpipe_received)
11784 break;
11785 te = got_object_tree_get_entry(tree, i);
11786 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11787 if (err)
11788 break;
11789 fprintf(outfile, "%s %.7o %s\n", id_str,
11790 got_tree_entry_get_mode(te),
11791 got_tree_entry_get_name(te));
11792 free(id_str);
11795 got_object_tree_close(tree);
11796 return err;
11799 static void
11800 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11802 long long h, m;
11803 char sign = '+';
11805 if (gmtoff < 0) {
11806 sign = '-';
11807 gmtoff = -gmtoff;
11810 h = (long long)gmtoff / 3600;
11811 m = ((long long)gmtoff - h*3600) / 60;
11812 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11815 static const struct got_error *
11816 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11818 const struct got_error *err;
11819 struct got_commit_object *commit;
11820 const struct got_object_id_queue *parent_ids;
11821 struct got_object_qid *pid;
11822 char *id_str = NULL;
11823 const char *logmsg = NULL;
11824 char gmtoff[6];
11826 err = got_object_open_as_commit(&commit, repo, id);
11827 if (err)
11828 return err;
11830 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11831 if (err)
11832 goto done;
11834 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11835 parent_ids = got_object_commit_get_parent_ids(commit);
11836 fprintf(outfile, "numparents %d\n",
11837 got_object_commit_get_nparents(commit));
11838 STAILQ_FOREACH(pid, parent_ids, entry) {
11839 char *pid_str;
11840 err = got_object_id_str(&pid_str, &pid->id);
11841 if (err)
11842 goto done;
11843 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11844 free(pid_str);
11846 format_gmtoff(gmtoff, sizeof(gmtoff),
11847 got_object_commit_get_author_gmtoff(commit));
11848 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11849 got_object_commit_get_author(commit),
11850 (long long)got_object_commit_get_author_time(commit),
11851 gmtoff);
11853 format_gmtoff(gmtoff, sizeof(gmtoff),
11854 got_object_commit_get_committer_gmtoff(commit));
11855 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11856 got_object_commit_get_author(commit),
11857 (long long)got_object_commit_get_committer_time(commit),
11858 gmtoff);
11860 logmsg = got_object_commit_get_logmsg_raw(commit);
11861 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11862 fprintf(outfile, "%s", logmsg);
11863 done:
11864 free(id_str);
11865 got_object_commit_close(commit);
11866 return err;
11869 static const struct got_error *
11870 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11872 const struct got_error *err;
11873 struct got_tag_object *tag;
11874 char *id_str = NULL;
11875 const char *tagmsg = NULL;
11876 char gmtoff[6];
11878 err = got_object_open_as_tag(&tag, repo, id);
11879 if (err)
11880 return err;
11882 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11883 if (err)
11884 goto done;
11886 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11888 switch (got_object_tag_get_object_type(tag)) {
11889 case GOT_OBJ_TYPE_BLOB:
11890 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11891 GOT_OBJ_LABEL_BLOB);
11892 break;
11893 case GOT_OBJ_TYPE_TREE:
11894 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11895 GOT_OBJ_LABEL_TREE);
11896 break;
11897 case GOT_OBJ_TYPE_COMMIT:
11898 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11899 GOT_OBJ_LABEL_COMMIT);
11900 break;
11901 case GOT_OBJ_TYPE_TAG:
11902 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11903 GOT_OBJ_LABEL_TAG);
11904 break;
11905 default:
11906 break;
11909 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11910 got_object_tag_get_name(tag));
11912 format_gmtoff(gmtoff, sizeof(gmtoff),
11913 got_object_tag_get_tagger_gmtoff(tag));
11914 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11915 got_object_tag_get_tagger(tag),
11916 (long long)got_object_tag_get_tagger_time(tag),
11917 gmtoff);
11919 tagmsg = got_object_tag_get_message(tag);
11920 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11921 fprintf(outfile, "%s", tagmsg);
11922 done:
11923 free(id_str);
11924 got_object_tag_close(tag);
11925 return err;
11928 static const struct got_error *
11929 cmd_cat(int argc, char *argv[])
11931 const struct got_error *error;
11932 struct got_repository *repo = NULL;
11933 struct got_worktree *worktree = NULL;
11934 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11935 const char *commit_id_str = NULL;
11936 struct got_object_id *id = NULL, *commit_id = NULL;
11937 struct got_commit_object *commit = NULL;
11938 int ch, obj_type, i, force_path = 0;
11939 struct got_reflist_head refs;
11941 TAILQ_INIT(&refs);
11943 #ifndef PROFILE
11944 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11945 NULL) == -1)
11946 err(1, "pledge");
11947 #endif
11949 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11950 switch (ch) {
11951 case 'c':
11952 commit_id_str = optarg;
11953 break;
11954 case 'r':
11955 repo_path = realpath(optarg, NULL);
11956 if (repo_path == NULL)
11957 return got_error_from_errno2("realpath",
11958 optarg);
11959 got_path_strip_trailing_slashes(repo_path);
11960 break;
11961 case 'P':
11962 force_path = 1;
11963 break;
11964 default:
11965 usage_cat();
11966 /* NOTREACHED */
11970 argc -= optind;
11971 argv += optind;
11973 cwd = getcwd(NULL, 0);
11974 if (cwd == NULL) {
11975 error = got_error_from_errno("getcwd");
11976 goto done;
11979 if (repo_path == NULL) {
11980 error = got_worktree_open(&worktree, cwd);
11981 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11982 goto done;
11983 if (worktree) {
11984 repo_path = strdup(
11985 got_worktree_get_repo_path(worktree));
11986 if (repo_path == NULL) {
11987 error = got_error_from_errno("strdup");
11988 goto done;
11991 /* Release work tree lock. */
11992 got_worktree_close(worktree);
11993 worktree = NULL;
11997 if (repo_path == NULL) {
11998 repo_path = strdup(cwd);
11999 if (repo_path == NULL)
12000 return got_error_from_errno("strdup");
12003 error = got_repo_open(&repo, repo_path, NULL);
12004 free(repo_path);
12005 if (error != NULL)
12006 goto done;
12008 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12009 if (error)
12010 goto done;
12012 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12013 if (error)
12014 goto done;
12016 if (commit_id_str == NULL)
12017 commit_id_str = GOT_REF_HEAD;
12018 error = got_repo_match_object_id(&commit_id, NULL,
12019 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12020 if (error)
12021 goto done;
12023 error = got_object_open_as_commit(&commit, repo, commit_id);
12024 if (error)
12025 goto done;
12027 for (i = 0; i < argc; i++) {
12028 if (force_path) {
12029 error = got_object_id_by_path(&id, repo, commit,
12030 argv[i]);
12031 if (error)
12032 break;
12033 } else {
12034 error = got_repo_match_object_id(&id, &label, argv[i],
12035 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12036 repo);
12037 if (error) {
12038 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12039 error->code != GOT_ERR_NOT_REF)
12040 break;
12041 error = got_object_id_by_path(&id, repo,
12042 commit, argv[i]);
12043 if (error)
12044 break;
12048 error = got_object_get_type(&obj_type, repo, id);
12049 if (error)
12050 break;
12052 switch (obj_type) {
12053 case GOT_OBJ_TYPE_BLOB:
12054 error = cat_blob(id, repo, stdout);
12055 break;
12056 case GOT_OBJ_TYPE_TREE:
12057 error = cat_tree(id, repo, stdout);
12058 break;
12059 case GOT_OBJ_TYPE_COMMIT:
12060 error = cat_commit(id, repo, stdout);
12061 break;
12062 case GOT_OBJ_TYPE_TAG:
12063 error = cat_tag(id, repo, stdout);
12064 break;
12065 default:
12066 error = got_error(GOT_ERR_OBJ_TYPE);
12067 break;
12069 if (error)
12070 break;
12071 free(label);
12072 label = NULL;
12073 free(id);
12074 id = NULL;
12076 done:
12077 free(label);
12078 free(id);
12079 free(commit_id);
12080 if (commit)
12081 got_object_commit_close(commit);
12082 if (worktree)
12083 got_worktree_close(worktree);
12084 if (repo) {
12085 const struct got_error *close_err = got_repo_close(repo);
12086 if (error == NULL)
12087 error = close_err;
12089 got_ref_list_free(&refs);
12090 return error;
12093 __dead static void
12094 usage_info(void)
12096 fprintf(stderr, "usage: %s info [path ...]\n",
12097 getprogname());
12098 exit(1);
12101 static const struct got_error *
12102 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12103 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12104 struct got_object_id *commit_id)
12106 const struct got_error *err = NULL;
12107 char *id_str = NULL;
12108 char datebuf[128];
12109 struct tm mytm, *tm;
12110 struct got_pathlist_head *paths = arg;
12111 struct got_pathlist_entry *pe;
12114 * Clear error indication from any of the path arguments which
12115 * would cause this file index entry to be displayed.
12117 TAILQ_FOREACH(pe, paths, entry) {
12118 if (got_path_cmp(path, pe->path, strlen(path),
12119 pe->path_len) == 0 ||
12120 got_path_is_child(path, pe->path, pe->path_len))
12121 pe->data = NULL; /* no error */
12124 printf(GOT_COMMIT_SEP_STR);
12125 if (S_ISLNK(mode))
12126 printf("symlink: %s\n", path);
12127 else if (S_ISREG(mode)) {
12128 printf("file: %s\n", path);
12129 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12130 } else if (S_ISDIR(mode))
12131 printf("directory: %s\n", path);
12132 else
12133 printf("something: %s\n", path);
12135 tm = localtime_r(&mtime, &mytm);
12136 if (tm == NULL)
12137 return NULL;
12138 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12139 return got_error(GOT_ERR_NO_SPACE);
12140 printf("timestamp: %s\n", datebuf);
12142 if (blob_id) {
12143 err = got_object_id_str(&id_str, blob_id);
12144 if (err)
12145 return err;
12146 printf("based on blob: %s\n", id_str);
12147 free(id_str);
12150 if (staged_blob_id) {
12151 err = got_object_id_str(&id_str, staged_blob_id);
12152 if (err)
12153 return err;
12154 printf("based on staged blob: %s\n", id_str);
12155 free(id_str);
12158 if (commit_id) {
12159 err = got_object_id_str(&id_str, commit_id);
12160 if (err)
12161 return err;
12162 printf("based on commit: %s\n", id_str);
12163 free(id_str);
12166 return NULL;
12169 static const struct got_error *
12170 cmd_info(int argc, char *argv[])
12172 const struct got_error *error = NULL;
12173 struct got_worktree *worktree = NULL;
12174 char *cwd = NULL, *id_str = NULL;
12175 struct got_pathlist_head paths;
12176 struct got_pathlist_entry *pe;
12177 char *uuidstr = NULL;
12178 int ch, show_files = 0;
12180 TAILQ_INIT(&paths);
12182 while ((ch = getopt(argc, argv, "")) != -1) {
12183 switch (ch) {
12184 default:
12185 usage_info();
12186 /* NOTREACHED */
12190 argc -= optind;
12191 argv += optind;
12193 #ifndef PROFILE
12194 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12195 NULL) == -1)
12196 err(1, "pledge");
12197 #endif
12198 cwd = getcwd(NULL, 0);
12199 if (cwd == NULL) {
12200 error = got_error_from_errno("getcwd");
12201 goto done;
12204 error = got_worktree_open(&worktree, cwd);
12205 if (error) {
12206 if (error->code == GOT_ERR_NOT_WORKTREE)
12207 error = wrap_not_worktree_error(error, "info", cwd);
12208 goto done;
12211 #ifndef PROFILE
12212 /* Remove "cpath" promise. */
12213 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12214 NULL) == -1)
12215 err(1, "pledge");
12216 #endif
12217 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12218 if (error)
12219 goto done;
12221 if (argc >= 1) {
12222 error = get_worktree_paths_from_argv(&paths, argc, argv,
12223 worktree);
12224 if (error)
12225 goto done;
12226 show_files = 1;
12229 error = got_object_id_str(&id_str,
12230 got_worktree_get_base_commit_id(worktree));
12231 if (error)
12232 goto done;
12234 error = got_worktree_get_uuid(&uuidstr, worktree);
12235 if (error)
12236 goto done;
12238 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12239 printf("work tree base commit: %s\n", id_str);
12240 printf("work tree path prefix: %s\n",
12241 got_worktree_get_path_prefix(worktree));
12242 printf("work tree branch reference: %s\n",
12243 got_worktree_get_head_ref_name(worktree));
12244 printf("work tree UUID: %s\n", uuidstr);
12245 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12247 if (show_files) {
12248 struct got_pathlist_entry *pe;
12249 TAILQ_FOREACH(pe, &paths, entry) {
12250 if (pe->path_len == 0)
12251 continue;
12253 * Assume this path will fail. This will be corrected
12254 * in print_path_info() in case the path does suceeed.
12256 pe->data = (void *)got_error_path(pe->path,
12257 GOT_ERR_BAD_PATH);
12259 error = got_worktree_path_info(worktree, &paths,
12260 print_path_info, &paths, check_cancelled, NULL);
12261 if (error)
12262 goto done;
12263 TAILQ_FOREACH(pe, &paths, entry) {
12264 if (pe->data != NULL) {
12265 error = pe->data; /* bad path */
12266 break;
12270 done:
12271 TAILQ_FOREACH(pe, &paths, entry)
12272 free((char *)pe->path);
12273 got_pathlist_free(&paths);
12274 free(cwd);
12275 free(id_str);
12276 free(uuidstr);
12277 return error;