Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/wait.h>
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <ctype.h>
30 #include <sha1.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
41 #include <util.h>
43 #include "got_version.h"
44 #include "got_error.h"
45 #include "got_object.h"
46 #include "got_reference.h"
47 #include "got_repository.h"
48 #include "got_path.h"
49 #include "got_cancel.h"
50 #include "got_worktree.h"
51 #include "got_diff.h"
52 #include "got_commit_graph.h"
53 #include "got_fetch.h"
54 #include "got_send.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_opentemp.h"
58 #include "got_gotconfig.h"
59 #include "got_dial.h"
60 #include "got_patch.h"
62 #ifndef nitems
63 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
64 #endif
66 static volatile sig_atomic_t sigint_received;
67 static volatile sig_atomic_t sigpipe_received;
69 static void
70 catch_sigint(int signo)
71 {
72 sigint_received = 1;
73 }
75 static void
76 catch_sigpipe(int signo)
77 {
78 sigpipe_received = 1;
79 }
82 struct got_cmd {
83 const char *cmd_name;
84 const struct got_error *(*cmd_main)(int, char *[]);
85 void (*cmd_usage)(void);
86 const char *cmd_alias;
87 };
89 __dead static void usage(int, int);
90 __dead static void usage_init(void);
91 __dead static void usage_import(void);
92 __dead static void usage_clone(void);
93 __dead static void usage_fetch(void);
94 __dead static void usage_checkout(void);
95 __dead static void usage_update(void);
96 __dead static void usage_log(void);
97 __dead static void usage_diff(void);
98 __dead static void usage_blame(void);
99 __dead static void usage_tree(void);
100 __dead static void usage_status(void);
101 __dead static void usage_ref(void);
102 __dead static void usage_branch(void);
103 __dead static void usage_tag(void);
104 __dead static void usage_add(void);
105 __dead static void usage_remove(void);
106 __dead static void usage_patch(void);
107 __dead static void usage_revert(void);
108 __dead static void usage_commit(void);
109 __dead static void usage_send(void);
110 __dead static void usage_cherrypick(void);
111 __dead static void usage_backout(void);
112 __dead static void usage_rebase(void);
113 __dead static void usage_histedit(void);
114 __dead static void usage_integrate(void);
115 __dead static void usage_merge(void);
116 __dead static void usage_stage(void);
117 __dead static void usage_unstage(void);
118 __dead static void usage_cat(void);
119 __dead static void usage_info(void);
121 static const struct got_error* cmd_init(int, char *[]);
122 static const struct got_error* cmd_import(int, char *[]);
123 static const struct got_error* cmd_clone(int, char *[]);
124 static const struct got_error* cmd_fetch(int, char *[]);
125 static const struct got_error* cmd_checkout(int, char *[]);
126 static const struct got_error* cmd_update(int, char *[]);
127 static const struct got_error* cmd_log(int, char *[]);
128 static const struct got_error* cmd_diff(int, char *[]);
129 static const struct got_error* cmd_blame(int, char *[]);
130 static const struct got_error* cmd_tree(int, char *[]);
131 static const struct got_error* cmd_status(int, char *[]);
132 static const struct got_error* cmd_ref(int, char *[]);
133 static const struct got_error* cmd_branch(int, char *[]);
134 static const struct got_error* cmd_tag(int, char *[]);
135 static const struct got_error* cmd_add(int, char *[]);
136 static const struct got_error* cmd_remove(int, char *[]);
137 static const struct got_error* cmd_patch(int, char *[]);
138 static const struct got_error* cmd_revert(int, char *[]);
139 static const struct got_error* cmd_commit(int, char *[]);
140 static const struct got_error* cmd_send(int, char *[]);
141 static const struct got_error* cmd_cherrypick(int, char *[]);
142 static const struct got_error* cmd_backout(int, char *[]);
143 static const struct got_error* cmd_rebase(int, char *[]);
144 static const struct got_error* cmd_histedit(int, char *[]);
145 static const struct got_error* cmd_integrate(int, char *[]);
146 static const struct got_error* cmd_merge(int, char *[]);
147 static const struct got_error* cmd_stage(int, char *[]);
148 static const struct got_error* cmd_unstage(int, char *[]);
149 static const struct got_error* cmd_cat(int, char *[]);
150 static const struct got_error* cmd_info(int, char *[]);
152 static const struct got_cmd got_commands[] = {
153 { "init", cmd_init, usage_init, "" },
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_init(void)
350 fprintf(stderr, "usage: %s init repository-path\n", getprogname());
351 exit(1);
354 static const struct got_error *
355 cmd_init(int argc, char *argv[])
357 const struct got_error *error = NULL;
358 char *repo_path = NULL;
359 int ch;
361 while ((ch = getopt(argc, argv, "")) != -1) {
362 switch (ch) {
363 default:
364 usage_init();
365 /* NOTREACHED */
369 argc -= optind;
370 argv += optind;
372 #ifndef PROFILE
373 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
374 err(1, "pledge");
375 #endif
376 if (argc != 1)
377 usage_init();
379 repo_path = strdup(argv[0]);
380 if (repo_path == NULL)
381 return got_error_from_errno("strdup");
383 got_path_strip_trailing_slashes(repo_path);
385 error = got_path_mkdir(repo_path);
386 if (error &&
387 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
388 goto done;
390 error = apply_unveil(repo_path, 0, NULL);
391 if (error)
392 goto done;
394 error = got_repo_init(repo_path);
395 done:
396 free(repo_path);
397 return error;
400 __dead static void
401 usage_import(void)
403 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
404 "[-r repository-path] [-I pattern] path\n", getprogname());
405 exit(1);
408 int
409 spawn_editor(const char *editor, const char *file)
411 pid_t pid;
412 sig_t sighup, sigint, sigquit;
413 int st = -1;
415 sighup = signal(SIGHUP, SIG_IGN);
416 sigint = signal(SIGINT, SIG_IGN);
417 sigquit = signal(SIGQUIT, SIG_IGN);
419 switch (pid = fork()) {
420 case -1:
421 goto doneediting;
422 case 0:
423 execl(editor, editor, file, (char *)NULL);
424 _exit(127);
427 while (waitpid(pid, &st, 0) == -1)
428 if (errno != EINTR)
429 break;
431 doneediting:
432 (void)signal(SIGHUP, sighup);
433 (void)signal(SIGINT, sigint);
434 (void)signal(SIGQUIT, sigquit);
436 if (!WIFEXITED(st)) {
437 errno = EINTR;
438 return -1;
441 return WEXITSTATUS(st);
444 static const struct got_error *
445 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
446 const char *initial_content, size_t initial_content_len,
447 int require_modification)
449 const struct got_error *err = NULL;
450 char *line = NULL;
451 size_t linesize = 0;
452 ssize_t linelen;
453 struct stat st, st2;
454 FILE *fp = NULL;
455 size_t len, logmsg_len;
456 char *initial_content_stripped = NULL, *buf = NULL, *s;
458 *logmsg = NULL;
460 if (stat(logmsg_path, &st) == -1)
461 return got_error_from_errno2("stat", logmsg_path);
463 if (spawn_editor(editor, logmsg_path) == -1)
464 return got_error_from_errno("failed spawning editor");
466 if (stat(logmsg_path, &st2) == -1)
467 return got_error_from_errno("stat");
469 if (require_modification &&
470 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
471 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
472 "no changes made to commit message, aborting");
474 /*
475 * Set up a stripped version of the initial content without comments
476 * and blank lines. We need this in order to check if the message
477 * has in fact been edited.
478 */
479 initial_content_stripped = malloc(initial_content_len + 1);
480 if (initial_content_stripped == NULL)
481 return got_error_from_errno("malloc");
482 initial_content_stripped[0] = '\0';
484 buf = strdup(initial_content);
485 if (buf == NULL) {
486 err = got_error_from_errno("strdup");
487 goto done;
489 s = buf;
490 len = 0;
491 while ((line = strsep(&s, "\n")) != NULL) {
492 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
493 continue; /* remove comments and leading empty lines */
494 len = strlcat(initial_content_stripped, line,
495 initial_content_len + 1);
496 if (len >= initial_content_len + 1) {
497 err = got_error(GOT_ERR_NO_SPACE);
498 goto done;
501 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
502 initial_content_stripped[len - 1] = '\0';
503 len--;
506 logmsg_len = st2.st_size;
507 *logmsg = malloc(logmsg_len + 1);
508 if (*logmsg == NULL)
509 return got_error_from_errno("malloc");
510 (*logmsg)[0] = '\0';
512 fp = fopen(logmsg_path, "re");
513 if (fp == NULL) {
514 err = got_error_from_errno("fopen");
515 goto done;
518 len = 0;
519 while ((linelen = getline(&line, &linesize, fp)) != -1) {
520 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
521 continue; /* remove comments and leading empty lines */
522 len = strlcat(*logmsg, line, logmsg_len + 1);
523 if (len >= logmsg_len + 1) {
524 err = got_error(GOT_ERR_NO_SPACE);
525 goto done;
528 free(line);
529 if (ferror(fp)) {
530 err = got_ferror(fp, GOT_ERR_IO);
531 goto done;
533 while (len > 0 && (*logmsg)[len - 1] == '\n') {
534 (*logmsg)[len - 1] = '\0';
535 len--;
538 if (len == 0) {
539 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
540 "commit message cannot be empty, aborting");
541 goto done;
543 if (require_modification &&
544 strcmp(*logmsg, initial_content_stripped) == 0)
545 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
546 "no changes made to commit message, aborting");
547 done:
548 free(initial_content_stripped);
549 free(buf);
550 if (fp && fclose(fp) == EOF && err == NULL)
551 err = got_error_from_errno("fclose");
552 if (err) {
553 free(*logmsg);
554 *logmsg = NULL;
556 return err;
559 static const struct got_error *
560 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
561 const char *path_dir, const char *branch_name)
563 char *initial_content = NULL;
564 const struct got_error *err = NULL;
565 int initial_content_len;
566 int fd = -1;
568 initial_content_len = asprintf(&initial_content,
569 "\n# %s to be imported to branch %s\n", path_dir,
570 branch_name);
571 if (initial_content_len == -1)
572 return got_error_from_errno("asprintf");
574 err = got_opentemp_named_fd(logmsg_path, &fd,
575 GOT_TMPDIR_STR "/got-importmsg");
576 if (err)
577 goto done;
579 if (write(fd, initial_content, initial_content_len) == -1) {
580 err = got_error_from_errno2("write", *logmsg_path);
581 goto done;
584 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
585 initial_content_len, 1);
586 done:
587 if (fd != -1 && close(fd) == -1 && err == NULL)
588 err = got_error_from_errno2("close", *logmsg_path);
589 free(initial_content);
590 if (err) {
591 free(*logmsg_path);
592 *logmsg_path = NULL;
594 return err;
597 static const struct got_error *
598 import_progress(void *arg, const char *path)
600 printf("A %s\n", path);
601 return NULL;
604 static int
605 valid_author(const char *author)
607 /*
608 * Really dumb email address check; we're only doing this to
609 * avoid git's object parser breaking on commits we create.
610 */
611 while (*author && *author != '<')
612 author++;
613 if (*author != '<')
614 return 0;
615 while (*author && *author != '@')
616 author++;
617 if (*author != '@')
618 return 0;
619 while (*author && *author != '>')
620 author++;
621 return *author == '>';
624 static const struct got_error *
625 get_author(char **author, struct got_repository *repo,
626 struct got_worktree *worktree)
628 const struct got_error *err = NULL;
629 const char *got_author = NULL, *name, *email;
630 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
632 *author = NULL;
634 if (worktree)
635 worktree_conf = got_worktree_get_gotconfig(worktree);
636 repo_conf = got_repo_get_gotconfig(repo);
638 /*
639 * Priority of potential author information sources, from most
640 * significant to least significant:
641 * 1) work tree's .got/got.conf file
642 * 2) repository's got.conf file
643 * 3) repository's git config file
644 * 4) environment variables
645 * 5) global git config files (in user's home directory or /etc)
646 */
648 if (worktree_conf)
649 got_author = got_gotconfig_get_author(worktree_conf);
650 if (got_author == NULL)
651 got_author = got_gotconfig_get_author(repo_conf);
652 if (got_author == NULL) {
653 name = got_repo_get_gitconfig_author_name(repo);
654 email = got_repo_get_gitconfig_author_email(repo);
655 if (name && email) {
656 if (asprintf(author, "%s <%s>", name, email) == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
661 got_author = getenv("GOT_AUTHOR");
662 if (got_author == NULL) {
663 name = got_repo_get_global_gitconfig_author_name(repo);
664 email = got_repo_get_global_gitconfig_author_email(
665 repo);
666 if (name && email) {
667 if (asprintf(author, "%s <%s>", name, email)
668 == -1)
669 return got_error_from_errno("asprintf");
670 return NULL;
672 /* TODO: Look up user in password database? */
673 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
677 *author = strdup(got_author);
678 if (*author == NULL)
679 return got_error_from_errno("strdup");
681 if (!valid_author(*author)) {
682 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
683 free(*author);
684 *author = NULL;
686 return err;
689 static const struct got_error *
690 get_gitconfig_path(char **gitconfig_path)
692 const char *homedir = getenv("HOME");
694 *gitconfig_path = NULL;
695 if (homedir) {
696 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
697 return got_error_from_errno("asprintf");
700 return NULL;
703 static const struct got_error *
704 cmd_import(int argc, char *argv[])
706 const struct got_error *error = NULL;
707 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
708 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
709 const char *branch_name = "main";
710 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
711 struct got_repository *repo = NULL;
712 struct got_reference *branch_ref = NULL, *head_ref = NULL;
713 struct got_object_id *new_commit_id = NULL;
714 int ch;
715 struct got_pathlist_head ignores;
716 struct got_pathlist_entry *pe;
717 int preserve_logmsg = 0;
719 TAILQ_INIT(&ignores);
721 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
722 switch (ch) {
723 case 'b':
724 branch_name = optarg;
725 break;
726 case 'm':
727 logmsg = strdup(optarg);
728 if (logmsg == NULL) {
729 error = got_error_from_errno("strdup");
730 goto done;
732 break;
733 case 'r':
734 repo_path = realpath(optarg, NULL);
735 if (repo_path == NULL) {
736 error = got_error_from_errno2("realpath",
737 optarg);
738 goto done;
740 break;
741 case 'I':
742 if (optarg[0] == '\0')
743 break;
744 error = got_pathlist_insert(&pe, &ignores, optarg,
745 NULL);
746 if (error)
747 goto done;
748 break;
749 default:
750 usage_import();
751 /* NOTREACHED */
755 argc -= optind;
756 argv += optind;
758 #ifndef PROFILE
759 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
760 "unveil",
761 NULL) == -1)
762 err(1, "pledge");
763 #endif
764 if (argc != 1)
765 usage_import();
767 if (repo_path == NULL) {
768 repo_path = getcwd(NULL, 0);
769 if (repo_path == NULL)
770 return got_error_from_errno("getcwd");
772 got_path_strip_trailing_slashes(repo_path);
773 error = get_gitconfig_path(&gitconfig_path);
774 if (error)
775 goto done;
776 error = got_repo_open(&repo, repo_path, gitconfig_path);
777 if (error)
778 goto done;
780 error = get_author(&author, repo, NULL);
781 if (error)
782 return error;
784 /*
785 * Don't let the user create a branch name with a leading '-'.
786 * While technically a valid reference name, this case is usually
787 * an unintended typo.
788 */
789 if (branch_name[0] == '-')
790 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
792 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
793 error = got_error_from_errno("asprintf");
794 goto done;
797 error = got_ref_open(&branch_ref, repo, refname, 0);
798 if (error) {
799 if (error->code != GOT_ERR_NOT_REF)
800 goto done;
801 } else {
802 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
803 "import target branch already exists");
804 goto done;
807 path_dir = realpath(argv[0], NULL);
808 if (path_dir == NULL) {
809 error = got_error_from_errno2("realpath", argv[0]);
810 goto done;
812 got_path_strip_trailing_slashes(path_dir);
814 /*
815 * unveil(2) traverses exec(2); if an editor is used we have
816 * to apply unveil after the log message has been written.
817 */
818 if (logmsg == NULL || strlen(logmsg) == 0) {
819 error = get_editor(&editor);
820 if (error)
821 goto done;
822 free(logmsg);
823 error = collect_import_msg(&logmsg, &logmsg_path, editor,
824 path_dir, refname);
825 if (error) {
826 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
827 logmsg_path != NULL)
828 preserve_logmsg = 1;
829 goto done;
833 if (unveil(path_dir, "r") != 0) {
834 error = got_error_from_errno2("unveil", path_dir);
835 if (logmsg_path)
836 preserve_logmsg = 1;
837 goto done;
840 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
841 if (error) {
842 if (logmsg_path)
843 preserve_logmsg = 1;
844 goto done;
847 error = got_repo_import(&new_commit_id, path_dir, logmsg,
848 author, &ignores, repo, import_progress, NULL);
849 if (error) {
850 if (logmsg_path)
851 preserve_logmsg = 1;
852 goto done;
855 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
856 if (error) {
857 if (logmsg_path)
858 preserve_logmsg = 1;
859 goto done;
862 error = got_ref_write(branch_ref, repo);
863 if (error) {
864 if (logmsg_path)
865 preserve_logmsg = 1;
866 goto done;
869 error = got_object_id_str(&id_str, new_commit_id);
870 if (error) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
877 if (error) {
878 if (error->code != GOT_ERR_NOT_REF) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
885 branch_ref);
886 if (error) {
887 if (logmsg_path)
888 preserve_logmsg = 1;
889 goto done;
892 error = got_ref_write(head_ref, repo);
893 if (error) {
894 if (logmsg_path)
895 preserve_logmsg = 1;
896 goto done;
900 printf("Created branch %s with commit %s\n",
901 got_ref_get_name(branch_ref), id_str);
902 done:
903 if (preserve_logmsg) {
904 fprintf(stderr, "%s: log message preserved in %s\n",
905 getprogname(), logmsg_path);
906 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
907 error = got_error_from_errno2("unlink", logmsg_path);
908 free(logmsg);
909 free(logmsg_path);
910 free(repo_path);
911 free(editor);
912 free(refname);
913 free(new_commit_id);
914 free(id_str);
915 free(author);
916 free(gitconfig_path);
917 if (branch_ref)
918 got_ref_close(branch_ref);
919 if (head_ref)
920 got_ref_close(head_ref);
921 return error;
924 __dead static void
925 usage_clone(void)
927 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
928 "[-R reference] repository-url [directory]\n", getprogname());
929 exit(1);
932 struct got_fetch_progress_arg {
933 char last_scaled_size[FMT_SCALED_STRSIZE];
934 int last_p_indexed;
935 int last_p_resolved;
936 int verbosity;
938 struct got_repository *repo;
940 int create_configs;
941 int configs_created;
942 struct {
943 struct got_pathlist_head *symrefs;
944 struct got_pathlist_head *wanted_branches;
945 struct got_pathlist_head *wanted_refs;
946 const char *proto;
947 const char *host;
948 const char *port;
949 const char *remote_repo_path;
950 const char *git_url;
951 int fetch_all_branches;
952 int mirror_references;
953 } config_info;
954 };
956 /* XXX forward declaration */
957 static const struct got_error *
958 create_config_files(const char *proto, const char *host, const char *port,
959 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
960 int mirror_references, struct got_pathlist_head *symrefs,
961 struct got_pathlist_head *wanted_branches,
962 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
964 static const struct got_error *
965 fetch_progress(void *arg, const char *message, off_t packfile_size,
966 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
968 const struct got_error *err = NULL;
969 struct got_fetch_progress_arg *a = arg;
970 char scaled_size[FMT_SCALED_STRSIZE];
971 int p_indexed, p_resolved;
972 int print_size = 0, print_indexed = 0, print_resolved = 0;
974 /*
975 * In order to allow a failed clone to be resumed with 'got fetch'
976 * we try to create configuration files as soon as possible.
977 * Once the server has sent information about its default branch
978 * we have all required information.
979 */
980 if (a->create_configs && !a->configs_created &&
981 !TAILQ_EMPTY(a->config_info.symrefs)) {
982 err = create_config_files(a->config_info.proto,
983 a->config_info.host, a->config_info.port,
984 a->config_info.remote_repo_path,
985 a->config_info.git_url,
986 a->config_info.fetch_all_branches,
987 a->config_info.mirror_references,
988 a->config_info.symrefs,
989 a->config_info.wanted_branches,
990 a->config_info.wanted_refs, a->repo);
991 if (err)
992 return err;
993 a->configs_created = 1;
996 if (a->verbosity < 0)
997 return NULL;
999 if (message && message[0] != '\0') {
1000 printf("\rserver: %s", message);
1001 fflush(stdout);
1002 return NULL;
1005 if (packfile_size > 0 || nobj_indexed > 0) {
1006 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1007 (a->last_scaled_size[0] == '\0' ||
1008 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1009 print_size = 1;
1010 if (strlcpy(a->last_scaled_size, scaled_size,
1011 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1012 return got_error(GOT_ERR_NO_SPACE);
1014 if (nobj_indexed > 0) {
1015 p_indexed = (nobj_indexed * 100) / nobj_total;
1016 if (p_indexed != a->last_p_indexed) {
1017 a->last_p_indexed = p_indexed;
1018 print_indexed = 1;
1019 print_size = 1;
1022 if (nobj_resolved > 0) {
1023 p_resolved = (nobj_resolved * 100) /
1024 (nobj_total - nobj_loose);
1025 if (p_resolved != a->last_p_resolved) {
1026 a->last_p_resolved = p_resolved;
1027 print_resolved = 1;
1028 print_indexed = 1;
1029 print_size = 1;
1034 if (print_size || print_indexed || print_resolved)
1035 printf("\r");
1036 if (print_size)
1037 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1038 if (print_indexed)
1039 printf("; indexing %d%%", p_indexed);
1040 if (print_resolved)
1041 printf("; resolving deltas %d%%", p_resolved);
1042 if (print_size || print_indexed || print_resolved)
1043 fflush(stdout);
1045 return NULL;
1048 static const struct got_error *
1049 create_symref(const char *refname, struct got_reference *target_ref,
1050 int verbosity, struct got_repository *repo)
1052 const struct got_error *err;
1053 struct got_reference *head_symref;
1055 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1056 if (err)
1057 return err;
1059 err = got_ref_write(head_symref, repo);
1060 if (err == NULL && verbosity > 0) {
1061 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1062 got_ref_get_name(target_ref));
1064 got_ref_close(head_symref);
1065 return err;
1068 static const struct got_error *
1069 list_remote_refs(struct got_pathlist_head *symrefs,
1070 struct got_pathlist_head *refs)
1072 const struct got_error *err;
1073 struct got_pathlist_entry *pe;
1075 TAILQ_FOREACH(pe, symrefs, entry) {
1076 const char *refname = pe->path;
1077 const char *targetref = pe->data;
1079 printf("%s: %s\n", refname, targetref);
1082 TAILQ_FOREACH(pe, refs, entry) {
1083 const char *refname = pe->path;
1084 struct got_object_id *id = pe->data;
1085 char *id_str;
1087 err = got_object_id_str(&id_str, id);
1088 if (err)
1089 return err;
1090 printf("%s: %s\n", refname, id_str);
1091 free(id_str);
1094 return NULL;
1097 static const struct got_error *
1098 create_ref(const char *refname, struct got_object_id *id,
1099 int verbosity, struct got_repository *repo)
1101 const struct got_error *err = NULL;
1102 struct got_reference *ref;
1103 char *id_str;
1105 err = got_object_id_str(&id_str, id);
1106 if (err)
1107 return err;
1109 err = got_ref_alloc(&ref, refname, id);
1110 if (err)
1111 goto done;
1113 err = got_ref_write(ref, repo);
1114 got_ref_close(ref);
1116 if (err == NULL && verbosity >= 0)
1117 printf("Created reference %s: %s\n", refname, id_str);
1118 done:
1119 free(id_str);
1120 return err;
1123 static int
1124 match_wanted_ref(const char *refname, const char *wanted_ref)
1126 if (strncmp(refname, "refs/", 5) != 0)
1127 return 0;
1128 refname += 5;
1131 * Prevent fetching of references that won't make any
1132 * sense outside of the remote repository's context.
1134 if (strncmp(refname, "got/", 4) == 0)
1135 return 0;
1136 if (strncmp(refname, "remotes/", 8) == 0)
1137 return 0;
1139 if (strncmp(wanted_ref, "refs/", 5) == 0)
1140 wanted_ref += 5;
1142 /* Allow prefix match. */
1143 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1144 return 1;
1146 /* Allow exact match. */
1147 return (strcmp(refname, wanted_ref) == 0);
1150 static int
1151 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1153 struct got_pathlist_entry *pe;
1155 TAILQ_FOREACH(pe, wanted_refs, entry) {
1156 if (match_wanted_ref(refname, pe->path))
1157 return 1;
1160 return 0;
1163 static const struct got_error *
1164 create_wanted_ref(const char *refname, struct got_object_id *id,
1165 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1167 const struct got_error *err;
1168 char *remote_refname;
1170 if (strncmp("refs/", refname, 5) == 0)
1171 refname += 5;
1173 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1174 remote_repo_name, refname) == -1)
1175 return got_error_from_errno("asprintf");
1177 err = create_ref(remote_refname, id, verbosity, repo);
1178 free(remote_refname);
1179 return err;
1182 static const struct got_error *
1183 create_gotconfig(const char *proto, const char *host, const char *port,
1184 const char *remote_repo_path, const char *default_branch,
1185 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1186 struct got_pathlist_head *wanted_refs, int mirror_references,
1187 struct got_repository *repo)
1189 const struct got_error *err = NULL;
1190 char *gotconfig_path = NULL;
1191 char *gotconfig = NULL;
1192 FILE *gotconfig_file = NULL;
1193 const char *branchname = NULL;
1194 char *branches = NULL, *refs = NULL;
1195 ssize_t n;
1197 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1198 struct got_pathlist_entry *pe;
1199 TAILQ_FOREACH(pe, wanted_branches, entry) {
1200 char *s;
1201 branchname = pe->path;
1202 if (strncmp(branchname, "refs/heads/", 11) == 0)
1203 branchname += 11;
1204 if (asprintf(&s, "%s\"%s\" ",
1205 branches ? branches : "", branchname) == -1) {
1206 err = got_error_from_errno("asprintf");
1207 goto done;
1209 free(branches);
1210 branches = s;
1212 } else if (!fetch_all_branches && default_branch) {
1213 branchname = default_branch;
1214 if (strncmp(branchname, "refs/heads/", 11) == 0)
1215 branchname += 11;
1216 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1217 err = got_error_from_errno("asprintf");
1218 goto done;
1221 if (!TAILQ_EMPTY(wanted_refs)) {
1222 struct got_pathlist_entry *pe;
1223 TAILQ_FOREACH(pe, wanted_refs, entry) {
1224 char *s;
1225 const char *refname = pe->path;
1226 if (strncmp(refname, "refs/", 5) == 0)
1227 branchname += 5;
1228 if (asprintf(&s, "%s\"%s\" ",
1229 refs ? refs : "", refname) == -1) {
1230 err = got_error_from_errno("asprintf");
1231 goto done;
1233 free(refs);
1234 refs = s;
1238 /* Create got.conf(5). */
1239 gotconfig_path = got_repo_get_path_gotconfig(repo);
1240 if (gotconfig_path == NULL) {
1241 err = got_error_from_errno("got_repo_get_path_gotconfig");
1242 goto done;
1244 gotconfig_file = fopen(gotconfig_path, "ae");
1245 if (gotconfig_file == NULL) {
1246 err = got_error_from_errno2("fopen", gotconfig_path);
1247 goto done;
1249 if (asprintf(&gotconfig,
1250 "remote \"%s\" {\n"
1251 "\tserver %s\n"
1252 "\tprotocol %s\n"
1253 "%s%s%s"
1254 "\trepository \"%s\"\n"
1255 "%s%s%s"
1256 "%s%s%s"
1257 "%s"
1258 "%s"
1259 "}\n",
1260 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1261 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1262 remote_repo_path, branches ? "\tbranch { " : "",
1263 branches ? branches : "", branches ? "}\n" : "",
1264 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1265 mirror_references ? "\tmirror-references yes\n" : "",
1266 fetch_all_branches ? "\tfetch-all-branches yes\n" : "") == -1) {
1267 err = got_error_from_errno("asprintf");
1268 goto done;
1270 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1271 if (n != strlen(gotconfig)) {
1272 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1273 goto done;
1276 done:
1277 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1278 err = got_error_from_errno2("fclose", gotconfig_path);
1279 free(gotconfig_path);
1280 free(branches);
1281 return err;
1284 static const struct got_error *
1285 create_gitconfig(const char *git_url, const char *default_branch,
1286 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1287 struct got_pathlist_head *wanted_refs, int mirror_references,
1288 struct got_repository *repo)
1290 const struct got_error *err = NULL;
1291 char *gitconfig_path = NULL;
1292 char *gitconfig = NULL;
1293 FILE *gitconfig_file = NULL;
1294 char *branches = NULL, *refs = NULL;
1295 const char *branchname;
1296 ssize_t n;
1298 /* Create a config file Git can understand. */
1299 gitconfig_path = got_repo_get_path_gitconfig(repo);
1300 if (gitconfig_path == NULL) {
1301 err = got_error_from_errno("got_repo_get_path_gitconfig");
1302 goto done;
1304 gitconfig_file = fopen(gitconfig_path, "ae");
1305 if (gitconfig_file == NULL) {
1306 err = got_error_from_errno2("fopen", gitconfig_path);
1307 goto done;
1309 if (fetch_all_branches) {
1310 if (mirror_references) {
1311 if (asprintf(&branches,
1312 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1313 err = got_error_from_errno("asprintf");
1314 goto done;
1316 } else if (asprintf(&branches,
1317 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1318 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1319 err = got_error_from_errno("asprintf");
1320 goto done;
1322 } else if (!TAILQ_EMPTY(wanted_branches)) {
1323 struct got_pathlist_entry *pe;
1324 TAILQ_FOREACH(pe, wanted_branches, entry) {
1325 char *s;
1326 branchname = pe->path;
1327 if (strncmp(branchname, "refs/heads/", 11) == 0)
1328 branchname += 11;
1329 if (mirror_references) {
1330 if (asprintf(&s,
1331 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1332 branches ? branches : "",
1333 branchname, branchname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 } else if (asprintf(&s,
1338 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1339 branches ? branches : "",
1340 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1341 branchname) == -1) {
1342 err = got_error_from_errno("asprintf");
1343 goto done;
1345 free(branches);
1346 branches = s;
1348 } else {
1350 * If the server specified a default branch, use just that one.
1351 * Otherwise fall back to fetching all branches on next fetch.
1353 if (default_branch) {
1354 branchname = default_branch;
1355 if (strncmp(branchname, "refs/heads/", 11) == 0)
1356 branchname += 11;
1357 } else
1358 branchname = "*"; /* fall back to all branches */
1359 if (mirror_references) {
1360 if (asprintf(&branches,
1361 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1362 branchname, branchname) == -1) {
1363 err = got_error_from_errno("asprintf");
1364 goto done;
1366 } else if (asprintf(&branches,
1367 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1368 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1369 branchname) == -1) {
1370 err = got_error_from_errno("asprintf");
1371 goto done;
1374 if (!TAILQ_EMPTY(wanted_refs)) {
1375 struct got_pathlist_entry *pe;
1376 TAILQ_FOREACH(pe, wanted_refs, entry) {
1377 char *s;
1378 const char *refname = pe->path;
1379 if (strncmp(refname, "refs/", 5) == 0)
1380 refname += 5;
1381 if (mirror_references) {
1382 if (asprintf(&s,
1383 "%s\tfetch = refs/%s:refs/%s\n",
1384 refs ? refs : "", refname, refname) == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&s,
1389 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1390 refs ? refs : "",
1391 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1392 refname) == -1) {
1393 err = got_error_from_errno("asprintf");
1394 goto done;
1396 free(refs);
1397 refs = s;
1401 if (asprintf(&gitconfig,
1402 "[remote \"%s\"]\n"
1403 "\turl = %s\n"
1404 "%s"
1405 "%s"
1406 "\tfetch = refs/tags/*:refs/tags/*\n",
1407 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1408 refs ? refs : "") == -1) {
1409 err = got_error_from_errno("asprintf");
1410 goto done;
1412 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1413 if (n != strlen(gitconfig)) {
1414 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1415 goto done;
1417 done:
1418 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1419 err = got_error_from_errno2("fclose", gitconfig_path);
1420 free(gitconfig_path);
1421 free(branches);
1422 return err;
1425 static const struct got_error *
1426 create_config_files(const char *proto, const char *host, const char *port,
1427 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1428 int mirror_references, struct got_pathlist_head *symrefs,
1429 struct got_pathlist_head *wanted_branches,
1430 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1432 const struct got_error *err = NULL;
1433 const char *default_branch = NULL;
1434 struct got_pathlist_entry *pe;
1437 * If we asked for a set of wanted branches then use the first
1438 * one of those.
1440 if (!TAILQ_EMPTY(wanted_branches)) {
1441 pe = TAILQ_FIRST(wanted_branches);
1442 default_branch = pe->path;
1443 } else {
1444 /* First HEAD ref listed by server is the default branch. */
1445 TAILQ_FOREACH(pe, symrefs, entry) {
1446 const char *refname = pe->path;
1447 const char *target = pe->data;
1449 if (strcmp(refname, GOT_REF_HEAD) != 0)
1450 continue;
1452 default_branch = target;
1453 break;
1457 /* Create got.conf(5). */
1458 err = create_gotconfig(proto, host, port, remote_repo_path,
1459 default_branch, fetch_all_branches, wanted_branches,
1460 wanted_refs, mirror_references, repo);
1461 if (err)
1462 return err;
1464 /* Create a config file Git can understand. */
1465 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1466 wanted_branches, wanted_refs, mirror_references, repo);
1469 static const struct got_error *
1470 cmd_clone(int argc, char *argv[])
1472 const struct got_error *error = NULL;
1473 const char *uri, *dirname;
1474 char *proto, *host, *port, *repo_name, *server_path;
1475 char *default_destdir = NULL, *id_str = NULL;
1476 const char *repo_path;
1477 struct got_repository *repo = NULL;
1478 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1479 struct got_pathlist_entry *pe;
1480 struct got_object_id *pack_hash = NULL;
1481 int ch, fetchfd = -1, fetchstatus;
1482 pid_t fetchpid = -1;
1483 struct got_fetch_progress_arg fpa;
1484 char *git_url = NULL;
1485 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1486 int list_refs_only = 0;
1488 TAILQ_INIT(&refs);
1489 TAILQ_INIT(&symrefs);
1490 TAILQ_INIT(&wanted_branches);
1491 TAILQ_INIT(&wanted_refs);
1493 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1494 switch (ch) {
1495 case 'a':
1496 fetch_all_branches = 1;
1497 break;
1498 case 'b':
1499 error = got_pathlist_append(&wanted_branches,
1500 optarg, NULL);
1501 if (error)
1502 return error;
1503 break;
1504 case 'l':
1505 list_refs_only = 1;
1506 break;
1507 case 'm':
1508 mirror_references = 1;
1509 break;
1510 case 'v':
1511 if (verbosity < 0)
1512 verbosity = 0;
1513 else if (verbosity < 3)
1514 verbosity++;
1515 break;
1516 case 'q':
1517 verbosity = -1;
1518 break;
1519 case 'R':
1520 error = got_pathlist_append(&wanted_refs,
1521 optarg, NULL);
1522 if (error)
1523 return error;
1524 break;
1525 default:
1526 usage_clone();
1527 break;
1530 argc -= optind;
1531 argv += optind;
1533 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1534 option_conflict('a', 'b');
1535 if (list_refs_only) {
1536 if (!TAILQ_EMPTY(&wanted_branches))
1537 option_conflict('l', 'b');
1538 if (fetch_all_branches)
1539 option_conflict('l', 'a');
1540 if (mirror_references)
1541 option_conflict('l', 'm');
1542 if (!TAILQ_EMPTY(&wanted_refs))
1543 option_conflict('l', 'R');
1546 uri = argv[0];
1548 if (argc == 1)
1549 dirname = NULL;
1550 else if (argc == 2)
1551 dirname = argv[1];
1552 else
1553 usage_clone();
1555 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1556 &repo_name, uri);
1557 if (error)
1558 goto done;
1560 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1561 host, port ? ":" : "", port ? port : "",
1562 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1563 error = got_error_from_errno("asprintf");
1564 goto done;
1567 if (strcmp(proto, "git") == 0) {
1568 #ifndef PROFILE
1569 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1570 "sendfd dns inet unveil", NULL) == -1)
1571 err(1, "pledge");
1572 #endif
1573 } else if (strcmp(proto, "git+ssh") == 0 ||
1574 strcmp(proto, "ssh") == 0) {
1575 #ifndef PROFILE
1576 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1577 "sendfd unveil", NULL) == -1)
1578 err(1, "pledge");
1579 #endif
1580 } else if (strcmp(proto, "http") == 0 ||
1581 strcmp(proto, "git+http") == 0) {
1582 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1583 goto done;
1584 } else {
1585 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1586 goto done;
1588 if (dirname == NULL) {
1589 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1590 error = got_error_from_errno("asprintf");
1591 goto done;
1593 repo_path = default_destdir;
1594 } else
1595 repo_path = dirname;
1597 if (!list_refs_only) {
1598 error = got_path_mkdir(repo_path);
1599 if (error &&
1600 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1601 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1602 goto done;
1603 if (!got_path_dir_is_empty(repo_path)) {
1604 error = got_error_path(repo_path,
1605 GOT_ERR_DIR_NOT_EMPTY);
1606 goto done;
1610 error = got_dial_apply_unveil(proto);
1611 if (error)
1612 goto done;
1614 error = apply_unveil(repo_path, 0, NULL);
1615 if (error)
1616 goto done;
1618 if (verbosity >= 0)
1619 printf("Connecting to %s%s%s\n", host,
1620 port ? ":" : "", port ? port : "");
1622 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1623 server_path, verbosity);
1624 if (error)
1625 goto done;
1627 if (!list_refs_only) {
1628 error = got_repo_init(repo_path);
1629 if (error)
1630 goto done;
1631 error = got_repo_open(&repo, repo_path, NULL);
1632 if (error)
1633 goto done;
1636 fpa.last_scaled_size[0] = '\0';
1637 fpa.last_p_indexed = -1;
1638 fpa.last_p_resolved = -1;
1639 fpa.verbosity = verbosity;
1640 fpa.create_configs = 1;
1641 fpa.configs_created = 0;
1642 fpa.repo = repo;
1643 fpa.config_info.symrefs = &symrefs;
1644 fpa.config_info.wanted_branches = &wanted_branches;
1645 fpa.config_info.wanted_refs = &wanted_refs;
1646 fpa.config_info.proto = proto;
1647 fpa.config_info.host = host;
1648 fpa.config_info.port = port;
1649 fpa.config_info.remote_repo_path = server_path;
1650 fpa.config_info.git_url = git_url;
1651 fpa.config_info.fetch_all_branches = fetch_all_branches;
1652 fpa.config_info.mirror_references = mirror_references;
1653 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1654 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1655 fetch_all_branches, &wanted_branches, &wanted_refs,
1656 list_refs_only, verbosity, fetchfd, repo,
1657 fetch_progress, &fpa);
1658 if (error)
1659 goto done;
1661 if (list_refs_only) {
1662 error = list_remote_refs(&symrefs, &refs);
1663 goto done;
1666 if (pack_hash == NULL) {
1667 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1668 "server sent an empty pack file");
1669 goto done;
1671 error = got_object_id_str(&id_str, pack_hash);
1672 if (error)
1673 goto done;
1674 if (verbosity >= 0)
1675 printf("\nFetched %s.pack\n", id_str);
1676 free(id_str);
1678 /* Set up references provided with the pack file. */
1679 TAILQ_FOREACH(pe, &refs, entry) {
1680 const char *refname = pe->path;
1681 struct got_object_id *id = pe->data;
1682 char *remote_refname;
1684 if (is_wanted_ref(&wanted_refs, refname) &&
1685 !mirror_references) {
1686 error = create_wanted_ref(refname, id,
1687 GOT_FETCH_DEFAULT_REMOTE_NAME,
1688 verbosity - 1, repo);
1689 if (error)
1690 goto done;
1691 continue;
1694 error = create_ref(refname, id, verbosity - 1, repo);
1695 if (error)
1696 goto done;
1698 if (mirror_references)
1699 continue;
1701 if (strncmp("refs/heads/", refname, 11) != 0)
1702 continue;
1704 if (asprintf(&remote_refname,
1705 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1706 refname + 11) == -1) {
1707 error = got_error_from_errno("asprintf");
1708 goto done;
1710 error = create_ref(remote_refname, id, verbosity - 1, repo);
1711 free(remote_refname);
1712 if (error)
1713 goto done;
1716 /* Set the HEAD reference if the server provided one. */
1717 TAILQ_FOREACH(pe, &symrefs, entry) {
1718 struct got_reference *target_ref;
1719 const char *refname = pe->path;
1720 const char *target = pe->data;
1721 char *remote_refname = NULL, *remote_target = NULL;
1723 if (strcmp(refname, GOT_REF_HEAD) != 0)
1724 continue;
1726 error = got_ref_open(&target_ref, repo, target, 0);
1727 if (error) {
1728 if (error->code == GOT_ERR_NOT_REF) {
1729 error = NULL;
1730 continue;
1732 goto done;
1735 error = create_symref(refname, target_ref, verbosity, repo);
1736 got_ref_close(target_ref);
1737 if (error)
1738 goto done;
1740 if (mirror_references)
1741 continue;
1743 if (strncmp("refs/heads/", target, 11) != 0)
1744 continue;
1746 if (asprintf(&remote_refname,
1747 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1748 refname) == -1) {
1749 error = got_error_from_errno("asprintf");
1750 goto done;
1752 if (asprintf(&remote_target,
1753 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1754 target + 11) == -1) {
1755 error = got_error_from_errno("asprintf");
1756 free(remote_refname);
1757 goto done;
1759 error = got_ref_open(&target_ref, repo, remote_target, 0);
1760 if (error) {
1761 free(remote_refname);
1762 free(remote_target);
1763 if (error->code == GOT_ERR_NOT_REF) {
1764 error = NULL;
1765 continue;
1767 goto done;
1769 error = create_symref(remote_refname, target_ref,
1770 verbosity - 1, repo);
1771 free(remote_refname);
1772 free(remote_target);
1773 got_ref_close(target_ref);
1774 if (error)
1775 goto done;
1777 if (pe == NULL) {
1779 * We failed to set the HEAD reference. If we asked for
1780 * a set of wanted branches use the first of one of those
1781 * which could be fetched instead.
1783 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1784 const char *target = pe->path;
1785 struct got_reference *target_ref;
1787 error = got_ref_open(&target_ref, repo, target, 0);
1788 if (error) {
1789 if (error->code == GOT_ERR_NOT_REF) {
1790 error = NULL;
1791 continue;
1793 goto done;
1796 error = create_symref(GOT_REF_HEAD, target_ref,
1797 verbosity, repo);
1798 got_ref_close(target_ref);
1799 if (error)
1800 goto done;
1801 break;
1805 if (verbosity >= 0)
1806 printf("Created %s repository '%s'\n",
1807 mirror_references ? "mirrored" : "cloned", repo_path);
1808 done:
1809 if (fetchpid > 0) {
1810 if (kill(fetchpid, SIGTERM) == -1)
1811 error = got_error_from_errno("kill");
1812 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1813 error = got_error_from_errno("waitpid");
1815 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1816 error = got_error_from_errno("close");
1817 if (repo) {
1818 const struct got_error *close_err = got_repo_close(repo);
1819 if (error == NULL)
1820 error = close_err;
1822 TAILQ_FOREACH(pe, &refs, entry) {
1823 free((void *)pe->path);
1824 free(pe->data);
1826 got_pathlist_free(&refs);
1827 TAILQ_FOREACH(pe, &symrefs, entry) {
1828 free((void *)pe->path);
1829 free(pe->data);
1831 got_pathlist_free(&symrefs);
1832 got_pathlist_free(&wanted_branches);
1833 got_pathlist_free(&wanted_refs);
1834 free(pack_hash);
1835 free(proto);
1836 free(host);
1837 free(port);
1838 free(server_path);
1839 free(repo_name);
1840 free(default_destdir);
1841 free(git_url);
1842 return error;
1845 static const struct got_error *
1846 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1847 int replace_tags, int verbosity, struct got_repository *repo)
1849 const struct got_error *err = NULL;
1850 char *new_id_str = NULL;
1851 struct got_object_id *old_id = NULL;
1853 err = got_object_id_str(&new_id_str, new_id);
1854 if (err)
1855 goto done;
1857 if (!replace_tags &&
1858 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1859 err = got_ref_resolve(&old_id, repo, ref);
1860 if (err)
1861 goto done;
1862 if (got_object_id_cmp(old_id, new_id) == 0)
1863 goto done;
1864 if (verbosity >= 0) {
1865 printf("Rejecting update of existing tag %s: %s\n",
1866 got_ref_get_name(ref), new_id_str);
1868 goto done;
1871 if (got_ref_is_symbolic(ref)) {
1872 if (verbosity >= 0) {
1873 printf("Replacing reference %s: %s\n",
1874 got_ref_get_name(ref),
1875 got_ref_get_symref_target(ref));
1877 err = got_ref_change_symref_to_ref(ref, new_id);
1878 if (err)
1879 goto done;
1880 err = got_ref_write(ref, repo);
1881 if (err)
1882 goto done;
1883 } else {
1884 err = got_ref_resolve(&old_id, repo, ref);
1885 if (err)
1886 goto done;
1887 if (got_object_id_cmp(old_id, new_id) == 0)
1888 goto done;
1890 err = got_ref_change_ref(ref, new_id);
1891 if (err)
1892 goto done;
1893 err = got_ref_write(ref, repo);
1894 if (err)
1895 goto done;
1898 if (verbosity >= 0)
1899 printf("Updated %s: %s\n", got_ref_get_name(ref),
1900 new_id_str);
1901 done:
1902 free(old_id);
1903 free(new_id_str);
1904 return err;
1907 static const struct got_error *
1908 update_symref(const char *refname, struct got_reference *target_ref,
1909 int verbosity, struct got_repository *repo)
1911 const struct got_error *err = NULL, *unlock_err;
1912 struct got_reference *symref;
1913 int symref_is_locked = 0;
1915 err = got_ref_open(&symref, repo, refname, 1);
1916 if (err) {
1917 if (err->code != GOT_ERR_NOT_REF)
1918 return err;
1919 err = got_ref_alloc_symref(&symref, refname, target_ref);
1920 if (err)
1921 goto done;
1923 err = got_ref_write(symref, repo);
1924 if (err)
1925 goto done;
1927 if (verbosity >= 0)
1928 printf("Created reference %s: %s\n",
1929 got_ref_get_name(symref),
1930 got_ref_get_symref_target(symref));
1931 } else {
1932 symref_is_locked = 1;
1934 if (strcmp(got_ref_get_symref_target(symref),
1935 got_ref_get_name(target_ref)) == 0)
1936 goto done;
1938 err = got_ref_change_symref(symref,
1939 got_ref_get_name(target_ref));
1940 if (err)
1941 goto done;
1943 err = got_ref_write(symref, repo);
1944 if (err)
1945 goto done;
1947 if (verbosity >= 0)
1948 printf("Updated %s: %s\n", got_ref_get_name(symref),
1949 got_ref_get_symref_target(symref));
1952 done:
1953 if (symref_is_locked) {
1954 unlock_err = got_ref_unlock(symref);
1955 if (unlock_err && err == NULL)
1956 err = unlock_err;
1958 got_ref_close(symref);
1959 return err;
1962 __dead static void
1963 usage_fetch(void)
1965 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
1966 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
1967 "[remote-repository-name]\n",
1968 getprogname());
1969 exit(1);
1972 static const struct got_error *
1973 delete_missing_ref(struct got_reference *ref,
1974 int verbosity, struct got_repository *repo)
1976 const struct got_error *err = NULL;
1977 struct got_object_id *id = NULL;
1978 char *id_str = NULL;
1980 if (got_ref_is_symbolic(ref)) {
1981 err = got_ref_delete(ref, repo);
1982 if (err)
1983 return err;
1984 if (verbosity >= 0) {
1985 printf("Deleted %s: %s\n",
1986 got_ref_get_name(ref),
1987 got_ref_get_symref_target(ref));
1989 } else {
1990 err = got_ref_resolve(&id, repo, ref);
1991 if (err)
1992 return err;
1993 err = got_object_id_str(&id_str, id);
1994 if (err)
1995 goto done;
1997 err = got_ref_delete(ref, repo);
1998 if (err)
1999 goto done;
2000 if (verbosity >= 0) {
2001 printf("Deleted %s: %s\n",
2002 got_ref_get_name(ref), id_str);
2005 done:
2006 free(id);
2007 free(id_str);
2008 return NULL;
2011 static const struct got_error *
2012 delete_missing_refs(struct got_pathlist_head *their_refs,
2013 struct got_pathlist_head *their_symrefs,
2014 const struct got_remote_repo *remote,
2015 int verbosity, struct got_repository *repo)
2017 const struct got_error *err = NULL, *unlock_err;
2018 struct got_reflist_head my_refs;
2019 struct got_reflist_entry *re;
2020 struct got_pathlist_entry *pe;
2021 char *remote_namespace = NULL;
2022 char *local_refname = NULL;
2024 TAILQ_INIT(&my_refs);
2026 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2027 == -1)
2028 return got_error_from_errno("asprintf");
2030 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2031 if (err)
2032 goto done;
2034 TAILQ_FOREACH(re, &my_refs, entry) {
2035 const char *refname = got_ref_get_name(re->ref);
2036 const char *their_refname;
2038 if (remote->mirror_references) {
2039 their_refname = refname;
2040 } else {
2041 if (strncmp(refname, remote_namespace,
2042 strlen(remote_namespace)) == 0) {
2043 if (strcmp(refname + strlen(remote_namespace),
2044 GOT_REF_HEAD) == 0)
2045 continue;
2046 if (asprintf(&local_refname, "refs/heads/%s",
2047 refname + strlen(remote_namespace)) == -1) {
2048 err = got_error_from_errno("asprintf");
2049 goto done;
2051 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2052 continue;
2054 their_refname = local_refname;
2057 TAILQ_FOREACH(pe, their_refs, entry) {
2058 if (strcmp(their_refname, pe->path) == 0)
2059 break;
2061 if (pe != NULL)
2062 continue;
2064 TAILQ_FOREACH(pe, their_symrefs, entry) {
2065 if (strcmp(their_refname, pe->path) == 0)
2066 break;
2068 if (pe != NULL)
2069 continue;
2071 err = delete_missing_ref(re->ref, verbosity, repo);
2072 if (err)
2073 break;
2075 if (local_refname) {
2076 struct got_reference *ref;
2077 err = got_ref_open(&ref, repo, local_refname, 1);
2078 if (err) {
2079 if (err->code != GOT_ERR_NOT_REF)
2080 break;
2081 free(local_refname);
2082 local_refname = NULL;
2083 continue;
2085 err = delete_missing_ref(ref, verbosity, repo);
2086 if (err)
2087 break;
2088 unlock_err = got_ref_unlock(ref);
2089 got_ref_close(ref);
2090 if (unlock_err && err == NULL) {
2091 err = unlock_err;
2092 break;
2095 free(local_refname);
2096 local_refname = NULL;
2099 done:
2100 free(remote_namespace);
2101 free(local_refname);
2102 return err;
2105 static const struct got_error *
2106 update_wanted_ref(const char *refname, struct got_object_id *id,
2107 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2109 const struct got_error *err, *unlock_err;
2110 char *remote_refname;
2111 struct got_reference *ref;
2113 if (strncmp("refs/", refname, 5) == 0)
2114 refname += 5;
2116 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2117 remote_repo_name, refname) == -1)
2118 return got_error_from_errno("asprintf");
2120 err = got_ref_open(&ref, repo, remote_refname, 1);
2121 if (err) {
2122 if (err->code != GOT_ERR_NOT_REF)
2123 goto done;
2124 err = create_ref(remote_refname, id, verbosity, repo);
2125 } else {
2126 err = update_ref(ref, id, 0, verbosity, repo);
2127 unlock_err = got_ref_unlock(ref);
2128 if (unlock_err && err == NULL)
2129 err = unlock_err;
2130 got_ref_close(ref);
2132 done:
2133 free(remote_refname);
2134 return err;
2137 static const struct got_error *
2138 delete_ref(struct got_repository *repo, struct got_reference *ref)
2140 const struct got_error *err = NULL;
2141 struct got_object_id *id = NULL;
2142 char *id_str = NULL;
2143 const char *target;
2145 if (got_ref_is_symbolic(ref)) {
2146 target = got_ref_get_symref_target(ref);
2147 } else {
2148 err = got_ref_resolve(&id, repo, ref);
2149 if (err)
2150 goto done;
2151 err = got_object_id_str(&id_str, id);
2152 if (err)
2153 goto done;
2154 target = id_str;
2157 err = got_ref_delete(ref, repo);
2158 if (err)
2159 goto done;
2161 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2162 done:
2163 free(id);
2164 free(id_str);
2165 return err;
2168 static const struct got_error *
2169 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2171 const struct got_error *err = NULL;
2172 struct got_reflist_head refs;
2173 struct got_reflist_entry *re;
2174 char *prefix;
2176 TAILQ_INIT(&refs);
2178 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2179 err = got_error_from_errno("asprintf");
2180 goto done;
2182 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2183 if (err)
2184 goto done;
2186 TAILQ_FOREACH(re, &refs, entry)
2187 delete_ref(repo, re->ref);
2188 done:
2189 got_ref_list_free(&refs);
2190 return err;
2193 static const struct got_error *
2194 cmd_fetch(int argc, char *argv[])
2196 const struct got_error *error = NULL, *unlock_err;
2197 char *cwd = NULL, *repo_path = NULL;
2198 const char *remote_name;
2199 char *proto = NULL, *host = NULL, *port = NULL;
2200 char *repo_name = NULL, *server_path = NULL;
2201 const struct got_remote_repo *remotes, *remote = NULL;
2202 int nremotes;
2203 char *id_str = NULL;
2204 struct got_repository *repo = NULL;
2205 struct got_worktree *worktree = NULL;
2206 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2207 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2208 struct got_pathlist_entry *pe;
2209 struct got_object_id *pack_hash = NULL;
2210 int i, ch, fetchfd = -1, fetchstatus;
2211 pid_t fetchpid = -1;
2212 struct got_fetch_progress_arg fpa;
2213 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2214 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2216 TAILQ_INIT(&refs);
2217 TAILQ_INIT(&symrefs);
2218 TAILQ_INIT(&wanted_branches);
2219 TAILQ_INIT(&wanted_refs);
2221 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2222 switch (ch) {
2223 case 'a':
2224 fetch_all_branches = 1;
2225 break;
2226 case 'b':
2227 error = got_pathlist_append(&wanted_branches,
2228 optarg, NULL);
2229 if (error)
2230 return error;
2231 break;
2232 case 'd':
2233 delete_refs = 1;
2234 break;
2235 case 'l':
2236 list_refs_only = 1;
2237 break;
2238 case 'r':
2239 repo_path = realpath(optarg, NULL);
2240 if (repo_path == NULL)
2241 return got_error_from_errno2("realpath",
2242 optarg);
2243 got_path_strip_trailing_slashes(repo_path);
2244 break;
2245 case 't':
2246 replace_tags = 1;
2247 break;
2248 case 'v':
2249 if (verbosity < 0)
2250 verbosity = 0;
2251 else if (verbosity < 3)
2252 verbosity++;
2253 break;
2254 case 'q':
2255 verbosity = -1;
2256 break;
2257 case 'R':
2258 error = got_pathlist_append(&wanted_refs,
2259 optarg, NULL);
2260 if (error)
2261 return error;
2262 break;
2263 case 'X':
2264 delete_remote = 1;
2265 break;
2266 default:
2267 usage_fetch();
2268 break;
2271 argc -= optind;
2272 argv += optind;
2274 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2275 option_conflict('a', 'b');
2276 if (list_refs_only) {
2277 if (!TAILQ_EMPTY(&wanted_branches))
2278 option_conflict('l', 'b');
2279 if (fetch_all_branches)
2280 option_conflict('l', 'a');
2281 if (delete_refs)
2282 option_conflict('l', 'd');
2283 if (delete_remote)
2284 option_conflict('l', 'X');
2286 if (delete_remote) {
2287 if (fetch_all_branches)
2288 option_conflict('X', 'a');
2289 if (!TAILQ_EMPTY(&wanted_branches))
2290 option_conflict('X', 'b');
2291 if (delete_refs)
2292 option_conflict('X', 'd');
2293 if (replace_tags)
2294 option_conflict('X', 't');
2295 if (!TAILQ_EMPTY(&wanted_refs))
2296 option_conflict('X', 'R');
2299 if (argc == 0) {
2300 if (delete_remote)
2301 errx(1, "-X option requires a remote name");
2302 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2303 } else if (argc == 1)
2304 remote_name = argv[0];
2305 else
2306 usage_fetch();
2308 cwd = getcwd(NULL, 0);
2309 if (cwd == NULL) {
2310 error = got_error_from_errno("getcwd");
2311 goto done;
2314 if (repo_path == NULL) {
2315 error = got_worktree_open(&worktree, cwd);
2316 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2317 goto done;
2318 else
2319 error = NULL;
2320 if (worktree) {
2321 repo_path =
2322 strdup(got_worktree_get_repo_path(worktree));
2323 if (repo_path == NULL)
2324 error = got_error_from_errno("strdup");
2325 if (error)
2326 goto done;
2327 } else {
2328 repo_path = strdup(cwd);
2329 if (repo_path == NULL) {
2330 error = got_error_from_errno("strdup");
2331 goto done;
2336 error = got_repo_open(&repo, repo_path, NULL);
2337 if (error)
2338 goto done;
2340 if (delete_remote) {
2341 error = delete_refs_for_remote(repo, remote_name);
2342 goto done; /* nothing else to do */
2345 if (worktree) {
2346 worktree_conf = got_worktree_get_gotconfig(worktree);
2347 if (worktree_conf) {
2348 got_gotconfig_get_remotes(&nremotes, &remotes,
2349 worktree_conf);
2350 for (i = 0; i < nremotes; i++) {
2351 if (strcmp(remotes[i].name, remote_name) == 0) {
2352 remote = &remotes[i];
2353 break;
2358 if (remote == NULL) {
2359 repo_conf = got_repo_get_gotconfig(repo);
2360 if (repo_conf) {
2361 got_gotconfig_get_remotes(&nremotes, &remotes,
2362 repo_conf);
2363 for (i = 0; i < nremotes; i++) {
2364 if (strcmp(remotes[i].name, remote_name) == 0) {
2365 remote = &remotes[i];
2366 break;
2371 if (remote == NULL) {
2372 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2373 for (i = 0; i < nremotes; i++) {
2374 if (strcmp(remotes[i].name, remote_name) == 0) {
2375 remote = &remotes[i];
2376 break;
2380 if (remote == NULL) {
2381 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2382 goto done;
2385 if (TAILQ_EMPTY(&wanted_branches)) {
2386 if (!fetch_all_branches)
2387 fetch_all_branches = remote->fetch_all_branches;
2388 for (i = 0; i < remote->nfetch_branches; i++) {
2389 got_pathlist_append(&wanted_branches,
2390 remote->fetch_branches[i], NULL);
2393 if (TAILQ_EMPTY(&wanted_refs)) {
2394 for (i = 0; i < remote->nfetch_refs; i++) {
2395 got_pathlist_append(&wanted_refs,
2396 remote->fetch_refs[i], NULL);
2400 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2401 &repo_name, remote->fetch_url);
2402 if (error)
2403 goto done;
2405 if (strcmp(proto, "git") == 0) {
2406 #ifndef PROFILE
2407 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2408 "sendfd dns inet unveil", NULL) == -1)
2409 err(1, "pledge");
2410 #endif
2411 } else if (strcmp(proto, "git+ssh") == 0 ||
2412 strcmp(proto, "ssh") == 0) {
2413 #ifndef PROFILE
2414 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2415 "sendfd unveil", NULL) == -1)
2416 err(1, "pledge");
2417 #endif
2418 } else if (strcmp(proto, "http") == 0 ||
2419 strcmp(proto, "git+http") == 0) {
2420 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2421 goto done;
2422 } else {
2423 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2424 goto done;
2427 error = got_dial_apply_unveil(proto);
2428 if (error)
2429 goto done;
2431 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2432 if (error)
2433 goto done;
2435 if (verbosity >= 0)
2436 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2437 port ? ":" : "", port ? port : "");
2439 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2440 server_path, verbosity);
2441 if (error)
2442 goto done;
2444 fpa.last_scaled_size[0] = '\0';
2445 fpa.last_p_indexed = -1;
2446 fpa.last_p_resolved = -1;
2447 fpa.verbosity = verbosity;
2448 fpa.repo = repo;
2449 fpa.create_configs = 0;
2450 fpa.configs_created = 0;
2451 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2452 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2453 remote->mirror_references, fetch_all_branches, &wanted_branches,
2454 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2455 fetch_progress, &fpa);
2456 if (error)
2457 goto done;
2459 if (list_refs_only) {
2460 error = list_remote_refs(&symrefs, &refs);
2461 goto done;
2464 if (pack_hash == NULL) {
2465 if (verbosity >= 0)
2466 printf("Already up-to-date\n");
2467 } else if (verbosity >= 0) {
2468 error = got_object_id_str(&id_str, pack_hash);
2469 if (error)
2470 goto done;
2471 printf("\nFetched %s.pack\n", id_str);
2472 free(id_str);
2473 id_str = NULL;
2476 /* Update references provided with the pack file. */
2477 TAILQ_FOREACH(pe, &refs, entry) {
2478 const char *refname = pe->path;
2479 struct got_object_id *id = pe->data;
2480 struct got_reference *ref;
2481 char *remote_refname;
2483 if (is_wanted_ref(&wanted_refs, refname) &&
2484 !remote->mirror_references) {
2485 error = update_wanted_ref(refname, id,
2486 remote->name, verbosity, repo);
2487 if (error)
2488 goto done;
2489 continue;
2492 if (remote->mirror_references ||
2493 strncmp("refs/tags/", refname, 10) == 0) {
2494 error = got_ref_open(&ref, repo, refname, 1);
2495 if (error) {
2496 if (error->code != GOT_ERR_NOT_REF)
2497 goto done;
2498 error = create_ref(refname, id, verbosity,
2499 repo);
2500 if (error)
2501 goto done;
2502 } else {
2503 error = update_ref(ref, id, replace_tags,
2504 verbosity, repo);
2505 unlock_err = got_ref_unlock(ref);
2506 if (unlock_err && error == NULL)
2507 error = unlock_err;
2508 got_ref_close(ref);
2509 if (error)
2510 goto done;
2512 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2513 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2514 remote_name, refname + 11) == -1) {
2515 error = got_error_from_errno("asprintf");
2516 goto done;
2519 error = got_ref_open(&ref, repo, remote_refname, 1);
2520 if (error) {
2521 if (error->code != GOT_ERR_NOT_REF)
2522 goto done;
2523 error = create_ref(remote_refname, id,
2524 verbosity, repo);
2525 if (error)
2526 goto done;
2527 } else {
2528 error = update_ref(ref, id, replace_tags,
2529 verbosity, repo);
2530 unlock_err = got_ref_unlock(ref);
2531 if (unlock_err && error == NULL)
2532 error = unlock_err;
2533 got_ref_close(ref);
2534 if (error)
2535 goto done;
2538 /* Also create a local branch if none exists yet. */
2539 error = got_ref_open(&ref, repo, refname, 1);
2540 if (error) {
2541 if (error->code != GOT_ERR_NOT_REF)
2542 goto done;
2543 error = create_ref(refname, id, verbosity,
2544 repo);
2545 if (error)
2546 goto done;
2547 } else {
2548 unlock_err = got_ref_unlock(ref);
2549 if (unlock_err && error == NULL)
2550 error = unlock_err;
2551 got_ref_close(ref);
2555 if (delete_refs) {
2556 error = delete_missing_refs(&refs, &symrefs, remote,
2557 verbosity, repo);
2558 if (error)
2559 goto done;
2562 if (!remote->mirror_references) {
2563 /* Update remote HEAD reference if the server provided one. */
2564 TAILQ_FOREACH(pe, &symrefs, entry) {
2565 struct got_reference *target_ref;
2566 const char *refname = pe->path;
2567 const char *target = pe->data;
2568 char *remote_refname = NULL, *remote_target = NULL;
2570 if (strcmp(refname, GOT_REF_HEAD) != 0)
2571 continue;
2573 if (strncmp("refs/heads/", target, 11) != 0)
2574 continue;
2576 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2577 remote->name, refname) == -1) {
2578 error = got_error_from_errno("asprintf");
2579 goto done;
2581 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2582 remote->name, target + 11) == -1) {
2583 error = got_error_from_errno("asprintf");
2584 free(remote_refname);
2585 goto done;
2588 error = got_ref_open(&target_ref, repo, remote_target,
2589 0);
2590 if (error) {
2591 free(remote_refname);
2592 free(remote_target);
2593 if (error->code == GOT_ERR_NOT_REF) {
2594 error = NULL;
2595 continue;
2597 goto done;
2599 error = update_symref(remote_refname, target_ref,
2600 verbosity, repo);
2601 free(remote_refname);
2602 free(remote_target);
2603 got_ref_close(target_ref);
2604 if (error)
2605 goto done;
2608 done:
2609 if (fetchpid > 0) {
2610 if (kill(fetchpid, SIGTERM) == -1)
2611 error = got_error_from_errno("kill");
2612 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2613 error = got_error_from_errno("waitpid");
2615 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2616 error = got_error_from_errno("close");
2617 if (repo) {
2618 const struct got_error *close_err = got_repo_close(repo);
2619 if (error == NULL)
2620 error = close_err;
2622 if (worktree)
2623 got_worktree_close(worktree);
2624 TAILQ_FOREACH(pe, &refs, entry) {
2625 free((void *)pe->path);
2626 free(pe->data);
2628 got_pathlist_free(&refs);
2629 TAILQ_FOREACH(pe, &symrefs, entry) {
2630 free((void *)pe->path);
2631 free(pe->data);
2633 got_pathlist_free(&symrefs);
2634 got_pathlist_free(&wanted_branches);
2635 got_pathlist_free(&wanted_refs);
2636 free(id_str);
2637 free(cwd);
2638 free(repo_path);
2639 free(pack_hash);
2640 free(proto);
2641 free(host);
2642 free(port);
2643 free(server_path);
2644 free(repo_name);
2645 return error;
2649 __dead static void
2650 usage_checkout(void)
2652 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2653 "[-p prefix] [-q] repository-path [worktree-path]\n",
2654 getprogname());
2655 exit(1);
2658 static void
2659 show_worktree_base_ref_warning(void)
2661 fprintf(stderr, "%s: warning: could not create a reference "
2662 "to the work tree's base commit; the commit could be "
2663 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2664 "repository writable and running 'got update' will prevent this\n",
2665 getprogname());
2668 struct got_checkout_progress_arg {
2669 const char *worktree_path;
2670 int had_base_commit_ref_error;
2671 int verbosity;
2674 static const struct got_error *
2675 checkout_progress(void *arg, unsigned char status, const char *path)
2677 struct got_checkout_progress_arg *a = arg;
2679 /* Base commit bump happens silently. */
2680 if (status == GOT_STATUS_BUMP_BASE)
2681 return NULL;
2683 if (status == GOT_STATUS_BASE_REF_ERR) {
2684 a->had_base_commit_ref_error = 1;
2685 return NULL;
2688 while (path[0] == '/')
2689 path++;
2691 if (a->verbosity >= 0)
2692 printf("%c %s/%s\n", status, a->worktree_path, path);
2694 return NULL;
2697 static const struct got_error *
2698 check_cancelled(void *arg)
2700 if (sigint_received || sigpipe_received)
2701 return got_error(GOT_ERR_CANCELLED);
2702 return NULL;
2705 static const struct got_error *
2706 check_linear_ancestry(struct got_object_id *commit_id,
2707 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2708 struct got_repository *repo)
2710 const struct got_error *err = NULL;
2711 struct got_object_id *yca_id;
2713 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2714 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2715 if (err)
2716 return err;
2718 if (yca_id == NULL)
2719 return got_error(GOT_ERR_ANCESTRY);
2722 * Require a straight line of history between the target commit
2723 * and the work tree's base commit.
2725 * Non-linear situations such as this require a rebase:
2727 * (commit) D F (base_commit)
2728 * \ /
2729 * C E
2730 * \ /
2731 * B (yca)
2732 * |
2733 * A
2735 * 'got update' only handles linear cases:
2736 * Update forwards in time: A (base/yca) - B - C - D (commit)
2737 * Update backwards in time: D (base) - C - B - A (commit/yca)
2739 if (allow_forwards_in_time_only) {
2740 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2741 return got_error(GOT_ERR_ANCESTRY);
2742 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2743 got_object_id_cmp(base_commit_id, yca_id) != 0)
2744 return got_error(GOT_ERR_ANCESTRY);
2746 free(yca_id);
2747 return NULL;
2750 static const struct got_error *
2751 check_same_branch(struct got_object_id *commit_id,
2752 struct got_reference *head_ref, struct got_object_id *yca_id,
2753 struct got_repository *repo)
2755 const struct got_error *err = NULL;
2756 struct got_commit_graph *graph = NULL;
2757 struct got_object_id *head_commit_id = NULL;
2758 int is_same_branch = 0;
2760 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2761 if (err)
2762 goto done;
2764 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2765 is_same_branch = 1;
2766 goto done;
2768 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2769 is_same_branch = 1;
2770 goto done;
2773 err = got_commit_graph_open(&graph, "/", 1);
2774 if (err)
2775 goto done;
2777 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2778 check_cancelled, NULL);
2779 if (err)
2780 goto done;
2782 for (;;) {
2783 struct got_object_id *id;
2784 err = got_commit_graph_iter_next(&id, graph, repo,
2785 check_cancelled, NULL);
2786 if (err) {
2787 if (err->code == GOT_ERR_ITER_COMPLETED)
2788 err = NULL;
2789 break;
2792 if (id) {
2793 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2794 break;
2795 if (got_object_id_cmp(id, commit_id) == 0) {
2796 is_same_branch = 1;
2797 break;
2801 done:
2802 if (graph)
2803 got_commit_graph_close(graph);
2804 free(head_commit_id);
2805 if (!err && !is_same_branch)
2806 err = got_error(GOT_ERR_ANCESTRY);
2807 return err;
2810 static const struct got_error *
2811 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2813 static char msg[512];
2814 const char *branch_name;
2816 if (got_ref_is_symbolic(ref))
2817 branch_name = got_ref_get_symref_target(ref);
2818 else
2819 branch_name = got_ref_get_name(ref);
2821 if (strncmp("refs/heads/", branch_name, 11) == 0)
2822 branch_name += 11;
2824 snprintf(msg, sizeof(msg),
2825 "target commit is not contained in branch '%s'; "
2826 "the branch to use must be specified with -b; "
2827 "if necessary a new branch can be created for "
2828 "this commit with 'got branch -c %s BRANCH_NAME'",
2829 branch_name, commit_id_str);
2831 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2834 static const struct got_error *
2835 cmd_checkout(int argc, char *argv[])
2837 const struct got_error *error = NULL;
2838 struct got_repository *repo = NULL;
2839 struct got_reference *head_ref = NULL, *ref = NULL;
2840 struct got_worktree *worktree = NULL;
2841 char *repo_path = NULL;
2842 char *worktree_path = NULL;
2843 const char *path_prefix = "";
2844 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2845 char *commit_id_str = NULL;
2846 struct got_object_id *commit_id = NULL;
2847 char *cwd = NULL;
2848 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2849 struct got_pathlist_head paths;
2850 struct got_checkout_progress_arg cpa;
2852 TAILQ_INIT(&paths);
2854 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2855 switch (ch) {
2856 case 'b':
2857 branch_name = optarg;
2858 break;
2859 case 'c':
2860 commit_id_str = strdup(optarg);
2861 if (commit_id_str == NULL)
2862 return got_error_from_errno("strdup");
2863 break;
2864 case 'E':
2865 allow_nonempty = 1;
2866 break;
2867 case 'p':
2868 path_prefix = optarg;
2869 break;
2870 case 'q':
2871 verbosity = -1;
2872 break;
2873 default:
2874 usage_checkout();
2875 /* NOTREACHED */
2879 argc -= optind;
2880 argv += optind;
2882 #ifndef PROFILE
2883 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2884 "unveil", NULL) == -1)
2885 err(1, "pledge");
2886 #endif
2887 if (argc == 1) {
2888 char *base, *dotgit;
2889 const char *path;
2890 repo_path = realpath(argv[0], NULL);
2891 if (repo_path == NULL)
2892 return got_error_from_errno2("realpath", argv[0]);
2893 cwd = getcwd(NULL, 0);
2894 if (cwd == NULL) {
2895 error = got_error_from_errno("getcwd");
2896 goto done;
2898 if (path_prefix[0])
2899 path = path_prefix;
2900 else
2901 path = repo_path;
2902 error = got_path_basename(&base, path);
2903 if (error)
2904 goto done;
2905 dotgit = strstr(base, ".git");
2906 if (dotgit)
2907 *dotgit = '\0';
2908 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2909 error = got_error_from_errno("asprintf");
2910 free(base);
2911 goto done;
2913 free(base);
2914 } else if (argc == 2) {
2915 repo_path = realpath(argv[0], NULL);
2916 if (repo_path == NULL) {
2917 error = got_error_from_errno2("realpath", argv[0]);
2918 goto done;
2920 worktree_path = realpath(argv[1], NULL);
2921 if (worktree_path == NULL) {
2922 if (errno != ENOENT) {
2923 error = got_error_from_errno2("realpath",
2924 argv[1]);
2925 goto done;
2927 worktree_path = strdup(argv[1]);
2928 if (worktree_path == NULL) {
2929 error = got_error_from_errno("strdup");
2930 goto done;
2933 } else
2934 usage_checkout();
2936 got_path_strip_trailing_slashes(repo_path);
2937 got_path_strip_trailing_slashes(worktree_path);
2939 error = got_repo_open(&repo, repo_path, NULL);
2940 if (error != NULL)
2941 goto done;
2943 /* Pre-create work tree path for unveil(2) */
2944 error = got_path_mkdir(worktree_path);
2945 if (error) {
2946 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2947 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2948 goto done;
2949 if (!allow_nonempty &&
2950 !got_path_dir_is_empty(worktree_path)) {
2951 error = got_error_path(worktree_path,
2952 GOT_ERR_DIR_NOT_EMPTY);
2953 goto done;
2957 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2958 if (error)
2959 goto done;
2961 error = got_ref_open(&head_ref, repo, branch_name, 0);
2962 if (error != NULL)
2963 goto done;
2965 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
2966 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2967 goto done;
2969 error = got_worktree_open(&worktree, worktree_path);
2970 if (error != NULL)
2971 goto done;
2973 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2974 path_prefix);
2975 if (error != NULL)
2976 goto done;
2977 if (!same_path_prefix) {
2978 error = got_error(GOT_ERR_PATH_PREFIX);
2979 goto done;
2982 if (commit_id_str) {
2983 struct got_reflist_head refs;
2984 TAILQ_INIT(&refs);
2985 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2986 NULL);
2987 if (error)
2988 goto done;
2989 error = got_repo_match_object_id(&commit_id, NULL,
2990 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2991 got_ref_list_free(&refs);
2992 if (error)
2993 goto done;
2994 error = check_linear_ancestry(commit_id,
2995 got_worktree_get_base_commit_id(worktree), 0, repo);
2996 if (error != NULL) {
2997 if (error->code == GOT_ERR_ANCESTRY) {
2998 error = checkout_ancestry_error(
2999 head_ref, commit_id_str);
3001 goto done;
3003 error = check_same_branch(commit_id, head_ref, NULL, repo);
3004 if (error) {
3005 if (error->code == GOT_ERR_ANCESTRY) {
3006 error = checkout_ancestry_error(
3007 head_ref, commit_id_str);
3009 goto done;
3011 error = got_worktree_set_base_commit_id(worktree, repo,
3012 commit_id);
3013 if (error)
3014 goto done;
3015 /* Expand potentially abbreviated commit ID string. */
3016 free(commit_id_str);
3017 error = got_object_id_str(&commit_id_str, commit_id);
3018 if (error)
3019 goto done;
3020 } else {
3021 commit_id = got_object_id_dup(
3022 got_worktree_get_base_commit_id(worktree));
3023 if (commit_id == NULL) {
3024 error = got_error_from_errno("got_object_id_dup");
3025 goto done;
3027 error = got_object_id_str(&commit_id_str, commit_id);
3028 if (error)
3029 goto done;
3032 error = got_pathlist_append(&paths, "", NULL);
3033 if (error)
3034 goto done;
3035 cpa.worktree_path = worktree_path;
3036 cpa.had_base_commit_ref_error = 0;
3037 cpa.verbosity = verbosity;
3038 error = got_worktree_checkout_files(worktree, &paths, repo,
3039 checkout_progress, &cpa, check_cancelled, NULL);
3040 if (error != NULL)
3041 goto done;
3043 if (got_ref_is_symbolic(head_ref)) {
3044 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3045 if (error)
3046 goto done;
3047 refname = got_ref_get_name(ref);
3048 } else
3049 refname = got_ref_get_name(head_ref);
3050 printf("Checked out %s: %s\n", refname, commit_id_str);
3051 printf("Now shut up and hack\n");
3052 if (cpa.had_base_commit_ref_error)
3053 show_worktree_base_ref_warning();
3054 done:
3055 if (head_ref)
3056 got_ref_close(head_ref);
3057 if (ref)
3058 got_ref_close(ref);
3059 got_pathlist_free(&paths);
3060 free(commit_id_str);
3061 free(commit_id);
3062 free(repo_path);
3063 free(worktree_path);
3064 free(cwd);
3065 return error;
3068 struct got_update_progress_arg {
3069 int did_something;
3070 int conflicts;
3071 int obstructed;
3072 int not_updated;
3073 int missing;
3074 int not_deleted;
3075 int unversioned;
3076 int verbosity;
3079 void
3080 print_update_progress_stats(struct got_update_progress_arg *upa)
3082 if (!upa->did_something)
3083 return;
3085 if (upa->conflicts > 0)
3086 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3087 if (upa->obstructed > 0)
3088 printf("File paths obstructed by a non-regular file: %d\n",
3089 upa->obstructed);
3090 if (upa->not_updated > 0)
3091 printf("Files not updated because of existing merge "
3092 "conflicts: %d\n", upa->not_updated);
3096 * The meaning of some status codes differs between merge-style operations and
3097 * update operations. For example, the ! status code means "file was missing"
3098 * if changes were merged into the work tree, and "missing file was restored"
3099 * if the work tree was updated. This function should be used by any operation
3100 * which merges changes into the work tree without updating the work tree.
3102 void
3103 print_merge_progress_stats(struct got_update_progress_arg *upa)
3105 if (!upa->did_something)
3106 return;
3108 if (upa->conflicts > 0)
3109 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3110 if (upa->obstructed > 0)
3111 printf("File paths obstructed by a non-regular file: %d\n",
3112 upa->obstructed);
3113 if (upa->missing > 0)
3114 printf("Files which had incoming changes but could not be "
3115 "found in the work tree: %d\n", upa->missing);
3116 if (upa->not_deleted > 0)
3117 printf("Files not deleted due to differences in deleted "
3118 "content: %d\n", upa->not_deleted);
3119 if (upa->unversioned > 0)
3120 printf("Files not merged because an unversioned file was "
3121 "found in the work tree: %d\n", upa->unversioned);
3124 __dead static void
3125 usage_update(void)
3127 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3128 "[path ...]\n",
3129 getprogname());
3130 exit(1);
3133 static const struct got_error *
3134 update_progress(void *arg, unsigned char status, const char *path)
3136 struct got_update_progress_arg *upa = arg;
3138 if (status == GOT_STATUS_EXISTS ||
3139 status == GOT_STATUS_BASE_REF_ERR)
3140 return NULL;
3142 upa->did_something = 1;
3144 /* Base commit bump happens silently. */
3145 if (status == GOT_STATUS_BUMP_BASE)
3146 return NULL;
3148 if (status == GOT_STATUS_CONFLICT)
3149 upa->conflicts++;
3150 if (status == GOT_STATUS_OBSTRUCTED)
3151 upa->obstructed++;
3152 if (status == GOT_STATUS_CANNOT_UPDATE)
3153 upa->not_updated++;
3154 if (status == GOT_STATUS_MISSING)
3155 upa->missing++;
3156 if (status == GOT_STATUS_CANNOT_DELETE)
3157 upa->not_deleted++;
3158 if (status == GOT_STATUS_UNVERSIONED)
3159 upa->unversioned++;
3161 while (path[0] == '/')
3162 path++;
3163 if (upa->verbosity >= 0)
3164 printf("%c %s\n", status, path);
3166 return NULL;
3169 static const struct got_error *
3170 switch_head_ref(struct got_reference *head_ref,
3171 struct got_object_id *commit_id, struct got_worktree *worktree,
3172 struct got_repository *repo)
3174 const struct got_error *err = NULL;
3175 char *base_id_str;
3176 int ref_has_moved = 0;
3178 /* Trivial case: switching between two different references. */
3179 if (strcmp(got_ref_get_name(head_ref),
3180 got_worktree_get_head_ref_name(worktree)) != 0) {
3181 printf("Switching work tree from %s to %s\n",
3182 got_worktree_get_head_ref_name(worktree),
3183 got_ref_get_name(head_ref));
3184 return got_worktree_set_head_ref(worktree, head_ref);
3187 err = check_linear_ancestry(commit_id,
3188 got_worktree_get_base_commit_id(worktree), 0, repo);
3189 if (err) {
3190 if (err->code != GOT_ERR_ANCESTRY)
3191 return err;
3192 ref_has_moved = 1;
3194 if (!ref_has_moved)
3195 return NULL;
3197 /* Switching to a rebased branch with the same reference name. */
3198 err = got_object_id_str(&base_id_str,
3199 got_worktree_get_base_commit_id(worktree));
3200 if (err)
3201 return err;
3202 printf("Reference %s now points at a different branch\n",
3203 got_worktree_get_head_ref_name(worktree));
3204 printf("Switching work tree from %s to %s\n", base_id_str,
3205 got_worktree_get_head_ref_name(worktree));
3206 return NULL;
3209 static const struct got_error *
3210 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3212 const struct got_error *err;
3213 int in_progress;
3215 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3216 if (err)
3217 return err;
3218 if (in_progress)
3219 return got_error(GOT_ERR_REBASING);
3221 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3222 if (err)
3223 return err;
3224 if (in_progress)
3225 return got_error(GOT_ERR_HISTEDIT_BUSY);
3227 return NULL;
3230 static const struct got_error *
3231 check_merge_in_progress(struct got_worktree *worktree,
3232 struct got_repository *repo)
3234 const struct got_error *err;
3235 int in_progress;
3237 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3238 if (err)
3239 return err;
3240 if (in_progress)
3241 return got_error(GOT_ERR_MERGE_BUSY);
3243 return NULL;
3246 static const struct got_error *
3247 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3248 char *argv[], struct got_worktree *worktree)
3250 const struct got_error *err = NULL;
3251 char *path;
3252 struct got_pathlist_entry *new;
3253 int i;
3255 if (argc == 0) {
3256 path = strdup("");
3257 if (path == NULL)
3258 return got_error_from_errno("strdup");
3259 return got_pathlist_append(paths, path, NULL);
3262 for (i = 0; i < argc; i++) {
3263 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3264 if (err)
3265 break;
3266 err = got_pathlist_insert(&new, paths, path, NULL);
3267 if (err || new == NULL /* duplicate */) {
3268 free(path);
3269 if (err)
3270 break;
3274 return err;
3277 static const struct got_error *
3278 wrap_not_worktree_error(const struct got_error *orig_err,
3279 const char *cmdname, const char *path)
3281 const struct got_error *err;
3282 struct got_repository *repo;
3283 static char msg[512];
3285 err = got_repo_open(&repo, path, NULL);
3286 if (err)
3287 return orig_err;
3289 snprintf(msg, sizeof(msg),
3290 "'got %s' needs a work tree in addition to a git repository\n"
3291 "Work trees can be checked out from this Git repository with "
3292 "'got checkout'.\n"
3293 "The got(1) manual page contains more information.", cmdname);
3294 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3295 got_repo_close(repo);
3296 return err;
3299 static const struct got_error *
3300 cmd_update(int argc, char *argv[])
3302 const struct got_error *error = NULL;
3303 struct got_repository *repo = NULL;
3304 struct got_worktree *worktree = NULL;
3305 char *worktree_path = NULL;
3306 struct got_object_id *commit_id = NULL;
3307 char *commit_id_str = NULL;
3308 const char *branch_name = NULL;
3309 struct got_reference *head_ref = NULL;
3310 struct got_pathlist_head paths;
3311 struct got_pathlist_entry *pe;
3312 int ch, verbosity = 0;
3313 struct got_update_progress_arg upa;
3315 TAILQ_INIT(&paths);
3317 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3318 switch (ch) {
3319 case 'b':
3320 branch_name = optarg;
3321 break;
3322 case 'c':
3323 commit_id_str = strdup(optarg);
3324 if (commit_id_str == NULL)
3325 return got_error_from_errno("strdup");
3326 break;
3327 case 'q':
3328 verbosity = -1;
3329 break;
3330 default:
3331 usage_update();
3332 /* NOTREACHED */
3336 argc -= optind;
3337 argv += optind;
3339 #ifndef PROFILE
3340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3341 "unveil", NULL) == -1)
3342 err(1, "pledge");
3343 #endif
3344 worktree_path = getcwd(NULL, 0);
3345 if (worktree_path == NULL) {
3346 error = got_error_from_errno("getcwd");
3347 goto done;
3349 error = got_worktree_open(&worktree, worktree_path);
3350 if (error) {
3351 if (error->code == GOT_ERR_NOT_WORKTREE)
3352 error = wrap_not_worktree_error(error, "update",
3353 worktree_path);
3354 goto done;
3357 error = check_rebase_or_histedit_in_progress(worktree);
3358 if (error)
3359 goto done;
3361 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3362 NULL);
3363 if (error != NULL)
3364 goto done;
3366 error = apply_unveil(got_repo_get_path(repo), 0,
3367 got_worktree_get_root_path(worktree));
3368 if (error)
3369 goto done;
3371 error = check_merge_in_progress(worktree, repo);
3372 if (error)
3373 goto done;
3375 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3376 if (error)
3377 goto done;
3379 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3380 got_worktree_get_head_ref_name(worktree), 0);
3381 if (error != NULL)
3382 goto done;
3383 if (commit_id_str == NULL) {
3384 error = got_ref_resolve(&commit_id, repo, head_ref);
3385 if (error != NULL)
3386 goto done;
3387 error = got_object_id_str(&commit_id_str, commit_id);
3388 if (error != NULL)
3389 goto done;
3390 } else {
3391 struct got_reflist_head refs;
3392 TAILQ_INIT(&refs);
3393 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3394 NULL);
3395 if (error)
3396 goto done;
3397 error = got_repo_match_object_id(&commit_id, NULL,
3398 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3399 got_ref_list_free(&refs);
3400 free(commit_id_str);
3401 commit_id_str = NULL;
3402 if (error)
3403 goto done;
3404 error = got_object_id_str(&commit_id_str, commit_id);
3405 if (error)
3406 goto done;
3409 if (branch_name) {
3410 struct got_object_id *head_commit_id;
3411 TAILQ_FOREACH(pe, &paths, entry) {
3412 if (pe->path_len == 0)
3413 continue;
3414 error = got_error_msg(GOT_ERR_BAD_PATH,
3415 "switching between branches requires that "
3416 "the entire work tree gets updated");
3417 goto done;
3419 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3420 if (error)
3421 goto done;
3422 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3423 repo);
3424 free(head_commit_id);
3425 if (error != NULL)
3426 goto done;
3427 error = check_same_branch(commit_id, head_ref, NULL, repo);
3428 if (error)
3429 goto done;
3430 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3431 if (error)
3432 goto done;
3433 } else {
3434 error = check_linear_ancestry(commit_id,
3435 got_worktree_get_base_commit_id(worktree), 0, repo);
3436 if (error != NULL) {
3437 if (error->code == GOT_ERR_ANCESTRY)
3438 error = got_error(GOT_ERR_BRANCH_MOVED);
3439 goto done;
3441 error = check_same_branch(commit_id, head_ref, NULL, repo);
3442 if (error)
3443 goto done;
3446 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3447 commit_id) != 0) {
3448 error = got_worktree_set_base_commit_id(worktree, repo,
3449 commit_id);
3450 if (error)
3451 goto done;
3454 memset(&upa, 0, sizeof(upa));
3455 upa.verbosity = verbosity;
3456 error = got_worktree_checkout_files(worktree, &paths, repo,
3457 update_progress, &upa, check_cancelled, NULL);
3458 if (error != NULL)
3459 goto done;
3461 if (upa.did_something) {
3462 printf("Updated to %s: %s\n",
3463 got_worktree_get_head_ref_name(worktree), commit_id_str);
3464 } else
3465 printf("Already up-to-date\n");
3466 print_update_progress_stats(&upa);
3467 done:
3468 free(worktree_path);
3469 TAILQ_FOREACH(pe, &paths, entry)
3470 free((char *)pe->path);
3471 got_pathlist_free(&paths);
3472 free(commit_id);
3473 free(commit_id_str);
3474 return error;
3477 static const struct got_error *
3478 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3479 const char *path, int diff_context, int ignore_whitespace,
3480 int force_text_diff, struct got_repository *repo)
3482 const struct got_error *err = NULL;
3483 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3484 FILE *f1 = NULL, *f2 = NULL;
3486 if (blob_id1) {
3487 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192);
3488 if (err)
3489 goto done;
3490 f1 = got_opentemp();
3491 if (f1 == NULL) {
3492 err = got_error_from_errno("got_opentemp");
3493 goto done;
3497 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192);
3498 if (err)
3499 goto done;
3501 f2 = got_opentemp();
3502 if (f2 == NULL) {
3503 err = got_error_from_errno("got_opentemp");
3504 goto done;
3507 while (path[0] == '/')
3508 path++;
3509 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3510 diff_context, ignore_whitespace, force_text_diff, stdout);
3511 done:
3512 if (blob1)
3513 got_object_blob_close(blob1);
3514 got_object_blob_close(blob2);
3515 if (f1 && fclose(f1) == EOF && err == NULL)
3516 err = got_error_from_errno("fclose");
3517 if (f2 && fclose(f2) == EOF && err == NULL)
3518 err = got_error_from_errno("fclose");
3519 return err;
3522 static const struct got_error *
3523 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3524 const char *path, int diff_context, int ignore_whitespace,
3525 int force_text_diff, struct got_repository *repo)
3527 const struct got_error *err = NULL;
3528 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3529 struct got_diff_blob_output_unidiff_arg arg;
3530 FILE *f1 = NULL, *f2 = NULL;
3532 if (tree_id1) {
3533 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3534 if (err)
3535 goto done;
3536 f1 = got_opentemp();
3537 if (f1 == NULL) {
3538 err = got_error_from_errno("got_opentemp");
3539 goto done;
3543 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3544 if (err)
3545 goto done;
3547 f2 = got_opentemp();
3548 if (f2 == NULL) {
3549 err = got_error_from_errno("got_opentemp");
3550 goto done;
3553 arg.diff_context = diff_context;
3554 arg.ignore_whitespace = ignore_whitespace;
3555 arg.force_text_diff = force_text_diff;
3556 arg.outfile = stdout;
3557 arg.line_offsets = NULL;
3558 arg.nlines = 0;
3559 while (path[0] == '/')
3560 path++;
3561 err = got_diff_tree(tree1, tree2, f1, f2, path, path, repo,
3562 got_diff_blob_output_unidiff, &arg, 1);
3563 done:
3564 if (tree1)
3565 got_object_tree_close(tree1);
3566 if (tree2)
3567 got_object_tree_close(tree2);
3568 if (f1 && fclose(f1) == EOF && err == NULL)
3569 err = got_error_from_errno("fclose");
3570 if (f2 && fclose(f2) == EOF && err == NULL)
3571 err = got_error_from_errno("fclose");
3572 return err;
3575 static const struct got_error *
3576 get_changed_paths(struct got_pathlist_head *paths,
3577 struct got_commit_object *commit, struct got_repository *repo)
3579 const struct got_error *err = NULL;
3580 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3581 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3582 struct got_object_qid *qid;
3584 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3585 if (qid != NULL) {
3586 struct got_commit_object *pcommit;
3587 err = got_object_open_as_commit(&pcommit, repo,
3588 &qid->id);
3589 if (err)
3590 return err;
3592 tree_id1 = got_object_id_dup(
3593 got_object_commit_get_tree_id(pcommit));
3594 if (tree_id1 == NULL) {
3595 got_object_commit_close(pcommit);
3596 return got_error_from_errno("got_object_id_dup");
3598 got_object_commit_close(pcommit);
3602 if (tree_id1) {
3603 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3604 if (err)
3605 goto done;
3608 tree_id2 = got_object_commit_get_tree_id(commit);
3609 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3610 if (err)
3611 goto done;
3613 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
3614 got_diff_tree_collect_changed_paths, paths, 0);
3615 done:
3616 if (tree1)
3617 got_object_tree_close(tree1);
3618 if (tree2)
3619 got_object_tree_close(tree2);
3620 free(tree_id1);
3621 return err;
3624 static const struct got_error *
3625 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3626 const char *path, int diff_context, struct got_repository *repo)
3628 const struct got_error *err = NULL;
3629 struct got_commit_object *pcommit = NULL;
3630 char *id_str1 = NULL, *id_str2 = NULL;
3631 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3632 struct got_object_qid *qid;
3634 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3635 if (qid != NULL) {
3636 err = got_object_open_as_commit(&pcommit, repo,
3637 &qid->id);
3638 if (err)
3639 return err;
3642 if (path && path[0] != '\0') {
3643 int obj_type;
3644 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3645 if (err)
3646 goto done;
3647 err = got_object_id_str(&id_str2, obj_id2);
3648 if (err) {
3649 free(obj_id2);
3650 goto done;
3652 if (pcommit) {
3653 err = got_object_id_by_path(&obj_id1, repo,
3654 pcommit, path);
3655 if (err) {
3656 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3657 free(obj_id2);
3658 goto done;
3660 } else {
3661 err = got_object_id_str(&id_str1, obj_id1);
3662 if (err) {
3663 free(obj_id2);
3664 goto done;
3668 err = got_object_get_type(&obj_type, repo, obj_id2);
3669 if (err) {
3670 free(obj_id2);
3671 goto done;
3673 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3674 switch (obj_type) {
3675 case GOT_OBJ_TYPE_BLOB:
3676 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3677 0, 0, repo);
3678 break;
3679 case GOT_OBJ_TYPE_TREE:
3680 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3681 0, 0, repo);
3682 break;
3683 default:
3684 err = got_error(GOT_ERR_OBJ_TYPE);
3685 break;
3687 free(obj_id1);
3688 free(obj_id2);
3689 } else {
3690 obj_id2 = got_object_commit_get_tree_id(commit);
3691 err = got_object_id_str(&id_str2, obj_id2);
3692 if (err)
3693 goto done;
3694 if (pcommit) {
3695 obj_id1 = got_object_commit_get_tree_id(pcommit);
3696 err = got_object_id_str(&id_str1, obj_id1);
3697 if (err)
3698 goto done;
3700 printf("diff %s %s\n", id_str1 ? id_str1 : "/dev/null",
3701 id_str2);
3702 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3703 repo);
3705 done:
3706 free(id_str1);
3707 free(id_str2);
3708 if (pcommit)
3709 got_object_commit_close(pcommit);
3710 return err;
3713 static char *
3714 get_datestr(time_t *time, char *datebuf)
3716 struct tm mytm, *tm;
3717 char *p, *s;
3719 tm = gmtime_r(time, &mytm);
3720 if (tm == NULL)
3721 return NULL;
3722 s = asctime_r(tm, datebuf);
3723 if (s == NULL)
3724 return NULL;
3725 p = strchr(s, '\n');
3726 if (p)
3727 *p = '\0';
3728 return s;
3731 static const struct got_error *
3732 match_logmsg(int *have_match, struct got_object_id *id,
3733 struct got_commit_object *commit, regex_t *regex)
3735 const struct got_error *err = NULL;
3736 regmatch_t regmatch;
3737 char *id_str = NULL, *logmsg = NULL;
3739 *have_match = 0;
3741 err = got_object_id_str(&id_str, id);
3742 if (err)
3743 return err;
3745 err = got_object_commit_get_logmsg(&logmsg, commit);
3746 if (err)
3747 goto done;
3749 if (regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3750 *have_match = 1;
3751 done:
3752 free(id_str);
3753 free(logmsg);
3754 return err;
3757 static void
3758 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3759 regex_t *regex)
3761 regmatch_t regmatch;
3762 struct got_pathlist_entry *pe;
3764 *have_match = 0;
3766 TAILQ_FOREACH(pe, changed_paths, entry) {
3767 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3768 *have_match = 1;
3769 break;
3774 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3776 static const struct got_error*
3777 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3778 struct got_object_id *id, struct got_repository *repo)
3780 static const struct got_error *err = NULL;
3781 struct got_reflist_entry *re;
3782 char *s;
3783 const char *name;
3785 *refs_str = NULL;
3787 TAILQ_FOREACH(re, refs, entry) {
3788 struct got_tag_object *tag = NULL;
3789 struct got_object_id *ref_id;
3790 int cmp;
3792 name = got_ref_get_name(re->ref);
3793 if (strcmp(name, GOT_REF_HEAD) == 0)
3794 continue;
3795 if (strncmp(name, "refs/", 5) == 0)
3796 name += 5;
3797 if (strncmp(name, "got/", 4) == 0)
3798 continue;
3799 if (strncmp(name, "heads/", 6) == 0)
3800 name += 6;
3801 if (strncmp(name, "remotes/", 8) == 0) {
3802 name += 8;
3803 s = strstr(name, "/" GOT_REF_HEAD);
3804 if (s != NULL && s[strlen(s)] == '\0')
3805 continue;
3807 err = got_ref_resolve(&ref_id, repo, re->ref);
3808 if (err)
3809 break;
3810 if (strncmp(name, "tags/", 5) == 0) {
3811 err = got_object_open_as_tag(&tag, repo, ref_id);
3812 if (err) {
3813 if (err->code != GOT_ERR_OBJ_TYPE) {
3814 free(ref_id);
3815 break;
3817 /* Ref points at something other than a tag. */
3818 err = NULL;
3819 tag = NULL;
3822 cmp = got_object_id_cmp(tag ?
3823 got_object_tag_get_object_id(tag) : ref_id, id);
3824 free(ref_id);
3825 if (tag)
3826 got_object_tag_close(tag);
3827 if (cmp != 0)
3828 continue;
3829 s = *refs_str;
3830 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3831 s ? ", " : "", name) == -1) {
3832 err = got_error_from_errno("asprintf");
3833 free(s);
3834 *refs_str = NULL;
3835 break;
3837 free(s);
3840 return err;
3843 static const struct got_error *
3844 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3845 struct got_repository *repo, const char *path,
3846 struct got_pathlist_head *changed_paths, int show_patch,
3847 int diff_context, struct got_reflist_object_id_map *refs_idmap,
3848 const char *custom_refs_str)
3850 const struct got_error *err = NULL;
3851 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3852 char datebuf[26];
3853 time_t committer_time;
3854 const char *author, *committer;
3855 char *refs_str = NULL;
3857 err = got_object_id_str(&id_str, id);
3858 if (err)
3859 return err;
3861 if (custom_refs_str == NULL) {
3862 struct got_reflist_head *refs;
3863 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3864 if (refs) {
3865 err = build_refs_str(&refs_str, refs, id, repo);
3866 if (err)
3867 goto done;
3871 printf(GOT_COMMIT_SEP_STR);
3872 if (custom_refs_str)
3873 printf("commit %s (%s)\n", id_str, custom_refs_str);
3874 else
3875 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
3876 refs_str ? refs_str : "", refs_str ? ")" : "");
3877 free(id_str);
3878 id_str = NULL;
3879 free(refs_str);
3880 refs_str = NULL;
3881 printf("from: %s\n", got_object_commit_get_author(commit));
3882 committer_time = got_object_commit_get_committer_time(commit);
3883 datestr = get_datestr(&committer_time, datebuf);
3884 if (datestr)
3885 printf("date: %s UTC\n", datestr);
3886 author = got_object_commit_get_author(commit);
3887 committer = got_object_commit_get_committer(commit);
3888 if (strcmp(author, committer) != 0)
3889 printf("via: %s\n", committer);
3890 if (got_object_commit_get_nparents(commit) > 1) {
3891 const struct got_object_id_queue *parent_ids;
3892 struct got_object_qid *qid;
3893 int n = 1;
3894 parent_ids = got_object_commit_get_parent_ids(commit);
3895 STAILQ_FOREACH(qid, parent_ids, entry) {
3896 err = got_object_id_str(&id_str, &qid->id);
3897 if (err)
3898 goto done;
3899 printf("parent %d: %s\n", n++, id_str);
3900 free(id_str);
3901 id_str = NULL;
3905 err = got_object_commit_get_logmsg(&logmsg0, commit);
3906 if (err)
3907 goto done;
3909 logmsg = logmsg0;
3910 do {
3911 line = strsep(&logmsg, "\n");
3912 if (line)
3913 printf(" %s\n", line);
3914 } while (line);
3915 free(logmsg0);
3917 if (changed_paths) {
3918 struct got_pathlist_entry *pe;
3919 TAILQ_FOREACH(pe, changed_paths, entry) {
3920 struct got_diff_changed_path *cp = pe->data;
3921 printf(" %c %s\n", cp->status, pe->path);
3923 printf("\n");
3925 if (show_patch) {
3926 err = print_patch(commit, id, path, diff_context, repo);
3927 if (err == 0)
3928 printf("\n");
3931 if (fflush(stdout) != 0 && err == NULL)
3932 err = got_error_from_errno("fflush");
3933 done:
3934 free(id_str);
3935 free(refs_str);
3936 return err;
3939 static const struct got_error *
3940 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3941 struct got_repository *repo, const char *path, int show_changed_paths,
3942 int show_patch, const char *search_pattern, int diff_context, int limit,
3943 int log_branches, int reverse_display_order,
3944 struct got_reflist_object_id_map *refs_idmap)
3946 const struct got_error *err;
3947 struct got_commit_graph *graph;
3948 regex_t regex;
3949 int have_match;
3950 struct got_object_id_queue reversed_commits;
3951 struct got_object_qid *qid;
3952 struct got_commit_object *commit;
3953 struct got_pathlist_head changed_paths;
3954 struct got_pathlist_entry *pe;
3956 STAILQ_INIT(&reversed_commits);
3957 TAILQ_INIT(&changed_paths);
3959 if (search_pattern && regcomp(&regex, search_pattern,
3960 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3961 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3963 err = got_commit_graph_open(&graph, path, !log_branches);
3964 if (err)
3965 return err;
3966 err = got_commit_graph_iter_start(graph, root_id, repo,
3967 check_cancelled, NULL);
3968 if (err)
3969 goto done;
3970 for (;;) {
3971 struct got_object_id *id;
3973 if (sigint_received || sigpipe_received)
3974 break;
3976 err = got_commit_graph_iter_next(&id, graph, repo,
3977 check_cancelled, NULL);
3978 if (err) {
3979 if (err->code == GOT_ERR_ITER_COMPLETED)
3980 err = NULL;
3981 break;
3983 if (id == NULL)
3984 break;
3986 err = got_object_open_as_commit(&commit, repo, id);
3987 if (err)
3988 break;
3990 if (show_changed_paths && !reverse_display_order) {
3991 err = get_changed_paths(&changed_paths, commit, repo);
3992 if (err)
3993 break;
3996 if (search_pattern) {
3997 err = match_logmsg(&have_match, id, commit, &regex);
3998 if (err) {
3999 got_object_commit_close(commit);
4000 break;
4002 if (have_match == 0 && show_changed_paths)
4003 match_changed_paths(&have_match,
4004 &changed_paths, &regex);
4005 if (have_match == 0) {
4006 got_object_commit_close(commit);
4007 TAILQ_FOREACH(pe, &changed_paths, entry) {
4008 free((char *)pe->path);
4009 free(pe->data);
4011 got_pathlist_free(&changed_paths);
4012 continue;
4016 if (reverse_display_order) {
4017 err = got_object_qid_alloc(&qid, id);
4018 if (err)
4019 break;
4020 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4021 got_object_commit_close(commit);
4022 } else {
4023 err = print_commit(commit, id, repo, path,
4024 show_changed_paths ? &changed_paths : NULL,
4025 show_patch, diff_context, refs_idmap, NULL);
4026 got_object_commit_close(commit);
4027 if (err)
4028 break;
4030 if ((limit && --limit == 0) ||
4031 (end_id && got_object_id_cmp(id, end_id) == 0))
4032 break;
4034 TAILQ_FOREACH(pe, &changed_paths, entry) {
4035 free((char *)pe->path);
4036 free(pe->data);
4038 got_pathlist_free(&changed_paths);
4040 if (reverse_display_order) {
4041 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4042 err = got_object_open_as_commit(&commit, repo,
4043 &qid->id);
4044 if (err)
4045 break;
4046 if (show_changed_paths) {
4047 err = get_changed_paths(&changed_paths,
4048 commit, repo);
4049 if (err)
4050 break;
4052 err = print_commit(commit, &qid->id, repo, path,
4053 show_changed_paths ? &changed_paths : NULL,
4054 show_patch, diff_context, refs_idmap, NULL);
4055 got_object_commit_close(commit);
4056 if (err)
4057 break;
4058 TAILQ_FOREACH(pe, &changed_paths, entry) {
4059 free((char *)pe->path);
4060 free(pe->data);
4062 got_pathlist_free(&changed_paths);
4065 done:
4066 while (!STAILQ_EMPTY(&reversed_commits)) {
4067 qid = STAILQ_FIRST(&reversed_commits);
4068 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4069 got_object_qid_free(qid);
4071 TAILQ_FOREACH(pe, &changed_paths, entry) {
4072 free((char *)pe->path);
4073 free(pe->data);
4075 got_pathlist_free(&changed_paths);
4076 if (search_pattern)
4077 regfree(&regex);
4078 got_commit_graph_close(graph);
4079 return err;
4082 __dead static void
4083 usage_log(void)
4085 fprintf(stderr, "usage: %s log [-b] [-c commit] [-C number] [ -l N ] "
4086 "[-p] [-P] [-x commit] [-s search-pattern] [-r repository-path] "
4087 "[-R] [path]\n", getprogname());
4088 exit(1);
4091 static int
4092 get_default_log_limit(void)
4094 const char *got_default_log_limit;
4095 long long n;
4096 const char *errstr;
4098 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4099 if (got_default_log_limit == NULL)
4100 return 0;
4101 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4102 if (errstr != NULL)
4103 return 0;
4104 return n;
4107 static const struct got_error *
4108 cmd_log(int argc, char *argv[])
4110 const struct got_error *error;
4111 struct got_repository *repo = NULL;
4112 struct got_worktree *worktree = NULL;
4113 struct got_object_id *start_id = NULL, *end_id = NULL;
4114 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4115 const char *start_commit = NULL, *end_commit = NULL;
4116 const char *search_pattern = NULL;
4117 int diff_context = -1, ch;
4118 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4119 int reverse_display_order = 0;
4120 const char *errstr;
4121 struct got_reflist_head refs;
4122 struct got_reflist_object_id_map *refs_idmap = NULL;
4124 TAILQ_INIT(&refs);
4126 #ifndef PROFILE
4127 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4128 NULL)
4129 == -1)
4130 err(1, "pledge");
4131 #endif
4133 limit = get_default_log_limit();
4135 while ((ch = getopt(argc, argv, "bpPc:C:l:r:Rs:x:")) != -1) {
4136 switch (ch) {
4137 case 'p':
4138 show_patch = 1;
4139 break;
4140 case 'P':
4141 show_changed_paths = 1;
4142 break;
4143 case 'c':
4144 start_commit = optarg;
4145 break;
4146 case 'C':
4147 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4148 &errstr);
4149 if (errstr != NULL)
4150 errx(1, "number of context lines is %s: %s",
4151 errstr, optarg);
4152 break;
4153 case 'l':
4154 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4155 if (errstr != NULL)
4156 errx(1, "number of commits is %s: %s",
4157 errstr, optarg);
4158 break;
4159 case 'b':
4160 log_branches = 1;
4161 break;
4162 case 'r':
4163 repo_path = realpath(optarg, NULL);
4164 if (repo_path == NULL)
4165 return got_error_from_errno2("realpath",
4166 optarg);
4167 got_path_strip_trailing_slashes(repo_path);
4168 break;
4169 case 'R':
4170 reverse_display_order = 1;
4171 break;
4172 case 's':
4173 search_pattern = optarg;
4174 break;
4175 case 'x':
4176 end_commit = optarg;
4177 break;
4178 default:
4179 usage_log();
4180 /* NOTREACHED */
4184 argc -= optind;
4185 argv += optind;
4187 if (diff_context == -1)
4188 diff_context = 3;
4189 else if (!show_patch)
4190 errx(1, "-C requires -p");
4192 cwd = getcwd(NULL, 0);
4193 if (cwd == NULL) {
4194 error = got_error_from_errno("getcwd");
4195 goto done;
4198 if (repo_path == NULL) {
4199 error = got_worktree_open(&worktree, cwd);
4200 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4201 goto done;
4202 error = NULL;
4205 if (argc == 1) {
4206 if (worktree) {
4207 error = got_worktree_resolve_path(&path, worktree,
4208 argv[0]);
4209 if (error)
4210 goto done;
4211 } else {
4212 path = strdup(argv[0]);
4213 if (path == NULL) {
4214 error = got_error_from_errno("strdup");
4215 goto done;
4218 } else if (argc != 0)
4219 usage_log();
4221 if (repo_path == NULL) {
4222 repo_path = worktree ?
4223 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4225 if (repo_path == NULL) {
4226 error = got_error_from_errno("strdup");
4227 goto done;
4230 error = got_repo_open(&repo, repo_path, NULL);
4231 if (error != NULL)
4232 goto done;
4234 error = apply_unveil(got_repo_get_path(repo), 1,
4235 worktree ? got_worktree_get_root_path(worktree) : NULL);
4236 if (error)
4237 goto done;
4239 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4240 if (error)
4241 goto done;
4243 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4244 if (error)
4245 goto done;
4247 if (start_commit == NULL) {
4248 struct got_reference *head_ref;
4249 struct got_commit_object *commit = NULL;
4250 error = got_ref_open(&head_ref, repo,
4251 worktree ? got_worktree_get_head_ref_name(worktree)
4252 : GOT_REF_HEAD, 0);
4253 if (error != NULL)
4254 goto done;
4255 error = got_ref_resolve(&start_id, repo, head_ref);
4256 got_ref_close(head_ref);
4257 if (error != NULL)
4258 goto done;
4259 error = got_object_open_as_commit(&commit, repo,
4260 start_id);
4261 if (error != NULL)
4262 goto done;
4263 got_object_commit_close(commit);
4264 } else {
4265 error = got_repo_match_object_id(&start_id, NULL,
4266 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4267 if (error != NULL)
4268 goto done;
4270 if (end_commit != NULL) {
4271 error = got_repo_match_object_id(&end_id, NULL,
4272 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4273 if (error != NULL)
4274 goto done;
4277 if (worktree) {
4279 * If a path was specified on the command line it was resolved
4280 * to a path in the work tree above. Prepend the work tree's
4281 * path prefix to obtain the corresponding in-repository path.
4283 if (path) {
4284 const char *prefix;
4285 prefix = got_worktree_get_path_prefix(worktree);
4286 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4287 (path[0] != '\0') ? "/" : "", path) == -1) {
4288 error = got_error_from_errno("asprintf");
4289 goto done;
4292 } else
4293 error = got_repo_map_path(&in_repo_path, repo,
4294 path ? path : "");
4295 if (error != NULL)
4296 goto done;
4297 if (in_repo_path) {
4298 free(path);
4299 path = in_repo_path;
4302 if (worktree) {
4303 /* Release work tree lock. */
4304 got_worktree_close(worktree);
4305 worktree = NULL;
4308 error = print_commits(start_id, end_id, repo, path ? path : "",
4309 show_changed_paths, show_patch, search_pattern, diff_context,
4310 limit, log_branches, reverse_display_order, refs_idmap);
4311 done:
4312 free(path);
4313 free(repo_path);
4314 free(cwd);
4315 if (worktree)
4316 got_worktree_close(worktree);
4317 if (repo) {
4318 const struct got_error *close_err = got_repo_close(repo);
4319 if (error == NULL)
4320 error = close_err;
4322 if (refs_idmap)
4323 got_reflist_object_id_map_free(refs_idmap);
4324 got_ref_list_free(&refs);
4325 return error;
4328 __dead static void
4329 usage_diff(void)
4331 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4332 "[-r repository-path] [-s] [-w] [-P] "
4333 "[object1 object2 | path ...]\n", getprogname());
4334 exit(1);
4337 struct print_diff_arg {
4338 struct got_repository *repo;
4339 struct got_worktree *worktree;
4340 int diff_context;
4341 const char *id_str;
4342 int header_shown;
4343 int diff_staged;
4344 int ignore_whitespace;
4345 int force_text_diff;
4349 * Create a file which contains the target path of a symlink so we can feed
4350 * it as content to the diff engine.
4352 static const struct got_error *
4353 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4354 const char *abspath)
4356 const struct got_error *err = NULL;
4357 char target_path[PATH_MAX];
4358 ssize_t target_len, outlen;
4360 *fd = -1;
4362 if (dirfd != -1) {
4363 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4364 if (target_len == -1)
4365 return got_error_from_errno2("readlinkat", abspath);
4366 } else {
4367 target_len = readlink(abspath, target_path, PATH_MAX);
4368 if (target_len == -1)
4369 return got_error_from_errno2("readlink", abspath);
4372 *fd = got_opentempfd();
4373 if (*fd == -1)
4374 return got_error_from_errno("got_opentempfd");
4376 outlen = write(*fd, target_path, target_len);
4377 if (outlen == -1) {
4378 err = got_error_from_errno("got_opentempfd");
4379 goto done;
4382 if (lseek(*fd, 0, SEEK_SET) == -1) {
4383 err = got_error_from_errno2("lseek", abspath);
4384 goto done;
4386 done:
4387 if (err) {
4388 close(*fd);
4389 *fd = -1;
4391 return err;
4394 static const struct got_error *
4395 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4396 const char *path, struct got_object_id *blob_id,
4397 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4398 int dirfd, const char *de_name)
4400 struct print_diff_arg *a = arg;
4401 const struct got_error *err = NULL;
4402 struct got_blob_object *blob1 = NULL;
4403 int fd = -1;
4404 FILE *f1 = NULL, *f2 = NULL;
4405 char *abspath = NULL, *label1 = NULL;
4406 struct stat sb;
4407 off_t size1 = 0;
4409 if (a->diff_staged) {
4410 if (staged_status != GOT_STATUS_MODIFY &&
4411 staged_status != GOT_STATUS_ADD &&
4412 staged_status != GOT_STATUS_DELETE)
4413 return NULL;
4414 } else {
4415 if (staged_status == GOT_STATUS_DELETE)
4416 return NULL;
4417 if (status == GOT_STATUS_NONEXISTENT)
4418 return got_error_set_errno(ENOENT, path);
4419 if (status != GOT_STATUS_MODIFY &&
4420 status != GOT_STATUS_ADD &&
4421 status != GOT_STATUS_DELETE &&
4422 status != GOT_STATUS_CONFLICT)
4423 return NULL;
4426 if (!a->header_shown) {
4427 printf("diff %s %s%s\n", a->id_str,
4428 got_worktree_get_root_path(a->worktree),
4429 a->diff_staged ? " (staged changes)" : "");
4430 a->header_shown = 1;
4433 if (a->diff_staged) {
4434 const char *label1 = NULL, *label2 = NULL;
4435 switch (staged_status) {
4436 case GOT_STATUS_MODIFY:
4437 label1 = path;
4438 label2 = path;
4439 break;
4440 case GOT_STATUS_ADD:
4441 label2 = path;
4442 break;
4443 case GOT_STATUS_DELETE:
4444 label1 = path;
4445 break;
4446 default:
4447 return got_error(GOT_ERR_FILE_STATUS);
4449 f1 = got_opentemp();
4450 if (f1 == NULL) {
4451 err = got_error_from_errno("got_opentemp");
4452 goto done;
4454 f2 = got_opentemp();
4455 if (f2 == NULL) {
4456 err = got_error_from_errno("got_opentemp");
4457 goto done;
4459 err = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4460 blob_id, staged_blob_id, label1, label2, a->diff_context,
4461 a->ignore_whitespace, a->force_text_diff, a->repo, stdout);
4462 goto done;
4465 if (staged_status == GOT_STATUS_ADD ||
4466 staged_status == GOT_STATUS_MODIFY) {
4467 char *id_str;
4468 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4469 8192);
4470 if (err)
4471 goto done;
4472 err = got_object_id_str(&id_str, staged_blob_id);
4473 if (err)
4474 goto done;
4475 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4476 err = got_error_from_errno("asprintf");
4477 free(id_str);
4478 goto done;
4480 free(id_str);
4481 } else if (status != GOT_STATUS_ADD) {
4482 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192);
4483 if (err)
4484 goto done;
4487 if (status != GOT_STATUS_DELETE) {
4488 if (asprintf(&abspath, "%s/%s",
4489 got_worktree_get_root_path(a->worktree), path) == -1) {
4490 err = got_error_from_errno("asprintf");
4491 goto done;
4494 if (dirfd != -1) {
4495 fd = openat(dirfd, de_name,
4496 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4497 if (fd == -1) {
4498 if (!got_err_open_nofollow_on_symlink()) {
4499 err = got_error_from_errno2("openat",
4500 abspath);
4501 goto done;
4503 err = get_symlink_target_file(&fd, dirfd,
4504 de_name, abspath);
4505 if (err)
4506 goto done;
4508 } else {
4509 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4510 if (fd == -1) {
4511 if (!got_err_open_nofollow_on_symlink()) {
4512 err = got_error_from_errno2("open",
4513 abspath);
4514 goto done;
4516 err = get_symlink_target_file(&fd, dirfd,
4517 de_name, abspath);
4518 if (err)
4519 goto done;
4522 if (fstat(fd, &sb) == -1) {
4523 err = got_error_from_errno2("fstat", abspath);
4524 goto done;
4526 f2 = fdopen(fd, "r");
4527 if (f2 == NULL) {
4528 err = got_error_from_errno2("fdopen", abspath);
4529 goto done;
4531 fd = -1;
4532 } else
4533 sb.st_size = 0;
4535 if (blob1) {
4536 f1 = got_opentemp();
4537 if (f1 == NULL) {
4538 err = got_error_from_errno("got_opentemp");
4539 goto done;
4541 err = got_object_blob_dump_to_file(&size1, NULL, NULL, f1,
4542 blob1);
4543 if (err)
4544 goto done;
4547 err = got_diff_blob_file(blob1, f1, size1, label1, f2, sb.st_size,
4548 path, a->diff_context, a->ignore_whitespace, a->force_text_diff,
4549 stdout);
4550 done:
4551 if (blob1)
4552 got_object_blob_close(blob1);
4553 if (f1 && fclose(f1) == EOF && err == NULL)
4554 err = got_error_from_errno("fclose");
4555 if (f2 && fclose(f2) == EOF && err == NULL)
4556 err = got_error_from_errno("fclose");
4557 if (fd != -1 && close(fd) == -1 && err == NULL)
4558 err = got_error_from_errno("close");
4559 free(abspath);
4560 return err;
4563 static const struct got_error *
4564 cmd_diff(int argc, char *argv[])
4566 const struct got_error *error;
4567 struct got_repository *repo = NULL;
4568 struct got_worktree *worktree = NULL;
4569 char *cwd = NULL, *repo_path = NULL;
4570 const char *commit_args[2] = { NULL, NULL };
4571 int ncommit_args = 0;
4572 struct got_object_id *ids[2] = { NULL, NULL };
4573 char *labels[2] = { NULL, NULL };
4574 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4575 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4576 int force_text_diff = 0, force_path = 0, rflag = 0;
4577 const char *errstr;
4578 struct got_reflist_head refs;
4579 struct got_pathlist_head paths;
4580 struct got_pathlist_entry *pe;
4581 FILE *f1 = NULL, *f2 = NULL;
4583 TAILQ_INIT(&refs);
4584 TAILQ_INIT(&paths);
4586 #ifndef PROFILE
4587 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4588 NULL) == -1)
4589 err(1, "pledge");
4590 #endif
4592 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4593 switch (ch) {
4594 case 'a':
4595 force_text_diff = 1;
4596 break;
4597 case 'c':
4598 if (ncommit_args >= 2)
4599 errx(1, "too many -c options used");
4600 commit_args[ncommit_args++] = optarg;
4601 break;
4602 case 'C':
4603 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4604 &errstr);
4605 if (errstr != NULL)
4606 errx(1, "number of context lines is %s: %s",
4607 errstr, optarg);
4608 break;
4609 case 'r':
4610 repo_path = realpath(optarg, NULL);
4611 if (repo_path == NULL)
4612 return got_error_from_errno2("realpath",
4613 optarg);
4614 got_path_strip_trailing_slashes(repo_path);
4615 rflag = 1;
4616 break;
4617 case 's':
4618 diff_staged = 1;
4619 break;
4620 case 'w':
4621 ignore_whitespace = 1;
4622 break;
4623 case 'P':
4624 force_path = 1;
4625 break;
4626 default:
4627 usage_diff();
4628 /* NOTREACHED */
4632 argc -= optind;
4633 argv += optind;
4635 cwd = getcwd(NULL, 0);
4636 if (cwd == NULL) {
4637 error = got_error_from_errno("getcwd");
4638 goto done;
4641 if (repo_path == NULL) {
4642 error = got_worktree_open(&worktree, cwd);
4643 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4644 goto done;
4645 else
4646 error = NULL;
4647 if (worktree) {
4648 repo_path =
4649 strdup(got_worktree_get_repo_path(worktree));
4650 if (repo_path == NULL) {
4651 error = got_error_from_errno("strdup");
4652 goto done;
4654 } else {
4655 repo_path = strdup(cwd);
4656 if (repo_path == NULL) {
4657 error = got_error_from_errno("strdup");
4658 goto done;
4663 error = got_repo_open(&repo, repo_path, NULL);
4664 free(repo_path);
4665 if (error != NULL)
4666 goto done;
4668 if (rflag || worktree == NULL || ncommit_args > 0) {
4669 if (force_path) {
4670 error = got_error_msg(GOT_ERR_NOT_IMPL,
4671 "-P option can only be used when diffing "
4672 "a work tree");
4673 goto done;
4675 if (diff_staged) {
4676 error = got_error_msg(GOT_ERR_NOT_IMPL,
4677 "-s option can only be used when diffing "
4678 "a work tree");
4679 goto done;
4683 error = apply_unveil(got_repo_get_path(repo), 1,
4684 worktree ? got_worktree_get_root_path(worktree) : NULL);
4685 if (error)
4686 goto done;
4688 if ((!force_path && argc == 2) || ncommit_args > 0) {
4689 int obj_type = (ncommit_args > 0 ?
4690 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4691 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4692 NULL);
4693 if (error)
4694 goto done;
4695 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4696 const char *arg;
4697 if (ncommit_args > 0)
4698 arg = commit_args[i];
4699 else
4700 arg = argv[i];
4701 error = got_repo_match_object_id(&ids[i], &labels[i],
4702 arg, obj_type, &refs, repo);
4703 if (error) {
4704 if (error->code != GOT_ERR_NOT_REF &&
4705 error->code != GOT_ERR_NO_OBJ)
4706 goto done;
4707 if (ncommit_args > 0)
4708 goto done;
4709 error = NULL;
4710 break;
4715 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4716 struct print_diff_arg arg;
4717 char *id_str;
4719 if (worktree == NULL) {
4720 if (argc == 2 && ids[0] == NULL) {
4721 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4722 goto done;
4723 } else if (argc == 2 && ids[1] == NULL) {
4724 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4725 goto done;
4726 } else if (argc > 0) {
4727 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4728 "%s", "specified paths cannot be resolved");
4729 goto done;
4730 } else {
4731 error = got_error(GOT_ERR_NOT_WORKTREE);
4732 goto done;
4736 error = get_worktree_paths_from_argv(&paths, argc, argv,
4737 worktree);
4738 if (error)
4739 goto done;
4741 error = got_object_id_str(&id_str,
4742 got_worktree_get_base_commit_id(worktree));
4743 if (error)
4744 goto done;
4745 arg.repo = repo;
4746 arg.worktree = worktree;
4747 arg.diff_context = diff_context;
4748 arg.id_str = id_str;
4749 arg.header_shown = 0;
4750 arg.diff_staged = diff_staged;
4751 arg.ignore_whitespace = ignore_whitespace;
4752 arg.force_text_diff = force_text_diff;
4754 error = got_worktree_status(worktree, &paths, repo, 0,
4755 print_diff, &arg, check_cancelled, NULL);
4756 free(id_str);
4757 goto done;
4760 if (ncommit_args == 1) {
4761 struct got_commit_object *commit;
4762 error = got_object_open_as_commit(&commit, repo, ids[0]);
4763 if (error)
4764 goto done;
4766 labels[1] = labels[0];
4767 ids[1] = ids[0];
4768 if (got_object_commit_get_nparents(commit) > 0) {
4769 const struct got_object_id_queue *pids;
4770 struct got_object_qid *pid;
4771 pids = got_object_commit_get_parent_ids(commit);
4772 pid = STAILQ_FIRST(pids);
4773 ids[0] = got_object_id_dup(&pid->id);
4774 if (ids[0] == NULL) {
4775 error = got_error_from_errno(
4776 "got_object_id_dup");
4777 got_object_commit_close(commit);
4778 goto done;
4780 error = got_object_id_str(&labels[0], ids[0]);
4781 if (error) {
4782 got_object_commit_close(commit);
4783 goto done;
4785 } else {
4786 ids[0] = NULL;
4787 labels[0] = strdup("/dev/null");
4788 if (labels[0] == NULL) {
4789 error = got_error_from_errno("strdup");
4790 got_object_commit_close(commit);
4791 goto done;
4795 got_object_commit_close(commit);
4798 if (ncommit_args == 0 && argc > 2) {
4799 error = got_error_msg(GOT_ERR_BAD_PATH,
4800 "path arguments cannot be used when diffing two objects");
4801 goto done;
4804 if (ids[0]) {
4805 error = got_object_get_type(&type1, repo, ids[0]);
4806 if (error)
4807 goto done;
4810 error = got_object_get_type(&type2, repo, ids[1]);
4811 if (error)
4812 goto done;
4813 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4814 error = got_error(GOT_ERR_OBJ_TYPE);
4815 goto done;
4817 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
4818 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4819 "path arguments cannot be used when diffing blobs");
4820 goto done;
4823 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4824 char *in_repo_path;
4825 struct got_pathlist_entry *new;
4826 if (worktree) {
4827 const char *prefix;
4828 char *p;
4829 error = got_worktree_resolve_path(&p, worktree,
4830 argv[i]);
4831 if (error)
4832 goto done;
4833 prefix = got_worktree_get_path_prefix(worktree);
4834 while (prefix[0] == '/')
4835 prefix++;
4836 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4837 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4838 p) == -1) {
4839 error = got_error_from_errno("asprintf");
4840 free(p);
4841 goto done;
4843 free(p);
4844 } else {
4845 char *mapped_path, *s;
4846 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4847 if (error)
4848 goto done;
4849 s = mapped_path;
4850 while (s[0] == '/')
4851 s++;
4852 in_repo_path = strdup(s);
4853 if (in_repo_path == NULL) {
4854 error = got_error_from_errno("asprintf");
4855 free(mapped_path);
4856 goto done;
4858 free(mapped_path);
4861 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4862 if (error || new == NULL /* duplicate */)
4863 free(in_repo_path);
4864 if (error)
4865 goto done;
4868 if (worktree) {
4869 /* Release work tree lock. */
4870 got_worktree_close(worktree);
4871 worktree = NULL;
4874 f1 = got_opentemp();
4875 if (f1 == NULL) {
4876 error = got_error_from_errno("got_opentemp");
4877 goto done;
4880 f2 = got_opentemp();
4881 if (f2 == NULL) {
4882 error = got_error_from_errno("got_opentemp");
4883 goto done;
4886 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4887 case GOT_OBJ_TYPE_BLOB:
4888 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4889 ids[0], ids[1], NULL, NULL, diff_context,
4890 ignore_whitespace, force_text_diff, repo, stdout);
4891 break;
4892 case GOT_OBJ_TYPE_TREE:
4893 error = got_diff_objects_as_trees(NULL, NULL, f1, f2,
4894 ids[0], ids[1], &paths, "", "", diff_context,
4895 ignore_whitespace, force_text_diff, repo, stdout);
4896 break;
4897 case GOT_OBJ_TYPE_COMMIT:
4898 printf("diff %s %s\n", labels[0], labels[1]);
4899 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4900 ids[0], ids[1], &paths, diff_context, ignore_whitespace,
4901 force_text_diff, repo, stdout);
4902 break;
4903 default:
4904 error = got_error(GOT_ERR_OBJ_TYPE);
4906 done:
4907 free(labels[0]);
4908 free(labels[1]);
4909 free(ids[0]);
4910 free(ids[1]);
4911 if (worktree)
4912 got_worktree_close(worktree);
4913 if (repo) {
4914 const struct got_error *close_err = got_repo_close(repo);
4915 if (error == NULL)
4916 error = close_err;
4918 TAILQ_FOREACH(pe, &paths, entry)
4919 free((char *)pe->path);
4920 got_pathlist_free(&paths);
4921 got_ref_list_free(&refs);
4922 if (f1 && fclose(f1) == EOF && error == NULL)
4923 error = got_error_from_errno("fclose");
4924 if (f2 && fclose(f2) == EOF && error == NULL)
4925 error = got_error_from_errno("fclose");
4926 return error;
4929 __dead static void
4930 usage_blame(void)
4932 fprintf(stderr,
4933 "usage: %s blame [-c commit] [-r repository-path] path\n",
4934 getprogname());
4935 exit(1);
4938 struct blame_line {
4939 int annotated;
4940 char *id_str;
4941 char *committer;
4942 char datebuf[11]; /* YYYY-MM-DD + NUL */
4945 struct blame_cb_args {
4946 struct blame_line *lines;
4947 int nlines;
4948 int nlines_prec;
4949 int lineno_cur;
4950 off_t *line_offsets;
4951 FILE *f;
4952 struct got_repository *repo;
4955 static const struct got_error *
4956 blame_cb(void *arg, int nlines, int lineno,
4957 struct got_commit_object *commit, struct got_object_id *id)
4959 const struct got_error *err = NULL;
4960 struct blame_cb_args *a = arg;
4961 struct blame_line *bline;
4962 char *line = NULL;
4963 size_t linesize = 0;
4964 off_t offset;
4965 struct tm tm;
4966 time_t committer_time;
4968 if (nlines != a->nlines ||
4969 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4970 return got_error(GOT_ERR_RANGE);
4972 if (sigint_received)
4973 return got_error(GOT_ERR_ITER_COMPLETED);
4975 if (lineno == -1)
4976 return NULL; /* no change in this commit */
4978 /* Annotate this line. */
4979 bline = &a->lines[lineno - 1];
4980 if (bline->annotated)
4981 return NULL;
4982 err = got_object_id_str(&bline->id_str, id);
4983 if (err)
4984 return err;
4986 bline->committer = strdup(got_object_commit_get_committer(commit));
4987 if (bline->committer == NULL) {
4988 err = got_error_from_errno("strdup");
4989 goto done;
4992 committer_time = got_object_commit_get_committer_time(commit);
4993 if (gmtime_r(&committer_time, &tm) == NULL)
4994 return got_error_from_errno("gmtime_r");
4995 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4996 &tm) == 0) {
4997 err = got_error(GOT_ERR_NO_SPACE);
4998 goto done;
5000 bline->annotated = 1;
5002 /* Print lines annotated so far. */
5003 bline = &a->lines[a->lineno_cur - 1];
5004 if (!bline->annotated)
5005 goto done;
5007 offset = a->line_offsets[a->lineno_cur - 1];
5008 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5009 err = got_error_from_errno("fseeko");
5010 goto done;
5013 while (bline->annotated) {
5014 char *smallerthan, *at, *nl, *committer;
5015 size_t len;
5017 if (getline(&line, &linesize, a->f) == -1) {
5018 if (ferror(a->f))
5019 err = got_error_from_errno("getline");
5020 break;
5023 committer = bline->committer;
5024 smallerthan = strchr(committer, '<');
5025 if (smallerthan && smallerthan[1] != '\0')
5026 committer = smallerthan + 1;
5027 at = strchr(committer, '@');
5028 if (at)
5029 *at = '\0';
5030 len = strlen(committer);
5031 if (len >= 9)
5032 committer[8] = '\0';
5034 nl = strchr(line, '\n');
5035 if (nl)
5036 *nl = '\0';
5037 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5038 bline->id_str, bline->datebuf, committer, line);
5040 a->lineno_cur++;
5041 bline = &a->lines[a->lineno_cur - 1];
5043 done:
5044 free(line);
5045 return err;
5048 static const struct got_error *
5049 cmd_blame(int argc, char *argv[])
5051 const struct got_error *error;
5052 struct got_repository *repo = NULL;
5053 struct got_worktree *worktree = NULL;
5054 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5055 char *link_target = NULL;
5056 struct got_object_id *obj_id = NULL;
5057 struct got_object_id *commit_id = NULL;
5058 struct got_commit_object *commit = NULL;
5059 struct got_blob_object *blob = NULL;
5060 char *commit_id_str = NULL;
5061 struct blame_cb_args bca;
5062 int ch, obj_type, i;
5063 off_t filesize;
5065 memset(&bca, 0, sizeof(bca));
5067 #ifndef PROFILE
5068 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5069 NULL) == -1)
5070 err(1, "pledge");
5071 #endif
5073 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5074 switch (ch) {
5075 case 'c':
5076 commit_id_str = optarg;
5077 break;
5078 case 'r':
5079 repo_path = realpath(optarg, NULL);
5080 if (repo_path == NULL)
5081 return got_error_from_errno2("realpath",
5082 optarg);
5083 got_path_strip_trailing_slashes(repo_path);
5084 break;
5085 default:
5086 usage_blame();
5087 /* NOTREACHED */
5091 argc -= optind;
5092 argv += optind;
5094 if (argc == 1)
5095 path = argv[0];
5096 else
5097 usage_blame();
5099 cwd = getcwd(NULL, 0);
5100 if (cwd == NULL) {
5101 error = got_error_from_errno("getcwd");
5102 goto done;
5104 if (repo_path == NULL) {
5105 error = got_worktree_open(&worktree, cwd);
5106 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5107 goto done;
5108 else
5109 error = NULL;
5110 if (worktree) {
5111 repo_path =
5112 strdup(got_worktree_get_repo_path(worktree));
5113 if (repo_path == NULL) {
5114 error = got_error_from_errno("strdup");
5115 if (error)
5116 goto done;
5118 } else {
5119 repo_path = strdup(cwd);
5120 if (repo_path == NULL) {
5121 error = got_error_from_errno("strdup");
5122 goto done;
5127 error = got_repo_open(&repo, repo_path, NULL);
5128 if (error != NULL)
5129 goto done;
5131 if (worktree) {
5132 const char *prefix = got_worktree_get_path_prefix(worktree);
5133 char *p;
5135 error = got_worktree_resolve_path(&p, worktree, path);
5136 if (error)
5137 goto done;
5138 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5139 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5140 p) == -1) {
5141 error = got_error_from_errno("asprintf");
5142 free(p);
5143 goto done;
5145 free(p);
5146 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5147 } else {
5148 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5149 if (error)
5150 goto done;
5151 error = got_repo_map_path(&in_repo_path, repo, path);
5153 if (error)
5154 goto done;
5156 if (commit_id_str == NULL) {
5157 struct got_reference *head_ref;
5158 error = got_ref_open(&head_ref, repo, worktree ?
5159 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5160 if (error != NULL)
5161 goto done;
5162 error = got_ref_resolve(&commit_id, repo, head_ref);
5163 got_ref_close(head_ref);
5164 if (error != NULL)
5165 goto done;
5166 } else {
5167 struct got_reflist_head refs;
5168 TAILQ_INIT(&refs);
5169 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5170 NULL);
5171 if (error)
5172 goto done;
5173 error = got_repo_match_object_id(&commit_id, NULL,
5174 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5175 got_ref_list_free(&refs);
5176 if (error)
5177 goto done;
5180 if (worktree) {
5181 /* Release work tree lock. */
5182 got_worktree_close(worktree);
5183 worktree = NULL;
5186 error = got_object_open_as_commit(&commit, repo, commit_id);
5187 if (error)
5188 goto done;
5190 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5191 commit, repo);
5192 if (error)
5193 goto done;
5195 error = got_object_id_by_path(&obj_id, repo, commit,
5196 link_target ? link_target : in_repo_path);
5197 if (error)
5198 goto done;
5200 error = got_object_get_type(&obj_type, repo, obj_id);
5201 if (error)
5202 goto done;
5204 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5205 error = got_error_path(link_target ? link_target : in_repo_path,
5206 GOT_ERR_OBJ_TYPE);
5207 goto done;
5210 error = got_object_open_as_blob(&blob, repo, obj_id, 8192);
5211 if (error)
5212 goto done;
5213 bca.f = got_opentemp();
5214 if (bca.f == NULL) {
5215 error = got_error_from_errno("got_opentemp");
5216 goto done;
5218 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5219 &bca.line_offsets, bca.f, blob);
5220 if (error || bca.nlines == 0)
5221 goto done;
5223 /* Don't include \n at EOF in the blame line count. */
5224 if (bca.line_offsets[bca.nlines - 1] == filesize)
5225 bca.nlines--;
5227 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5228 if (bca.lines == NULL) {
5229 error = got_error_from_errno("calloc");
5230 goto done;
5232 bca.lineno_cur = 1;
5233 bca.nlines_prec = 0;
5234 i = bca.nlines;
5235 while (i > 0) {
5236 i /= 10;
5237 bca.nlines_prec++;
5239 bca.repo = repo;
5241 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5242 repo, blame_cb, &bca, check_cancelled, NULL);
5243 done:
5244 free(in_repo_path);
5245 free(link_target);
5246 free(repo_path);
5247 free(cwd);
5248 free(commit_id);
5249 free(obj_id);
5250 if (commit)
5251 got_object_commit_close(commit);
5252 if (blob)
5253 got_object_blob_close(blob);
5254 if (worktree)
5255 got_worktree_close(worktree);
5256 if (repo) {
5257 const struct got_error *close_err = got_repo_close(repo);
5258 if (error == NULL)
5259 error = close_err;
5261 if (bca.lines) {
5262 for (i = 0; i < bca.nlines; i++) {
5263 struct blame_line *bline = &bca.lines[i];
5264 free(bline->id_str);
5265 free(bline->committer);
5267 free(bca.lines);
5269 free(bca.line_offsets);
5270 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5271 error = got_error_from_errno("fclose");
5272 return error;
5275 __dead static void
5276 usage_tree(void)
5278 fprintf(stderr,
5279 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5280 getprogname());
5281 exit(1);
5284 static const struct got_error *
5285 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5286 const char *root_path, struct got_repository *repo)
5288 const struct got_error *err = NULL;
5289 int is_root_path = (strcmp(path, root_path) == 0);
5290 const char *modestr = "";
5291 mode_t mode = got_tree_entry_get_mode(te);
5292 char *link_target = NULL;
5294 path += strlen(root_path);
5295 while (path[0] == '/')
5296 path++;
5298 if (got_object_tree_entry_is_submodule(te))
5299 modestr = "$";
5300 else if (S_ISLNK(mode)) {
5301 int i;
5303 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5304 if (err)
5305 return err;
5306 for (i = 0; i < strlen(link_target); i++) {
5307 if (!isprint((unsigned char)link_target[i]))
5308 link_target[i] = '?';
5311 modestr = "@";
5313 else if (S_ISDIR(mode))
5314 modestr = "/";
5315 else if (mode & S_IXUSR)
5316 modestr = "*";
5318 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5319 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5320 link_target ? " -> ": "", link_target ? link_target : "");
5322 free(link_target);
5323 return NULL;
5326 static const struct got_error *
5327 print_tree(const char *path, struct got_commit_object *commit,
5328 int show_ids, int recurse, const char *root_path,
5329 struct got_repository *repo)
5331 const struct got_error *err = NULL;
5332 struct got_object_id *tree_id = NULL;
5333 struct got_tree_object *tree = NULL;
5334 int nentries, i;
5336 err = got_object_id_by_path(&tree_id, repo, commit, path);
5337 if (err)
5338 goto done;
5340 err = got_object_open_as_tree(&tree, repo, tree_id);
5341 if (err)
5342 goto done;
5343 nentries = got_object_tree_get_nentries(tree);
5344 for (i = 0; i < nentries; i++) {
5345 struct got_tree_entry *te;
5346 char *id = NULL;
5348 if (sigint_received || sigpipe_received)
5349 break;
5351 te = got_object_tree_get_entry(tree, i);
5352 if (show_ids) {
5353 char *id_str;
5354 err = got_object_id_str(&id_str,
5355 got_tree_entry_get_id(te));
5356 if (err)
5357 goto done;
5358 if (asprintf(&id, "%s ", id_str) == -1) {
5359 err = got_error_from_errno("asprintf");
5360 free(id_str);
5361 goto done;
5363 free(id_str);
5365 err = print_entry(te, id, path, root_path, repo);
5366 free(id);
5367 if (err)
5368 goto done;
5370 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5371 char *child_path;
5372 if (asprintf(&child_path, "%s%s%s", path,
5373 path[0] == '/' && path[1] == '\0' ? "" : "/",
5374 got_tree_entry_get_name(te)) == -1) {
5375 err = got_error_from_errno("asprintf");
5376 goto done;
5378 err = print_tree(child_path, commit, show_ids, 1,
5379 root_path, repo);
5380 free(child_path);
5381 if (err)
5382 goto done;
5385 done:
5386 if (tree)
5387 got_object_tree_close(tree);
5388 free(tree_id);
5389 return err;
5392 static const struct got_error *
5393 cmd_tree(int argc, char *argv[])
5395 const struct got_error *error;
5396 struct got_repository *repo = NULL;
5397 struct got_worktree *worktree = NULL;
5398 const char *path, *refname = NULL;
5399 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5400 struct got_object_id *commit_id = NULL;
5401 struct got_commit_object *commit = NULL;
5402 char *commit_id_str = NULL;
5403 int show_ids = 0, recurse = 0;
5404 int ch;
5406 #ifndef PROFILE
5407 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5408 NULL) == -1)
5409 err(1, "pledge");
5410 #endif
5412 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5413 switch (ch) {
5414 case 'c':
5415 commit_id_str = optarg;
5416 break;
5417 case 'r':
5418 repo_path = realpath(optarg, NULL);
5419 if (repo_path == NULL)
5420 return got_error_from_errno2("realpath",
5421 optarg);
5422 got_path_strip_trailing_slashes(repo_path);
5423 break;
5424 case 'i':
5425 show_ids = 1;
5426 break;
5427 case 'R':
5428 recurse = 1;
5429 break;
5430 default:
5431 usage_tree();
5432 /* NOTREACHED */
5436 argc -= optind;
5437 argv += optind;
5439 if (argc == 1)
5440 path = argv[0];
5441 else if (argc > 1)
5442 usage_tree();
5443 else
5444 path = NULL;
5446 cwd = getcwd(NULL, 0);
5447 if (cwd == NULL) {
5448 error = got_error_from_errno("getcwd");
5449 goto done;
5451 if (repo_path == NULL) {
5452 error = got_worktree_open(&worktree, cwd);
5453 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5454 goto done;
5455 else
5456 error = NULL;
5457 if (worktree) {
5458 repo_path =
5459 strdup(got_worktree_get_repo_path(worktree));
5460 if (repo_path == NULL)
5461 error = got_error_from_errno("strdup");
5462 if (error)
5463 goto done;
5464 } else {
5465 repo_path = strdup(cwd);
5466 if (repo_path == NULL) {
5467 error = got_error_from_errno("strdup");
5468 goto done;
5473 error = got_repo_open(&repo, repo_path, NULL);
5474 if (error != NULL)
5475 goto done;
5477 if (worktree) {
5478 const char *prefix = got_worktree_get_path_prefix(worktree);
5479 char *p;
5481 if (path == NULL)
5482 path = "";
5483 error = got_worktree_resolve_path(&p, worktree, path);
5484 if (error)
5485 goto done;
5486 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5487 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5488 p) == -1) {
5489 error = got_error_from_errno("asprintf");
5490 free(p);
5491 goto done;
5493 free(p);
5494 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5495 if (error)
5496 goto done;
5497 } else {
5498 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5499 if (error)
5500 goto done;
5501 if (path == NULL)
5502 path = "/";
5503 error = got_repo_map_path(&in_repo_path, repo, path);
5504 if (error != NULL)
5505 goto done;
5508 if (commit_id_str == NULL) {
5509 struct got_reference *head_ref;
5510 if (worktree)
5511 refname = got_worktree_get_head_ref_name(worktree);
5512 else
5513 refname = GOT_REF_HEAD;
5514 error = got_ref_open(&head_ref, repo, refname, 0);
5515 if (error != NULL)
5516 goto done;
5517 error = got_ref_resolve(&commit_id, repo, head_ref);
5518 got_ref_close(head_ref);
5519 if (error != NULL)
5520 goto done;
5521 } else {
5522 struct got_reflist_head refs;
5523 TAILQ_INIT(&refs);
5524 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5525 NULL);
5526 if (error)
5527 goto done;
5528 error = got_repo_match_object_id(&commit_id, NULL,
5529 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5530 got_ref_list_free(&refs);
5531 if (error)
5532 goto done;
5535 if (worktree) {
5536 /* Release work tree lock. */
5537 got_worktree_close(worktree);
5538 worktree = NULL;
5541 error = got_object_open_as_commit(&commit, repo, commit_id);
5542 if (error)
5543 goto done;
5545 error = print_tree(in_repo_path, commit, show_ids, recurse,
5546 in_repo_path, repo);
5547 done:
5548 free(in_repo_path);
5549 free(repo_path);
5550 free(cwd);
5551 free(commit_id);
5552 if (commit)
5553 got_object_commit_close(commit);
5554 if (worktree)
5555 got_worktree_close(worktree);
5556 if (repo) {
5557 const struct got_error *close_err = got_repo_close(repo);
5558 if (error == NULL)
5559 error = close_err;
5561 return error;
5564 __dead static void
5565 usage_status(void)
5567 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5568 "[-S status-codes] [path ...]\n", getprogname());
5569 exit(1);
5572 struct got_status_arg {
5573 char *status_codes;
5574 int suppress;
5577 static const struct got_error *
5578 print_status(void *arg, unsigned char status, unsigned char staged_status,
5579 const char *path, struct got_object_id *blob_id,
5580 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5581 int dirfd, const char *de_name)
5583 struct got_status_arg *st = arg;
5585 if (status == staged_status && (status == GOT_STATUS_DELETE))
5586 status = GOT_STATUS_NO_CHANGE;
5587 if (st != NULL && st->status_codes) {
5588 size_t ncodes = strlen(st->status_codes);
5589 int i, j = 0;
5591 for (i = 0; i < ncodes ; i++) {
5592 if (st->suppress) {
5593 if (status == st->status_codes[i] ||
5594 staged_status == st->status_codes[i]) {
5595 j++;
5596 continue;
5598 } else {
5599 if (status == st->status_codes[i] ||
5600 staged_status == st->status_codes[i])
5601 break;
5605 if (st->suppress && j == 0)
5606 goto print;
5608 if (i == ncodes)
5609 return NULL;
5611 print:
5612 printf("%c%c %s\n", status, staged_status, path);
5613 return NULL;
5616 static const struct got_error *
5617 cmd_status(int argc, char *argv[])
5619 const struct got_error *error = NULL;
5620 struct got_repository *repo = NULL;
5621 struct got_worktree *worktree = NULL;
5622 struct got_status_arg st;
5623 char *cwd = NULL;
5624 struct got_pathlist_head paths;
5625 struct got_pathlist_entry *pe;
5626 int ch, i, no_ignores = 0;
5628 TAILQ_INIT(&paths);
5630 memset(&st, 0, sizeof(st));
5631 st.status_codes = NULL;
5632 st.suppress = 0;
5634 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
5635 switch (ch) {
5636 case 'I':
5637 no_ignores = 1;
5638 break;
5639 case 'S':
5640 if (st.status_codes != NULL && st.suppress == 0)
5641 option_conflict('S', 's');
5642 st.suppress = 1;
5643 /* fallthrough */
5644 case 's':
5645 for (i = 0; i < strlen(optarg); i++) {
5646 switch (optarg[i]) {
5647 case GOT_STATUS_MODIFY:
5648 case GOT_STATUS_ADD:
5649 case GOT_STATUS_DELETE:
5650 case GOT_STATUS_CONFLICT:
5651 case GOT_STATUS_MISSING:
5652 case GOT_STATUS_OBSTRUCTED:
5653 case GOT_STATUS_UNVERSIONED:
5654 case GOT_STATUS_MODE_CHANGE:
5655 case GOT_STATUS_NONEXISTENT:
5656 break;
5657 default:
5658 errx(1, "invalid status code '%c'",
5659 optarg[i]);
5662 if (ch == 's' && st.suppress)
5663 option_conflict('s', 'S');
5664 st.status_codes = optarg;
5665 break;
5666 default:
5667 usage_status();
5668 /* NOTREACHED */
5672 argc -= optind;
5673 argv += optind;
5675 #ifndef PROFILE
5676 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5677 NULL) == -1)
5678 err(1, "pledge");
5679 #endif
5680 cwd = getcwd(NULL, 0);
5681 if (cwd == NULL) {
5682 error = got_error_from_errno("getcwd");
5683 goto done;
5686 error = got_worktree_open(&worktree, cwd);
5687 if (error) {
5688 if (error->code == GOT_ERR_NOT_WORKTREE)
5689 error = wrap_not_worktree_error(error, "status", cwd);
5690 goto done;
5693 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5694 NULL);
5695 if (error != NULL)
5696 goto done;
5698 error = apply_unveil(got_repo_get_path(repo), 1,
5699 got_worktree_get_root_path(worktree));
5700 if (error)
5701 goto done;
5703 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5704 if (error)
5705 goto done;
5707 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5708 print_status, &st, check_cancelled, NULL);
5709 done:
5710 TAILQ_FOREACH(pe, &paths, entry)
5711 free((char *)pe->path);
5712 got_pathlist_free(&paths);
5713 free(cwd);
5714 return error;
5717 __dead static void
5718 usage_ref(void)
5720 fprintf(stderr,
5721 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
5722 "[-s reference] [-d] [name]\n",
5723 getprogname());
5724 exit(1);
5727 static const struct got_error *
5728 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
5730 static const struct got_error *err = NULL;
5731 struct got_reflist_head refs;
5732 struct got_reflist_entry *re;
5734 TAILQ_INIT(&refs);
5735 err = got_ref_list(&refs, repo, refname, sort_by_time ?
5736 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
5737 repo);
5738 if (err)
5739 return err;
5741 TAILQ_FOREACH(re, &refs, entry) {
5742 char *refstr;
5743 refstr = got_ref_to_str(re->ref);
5744 if (refstr == NULL) {
5745 err = got_error_from_errno("got_ref_to_str");
5746 break;
5748 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
5749 free(refstr);
5752 got_ref_list_free(&refs);
5753 return err;
5756 static const struct got_error *
5757 delete_ref_by_name(struct got_repository *repo, const char *refname)
5759 const struct got_error *err;
5760 struct got_reference *ref;
5762 err = got_ref_open(&ref, repo, refname, 0);
5763 if (err)
5764 return err;
5766 err = delete_ref(repo, ref);
5767 got_ref_close(ref);
5768 return err;
5771 static const struct got_error *
5772 add_ref(struct got_repository *repo, const char *refname, const char *target)
5774 const struct got_error *err = NULL;
5775 struct got_object_id *id = NULL;
5776 struct got_reference *ref = NULL;
5777 struct got_reflist_head refs;
5780 * Don't let the user create a reference name with a leading '-'.
5781 * While technically a valid reference name, this case is usually
5782 * an unintended typo.
5784 if (refname[0] == '-')
5785 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5787 TAILQ_INIT(&refs);
5788 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
5789 if (err)
5790 goto done;
5791 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
5792 &refs, repo);
5793 got_ref_list_free(&refs);
5794 if (err)
5795 goto done;
5797 err = got_ref_alloc(&ref, refname, id);
5798 if (err)
5799 goto done;
5801 err = got_ref_write(ref, repo);
5802 done:
5803 if (ref)
5804 got_ref_close(ref);
5805 free(id);
5806 return err;
5809 static const struct got_error *
5810 add_symref(struct got_repository *repo, const char *refname, const char *target)
5812 const struct got_error *err = NULL;
5813 struct got_reference *ref = NULL;
5814 struct got_reference *target_ref = NULL;
5817 * Don't let the user create a reference name with a leading '-'.
5818 * While technically a valid reference name, this case is usually
5819 * an unintended typo.
5821 if (refname[0] == '-')
5822 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
5824 err = got_ref_open(&target_ref, repo, target, 0);
5825 if (err)
5826 return err;
5828 err = got_ref_alloc_symref(&ref, refname, target_ref);
5829 if (err)
5830 goto done;
5832 err = got_ref_write(ref, repo);
5833 done:
5834 if (target_ref)
5835 got_ref_close(target_ref);
5836 if (ref)
5837 got_ref_close(ref);
5838 return err;
5841 static const struct got_error *
5842 cmd_ref(int argc, char *argv[])
5844 const struct got_error *error = NULL;
5845 struct got_repository *repo = NULL;
5846 struct got_worktree *worktree = NULL;
5847 char *cwd = NULL, *repo_path = NULL;
5848 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
5849 const char *obj_arg = NULL, *symref_target= NULL;
5850 char *refname = NULL;
5852 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
5853 switch (ch) {
5854 case 'c':
5855 obj_arg = optarg;
5856 break;
5857 case 'd':
5858 do_delete = 1;
5859 break;
5860 case 'r':
5861 repo_path = realpath(optarg, NULL);
5862 if (repo_path == NULL)
5863 return got_error_from_errno2("realpath",
5864 optarg);
5865 got_path_strip_trailing_slashes(repo_path);
5866 break;
5867 case 'l':
5868 do_list = 1;
5869 break;
5870 case 's':
5871 symref_target = optarg;
5872 break;
5873 case 't':
5874 sort_by_time = 1;
5875 break;
5876 default:
5877 usage_ref();
5878 /* NOTREACHED */
5882 if (obj_arg && do_list)
5883 option_conflict('c', 'l');
5884 if (obj_arg && do_delete)
5885 option_conflict('c', 'd');
5886 if (obj_arg && symref_target)
5887 option_conflict('c', 's');
5888 if (symref_target && do_delete)
5889 option_conflict('s', 'd');
5890 if (symref_target && do_list)
5891 option_conflict('s', 'l');
5892 if (do_delete && do_list)
5893 option_conflict('d', 'l');
5894 if (sort_by_time && !do_list)
5895 errx(1, "-t option requires -l option");
5897 argc -= optind;
5898 argv += optind;
5900 if (do_list) {
5901 if (argc != 0 && argc != 1)
5902 usage_ref();
5903 if (argc == 1) {
5904 refname = strdup(argv[0]);
5905 if (refname == NULL) {
5906 error = got_error_from_errno("strdup");
5907 goto done;
5910 } else {
5911 if (argc != 1)
5912 usage_ref();
5913 refname = strdup(argv[0]);
5914 if (refname == NULL) {
5915 error = got_error_from_errno("strdup");
5916 goto done;
5920 if (refname)
5921 got_path_strip_trailing_slashes(refname);
5923 #ifndef PROFILE
5924 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
5925 "sendfd unveil", NULL) == -1)
5926 err(1, "pledge");
5927 #endif
5928 cwd = getcwd(NULL, 0);
5929 if (cwd == NULL) {
5930 error = got_error_from_errno("getcwd");
5931 goto done;
5934 if (repo_path == NULL) {
5935 error = got_worktree_open(&worktree, cwd);
5936 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5937 goto done;
5938 else
5939 error = NULL;
5940 if (worktree) {
5941 repo_path =
5942 strdup(got_worktree_get_repo_path(worktree));
5943 if (repo_path == NULL)
5944 error = got_error_from_errno("strdup");
5945 if (error)
5946 goto done;
5947 } else {
5948 repo_path = strdup(cwd);
5949 if (repo_path == NULL) {
5950 error = got_error_from_errno("strdup");
5951 goto done;
5956 error = got_repo_open(&repo, repo_path, NULL);
5957 if (error != NULL)
5958 goto done;
5960 #ifndef PROFILE
5961 if (do_list) {
5962 /* Remove "cpath" promise. */
5963 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
5964 NULL) == -1)
5965 err(1, "pledge");
5967 #endif
5969 error = apply_unveil(got_repo_get_path(repo), do_list,
5970 worktree ? got_worktree_get_root_path(worktree) : NULL);
5971 if (error)
5972 goto done;
5974 if (do_list)
5975 error = list_refs(repo, refname, sort_by_time);
5976 else if (do_delete)
5977 error = delete_ref_by_name(repo, refname);
5978 else if (symref_target)
5979 error = add_symref(repo, refname, symref_target);
5980 else {
5981 if (obj_arg == NULL)
5982 usage_ref();
5983 error = add_ref(repo, refname, obj_arg);
5985 done:
5986 free(refname);
5987 if (repo) {
5988 const struct got_error *close_err = got_repo_close(repo);
5989 if (error == NULL)
5990 error = close_err;
5992 if (worktree)
5993 got_worktree_close(worktree);
5994 free(cwd);
5995 free(repo_path);
5996 return error;
5999 __dead static void
6000 usage_branch(void)
6002 fprintf(stderr,
6003 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6004 "[-n] [name]\n", getprogname());
6005 exit(1);
6008 static const struct got_error *
6009 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6010 struct got_reference *ref)
6012 const struct got_error *err = NULL;
6013 const char *refname, *marker = " ";
6014 char *refstr;
6016 refname = got_ref_get_name(ref);
6017 if (worktree && strcmp(refname,
6018 got_worktree_get_head_ref_name(worktree)) == 0) {
6019 struct got_object_id *id = NULL;
6021 err = got_ref_resolve(&id, repo, ref);
6022 if (err)
6023 return err;
6024 if (got_object_id_cmp(id,
6025 got_worktree_get_base_commit_id(worktree)) == 0)
6026 marker = "* ";
6027 else
6028 marker = "~ ";
6029 free(id);
6032 if (strncmp(refname, "refs/heads/", 11) == 0)
6033 refname += 11;
6034 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6035 refname += 18;
6036 if (strncmp(refname, "refs/remotes/", 13) == 0)
6037 refname += 13;
6039 refstr = got_ref_to_str(ref);
6040 if (refstr == NULL)
6041 return got_error_from_errno("got_ref_to_str");
6043 printf("%s%s: %s\n", marker, refname, refstr);
6044 free(refstr);
6045 return NULL;
6048 static const struct got_error *
6049 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6051 const char *refname;
6053 if (worktree == NULL)
6054 return got_error(GOT_ERR_NOT_WORKTREE);
6056 refname = got_worktree_get_head_ref_name(worktree);
6058 if (strncmp(refname, "refs/heads/", 11) == 0)
6059 refname += 11;
6060 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6061 refname += 18;
6063 printf("%s\n", refname);
6065 return NULL;
6068 static const struct got_error *
6069 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6070 int sort_by_time)
6072 static const struct got_error *err = NULL;
6073 struct got_reflist_head refs;
6074 struct got_reflist_entry *re;
6075 struct got_reference *temp_ref = NULL;
6076 int rebase_in_progress, histedit_in_progress;
6078 TAILQ_INIT(&refs);
6080 if (worktree) {
6081 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6082 worktree);
6083 if (err)
6084 return err;
6086 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6087 worktree);
6088 if (err)
6089 return err;
6091 if (rebase_in_progress || histedit_in_progress) {
6092 err = got_ref_open(&temp_ref, repo,
6093 got_worktree_get_head_ref_name(worktree), 0);
6094 if (err)
6095 return err;
6096 list_branch(repo, worktree, temp_ref);
6097 got_ref_close(temp_ref);
6101 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6102 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6103 repo);
6104 if (err)
6105 return err;
6107 TAILQ_FOREACH(re, &refs, entry)
6108 list_branch(repo, worktree, re->ref);
6110 got_ref_list_free(&refs);
6112 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6113 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6114 repo);
6115 if (err)
6116 return err;
6118 TAILQ_FOREACH(re, &refs, entry)
6119 list_branch(repo, worktree, re->ref);
6121 got_ref_list_free(&refs);
6123 return NULL;
6126 static const struct got_error *
6127 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6128 const char *branch_name)
6130 const struct got_error *err = NULL;
6131 struct got_reference *ref = NULL;
6132 char *refname, *remote_refname = NULL;
6134 if (strncmp(branch_name, "refs/", 5) == 0)
6135 branch_name += 5;
6136 if (strncmp(branch_name, "heads/", 6) == 0)
6137 branch_name += 6;
6138 else if (strncmp(branch_name, "remotes/", 8) == 0)
6139 branch_name += 8;
6141 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6142 return got_error_from_errno("asprintf");
6144 if (asprintf(&remote_refname, "refs/remotes/%s",
6145 branch_name) == -1) {
6146 err = got_error_from_errno("asprintf");
6147 goto done;
6150 err = got_ref_open(&ref, repo, refname, 0);
6151 if (err) {
6152 const struct got_error *err2;
6153 if (err->code != GOT_ERR_NOT_REF)
6154 goto done;
6156 * Keep 'err' intact such that if neither branch exists
6157 * we report "refs/heads" rather than "refs/remotes" in
6158 * our error message.
6160 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6161 if (err2)
6162 goto done;
6163 err = NULL;
6166 if (worktree &&
6167 strcmp(got_worktree_get_head_ref_name(worktree),
6168 got_ref_get_name(ref)) == 0) {
6169 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6170 "will not delete this work tree's current branch");
6171 goto done;
6174 err = delete_ref(repo, ref);
6175 done:
6176 if (ref)
6177 got_ref_close(ref);
6178 free(refname);
6179 free(remote_refname);
6180 return err;
6183 static const struct got_error *
6184 add_branch(struct got_repository *repo, const char *branch_name,
6185 struct got_object_id *base_commit_id)
6187 const struct got_error *err = NULL;
6188 struct got_reference *ref = NULL;
6189 char *base_refname = NULL, *refname = NULL;
6192 * Don't let the user create a branch name with a leading '-'.
6193 * While technically a valid reference name, this case is usually
6194 * an unintended typo.
6196 if (branch_name[0] == '-')
6197 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6199 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6200 branch_name += 11;
6202 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6203 err = got_error_from_errno("asprintf");
6204 goto done;
6207 err = got_ref_open(&ref, repo, refname, 0);
6208 if (err == NULL) {
6209 err = got_error(GOT_ERR_BRANCH_EXISTS);
6210 goto done;
6211 } else if (err->code != GOT_ERR_NOT_REF)
6212 goto done;
6214 err = got_ref_alloc(&ref, refname, base_commit_id);
6215 if (err)
6216 goto done;
6218 err = got_ref_write(ref, repo);
6219 done:
6220 if (ref)
6221 got_ref_close(ref);
6222 free(base_refname);
6223 free(refname);
6224 return err;
6227 static const struct got_error *
6228 cmd_branch(int argc, char *argv[])
6230 const struct got_error *error = NULL;
6231 struct got_repository *repo = NULL;
6232 struct got_worktree *worktree = NULL;
6233 char *cwd = NULL, *repo_path = NULL;
6234 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6235 const char *delref = NULL, *commit_id_arg = NULL;
6236 struct got_reference *ref = NULL;
6237 struct got_pathlist_head paths;
6238 struct got_pathlist_entry *pe;
6239 struct got_object_id *commit_id = NULL;
6240 char *commit_id_str = NULL;
6242 TAILQ_INIT(&paths);
6244 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6245 switch (ch) {
6246 case 'c':
6247 commit_id_arg = optarg;
6248 break;
6249 case 'd':
6250 delref = optarg;
6251 break;
6252 case 'r':
6253 repo_path = realpath(optarg, NULL);
6254 if (repo_path == NULL)
6255 return got_error_from_errno2("realpath",
6256 optarg);
6257 got_path_strip_trailing_slashes(repo_path);
6258 break;
6259 case 'l':
6260 do_list = 1;
6261 break;
6262 case 'n':
6263 do_update = 0;
6264 break;
6265 case 't':
6266 sort_by_time = 1;
6267 break;
6268 default:
6269 usage_branch();
6270 /* NOTREACHED */
6274 if (do_list && delref)
6275 option_conflict('l', 'd');
6276 if (sort_by_time && !do_list)
6277 errx(1, "-t option requires -l option");
6279 argc -= optind;
6280 argv += optind;
6282 if (!do_list && !delref && argc == 0)
6283 do_show = 1;
6285 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6286 errx(1, "-c option can only be used when creating a branch");
6288 if (do_list || delref) {
6289 if (argc > 0)
6290 usage_branch();
6291 } else if (!do_show && argc != 1)
6292 usage_branch();
6294 #ifndef PROFILE
6295 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6296 "sendfd unveil", NULL) == -1)
6297 err(1, "pledge");
6298 #endif
6299 cwd = getcwd(NULL, 0);
6300 if (cwd == NULL) {
6301 error = got_error_from_errno("getcwd");
6302 goto done;
6305 if (repo_path == NULL) {
6306 error = got_worktree_open(&worktree, cwd);
6307 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6308 goto done;
6309 else
6310 error = NULL;
6311 if (worktree) {
6312 repo_path =
6313 strdup(got_worktree_get_repo_path(worktree));
6314 if (repo_path == NULL)
6315 error = got_error_from_errno("strdup");
6316 if (error)
6317 goto done;
6318 } else {
6319 repo_path = strdup(cwd);
6320 if (repo_path == NULL) {
6321 error = got_error_from_errno("strdup");
6322 goto done;
6327 error = got_repo_open(&repo, repo_path, NULL);
6328 if (error != NULL)
6329 goto done;
6331 #ifndef PROFILE
6332 if (do_list || do_show) {
6333 /* Remove "cpath" promise. */
6334 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6335 NULL) == -1)
6336 err(1, "pledge");
6338 #endif
6340 error = apply_unveil(got_repo_get_path(repo), do_list,
6341 worktree ? got_worktree_get_root_path(worktree) : NULL);
6342 if (error)
6343 goto done;
6345 if (do_show)
6346 error = show_current_branch(repo, worktree);
6347 else if (do_list)
6348 error = list_branches(repo, worktree, sort_by_time);
6349 else if (delref)
6350 error = delete_branch(repo, worktree, delref);
6351 else {
6352 struct got_reflist_head refs;
6353 TAILQ_INIT(&refs);
6354 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6355 NULL);
6356 if (error)
6357 goto done;
6358 if (commit_id_arg == NULL)
6359 commit_id_arg = worktree ?
6360 got_worktree_get_head_ref_name(worktree) :
6361 GOT_REF_HEAD;
6362 error = got_repo_match_object_id(&commit_id, NULL,
6363 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6364 got_ref_list_free(&refs);
6365 if (error)
6366 goto done;
6367 error = add_branch(repo, argv[0], commit_id);
6368 if (error)
6369 goto done;
6370 if (worktree && do_update) {
6371 struct got_update_progress_arg upa;
6372 char *branch_refname = NULL;
6374 error = got_object_id_str(&commit_id_str, commit_id);
6375 if (error)
6376 goto done;
6377 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6378 worktree);
6379 if (error)
6380 goto done;
6381 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6382 == -1) {
6383 error = got_error_from_errno("asprintf");
6384 goto done;
6386 error = got_ref_open(&ref, repo, branch_refname, 0);
6387 free(branch_refname);
6388 if (error)
6389 goto done;
6390 error = switch_head_ref(ref, commit_id, worktree,
6391 repo);
6392 if (error)
6393 goto done;
6394 error = got_worktree_set_base_commit_id(worktree, repo,
6395 commit_id);
6396 if (error)
6397 goto done;
6398 memset(&upa, 0, sizeof(upa));
6399 error = got_worktree_checkout_files(worktree, &paths,
6400 repo, update_progress, &upa, check_cancelled,
6401 NULL);
6402 if (error)
6403 goto done;
6404 if (upa.did_something) {
6405 printf("Updated to %s: %s\n",
6406 got_worktree_get_head_ref_name(worktree),
6407 commit_id_str);
6409 print_update_progress_stats(&upa);
6412 done:
6413 if (ref)
6414 got_ref_close(ref);
6415 if (repo) {
6416 const struct got_error *close_err = got_repo_close(repo);
6417 if (error == NULL)
6418 error = close_err;
6420 if (worktree)
6421 got_worktree_close(worktree);
6422 free(cwd);
6423 free(repo_path);
6424 free(commit_id);
6425 free(commit_id_str);
6426 TAILQ_FOREACH(pe, &paths, entry)
6427 free((char *)pe->path);
6428 got_pathlist_free(&paths);
6429 return error;
6433 __dead static void
6434 usage_tag(void)
6436 fprintf(stderr,
6437 "usage: %s tag [-c commit] [-r repository] [-l] "
6438 "[-m message] name\n", getprogname());
6439 exit(1);
6442 #if 0
6443 static const struct got_error *
6444 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6446 const struct got_error *err = NULL;
6447 struct got_reflist_entry *re, *se, *new;
6448 struct got_object_id *re_id, *se_id;
6449 struct got_tag_object *re_tag, *se_tag;
6450 time_t re_time, se_time;
6452 STAILQ_FOREACH(re, tags, entry) {
6453 se = STAILQ_FIRST(sorted);
6454 if (se == NULL) {
6455 err = got_reflist_entry_dup(&new, re);
6456 if (err)
6457 return err;
6458 STAILQ_INSERT_HEAD(sorted, new, entry);
6459 continue;
6460 } else {
6461 err = got_ref_resolve(&re_id, repo, re->ref);
6462 if (err)
6463 break;
6464 err = got_object_open_as_tag(&re_tag, repo, re_id);
6465 free(re_id);
6466 if (err)
6467 break;
6468 re_time = got_object_tag_get_tagger_time(re_tag);
6469 got_object_tag_close(re_tag);
6472 while (se) {
6473 err = got_ref_resolve(&se_id, repo, re->ref);
6474 if (err)
6475 break;
6476 err = got_object_open_as_tag(&se_tag, repo, se_id);
6477 free(se_id);
6478 if (err)
6479 break;
6480 se_time = got_object_tag_get_tagger_time(se_tag);
6481 got_object_tag_close(se_tag);
6483 if (se_time > re_time) {
6484 err = got_reflist_entry_dup(&new, re);
6485 if (err)
6486 return err;
6487 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6488 break;
6490 se = STAILQ_NEXT(se, entry);
6491 continue;
6494 done:
6495 return err;
6497 #endif
6499 static const struct got_error *
6500 list_tags(struct got_repository *repo)
6502 static const struct got_error *err = NULL;
6503 struct got_reflist_head refs;
6504 struct got_reflist_entry *re;
6506 TAILQ_INIT(&refs);
6508 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6509 if (err)
6510 return err;
6512 TAILQ_FOREACH(re, &refs, entry) {
6513 const char *refname;
6514 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6515 char datebuf[26];
6516 const char *tagger;
6517 time_t tagger_time;
6518 struct got_object_id *id;
6519 struct got_tag_object *tag;
6520 struct got_commit_object *commit = NULL;
6522 refname = got_ref_get_name(re->ref);
6523 if (strncmp(refname, "refs/tags/", 10) != 0)
6524 continue;
6525 refname += 10;
6526 refstr = got_ref_to_str(re->ref);
6527 if (refstr == NULL) {
6528 err = got_error_from_errno("got_ref_to_str");
6529 break;
6531 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
6532 free(refstr);
6534 err = got_ref_resolve(&id, repo, re->ref);
6535 if (err)
6536 break;
6537 err = got_object_open_as_tag(&tag, repo, id);
6538 if (err) {
6539 if (err->code != GOT_ERR_OBJ_TYPE) {
6540 free(id);
6541 break;
6543 /* "lightweight" tag */
6544 err = got_object_open_as_commit(&commit, repo, id);
6545 if (err) {
6546 free(id);
6547 break;
6549 tagger = got_object_commit_get_committer(commit);
6550 tagger_time =
6551 got_object_commit_get_committer_time(commit);
6552 err = got_object_id_str(&id_str, id);
6553 free(id);
6554 if (err)
6555 break;
6556 } else {
6557 free(id);
6558 tagger = got_object_tag_get_tagger(tag);
6559 tagger_time = got_object_tag_get_tagger_time(tag);
6560 err = got_object_id_str(&id_str,
6561 got_object_tag_get_object_id(tag));
6562 if (err)
6563 break;
6565 printf("from: %s\n", tagger);
6566 datestr = get_datestr(&tagger_time, datebuf);
6567 if (datestr)
6568 printf("date: %s UTC\n", datestr);
6569 if (commit)
6570 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
6571 else {
6572 switch (got_object_tag_get_object_type(tag)) {
6573 case GOT_OBJ_TYPE_BLOB:
6574 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
6575 id_str);
6576 break;
6577 case GOT_OBJ_TYPE_TREE:
6578 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6579 id_str);
6580 break;
6581 case GOT_OBJ_TYPE_COMMIT:
6582 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6583 id_str);
6584 break;
6585 case GOT_OBJ_TYPE_TAG:
6586 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6587 id_str);
6588 break;
6589 default:
6590 break;
6593 free(id_str);
6594 if (commit) {
6595 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6596 if (err)
6597 break;
6598 got_object_commit_close(commit);
6599 } else {
6600 tagmsg0 = strdup(got_object_tag_get_message(tag));
6601 got_object_tag_close(tag);
6602 if (tagmsg0 == NULL) {
6603 err = got_error_from_errno("strdup");
6604 break;
6608 tagmsg = tagmsg0;
6609 do {
6610 line = strsep(&tagmsg, "\n");
6611 if (line)
6612 printf(" %s\n", line);
6613 } while (line);
6614 free(tagmsg0);
6617 got_ref_list_free(&refs);
6618 return NULL;
6621 static const struct got_error *
6622 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6623 const char *tag_name, const char *repo_path)
6625 const struct got_error *err = NULL;
6626 char *template = NULL, *initial_content = NULL;
6627 char *editor = NULL;
6628 int initial_content_len;
6629 int fd = -1;
6631 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6632 err = got_error_from_errno("asprintf");
6633 goto done;
6636 initial_content_len = asprintf(&initial_content,
6637 "\n# tagging commit %s as %s\n",
6638 commit_id_str, tag_name);
6639 if (initial_content_len == -1) {
6640 err = got_error_from_errno("asprintf");
6641 goto done;
6644 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
6645 if (err)
6646 goto done;
6648 if (write(fd, initial_content, initial_content_len) == -1) {
6649 err = got_error_from_errno2("write", *tagmsg_path);
6650 goto done;
6653 err = get_editor(&editor);
6654 if (err)
6655 goto done;
6656 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6657 initial_content_len, 1);
6658 done:
6659 free(initial_content);
6660 free(template);
6661 free(editor);
6663 if (fd != -1 && close(fd) == -1 && err == NULL)
6664 err = got_error_from_errno2("close", *tagmsg_path);
6666 /* Editor is done; we can now apply unveil(2) */
6667 if (err == NULL)
6668 err = apply_unveil(repo_path, 0, NULL);
6669 if (err) {
6670 free(*tagmsg);
6671 *tagmsg = NULL;
6673 return err;
6676 static const struct got_error *
6677 add_tag(struct got_repository *repo, const char *tagger,
6678 const char *tag_name, const char *commit_arg, const char *tagmsg_arg)
6680 const struct got_error *err = NULL;
6681 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6682 char *label = NULL, *commit_id_str = NULL;
6683 struct got_reference *ref = NULL;
6684 char *refname = NULL, *tagmsg = NULL;
6685 char *tagmsg_path = NULL, *tag_id_str = NULL;
6686 int preserve_tagmsg = 0;
6687 struct got_reflist_head refs;
6689 TAILQ_INIT(&refs);
6692 * Don't let the user create a tag name with a leading '-'.
6693 * While technically a valid reference name, this case is usually
6694 * an unintended typo.
6696 if (tag_name[0] == '-')
6697 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6699 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6700 if (err)
6701 goto done;
6703 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6704 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6705 if (err)
6706 goto done;
6708 err = got_object_id_str(&commit_id_str, commit_id);
6709 if (err)
6710 goto done;
6712 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6713 refname = strdup(tag_name);
6714 if (refname == NULL) {
6715 err = got_error_from_errno("strdup");
6716 goto done;
6718 tag_name += 10;
6719 } else if (asprintf(&refname, "refs/tags/%s", tag_name) == -1) {
6720 err = got_error_from_errno("asprintf");
6721 goto done;
6724 err = got_ref_open(&ref, repo, refname, 0);
6725 if (err == NULL) {
6726 err = got_error(GOT_ERR_TAG_EXISTS);
6727 goto done;
6728 } else if (err->code != GOT_ERR_NOT_REF)
6729 goto done;
6731 if (tagmsg_arg == NULL) {
6732 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6733 tag_name, got_repo_get_path(repo));
6734 if (err) {
6735 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6736 tagmsg_path != NULL)
6737 preserve_tagmsg = 1;
6738 goto done;
6742 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6743 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, repo);
6744 if (err) {
6745 if (tagmsg_path)
6746 preserve_tagmsg = 1;
6747 goto done;
6750 err = got_ref_alloc(&ref, refname, tag_id);
6751 if (err) {
6752 if (tagmsg_path)
6753 preserve_tagmsg = 1;
6754 goto done;
6757 err = got_ref_write(ref, repo);
6758 if (err) {
6759 if (tagmsg_path)
6760 preserve_tagmsg = 1;
6761 goto done;
6764 err = got_object_id_str(&tag_id_str, tag_id);
6765 if (err) {
6766 if (tagmsg_path)
6767 preserve_tagmsg = 1;
6768 goto done;
6770 printf("Created tag %s\n", tag_id_str);
6771 done:
6772 if (preserve_tagmsg) {
6773 fprintf(stderr, "%s: tag message preserved in %s\n",
6774 getprogname(), tagmsg_path);
6775 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6776 err = got_error_from_errno2("unlink", tagmsg_path);
6777 free(tag_id_str);
6778 if (ref)
6779 got_ref_close(ref);
6780 free(commit_id);
6781 free(commit_id_str);
6782 free(refname);
6783 free(tagmsg);
6784 free(tagmsg_path);
6785 got_ref_list_free(&refs);
6786 return err;
6789 static const struct got_error *
6790 cmd_tag(int argc, char *argv[])
6792 const struct got_error *error = NULL;
6793 struct got_repository *repo = NULL;
6794 struct got_worktree *worktree = NULL;
6795 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6796 char *gitconfig_path = NULL, *tagger = NULL;
6797 const char *tag_name, *commit_id_arg = NULL, *tagmsg = NULL;
6798 int ch, do_list = 0;
6800 while ((ch = getopt(argc, argv, "c:m:r:l")) != -1) {
6801 switch (ch) {
6802 case 'c':
6803 commit_id_arg = optarg;
6804 break;
6805 case 'm':
6806 tagmsg = optarg;
6807 break;
6808 case 'r':
6809 repo_path = realpath(optarg, NULL);
6810 if (repo_path == NULL)
6811 return got_error_from_errno2("realpath",
6812 optarg);
6813 got_path_strip_trailing_slashes(repo_path);
6814 break;
6815 case 'l':
6816 do_list = 1;
6817 break;
6818 default:
6819 usage_tag();
6820 /* NOTREACHED */
6824 argc -= optind;
6825 argv += optind;
6827 if (do_list) {
6828 if (commit_id_arg != NULL)
6829 errx(1,
6830 "-c option can only be used when creating a tag");
6831 if (tagmsg)
6832 option_conflict('l', 'm');
6833 if (argc > 0)
6834 usage_tag();
6835 } else if (argc != 1)
6836 usage_tag();
6838 tag_name = argv[0];
6840 #ifndef PROFILE
6841 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6842 "sendfd unveil", NULL) == -1)
6843 err(1, "pledge");
6844 #endif
6845 cwd = getcwd(NULL, 0);
6846 if (cwd == NULL) {
6847 error = got_error_from_errno("getcwd");
6848 goto done;
6851 if (repo_path == NULL) {
6852 error = got_worktree_open(&worktree, cwd);
6853 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6854 goto done;
6855 else
6856 error = NULL;
6857 if (worktree) {
6858 repo_path =
6859 strdup(got_worktree_get_repo_path(worktree));
6860 if (repo_path == NULL)
6861 error = got_error_from_errno("strdup");
6862 if (error)
6863 goto done;
6864 } else {
6865 repo_path = strdup(cwd);
6866 if (repo_path == NULL) {
6867 error = got_error_from_errno("strdup");
6868 goto done;
6873 if (do_list) {
6874 if (worktree) {
6875 /* Release work tree lock. */
6876 got_worktree_close(worktree);
6877 worktree = NULL;
6879 error = got_repo_open(&repo, repo_path, NULL);
6880 if (error != NULL)
6881 goto done;
6882 #ifndef PROFILE
6883 /* Remove "cpath" promise. */
6884 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6885 NULL) == -1)
6886 err(1, "pledge");
6887 #endif
6888 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6889 if (error)
6890 goto done;
6891 error = list_tags(repo);
6892 } else {
6893 error = get_gitconfig_path(&gitconfig_path);
6894 if (error)
6895 goto done;
6896 error = got_repo_open(&repo, repo_path, gitconfig_path);
6897 if (error != NULL)
6898 goto done;
6900 error = get_author(&tagger, repo, worktree);
6901 if (error)
6902 goto done;
6903 if (worktree) {
6904 /* Release work tree lock. */
6905 got_worktree_close(worktree);
6906 worktree = NULL;
6909 if (tagmsg) {
6910 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6911 if (error)
6912 goto done;
6915 if (commit_id_arg == NULL) {
6916 struct got_reference *head_ref;
6917 struct got_object_id *commit_id;
6918 error = got_ref_open(&head_ref, repo,
6919 worktree ? got_worktree_get_head_ref_name(worktree)
6920 : GOT_REF_HEAD, 0);
6921 if (error)
6922 goto done;
6923 error = got_ref_resolve(&commit_id, repo, head_ref);
6924 got_ref_close(head_ref);
6925 if (error)
6926 goto done;
6927 error = got_object_id_str(&commit_id_str, commit_id);
6928 free(commit_id);
6929 if (error)
6930 goto done;
6933 error = add_tag(repo, tagger, tag_name,
6934 commit_id_str ? commit_id_str : commit_id_arg, tagmsg);
6936 done:
6937 if (repo) {
6938 const struct got_error *close_err = got_repo_close(repo);
6939 if (error == NULL)
6940 error = close_err;
6942 if (worktree)
6943 got_worktree_close(worktree);
6944 free(cwd);
6945 free(repo_path);
6946 free(gitconfig_path);
6947 free(commit_id_str);
6948 free(tagger);
6949 return error;
6952 __dead static void
6953 usage_add(void)
6955 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
6956 getprogname());
6957 exit(1);
6960 static const struct got_error *
6961 add_progress(void *arg, unsigned char status, const char *path)
6963 while (path[0] == '/')
6964 path++;
6965 printf("%c %s\n", status, path);
6966 return NULL;
6969 static const struct got_error *
6970 cmd_add(int argc, char *argv[])
6972 const struct got_error *error = NULL;
6973 struct got_repository *repo = NULL;
6974 struct got_worktree *worktree = NULL;
6975 char *cwd = NULL;
6976 struct got_pathlist_head paths;
6977 struct got_pathlist_entry *pe;
6978 int ch, can_recurse = 0, no_ignores = 0;
6980 TAILQ_INIT(&paths);
6982 while ((ch = getopt(argc, argv, "IR")) != -1) {
6983 switch (ch) {
6984 case 'I':
6985 no_ignores = 1;
6986 break;
6987 case 'R':
6988 can_recurse = 1;
6989 break;
6990 default:
6991 usage_add();
6992 /* NOTREACHED */
6996 argc -= optind;
6997 argv += optind;
6999 #ifndef PROFILE
7000 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7001 NULL) == -1)
7002 err(1, "pledge");
7003 #endif
7004 if (argc < 1)
7005 usage_add();
7007 cwd = getcwd(NULL, 0);
7008 if (cwd == NULL) {
7009 error = got_error_from_errno("getcwd");
7010 goto done;
7013 error = got_worktree_open(&worktree, cwd);
7014 if (error) {
7015 if (error->code == GOT_ERR_NOT_WORKTREE)
7016 error = wrap_not_worktree_error(error, "add", cwd);
7017 goto done;
7020 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7021 NULL);
7022 if (error != NULL)
7023 goto done;
7025 error = apply_unveil(got_repo_get_path(repo), 1,
7026 got_worktree_get_root_path(worktree));
7027 if (error)
7028 goto done;
7030 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7031 if (error)
7032 goto done;
7034 if (!can_recurse) {
7035 char *ondisk_path;
7036 struct stat sb;
7037 TAILQ_FOREACH(pe, &paths, entry) {
7038 if (asprintf(&ondisk_path, "%s/%s",
7039 got_worktree_get_root_path(worktree),
7040 pe->path) == -1) {
7041 error = got_error_from_errno("asprintf");
7042 goto done;
7044 if (lstat(ondisk_path, &sb) == -1) {
7045 if (errno == ENOENT) {
7046 free(ondisk_path);
7047 continue;
7049 error = got_error_from_errno2("lstat",
7050 ondisk_path);
7051 free(ondisk_path);
7052 goto done;
7054 free(ondisk_path);
7055 if (S_ISDIR(sb.st_mode)) {
7056 error = got_error_msg(GOT_ERR_BAD_PATH,
7057 "adding directories requires -R option");
7058 goto done;
7063 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7064 NULL, repo, no_ignores);
7065 done:
7066 if (repo) {
7067 const struct got_error *close_err = got_repo_close(repo);
7068 if (error == NULL)
7069 error = close_err;
7071 if (worktree)
7072 got_worktree_close(worktree);
7073 TAILQ_FOREACH(pe, &paths, entry)
7074 free((char *)pe->path);
7075 got_pathlist_free(&paths);
7076 free(cwd);
7077 return error;
7080 __dead static void
7081 usage_remove(void)
7083 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7084 "path ...\n", getprogname());
7085 exit(1);
7088 static const struct got_error *
7089 print_remove_status(void *arg, unsigned char status,
7090 unsigned char staged_status, const char *path)
7092 while (path[0] == '/')
7093 path++;
7094 if (status == GOT_STATUS_NONEXISTENT)
7095 return NULL;
7096 if (status == staged_status && (status == GOT_STATUS_DELETE))
7097 status = GOT_STATUS_NO_CHANGE;
7098 printf("%c%c %s\n", status, staged_status, path);
7099 return NULL;
7102 static const struct got_error *
7103 cmd_remove(int argc, char *argv[])
7105 const struct got_error *error = NULL;
7106 struct got_worktree *worktree = NULL;
7107 struct got_repository *repo = NULL;
7108 const char *status_codes = NULL;
7109 char *cwd = NULL;
7110 struct got_pathlist_head paths;
7111 struct got_pathlist_entry *pe;
7112 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7113 int ignore_missing_paths = 0;
7115 TAILQ_INIT(&paths);
7117 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7118 switch (ch) {
7119 case 'f':
7120 delete_local_mods = 1;
7121 ignore_missing_paths = 1;
7122 break;
7123 case 'k':
7124 keep_on_disk = 1;
7125 break;
7126 case 'R':
7127 can_recurse = 1;
7128 break;
7129 case 's':
7130 for (i = 0; i < strlen(optarg); i++) {
7131 switch (optarg[i]) {
7132 case GOT_STATUS_MODIFY:
7133 delete_local_mods = 1;
7134 break;
7135 case GOT_STATUS_MISSING:
7136 ignore_missing_paths = 1;
7137 break;
7138 default:
7139 errx(1, "invalid status code '%c'",
7140 optarg[i]);
7143 status_codes = optarg;
7144 break;
7145 default:
7146 usage_remove();
7147 /* NOTREACHED */
7151 argc -= optind;
7152 argv += optind;
7154 #ifndef PROFILE
7155 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7156 NULL) == -1)
7157 err(1, "pledge");
7158 #endif
7159 if (argc < 1)
7160 usage_remove();
7162 cwd = getcwd(NULL, 0);
7163 if (cwd == NULL) {
7164 error = got_error_from_errno("getcwd");
7165 goto done;
7167 error = got_worktree_open(&worktree, cwd);
7168 if (error) {
7169 if (error->code == GOT_ERR_NOT_WORKTREE)
7170 error = wrap_not_worktree_error(error, "remove", cwd);
7171 goto done;
7174 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7175 NULL);
7176 if (error)
7177 goto done;
7179 error = apply_unveil(got_repo_get_path(repo), 1,
7180 got_worktree_get_root_path(worktree));
7181 if (error)
7182 goto done;
7184 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7185 if (error)
7186 goto done;
7188 if (!can_recurse) {
7189 char *ondisk_path;
7190 struct stat sb;
7191 TAILQ_FOREACH(pe, &paths, entry) {
7192 if (asprintf(&ondisk_path, "%s/%s",
7193 got_worktree_get_root_path(worktree),
7194 pe->path) == -1) {
7195 error = got_error_from_errno("asprintf");
7196 goto done;
7198 if (lstat(ondisk_path, &sb) == -1) {
7199 if (errno == ENOENT) {
7200 free(ondisk_path);
7201 continue;
7203 error = got_error_from_errno2("lstat",
7204 ondisk_path);
7205 free(ondisk_path);
7206 goto done;
7208 free(ondisk_path);
7209 if (S_ISDIR(sb.st_mode)) {
7210 error = got_error_msg(GOT_ERR_BAD_PATH,
7211 "removing directories requires -R option");
7212 goto done;
7217 error = got_worktree_schedule_delete(worktree, &paths,
7218 delete_local_mods, status_codes, print_remove_status, NULL,
7219 repo, keep_on_disk, ignore_missing_paths);
7220 done:
7221 if (repo) {
7222 const struct got_error *close_err = got_repo_close(repo);
7223 if (error == NULL)
7224 error = close_err;
7226 if (worktree)
7227 got_worktree_close(worktree);
7228 TAILQ_FOREACH(pe, &paths, entry)
7229 free((char *)pe->path);
7230 got_pathlist_free(&paths);
7231 free(cwd);
7232 return error;
7235 __dead static void
7236 usage_patch(void)
7238 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7239 "[-R] [patchfile]\n", getprogname());
7240 exit(1);
7243 static const struct got_error *
7244 patch_from_stdin(int *patchfd)
7246 const struct got_error *err = NULL;
7247 ssize_t r;
7248 char *path, buf[BUFSIZ];
7249 sig_t sighup, sigint, sigquit;
7251 err = got_opentemp_named_fd(&path, patchfd,
7252 GOT_TMPDIR_STR "/got-patch");
7253 if (err)
7254 return err;
7255 unlink(path);
7256 free(path);
7258 sighup = signal(SIGHUP, SIG_DFL);
7259 sigint = signal(SIGINT, SIG_DFL);
7260 sigquit = signal(SIGQUIT, SIG_DFL);
7262 for (;;) {
7263 r = read(0, buf, sizeof(buf));
7264 if (r == -1) {
7265 err = got_error_from_errno("read");
7266 break;
7268 if (r == 0)
7269 break;
7270 if (write(*patchfd, buf, r) == -1) {
7271 err = got_error_from_errno("write");
7272 break;
7276 signal(SIGHUP, sighup);
7277 signal(SIGINT, sigint);
7278 signal(SIGQUIT, sigquit);
7280 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7281 err = got_error_from_errno("lseek");
7283 if (err != NULL) {
7284 close(*patchfd);
7285 *patchfd = -1;
7288 return err;
7291 static const struct got_error *
7292 patch_progress(void *arg, const char *old, const char *new,
7293 unsigned char status, const struct got_error *error, long old_from,
7294 long old_lines, long new_from, long new_lines, long offset,
7295 const struct got_error *hunk_err)
7297 const char *path = new == NULL ? old : new;
7299 while (*path == '/')
7300 path++;
7302 if (status != 0)
7303 printf("%c %s\n", status, path);
7305 if (error != NULL)
7306 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7308 if (offset != 0 || hunk_err != NULL) {
7309 printf("@@ -%ld,%ld +%ld,%ld @@ ", old_from,
7310 old_lines, new_from, new_lines);
7311 if (hunk_err != NULL)
7312 printf("%s\n", hunk_err->msg);
7313 else
7314 printf("applied with offset %ld\n", offset);
7317 return NULL;
7320 static const struct got_error *
7321 cmd_patch(int argc, char *argv[])
7323 const struct got_error *error = NULL, *close_error = NULL;
7324 struct got_worktree *worktree = NULL;
7325 struct got_repository *repo = NULL;
7326 const char *errstr;
7327 char *cwd = NULL;
7328 int ch, nop = 0, strip = -1, reverse = 0;
7329 int patchfd;
7331 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7332 switch (ch) {
7333 case 'n':
7334 nop = 1;
7335 break;
7336 case 'p':
7337 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7338 if (errstr != NULL)
7339 errx(1, "pathname strip count is %s: %s",
7340 errstr, optarg);
7341 break;
7342 case 'R':
7343 reverse = 1;
7344 break;
7345 default:
7346 usage_patch();
7347 /* NOTREACHED */
7351 argc -= optind;
7352 argv += optind;
7354 if (argc == 0) {
7355 error = patch_from_stdin(&patchfd);
7356 if (error)
7357 return error;
7358 } else if (argc == 1) {
7359 patchfd = open(argv[0], O_RDONLY);
7360 if (patchfd == -1) {
7361 error = got_error_from_errno2("open", argv[0]);
7362 return error;
7364 } else
7365 usage_patch();
7367 if ((cwd = getcwd(NULL, 0)) == NULL) {
7368 error = got_error_from_errno("getcwd");
7369 goto done;
7372 error = got_worktree_open(&worktree, cwd);
7373 if (error != NULL)
7374 goto done;
7376 const char *repo_path = got_worktree_get_repo_path(worktree);
7377 error = got_repo_open(&repo, repo_path, NULL);
7378 if (error != NULL)
7379 goto done;
7381 error = apply_unveil(got_repo_get_path(repo), 0,
7382 got_worktree_get_root_path(worktree));
7383 if (error != NULL)
7384 goto done;
7386 #ifndef PROFILE
7387 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7388 NULL) == -1)
7389 err(1, "pledge");
7390 #endif
7392 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7393 &patch_progress, NULL, check_cancelled, NULL);
7395 done:
7396 if (repo) {
7397 close_error = got_repo_close(repo);
7398 if (error == NULL)
7399 error = close_error;
7401 if (worktree != NULL) {
7402 close_error = got_worktree_close(worktree);
7403 if (error == NULL)
7404 error = close_error;
7406 free(cwd);
7407 return error;
7410 __dead static void
7411 usage_revert(void)
7413 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7414 "path ...\n", getprogname());
7415 exit(1);
7418 static const struct got_error *
7419 revert_progress(void *arg, unsigned char status, const char *path)
7421 if (status == GOT_STATUS_UNVERSIONED)
7422 return NULL;
7424 while (path[0] == '/')
7425 path++;
7426 printf("%c %s\n", status, path);
7427 return NULL;
7430 struct choose_patch_arg {
7431 FILE *patch_script_file;
7432 const char *action;
7435 static const struct got_error *
7436 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7437 int nchanges, const char *action)
7439 char *line = NULL;
7440 size_t linesize = 0;
7441 ssize_t linelen;
7443 switch (status) {
7444 case GOT_STATUS_ADD:
7445 printf("A %s\n%s this addition? [y/n] ", path, action);
7446 break;
7447 case GOT_STATUS_DELETE:
7448 printf("D %s\n%s this deletion? [y/n] ", path, action);
7449 break;
7450 case GOT_STATUS_MODIFY:
7451 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7452 return got_error_from_errno("fseek");
7453 printf(GOT_COMMIT_SEP_STR);
7454 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7455 printf("%s", line);
7456 if (ferror(patch_file))
7457 return got_error_from_errno("getline");
7458 printf(GOT_COMMIT_SEP_STR);
7459 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7460 path, n, nchanges, action);
7461 break;
7462 default:
7463 return got_error_path(path, GOT_ERR_FILE_STATUS);
7466 return NULL;
7469 static const struct got_error *
7470 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7471 FILE *patch_file, int n, int nchanges)
7473 const struct got_error *err = NULL;
7474 char *line = NULL;
7475 size_t linesize = 0;
7476 ssize_t linelen;
7477 int resp = ' ';
7478 struct choose_patch_arg *a = arg;
7480 *choice = GOT_PATCH_CHOICE_NONE;
7482 if (a->patch_script_file) {
7483 char *nl;
7484 err = show_change(status, path, patch_file, n, nchanges,
7485 a->action);
7486 if (err)
7487 return err;
7488 linelen = getline(&line, &linesize, a->patch_script_file);
7489 if (linelen == -1) {
7490 if (ferror(a->patch_script_file))
7491 return got_error_from_errno("getline");
7492 return NULL;
7494 nl = strchr(line, '\n');
7495 if (nl)
7496 *nl = '\0';
7497 if (strcmp(line, "y") == 0) {
7498 *choice = GOT_PATCH_CHOICE_YES;
7499 printf("y\n");
7500 } else if (strcmp(line, "n") == 0) {
7501 *choice = GOT_PATCH_CHOICE_NO;
7502 printf("n\n");
7503 } else if (strcmp(line, "q") == 0 &&
7504 status == GOT_STATUS_MODIFY) {
7505 *choice = GOT_PATCH_CHOICE_QUIT;
7506 printf("q\n");
7507 } else
7508 printf("invalid response '%s'\n", line);
7509 free(line);
7510 return NULL;
7513 while (resp != 'y' && resp != 'n' && resp != 'q') {
7514 err = show_change(status, path, patch_file, n, nchanges,
7515 a->action);
7516 if (err)
7517 return err;
7518 resp = getchar();
7519 if (resp == '\n')
7520 resp = getchar();
7521 if (status == GOT_STATUS_MODIFY) {
7522 if (resp != 'y' && resp != 'n' && resp != 'q') {
7523 printf("invalid response '%c'\n", resp);
7524 resp = ' ';
7526 } else if (resp != 'y' && resp != 'n') {
7527 printf("invalid response '%c'\n", resp);
7528 resp = ' ';
7532 if (resp == 'y')
7533 *choice = GOT_PATCH_CHOICE_YES;
7534 else if (resp == 'n')
7535 *choice = GOT_PATCH_CHOICE_NO;
7536 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7537 *choice = GOT_PATCH_CHOICE_QUIT;
7539 return NULL;
7542 static const struct got_error *
7543 cmd_revert(int argc, char *argv[])
7545 const struct got_error *error = NULL;
7546 struct got_worktree *worktree = NULL;
7547 struct got_repository *repo = NULL;
7548 char *cwd = NULL, *path = NULL;
7549 struct got_pathlist_head paths;
7550 struct got_pathlist_entry *pe;
7551 int ch, can_recurse = 0, pflag = 0;
7552 FILE *patch_script_file = NULL;
7553 const char *patch_script_path = NULL;
7554 struct choose_patch_arg cpa;
7556 TAILQ_INIT(&paths);
7558 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
7559 switch (ch) {
7560 case 'p':
7561 pflag = 1;
7562 break;
7563 case 'F':
7564 patch_script_path = optarg;
7565 break;
7566 case 'R':
7567 can_recurse = 1;
7568 break;
7569 default:
7570 usage_revert();
7571 /* NOTREACHED */
7575 argc -= optind;
7576 argv += optind;
7578 #ifndef PROFILE
7579 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7580 "unveil", NULL) == -1)
7581 err(1, "pledge");
7582 #endif
7583 if (argc < 1)
7584 usage_revert();
7585 if (patch_script_path && !pflag)
7586 errx(1, "-F option can only be used together with -p option");
7588 cwd = getcwd(NULL, 0);
7589 if (cwd == NULL) {
7590 error = got_error_from_errno("getcwd");
7591 goto done;
7593 error = got_worktree_open(&worktree, cwd);
7594 if (error) {
7595 if (error->code == GOT_ERR_NOT_WORKTREE)
7596 error = wrap_not_worktree_error(error, "revert", cwd);
7597 goto done;
7600 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7601 NULL);
7602 if (error != NULL)
7603 goto done;
7605 if (patch_script_path) {
7606 patch_script_file = fopen(patch_script_path, "re");
7607 if (patch_script_file == NULL) {
7608 error = got_error_from_errno2("fopen",
7609 patch_script_path);
7610 goto done;
7613 error = apply_unveil(got_repo_get_path(repo), 1,
7614 got_worktree_get_root_path(worktree));
7615 if (error)
7616 goto done;
7618 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7619 if (error)
7620 goto done;
7622 if (!can_recurse) {
7623 char *ondisk_path;
7624 struct stat sb;
7625 TAILQ_FOREACH(pe, &paths, entry) {
7626 if (asprintf(&ondisk_path, "%s/%s",
7627 got_worktree_get_root_path(worktree),
7628 pe->path) == -1) {
7629 error = got_error_from_errno("asprintf");
7630 goto done;
7632 if (lstat(ondisk_path, &sb) == -1) {
7633 if (errno == ENOENT) {
7634 free(ondisk_path);
7635 continue;
7637 error = got_error_from_errno2("lstat",
7638 ondisk_path);
7639 free(ondisk_path);
7640 goto done;
7642 free(ondisk_path);
7643 if (S_ISDIR(sb.st_mode)) {
7644 error = got_error_msg(GOT_ERR_BAD_PATH,
7645 "reverting directories requires -R option");
7646 goto done;
7651 cpa.patch_script_file = patch_script_file;
7652 cpa.action = "revert";
7653 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7654 pflag ? choose_patch : NULL, &cpa, repo);
7655 done:
7656 if (patch_script_file && fclose(patch_script_file) == EOF &&
7657 error == NULL)
7658 error = got_error_from_errno2("fclose", patch_script_path);
7659 if (repo) {
7660 const struct got_error *close_err = got_repo_close(repo);
7661 if (error == NULL)
7662 error = close_err;
7664 if (worktree)
7665 got_worktree_close(worktree);
7666 free(path);
7667 free(cwd);
7668 return error;
7671 __dead static void
7672 usage_commit(void)
7674 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
7675 "[path ...]\n", getprogname());
7676 exit(1);
7679 struct collect_commit_logmsg_arg {
7680 const char *cmdline_log;
7681 const char *prepared_log;
7682 int non_interactive;
7683 const char *editor;
7684 const char *worktree_path;
7685 const char *branch_name;
7686 const char *repo_path;
7687 char *logmsg_path;
7691 static const struct got_error *
7692 read_prepared_logmsg(char **logmsg, const char *path)
7694 const struct got_error *err = NULL;
7695 FILE *f = NULL;
7696 struct stat sb;
7697 size_t r;
7699 *logmsg = NULL;
7700 memset(&sb, 0, sizeof(sb));
7702 f = fopen(path, "re");
7703 if (f == NULL)
7704 return got_error_from_errno2("fopen", path);
7706 if (fstat(fileno(f), &sb) == -1) {
7707 err = got_error_from_errno2("fstat", path);
7708 goto done;
7710 if (sb.st_size == 0) {
7711 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7712 goto done;
7715 *logmsg = malloc(sb.st_size + 1);
7716 if (*logmsg == NULL) {
7717 err = got_error_from_errno("malloc");
7718 goto done;
7721 r = fread(*logmsg, 1, sb.st_size, f);
7722 if (r != sb.st_size) {
7723 if (ferror(f))
7724 err = got_error_from_errno2("fread", path);
7725 else
7726 err = got_error(GOT_ERR_IO);
7727 goto done;
7729 (*logmsg)[sb.st_size] = '\0';
7730 done:
7731 if (fclose(f) == EOF && err == NULL)
7732 err = got_error_from_errno2("fclose", path);
7733 if (err) {
7734 free(*logmsg);
7735 *logmsg = NULL;
7737 return err;
7741 static const struct got_error *
7742 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
7743 void *arg)
7745 char *initial_content = NULL;
7746 struct got_pathlist_entry *pe;
7747 const struct got_error *err = NULL;
7748 char *template = NULL;
7749 struct collect_commit_logmsg_arg *a = arg;
7750 int initial_content_len;
7751 int fd = -1;
7752 size_t len;
7754 /* if a message was specified on the command line, just use it */
7755 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
7756 len = strlen(a->cmdline_log) + 1;
7757 *logmsg = malloc(len + 1);
7758 if (*logmsg == NULL)
7759 return got_error_from_errno("malloc");
7760 strlcpy(*logmsg, a->cmdline_log, len);
7761 return NULL;
7762 } else if (a->prepared_log != NULL && a->non_interactive)
7763 return read_prepared_logmsg(logmsg, a->prepared_log);
7765 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7766 return got_error_from_errno("asprintf");
7768 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
7769 if (err)
7770 goto done;
7772 if (a->prepared_log) {
7773 char *msg;
7774 err = read_prepared_logmsg(&msg, a->prepared_log);
7775 if (err)
7776 goto done;
7777 if (write(fd, msg, strlen(msg)) == -1) {
7778 err = got_error_from_errno2("write", a->logmsg_path);
7779 free(msg);
7780 goto done;
7782 free(msg);
7785 initial_content_len = asprintf(&initial_content,
7786 "\n# changes to be committed on branch %s:\n",
7787 a->branch_name);
7788 if (initial_content_len == -1) {
7789 err = got_error_from_errno("asprintf");
7790 goto done;
7793 if (write(fd, initial_content, initial_content_len) == -1) {
7794 err = got_error_from_errno2("write", a->logmsg_path);
7795 goto done;
7798 TAILQ_FOREACH(pe, commitable_paths, entry) {
7799 struct got_commitable *ct = pe->data;
7800 dprintf(fd, "# %c %s\n",
7801 got_commitable_get_status(ct),
7802 got_commitable_get_path(ct));
7805 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7806 initial_content_len, a->prepared_log ? 0 : 1);
7807 done:
7808 free(initial_content);
7809 free(template);
7811 if (fd != -1 && close(fd) == -1 && err == NULL)
7812 err = got_error_from_errno2("close", a->logmsg_path);
7814 /* Editor is done; we can now apply unveil(2) */
7815 if (err == NULL)
7816 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7817 if (err) {
7818 free(*logmsg);
7819 *logmsg = NULL;
7821 return err;
7824 static const struct got_error *
7825 cmd_commit(int argc, char *argv[])
7827 const struct got_error *error = NULL;
7828 struct got_worktree *worktree = NULL;
7829 struct got_repository *repo = NULL;
7830 char *cwd = NULL, *id_str = NULL;
7831 struct got_object_id *id = NULL;
7832 const char *logmsg = NULL;
7833 char *prepared_logmsg = NULL;
7834 struct collect_commit_logmsg_arg cl_arg;
7835 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
7836 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7837 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7838 struct got_pathlist_head paths;
7840 TAILQ_INIT(&paths);
7841 cl_arg.logmsg_path = NULL;
7843 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
7844 switch (ch) {
7845 case 'F':
7846 if (logmsg != NULL)
7847 option_conflict('F', 'm');
7848 prepared_logmsg = realpath(optarg, NULL);
7849 if (prepared_logmsg == NULL)
7850 return got_error_from_errno2("realpath",
7851 optarg);
7852 break;
7853 case 'm':
7854 if (prepared_logmsg)
7855 option_conflict('m', 'F');
7856 logmsg = optarg;
7857 break;
7858 case 'N':
7859 non_interactive = 1;
7860 break;
7861 case 'S':
7862 allow_bad_symlinks = 1;
7863 break;
7864 default:
7865 usage_commit();
7866 /* NOTREACHED */
7870 argc -= optind;
7871 argv += optind;
7873 #ifndef PROFILE
7874 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7875 "unveil", NULL) == -1)
7876 err(1, "pledge");
7877 #endif
7878 cwd = getcwd(NULL, 0);
7879 if (cwd == NULL) {
7880 error = got_error_from_errno("getcwd");
7881 goto done;
7883 error = got_worktree_open(&worktree, cwd);
7884 if (error) {
7885 if (error->code == GOT_ERR_NOT_WORKTREE)
7886 error = wrap_not_worktree_error(error, "commit", cwd);
7887 goto done;
7890 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7891 if (error)
7892 goto done;
7893 if (rebase_in_progress) {
7894 error = got_error(GOT_ERR_REBASING);
7895 goto done;
7898 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7899 worktree);
7900 if (error)
7901 goto done;
7903 error = get_gitconfig_path(&gitconfig_path);
7904 if (error)
7905 goto done;
7906 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7907 gitconfig_path);
7908 if (error != NULL)
7909 goto done;
7911 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7912 if (error)
7913 goto done;
7914 if (merge_in_progress) {
7915 error = got_error(GOT_ERR_MERGE_BUSY);
7916 goto done;
7919 error = get_author(&author, repo, worktree);
7920 if (error)
7921 return error;
7924 * unveil(2) traverses exec(2); if an editor is used we have
7925 * to apply unveil after the log message has been written.
7927 if (logmsg == NULL || strlen(logmsg) == 0)
7928 error = get_editor(&editor);
7929 else
7930 error = apply_unveil(got_repo_get_path(repo), 0,
7931 got_worktree_get_root_path(worktree));
7932 if (error)
7933 goto done;
7935 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7936 if (error)
7937 goto done;
7939 cl_arg.editor = editor;
7940 cl_arg.cmdline_log = logmsg;
7941 cl_arg.prepared_log = prepared_logmsg;
7942 cl_arg.non_interactive = non_interactive;
7943 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
7944 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
7945 if (!histedit_in_progress) {
7946 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
7947 error = got_error(GOT_ERR_COMMIT_BRANCH);
7948 goto done;
7950 cl_arg.branch_name += 11;
7952 cl_arg.repo_path = got_repo_get_path(repo);
7953 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
7954 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
7955 print_status, NULL, repo);
7956 if (error) {
7957 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7958 cl_arg.logmsg_path != NULL)
7959 preserve_logmsg = 1;
7960 goto done;
7963 error = got_object_id_str(&id_str, id);
7964 if (error)
7965 goto done;
7966 printf("Created commit %s\n", id_str);
7967 done:
7968 if (preserve_logmsg) {
7969 fprintf(stderr, "%s: log message preserved in %s\n",
7970 getprogname(), cl_arg.logmsg_path);
7971 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
7972 error == NULL)
7973 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
7974 free(cl_arg.logmsg_path);
7975 if (repo) {
7976 const struct got_error *close_err = got_repo_close(repo);
7977 if (error == NULL)
7978 error = close_err;
7980 if (worktree)
7981 got_worktree_close(worktree);
7982 free(cwd);
7983 free(id_str);
7984 free(gitconfig_path);
7985 free(editor);
7986 free(author);
7987 free(prepared_logmsg);
7988 return error;
7991 __dead static void
7992 usage_send(void)
7994 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
7995 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
7996 "[remote-repository]\n", getprogname());
7997 exit(1);
8000 static void
8001 print_load_info(int print_colored, int print_found, int print_trees,
8002 int ncolored, int nfound, int ntrees)
8004 if (print_colored) {
8005 printf("%d commit%s colored", ncolored,
8006 ncolored == 1 ? "" : "s");
8008 if (print_found) {
8009 printf("%s%d object%s found",
8010 ncolored > 0 ? "; " : "",
8011 nfound, nfound == 1 ? "" : "s");
8013 if (print_trees) {
8014 printf("; %d tree%s scanned", ntrees,
8015 ntrees == 1 ? "" : "s");
8019 struct got_send_progress_arg {
8020 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8021 int verbosity;
8022 int last_ncolored;
8023 int last_nfound;
8024 int last_ntrees;
8025 int loading_done;
8026 int last_ncommits;
8027 int last_nobj_total;
8028 int last_p_deltify;
8029 int last_p_written;
8030 int last_p_sent;
8031 int printed_something;
8032 int sent_something;
8033 struct got_pathlist_head *delete_branches;
8036 static const struct got_error *
8037 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8038 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8039 int nobj_written, off_t bytes_sent, const char *refname, int success)
8041 struct got_send_progress_arg *a = arg;
8042 char scaled_packsize[FMT_SCALED_STRSIZE];
8043 char scaled_sent[FMT_SCALED_STRSIZE];
8044 int p_deltify = 0, p_written = 0, p_sent = 0;
8045 int print_colored = 0, print_found = 0, print_trees = 0;
8046 int print_searching = 0, print_total = 0;
8047 int print_deltify = 0, print_written = 0, print_sent = 0;
8049 if (a->verbosity < 0)
8050 return NULL;
8052 if (refname) {
8053 const char *status = success ? "accepted" : "rejected";
8055 if (success) {
8056 struct got_pathlist_entry *pe;
8057 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8058 const char *branchname = pe->path;
8059 if (got_path_cmp(branchname, refname,
8060 strlen(branchname), strlen(refname)) == 0) {
8061 status = "deleted";
8062 a->sent_something = 1;
8063 break;
8068 if (a->printed_something)
8069 putchar('\n');
8070 printf("Server has %s %s", status, refname);
8071 a->printed_something = 1;
8072 return NULL;
8075 if (a->last_ncolored != ncolored) {
8076 print_colored = 1;
8077 a->last_ncolored = ncolored;
8080 if (a->last_nfound != nfound) {
8081 print_colored = 1;
8082 print_found = 1;
8083 a->last_nfound = nfound;
8086 if (a->last_ntrees != ntrees) {
8087 print_colored = 1;
8088 print_found = 1;
8089 print_trees = 1;
8090 a->last_ntrees = ntrees;
8093 if ((print_colored || print_found || print_trees) &&
8094 !a->loading_done) {
8095 printf("\r");
8096 print_load_info(print_colored, print_found, print_trees,
8097 ncolored, nfound, ntrees);
8098 a->printed_something = 1;
8099 fflush(stdout);
8100 return NULL;
8101 } else if (!a->loading_done) {
8102 printf("\r");
8103 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8104 printf("\n");
8105 a->loading_done = 1;
8108 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8109 return got_error_from_errno("fmt_scaled");
8110 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8111 return got_error_from_errno("fmt_scaled");
8113 if (a->last_ncommits != ncommits) {
8114 print_searching = 1;
8115 a->last_ncommits = ncommits;
8118 if (a->last_nobj_total != nobj_total) {
8119 print_searching = 1;
8120 print_total = 1;
8121 a->last_nobj_total = nobj_total;
8124 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8125 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8126 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8127 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8128 return got_error(GOT_ERR_NO_SPACE);
8131 if (nobj_deltify > 0 || nobj_written > 0) {
8132 if (nobj_deltify > 0) {
8133 p_deltify = (nobj_deltify * 100) / nobj_total;
8134 if (p_deltify != a->last_p_deltify) {
8135 a->last_p_deltify = p_deltify;
8136 print_searching = 1;
8137 print_total = 1;
8138 print_deltify = 1;
8141 if (nobj_written > 0) {
8142 p_written = (nobj_written * 100) / nobj_total;
8143 if (p_written != a->last_p_written) {
8144 a->last_p_written = p_written;
8145 print_searching = 1;
8146 print_total = 1;
8147 print_deltify = 1;
8148 print_written = 1;
8153 if (bytes_sent > 0) {
8154 p_sent = (bytes_sent * 100) / packfile_size;
8155 if (p_sent != a->last_p_sent) {
8156 a->last_p_sent = p_sent;
8157 print_searching = 1;
8158 print_total = 1;
8159 print_deltify = 1;
8160 print_written = 1;
8161 print_sent = 1;
8163 a->sent_something = 1;
8166 if (print_searching || print_total || print_deltify || print_written ||
8167 print_sent)
8168 printf("\r");
8169 if (print_searching)
8170 printf("packing %d reference%s", ncommits,
8171 ncommits == 1 ? "" : "s");
8172 if (print_total)
8173 printf("; %d object%s", nobj_total,
8174 nobj_total == 1 ? "" : "s");
8175 if (print_deltify)
8176 printf("; deltify: %d%%", p_deltify);
8177 if (print_sent)
8178 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8179 scaled_packsize, p_sent);
8180 else if (print_written)
8181 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8182 scaled_packsize, p_written);
8183 if (print_searching || print_total || print_deltify ||
8184 print_written || print_sent) {
8185 a->printed_something = 1;
8186 fflush(stdout);
8188 return NULL;
8191 static const struct got_error *
8192 cmd_send(int argc, char *argv[])
8194 const struct got_error *error = NULL;
8195 char *cwd = NULL, *repo_path = NULL;
8196 const char *remote_name;
8197 char *proto = NULL, *host = NULL, *port = NULL;
8198 char *repo_name = NULL, *server_path = NULL;
8199 const struct got_remote_repo *remotes, *remote = NULL;
8200 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8201 struct got_repository *repo = NULL;
8202 struct got_worktree *worktree = NULL;
8203 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8204 struct got_pathlist_head branches;
8205 struct got_pathlist_head tags;
8206 struct got_reflist_head all_branches;
8207 struct got_reflist_head all_tags;
8208 struct got_pathlist_head delete_args;
8209 struct got_pathlist_head delete_branches;
8210 struct got_reflist_entry *re;
8211 struct got_pathlist_entry *pe;
8212 int i, ch, sendfd = -1, sendstatus;
8213 pid_t sendpid = -1;
8214 struct got_send_progress_arg spa;
8215 int verbosity = 0, overwrite_refs = 0;
8216 int send_all_branches = 0, send_all_tags = 0;
8217 struct got_reference *ref = NULL;
8219 TAILQ_INIT(&branches);
8220 TAILQ_INIT(&tags);
8221 TAILQ_INIT(&all_branches);
8222 TAILQ_INIT(&all_tags);
8223 TAILQ_INIT(&delete_args);
8224 TAILQ_INIT(&delete_branches);
8226 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8227 switch (ch) {
8228 case 'a':
8229 send_all_branches = 1;
8230 break;
8231 case 'b':
8232 error = got_pathlist_append(&branches, optarg, NULL);
8233 if (error)
8234 return error;
8235 nbranches++;
8236 break;
8237 case 'd':
8238 error = got_pathlist_append(&delete_args, optarg, NULL);
8239 if (error)
8240 return error;
8241 break;
8242 case 'f':
8243 overwrite_refs = 1;
8244 break;
8245 case 'r':
8246 repo_path = realpath(optarg, NULL);
8247 if (repo_path == NULL)
8248 return got_error_from_errno2("realpath",
8249 optarg);
8250 got_path_strip_trailing_slashes(repo_path);
8251 break;
8252 case 't':
8253 error = got_pathlist_append(&tags, optarg, NULL);
8254 if (error)
8255 return error;
8256 ntags++;
8257 break;
8258 case 'T':
8259 send_all_tags = 1;
8260 break;
8261 case 'v':
8262 if (verbosity < 0)
8263 verbosity = 0;
8264 else if (verbosity < 3)
8265 verbosity++;
8266 break;
8267 case 'q':
8268 verbosity = -1;
8269 break;
8270 default:
8271 usage_send();
8272 /* NOTREACHED */
8275 argc -= optind;
8276 argv += optind;
8278 if (send_all_branches && !TAILQ_EMPTY(&branches))
8279 option_conflict('a', 'b');
8280 if (send_all_tags && !TAILQ_EMPTY(&tags))
8281 option_conflict('T', 't');
8284 if (argc == 0)
8285 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8286 else if (argc == 1)
8287 remote_name = argv[0];
8288 else
8289 usage_send();
8291 cwd = getcwd(NULL, 0);
8292 if (cwd == NULL) {
8293 error = got_error_from_errno("getcwd");
8294 goto done;
8297 if (repo_path == NULL) {
8298 error = got_worktree_open(&worktree, cwd);
8299 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8300 goto done;
8301 else
8302 error = NULL;
8303 if (worktree) {
8304 repo_path =
8305 strdup(got_worktree_get_repo_path(worktree));
8306 if (repo_path == NULL)
8307 error = got_error_from_errno("strdup");
8308 if (error)
8309 goto done;
8310 } else {
8311 repo_path = strdup(cwd);
8312 if (repo_path == NULL) {
8313 error = got_error_from_errno("strdup");
8314 goto done;
8319 error = got_repo_open(&repo, repo_path, NULL);
8320 if (error)
8321 goto done;
8323 if (worktree) {
8324 worktree_conf = got_worktree_get_gotconfig(worktree);
8325 if (worktree_conf) {
8326 got_gotconfig_get_remotes(&nremotes, &remotes,
8327 worktree_conf);
8328 for (i = 0; i < nremotes; i++) {
8329 if (strcmp(remotes[i].name, remote_name) == 0) {
8330 remote = &remotes[i];
8331 break;
8336 if (remote == NULL) {
8337 repo_conf = got_repo_get_gotconfig(repo);
8338 if (repo_conf) {
8339 got_gotconfig_get_remotes(&nremotes, &remotes,
8340 repo_conf);
8341 for (i = 0; i < nremotes; i++) {
8342 if (strcmp(remotes[i].name, remote_name) == 0) {
8343 remote = &remotes[i];
8344 break;
8349 if (remote == NULL) {
8350 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8351 for (i = 0; i < nremotes; i++) {
8352 if (strcmp(remotes[i].name, remote_name) == 0) {
8353 remote = &remotes[i];
8354 break;
8358 if (remote == NULL) {
8359 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8360 goto done;
8363 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8364 &repo_name, remote->send_url);
8365 if (error)
8366 goto done;
8368 if (strcmp(proto, "git") == 0) {
8369 #ifndef PROFILE
8370 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8371 "sendfd dns inet unveil", NULL) == -1)
8372 err(1, "pledge");
8373 #endif
8374 } else if (strcmp(proto, "git+ssh") == 0 ||
8375 strcmp(proto, "ssh") == 0) {
8376 #ifndef PROFILE
8377 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8378 "sendfd unveil", NULL) == -1)
8379 err(1, "pledge");
8380 #endif
8381 } else if (strcmp(proto, "http") == 0 ||
8382 strcmp(proto, "git+http") == 0) {
8383 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8384 goto done;
8385 } else {
8386 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8387 goto done;
8390 error = got_dial_apply_unveil(proto);
8391 if (error)
8392 goto done;
8394 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8395 if (error)
8396 goto done;
8398 if (send_all_branches) {
8399 error = got_ref_list(&all_branches, repo, "refs/heads",
8400 got_ref_cmp_by_name, NULL);
8401 if (error)
8402 goto done;
8403 TAILQ_FOREACH(re, &all_branches, entry) {
8404 const char *branchname = got_ref_get_name(re->ref);
8405 error = got_pathlist_append(&branches,
8406 branchname, NULL);
8407 if (error)
8408 goto done;
8409 nbranches++;
8411 } else if (nbranches == 0) {
8412 for (i = 0; i < remote->nsend_branches; i++) {
8413 got_pathlist_append(&branches,
8414 remote->send_branches[i], NULL);
8418 if (send_all_tags) {
8419 error = got_ref_list(&all_tags, repo, "refs/tags",
8420 got_ref_cmp_by_name, NULL);
8421 if (error)
8422 goto done;
8423 TAILQ_FOREACH(re, &all_tags, entry) {
8424 const char *tagname = got_ref_get_name(re->ref);
8425 error = got_pathlist_append(&tags,
8426 tagname, NULL);
8427 if (error)
8428 goto done;
8429 ntags++;
8434 * To prevent accidents only branches in refs/heads/ can be deleted
8435 * with 'got send -d'.
8436 * Deleting anything else requires local repository access or Git.
8438 TAILQ_FOREACH(pe, &delete_args, entry) {
8439 const char *branchname = pe->path;
8440 char *s;
8441 struct got_pathlist_entry *new;
8442 if (strncmp(branchname, "refs/heads/", 11) == 0) {
8443 s = strdup(branchname);
8444 if (s == NULL) {
8445 error = got_error_from_errno("strdup");
8446 goto done;
8448 } else {
8449 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
8450 error = got_error_from_errno("asprintf");
8451 goto done;
8454 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
8455 if (error || new == NULL /* duplicate */)
8456 free(s);
8457 if (error)
8458 goto done;
8459 ndelete_branches++;
8462 if (nbranches == 0 && ndelete_branches == 0) {
8463 struct got_reference *head_ref;
8464 if (worktree)
8465 error = got_ref_open(&head_ref, repo,
8466 got_worktree_get_head_ref_name(worktree), 0);
8467 else
8468 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
8469 if (error)
8470 goto done;
8471 if (got_ref_is_symbolic(head_ref)) {
8472 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
8473 got_ref_close(head_ref);
8474 if (error)
8475 goto done;
8476 } else
8477 ref = head_ref;
8478 error = got_pathlist_append(&branches, got_ref_get_name(ref),
8479 NULL);
8480 if (error)
8481 goto done;
8482 nbranches++;
8485 if (verbosity >= 0)
8486 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
8487 port ? ":" : "", port ? port : "");
8489 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
8490 server_path, verbosity);
8491 if (error)
8492 goto done;
8494 memset(&spa, 0, sizeof(spa));
8495 spa.last_scaled_packsize[0] = '\0';
8496 spa.last_p_deltify = -1;
8497 spa.last_p_written = -1;
8498 spa.verbosity = verbosity;
8499 spa.delete_branches = &delete_branches;
8500 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
8501 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
8502 check_cancelled, NULL);
8503 if (spa.printed_something)
8504 putchar('\n');
8505 if (error)
8506 goto done;
8507 if (!spa.sent_something && verbosity >= 0)
8508 printf("Already up-to-date\n");
8509 done:
8510 if (sendpid > 0) {
8511 if (kill(sendpid, SIGTERM) == -1)
8512 error = got_error_from_errno("kill");
8513 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
8514 error = got_error_from_errno("waitpid");
8516 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
8517 error = got_error_from_errno("close");
8518 if (repo) {
8519 const struct got_error *close_err = got_repo_close(repo);
8520 if (error == NULL)
8521 error = close_err;
8523 if (worktree)
8524 got_worktree_close(worktree);
8525 if (ref)
8526 got_ref_close(ref);
8527 got_pathlist_free(&branches);
8528 got_pathlist_free(&tags);
8529 got_ref_list_free(&all_branches);
8530 got_ref_list_free(&all_tags);
8531 got_pathlist_free(&delete_args);
8532 TAILQ_FOREACH(pe, &delete_branches, entry)
8533 free((char *)pe->path);
8534 got_pathlist_free(&delete_branches);
8535 free(cwd);
8536 free(repo_path);
8537 free(proto);
8538 free(host);
8539 free(port);
8540 free(server_path);
8541 free(repo_name);
8542 return error;
8545 __dead static void
8546 usage_cherrypick(void)
8548 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
8549 exit(1);
8552 static const struct got_error *
8553 cmd_cherrypick(int argc, char *argv[])
8555 const struct got_error *error = NULL;
8556 struct got_worktree *worktree = NULL;
8557 struct got_repository *repo = NULL;
8558 char *cwd = NULL, *commit_id_str = NULL;
8559 struct got_object_id *commit_id = NULL;
8560 struct got_commit_object *commit = NULL;
8561 struct got_object_qid *pid;
8562 int ch;
8563 struct got_update_progress_arg upa;
8565 while ((ch = getopt(argc, argv, "")) != -1) {
8566 switch (ch) {
8567 default:
8568 usage_cherrypick();
8569 /* NOTREACHED */
8573 argc -= optind;
8574 argv += optind;
8576 #ifndef PROFILE
8577 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8578 "unveil", NULL) == -1)
8579 err(1, "pledge");
8580 #endif
8581 if (argc != 1)
8582 usage_cherrypick();
8584 cwd = getcwd(NULL, 0);
8585 if (cwd == NULL) {
8586 error = got_error_from_errno("getcwd");
8587 goto done;
8589 error = got_worktree_open(&worktree, cwd);
8590 if (error) {
8591 if (error->code == GOT_ERR_NOT_WORKTREE)
8592 error = wrap_not_worktree_error(error, "cherrypick",
8593 cwd);
8594 goto done;
8597 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8598 NULL);
8599 if (error != NULL)
8600 goto done;
8602 error = apply_unveil(got_repo_get_path(repo), 0,
8603 got_worktree_get_root_path(worktree));
8604 if (error)
8605 goto done;
8607 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8608 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8609 if (error)
8610 goto done;
8611 error = got_object_id_str(&commit_id_str, commit_id);
8612 if (error)
8613 goto done;
8615 error = got_object_open_as_commit(&commit, repo, commit_id);
8616 if (error)
8617 goto done;
8618 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8619 memset(&upa, 0, sizeof(upa));
8620 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8621 commit_id, repo, update_progress, &upa, check_cancelled,
8622 NULL);
8623 if (error != NULL)
8624 goto done;
8626 if (upa.did_something)
8627 printf("Merged commit %s\n", commit_id_str);
8628 print_merge_progress_stats(&upa);
8629 done:
8630 if (commit)
8631 got_object_commit_close(commit);
8632 free(commit_id_str);
8633 if (worktree)
8634 got_worktree_close(worktree);
8635 if (repo) {
8636 const struct got_error *close_err = got_repo_close(repo);
8637 if (error == NULL)
8638 error = close_err;
8640 return error;
8643 __dead static void
8644 usage_backout(void)
8646 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
8647 exit(1);
8650 static const struct got_error *
8651 cmd_backout(int argc, char *argv[])
8653 const struct got_error *error = NULL;
8654 struct got_worktree *worktree = NULL;
8655 struct got_repository *repo = NULL;
8656 char *cwd = NULL, *commit_id_str = NULL;
8657 struct got_object_id *commit_id = NULL;
8658 struct got_commit_object *commit = NULL;
8659 struct got_object_qid *pid;
8660 int ch;
8661 struct got_update_progress_arg upa;
8663 while ((ch = getopt(argc, argv, "")) != -1) {
8664 switch (ch) {
8665 default:
8666 usage_backout();
8667 /* NOTREACHED */
8671 argc -= optind;
8672 argv += optind;
8674 #ifndef PROFILE
8675 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8676 "unveil", NULL) == -1)
8677 err(1, "pledge");
8678 #endif
8679 if (argc != 1)
8680 usage_backout();
8682 cwd = getcwd(NULL, 0);
8683 if (cwd == NULL) {
8684 error = got_error_from_errno("getcwd");
8685 goto done;
8687 error = got_worktree_open(&worktree, cwd);
8688 if (error) {
8689 if (error->code == GOT_ERR_NOT_WORKTREE)
8690 error = wrap_not_worktree_error(error, "backout", cwd);
8691 goto done;
8694 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8695 NULL);
8696 if (error != NULL)
8697 goto done;
8699 error = apply_unveil(got_repo_get_path(repo), 0,
8700 got_worktree_get_root_path(worktree));
8701 if (error)
8702 goto done;
8704 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8705 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8706 if (error)
8707 goto done;
8708 error = got_object_id_str(&commit_id_str, commit_id);
8709 if (error)
8710 goto done;
8712 error = got_object_open_as_commit(&commit, repo, commit_id);
8713 if (error)
8714 goto done;
8715 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8716 if (pid == NULL) {
8717 error = got_error(GOT_ERR_ROOT_COMMIT);
8718 goto done;
8721 memset(&upa, 0, sizeof(upa));
8722 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8723 repo, update_progress, &upa, check_cancelled, NULL);
8724 if (error != NULL)
8725 goto done;
8727 if (upa.did_something)
8728 printf("Backed out commit %s\n", commit_id_str);
8729 print_merge_progress_stats(&upa);
8730 done:
8731 if (commit)
8732 got_object_commit_close(commit);
8733 free(commit_id_str);
8734 if (worktree)
8735 got_worktree_close(worktree);
8736 if (repo) {
8737 const struct got_error *close_err = got_repo_close(repo);
8738 if (error == NULL)
8739 error = close_err;
8741 return error;
8744 __dead static void
8745 usage_rebase(void)
8747 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
8748 getprogname());
8749 exit(1);
8752 void
8753 trim_logmsg(char *logmsg, int limit)
8755 char *nl;
8756 size_t len;
8758 len = strlen(logmsg);
8759 if (len > limit)
8760 len = limit;
8761 logmsg[len] = '\0';
8762 nl = strchr(logmsg, '\n');
8763 if (nl)
8764 *nl = '\0';
8767 static const struct got_error *
8768 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
8770 const struct got_error *err;
8771 char *logmsg0 = NULL;
8772 const char *s;
8774 err = got_object_commit_get_logmsg(&logmsg0, commit);
8775 if (err)
8776 return err;
8778 s = logmsg0;
8779 while (isspace((unsigned char)s[0]))
8780 s++;
8782 *logmsg = strdup(s);
8783 if (*logmsg == NULL) {
8784 err = got_error_from_errno("strdup");
8785 goto done;
8788 trim_logmsg(*logmsg, limit);
8789 done:
8790 free(logmsg0);
8791 return err;
8794 static const struct got_error *
8795 show_rebase_merge_conflict(struct got_object_id *id,
8796 struct got_repository *repo)
8798 const struct got_error *err;
8799 struct got_commit_object *commit = NULL;
8800 char *id_str = NULL, *logmsg = NULL;
8802 err = got_object_open_as_commit(&commit, repo, id);
8803 if (err)
8804 return err;
8806 err = got_object_id_str(&id_str, id);
8807 if (err)
8808 goto done;
8810 id_str[12] = '\0';
8812 err = get_short_logmsg(&logmsg, 42, commit);
8813 if (err)
8814 goto done;
8816 printf("%s -> merge conflict: %s\n", id_str, logmsg);
8817 done:
8818 free(id_str);
8819 got_object_commit_close(commit);
8820 free(logmsg);
8821 return err;
8824 static const struct got_error *
8825 show_rebase_progress(struct got_commit_object *commit,
8826 struct got_object_id *old_id, struct got_object_id *new_id)
8828 const struct got_error *err;
8829 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
8831 err = got_object_id_str(&old_id_str, old_id);
8832 if (err)
8833 goto done;
8835 if (new_id) {
8836 err = got_object_id_str(&new_id_str, new_id);
8837 if (err)
8838 goto done;
8841 old_id_str[12] = '\0';
8842 if (new_id_str)
8843 new_id_str[12] = '\0';
8845 err = get_short_logmsg(&logmsg, 42, commit);
8846 if (err)
8847 goto done;
8849 printf("%s -> %s: %s\n", old_id_str,
8850 new_id_str ? new_id_str : "no-op change", logmsg);
8851 done:
8852 free(old_id_str);
8853 free(new_id_str);
8854 free(logmsg);
8855 return err;
8858 static const struct got_error *
8859 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
8860 struct got_reference *branch, struct got_reference *new_base_branch,
8861 struct got_reference *tmp_branch, struct got_repository *repo,
8862 int create_backup)
8864 printf("Switching work tree to %s\n", got_ref_get_name(branch));
8865 return got_worktree_rebase_complete(worktree, fileindex,
8866 new_base_branch, tmp_branch, branch, repo, create_backup);
8869 static const struct got_error *
8870 rebase_commit(struct got_pathlist_head *merged_paths,
8871 struct got_worktree *worktree, struct got_fileindex *fileindex,
8872 struct got_reference *tmp_branch,
8873 struct got_object_id *commit_id, struct got_repository *repo)
8875 const struct got_error *error;
8876 struct got_commit_object *commit;
8877 struct got_object_id *new_commit_id;
8879 error = got_object_open_as_commit(&commit, repo, commit_id);
8880 if (error)
8881 return error;
8883 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
8884 worktree, fileindex, tmp_branch, commit, commit_id, repo);
8885 if (error) {
8886 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
8887 goto done;
8888 error = show_rebase_progress(commit, commit_id, NULL);
8889 } else {
8890 error = show_rebase_progress(commit, commit_id, new_commit_id);
8891 free(new_commit_id);
8893 done:
8894 got_object_commit_close(commit);
8895 return error;
8898 struct check_path_prefix_arg {
8899 const char *path_prefix;
8900 size_t len;
8901 int errcode;
8904 static const struct got_error *
8905 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
8906 struct got_blob_object *blob2, FILE *f1, FILE *f2,
8907 struct got_object_id *id1, struct got_object_id *id2,
8908 const char *path1, const char *path2,
8909 mode_t mode1, mode_t mode2, struct got_repository *repo)
8911 struct check_path_prefix_arg *a = arg;
8913 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
8914 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
8915 return got_error(a->errcode);
8917 return NULL;
8920 static const struct got_error *
8921 check_path_prefix(struct got_object_id *parent_id,
8922 struct got_object_id *commit_id, const char *path_prefix,
8923 int errcode, struct got_repository *repo)
8925 const struct got_error *err;
8926 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
8927 struct got_commit_object *commit = NULL, *parent_commit = NULL;
8928 struct check_path_prefix_arg cpp_arg;
8930 if (got_path_is_root_dir(path_prefix))
8931 return NULL;
8933 err = got_object_open_as_commit(&commit, repo, commit_id);
8934 if (err)
8935 goto done;
8937 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
8938 if (err)
8939 goto done;
8941 err = got_object_open_as_tree(&tree1, repo,
8942 got_object_commit_get_tree_id(parent_commit));
8943 if (err)
8944 goto done;
8946 err = got_object_open_as_tree(&tree2, repo,
8947 got_object_commit_get_tree_id(commit));
8948 if (err)
8949 goto done;
8951 cpp_arg.path_prefix = path_prefix;
8952 while (cpp_arg.path_prefix[0] == '/')
8953 cpp_arg.path_prefix++;
8954 cpp_arg.len = strlen(cpp_arg.path_prefix);
8955 cpp_arg.errcode = errcode;
8956 err = got_diff_tree(tree1, tree2, NULL, NULL, "", "", repo,
8957 check_path_prefix_in_diff, &cpp_arg, 0);
8958 done:
8959 if (tree1)
8960 got_object_tree_close(tree1);
8961 if (tree2)
8962 got_object_tree_close(tree2);
8963 if (commit)
8964 got_object_commit_close(commit);
8965 if (parent_commit)
8966 got_object_commit_close(parent_commit);
8967 return err;
8970 static const struct got_error *
8971 collect_commits(struct got_object_id_queue *commits,
8972 struct got_object_id *initial_commit_id,
8973 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
8974 const char *path_prefix, int path_prefix_errcode,
8975 struct got_repository *repo)
8977 const struct got_error *err = NULL;
8978 struct got_commit_graph *graph = NULL;
8979 struct got_object_id *parent_id = NULL;
8980 struct got_object_qid *qid;
8981 struct got_object_id *commit_id = initial_commit_id;
8983 err = got_commit_graph_open(&graph, "/", 1);
8984 if (err)
8985 return err;
8987 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
8988 check_cancelled, NULL);
8989 if (err)
8990 goto done;
8991 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
8992 err = got_commit_graph_iter_next(&parent_id, graph, repo,
8993 check_cancelled, NULL);
8994 if (err) {
8995 if (err->code == GOT_ERR_ITER_COMPLETED) {
8996 err = got_error_msg(GOT_ERR_ANCESTRY,
8997 "ran out of commits to rebase before "
8998 "youngest common ancestor commit has "
8999 "been reached?!?");
9001 goto done;
9002 } else {
9003 err = check_path_prefix(parent_id, commit_id,
9004 path_prefix, path_prefix_errcode, repo);
9005 if (err)
9006 goto done;
9008 err = got_object_qid_alloc(&qid, commit_id);
9009 if (err)
9010 goto done;
9011 STAILQ_INSERT_HEAD(commits, qid, entry);
9012 commit_id = parent_id;
9015 done:
9016 got_commit_graph_close(graph);
9017 return err;
9020 static const struct got_error *
9021 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9023 const struct got_error *err = NULL;
9024 time_t committer_time;
9025 struct tm tm;
9026 char datebuf[11]; /* YYYY-MM-DD + NUL */
9027 char *author0 = NULL, *author, *smallerthan;
9028 char *logmsg0 = NULL, *logmsg, *newline;
9030 committer_time = got_object_commit_get_committer_time(commit);
9031 if (gmtime_r(&committer_time, &tm) == NULL)
9032 return got_error_from_errno("gmtime_r");
9033 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9034 return got_error(GOT_ERR_NO_SPACE);
9036 author0 = strdup(got_object_commit_get_author(commit));
9037 if (author0 == NULL)
9038 return got_error_from_errno("strdup");
9039 author = author0;
9040 smallerthan = strchr(author, '<');
9041 if (smallerthan && smallerthan[1] != '\0')
9042 author = smallerthan + 1;
9043 author[strcspn(author, "@>")] = '\0';
9045 err = got_object_commit_get_logmsg(&logmsg0, commit);
9046 if (err)
9047 goto done;
9048 logmsg = logmsg0;
9049 while (*logmsg == '\n')
9050 logmsg++;
9051 newline = strchr(logmsg, '\n');
9052 if (newline)
9053 *newline = '\0';
9055 if (asprintf(brief_str, "%s %s %s",
9056 datebuf, author, logmsg) == -1)
9057 err = got_error_from_errno("asprintf");
9058 done:
9059 free(author0);
9060 free(logmsg0);
9061 return err;
9064 static const struct got_error *
9065 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9066 struct got_repository *repo)
9068 const struct got_error *err;
9069 char *id_str;
9071 err = got_object_id_str(&id_str, id);
9072 if (err)
9073 return err;
9075 err = got_ref_delete(ref, repo);
9076 if (err)
9077 goto done;
9079 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9080 done:
9081 free(id_str);
9082 return err;
9085 static const struct got_error *
9086 print_backup_ref(const char *branch_name, const char *new_id_str,
9087 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9088 struct got_reflist_object_id_map *refs_idmap,
9089 struct got_repository *repo)
9091 const struct got_error *err = NULL;
9092 struct got_reflist_head *refs;
9093 char *refs_str = NULL;
9094 struct got_object_id *new_commit_id = NULL;
9095 struct got_commit_object *new_commit = NULL;
9096 char *new_commit_brief_str = NULL;
9097 struct got_object_id *yca_id = NULL;
9098 struct got_commit_object *yca_commit = NULL;
9099 char *yca_id_str = NULL, *yca_brief_str = NULL;
9100 char *custom_refs_str;
9102 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9103 return got_error_from_errno("asprintf");
9105 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9106 0, 0, refs_idmap, custom_refs_str);
9107 if (err)
9108 goto done;
9110 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9111 if (err)
9112 goto done;
9114 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9115 if (refs) {
9116 err = build_refs_str(&refs_str, refs, new_commit_id, repo);
9117 if (err)
9118 goto done;
9121 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9122 if (err)
9123 goto done;
9125 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9126 if (err)
9127 goto done;
9129 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9130 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9131 if (err)
9132 goto done;
9134 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9135 refs_str ? " (" : "", refs_str ? refs_str : "",
9136 refs_str ? ")" : "", new_commit_brief_str);
9137 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9138 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9139 free(refs_str);
9140 refs_str = NULL;
9142 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9143 if (err)
9144 goto done;
9146 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9147 if (err)
9148 goto done;
9150 err = got_object_id_str(&yca_id_str, yca_id);
9151 if (err)
9152 goto done;
9154 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9155 if (refs) {
9156 err = build_refs_str(&refs_str, refs, yca_id, repo);
9157 if (err)
9158 goto done;
9160 printf("history forked at %s%s%s%s\n %s\n",
9161 yca_id_str,
9162 refs_str ? " (" : "", refs_str ? refs_str : "",
9163 refs_str ? ")" : "", yca_brief_str);
9165 done:
9166 free(custom_refs_str);
9167 free(new_commit_id);
9168 free(refs_str);
9169 free(yca_id);
9170 free(yca_id_str);
9171 free(yca_brief_str);
9172 if (new_commit)
9173 got_object_commit_close(new_commit);
9174 if (yca_commit)
9175 got_object_commit_close(yca_commit);
9177 return NULL;
9180 static const struct got_error *
9181 process_backup_refs(const char *backup_ref_prefix,
9182 const char *wanted_branch_name,
9183 int delete, struct got_repository *repo)
9185 const struct got_error *err;
9186 struct got_reflist_head refs, backup_refs;
9187 struct got_reflist_entry *re;
9188 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9189 struct got_object_id *old_commit_id = NULL;
9190 char *branch_name = NULL;
9191 struct got_commit_object *old_commit = NULL;
9192 struct got_reflist_object_id_map *refs_idmap = NULL;
9193 int wanted_branch_found = 0;
9195 TAILQ_INIT(&refs);
9196 TAILQ_INIT(&backup_refs);
9198 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9199 if (err)
9200 return err;
9202 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9203 if (err)
9204 goto done;
9206 if (wanted_branch_name) {
9207 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9208 wanted_branch_name += 11;
9211 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9212 got_ref_cmp_by_commit_timestamp_descending, repo);
9213 if (err)
9214 goto done;
9216 TAILQ_FOREACH(re, &backup_refs, entry) {
9217 const char *refname = got_ref_get_name(re->ref);
9218 char *slash;
9220 err = check_cancelled(NULL);
9221 if (err)
9222 break;
9224 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9225 if (err)
9226 break;
9228 err = got_object_open_as_commit(&old_commit, repo,
9229 old_commit_id);
9230 if (err)
9231 break;
9233 if (strncmp(backup_ref_prefix, refname,
9234 backup_ref_prefix_len) == 0)
9235 refname += backup_ref_prefix_len;
9237 while (refname[0] == '/')
9238 refname++;
9240 branch_name = strdup(refname);
9241 if (branch_name == NULL) {
9242 err = got_error_from_errno("strdup");
9243 break;
9245 slash = strrchr(branch_name, '/');
9246 if (slash) {
9247 *slash = '\0';
9248 refname += strlen(branch_name) + 1;
9251 if (wanted_branch_name == NULL ||
9252 strcmp(wanted_branch_name, branch_name) == 0) {
9253 wanted_branch_found = 1;
9254 if (delete) {
9255 err = delete_backup_ref(re->ref,
9256 old_commit_id, repo);
9257 } else {
9258 err = print_backup_ref(branch_name, refname,
9259 old_commit_id, old_commit, refs_idmap,
9260 repo);
9262 if (err)
9263 break;
9266 free(old_commit_id);
9267 old_commit_id = NULL;
9268 free(branch_name);
9269 branch_name = NULL;
9270 got_object_commit_close(old_commit);
9271 old_commit = NULL;
9274 if (wanted_branch_name && !wanted_branch_found) {
9275 err = got_error_fmt(GOT_ERR_NOT_REF,
9276 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9278 done:
9279 if (refs_idmap)
9280 got_reflist_object_id_map_free(refs_idmap);
9281 got_ref_list_free(&refs);
9282 got_ref_list_free(&backup_refs);
9283 free(old_commit_id);
9284 free(branch_name);
9285 if (old_commit)
9286 got_object_commit_close(old_commit);
9287 return err;
9290 static const struct got_error *
9291 abort_progress(void *arg, unsigned char status, const char *path)
9294 * Unversioned files should not clutter progress output when
9295 * an operation is aborted.
9297 if (status == GOT_STATUS_UNVERSIONED)
9298 return NULL;
9300 return update_progress(arg, status, path);
9303 static const struct got_error *
9304 cmd_rebase(int argc, char *argv[])
9306 const struct got_error *error = NULL;
9307 struct got_worktree *worktree = NULL;
9308 struct got_repository *repo = NULL;
9309 struct got_fileindex *fileindex = NULL;
9310 char *cwd = NULL;
9311 struct got_reference *branch = NULL;
9312 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9313 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9314 struct got_object_id *resume_commit_id = NULL;
9315 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9316 struct got_commit_object *commit = NULL;
9317 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9318 int histedit_in_progress = 0, merge_in_progress = 0;
9319 int create_backup = 1, list_backups = 0, delete_backups = 0;
9320 struct got_object_id_queue commits;
9321 struct got_pathlist_head merged_paths;
9322 const struct got_object_id_queue *parent_ids;
9323 struct got_object_qid *qid, *pid;
9324 struct got_update_progress_arg upa;
9326 STAILQ_INIT(&commits);
9327 TAILQ_INIT(&merged_paths);
9328 memset(&upa, 0, sizeof(upa));
9330 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9331 switch (ch) {
9332 case 'a':
9333 abort_rebase = 1;
9334 break;
9335 case 'c':
9336 continue_rebase = 1;
9337 break;
9338 case 'l':
9339 list_backups = 1;
9340 break;
9341 case 'X':
9342 delete_backups = 1;
9343 break;
9344 default:
9345 usage_rebase();
9346 /* NOTREACHED */
9350 argc -= optind;
9351 argv += optind;
9353 #ifndef PROFILE
9354 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9355 "unveil", NULL) == -1)
9356 err(1, "pledge");
9357 #endif
9358 if (list_backups) {
9359 if (abort_rebase)
9360 option_conflict('l', 'a');
9361 if (continue_rebase)
9362 option_conflict('l', 'c');
9363 if (delete_backups)
9364 option_conflict('l', 'X');
9365 if (argc != 0 && argc != 1)
9366 usage_rebase();
9367 } else if (delete_backups) {
9368 if (abort_rebase)
9369 option_conflict('X', 'a');
9370 if (continue_rebase)
9371 option_conflict('X', 'c');
9372 if (list_backups)
9373 option_conflict('l', 'X');
9374 if (argc != 0 && argc != 1)
9375 usage_rebase();
9376 } else {
9377 if (abort_rebase && continue_rebase)
9378 usage_rebase();
9379 else if (abort_rebase || continue_rebase) {
9380 if (argc != 0)
9381 usage_rebase();
9382 } else if (argc != 1)
9383 usage_rebase();
9386 cwd = getcwd(NULL, 0);
9387 if (cwd == NULL) {
9388 error = got_error_from_errno("getcwd");
9389 goto done;
9391 error = got_worktree_open(&worktree, cwd);
9392 if (error) {
9393 if (list_backups || delete_backups) {
9394 if (error->code != GOT_ERR_NOT_WORKTREE)
9395 goto done;
9396 } else {
9397 if (error->code == GOT_ERR_NOT_WORKTREE)
9398 error = wrap_not_worktree_error(error,
9399 "rebase", cwd);
9400 goto done;
9404 error = got_repo_open(&repo,
9405 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
9406 if (error != NULL)
9407 goto done;
9409 error = apply_unveil(got_repo_get_path(repo), 0,
9410 worktree ? got_worktree_get_root_path(worktree) : NULL);
9411 if (error)
9412 goto done;
9414 if (list_backups || delete_backups) {
9415 error = process_backup_refs(
9416 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
9417 argc == 1 ? argv[0] : NULL, delete_backups, repo);
9418 goto done; /* nothing else to do */
9421 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9422 worktree);
9423 if (error)
9424 goto done;
9425 if (histedit_in_progress) {
9426 error = got_error(GOT_ERR_HISTEDIT_BUSY);
9427 goto done;
9430 error = got_worktree_merge_in_progress(&merge_in_progress,
9431 worktree, repo);
9432 if (error)
9433 goto done;
9434 if (merge_in_progress) {
9435 error = got_error(GOT_ERR_MERGE_BUSY);
9436 goto done;
9439 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9440 if (error)
9441 goto done;
9443 if (abort_rebase) {
9444 if (!rebase_in_progress) {
9445 error = got_error(GOT_ERR_NOT_REBASING);
9446 goto done;
9448 error = got_worktree_rebase_continue(&resume_commit_id,
9449 &new_base_branch, &tmp_branch, &branch, &fileindex,
9450 worktree, repo);
9451 if (error)
9452 goto done;
9453 printf("Switching work tree to %s\n",
9454 got_ref_get_symref_target(new_base_branch));
9455 error = got_worktree_rebase_abort(worktree, fileindex, repo,
9456 new_base_branch, abort_progress, &upa);
9457 if (error)
9458 goto done;
9459 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
9460 print_merge_progress_stats(&upa);
9461 goto done; /* nothing else to do */
9464 if (continue_rebase) {
9465 if (!rebase_in_progress) {
9466 error = got_error(GOT_ERR_NOT_REBASING);
9467 goto done;
9469 error = got_worktree_rebase_continue(&resume_commit_id,
9470 &new_base_branch, &tmp_branch, &branch, &fileindex,
9471 worktree, repo);
9472 if (error)
9473 goto done;
9475 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
9476 resume_commit_id, repo);
9477 if (error)
9478 goto done;
9480 yca_id = got_object_id_dup(resume_commit_id);
9481 if (yca_id == NULL) {
9482 error = got_error_from_errno("got_object_id_dup");
9483 goto done;
9485 } else {
9486 error = got_ref_open(&branch, repo, argv[0], 0);
9487 if (error != NULL)
9488 goto done;
9491 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
9492 if (error)
9493 goto done;
9495 if (!continue_rebase) {
9496 struct got_object_id *base_commit_id;
9498 base_commit_id = got_worktree_get_base_commit_id(worktree);
9499 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9500 base_commit_id, branch_head_commit_id, 1, repo,
9501 check_cancelled, NULL);
9502 if (error)
9503 goto done;
9504 if (yca_id == NULL) {
9505 error = got_error_msg(GOT_ERR_ANCESTRY,
9506 "specified branch shares no common ancestry "
9507 "with work tree's branch");
9508 goto done;
9511 error = check_same_branch(base_commit_id, branch, yca_id, repo);
9512 if (error) {
9513 if (error->code != GOT_ERR_ANCESTRY)
9514 goto done;
9515 error = NULL;
9516 } else {
9517 struct got_pathlist_head paths;
9518 printf("%s is already based on %s\n",
9519 got_ref_get_name(branch),
9520 got_worktree_get_head_ref_name(worktree));
9521 error = switch_head_ref(branch, branch_head_commit_id,
9522 worktree, repo);
9523 if (error)
9524 goto done;
9525 error = got_worktree_set_base_commit_id(worktree, repo,
9526 branch_head_commit_id);
9527 if (error)
9528 goto done;
9529 TAILQ_INIT(&paths);
9530 error = got_pathlist_append(&paths, "", NULL);
9531 if (error)
9532 goto done;
9533 error = got_worktree_checkout_files(worktree,
9534 &paths, repo, update_progress, &upa,
9535 check_cancelled, NULL);
9536 got_pathlist_free(&paths);
9537 if (error)
9538 goto done;
9539 if (upa.did_something) {
9540 char *id_str;
9541 error = got_object_id_str(&id_str,
9542 branch_head_commit_id);
9543 if (error)
9544 goto done;
9545 printf("Updated to %s: %s\n",
9546 got_worktree_get_head_ref_name(worktree),
9547 id_str);
9548 free(id_str);
9549 } else
9550 printf("Already up-to-date\n");
9551 print_update_progress_stats(&upa);
9552 goto done;
9556 commit_id = branch_head_commit_id;
9557 error = got_object_open_as_commit(&commit, repo, commit_id);
9558 if (error)
9559 goto done;
9561 parent_ids = got_object_commit_get_parent_ids(commit);
9562 pid = STAILQ_FIRST(parent_ids);
9563 if (pid == NULL) {
9564 error = got_error(GOT_ERR_EMPTY_REBASE);
9565 goto done;
9567 error = collect_commits(&commits, commit_id, &pid->id,
9568 yca_id, got_worktree_get_path_prefix(worktree),
9569 GOT_ERR_REBASE_PATH, repo);
9570 got_object_commit_close(commit);
9571 commit = NULL;
9572 if (error)
9573 goto done;
9575 if (!continue_rebase) {
9576 error = got_worktree_rebase_prepare(&new_base_branch,
9577 &tmp_branch, &fileindex, worktree, branch, repo);
9578 if (error)
9579 goto done;
9582 if (STAILQ_EMPTY(&commits)) {
9583 if (continue_rebase) {
9584 error = rebase_complete(worktree, fileindex,
9585 branch, new_base_branch, tmp_branch, repo,
9586 create_backup);
9587 goto done;
9588 } else {
9589 /* Fast-forward the reference of the branch. */
9590 struct got_object_id *new_head_commit_id;
9591 char *id_str;
9592 error = got_ref_resolve(&new_head_commit_id, repo,
9593 new_base_branch);
9594 if (error)
9595 goto done;
9596 error = got_object_id_str(&id_str, new_head_commit_id);
9597 printf("Forwarding %s to commit %s\n",
9598 got_ref_get_name(branch), id_str);
9599 free(id_str);
9600 error = got_ref_change_ref(branch,
9601 new_head_commit_id);
9602 if (error)
9603 goto done;
9604 /* No backup needed since objects did not change. */
9605 create_backup = 0;
9609 pid = NULL;
9610 STAILQ_FOREACH(qid, &commits, entry) {
9612 commit_id = &qid->id;
9613 parent_id = pid ? &pid->id : yca_id;
9614 pid = qid;
9616 memset(&upa, 0, sizeof(upa));
9617 error = got_worktree_rebase_merge_files(&merged_paths,
9618 worktree, fileindex, parent_id, commit_id, repo,
9619 update_progress, &upa, check_cancelled, NULL);
9620 if (error)
9621 goto done;
9623 print_merge_progress_stats(&upa);
9624 if (upa.conflicts > 0 || upa.missing > 0 ||
9625 upa.not_deleted > 0 || upa.unversioned > 0) {
9626 if (upa.conflicts > 0) {
9627 error = show_rebase_merge_conflict(&qid->id,
9628 repo);
9629 if (error)
9630 goto done;
9632 got_worktree_rebase_pathlist_free(&merged_paths);
9633 break;
9636 error = rebase_commit(&merged_paths, worktree, fileindex,
9637 tmp_branch, commit_id, repo);
9638 got_worktree_rebase_pathlist_free(&merged_paths);
9639 if (error)
9640 goto done;
9643 if (upa.conflicts > 0 || upa.missing > 0 ||
9644 upa.not_deleted > 0 || upa.unversioned > 0) {
9645 error = got_worktree_rebase_postpone(worktree, fileindex);
9646 if (error)
9647 goto done;
9648 if (upa.conflicts > 0 && upa.missing == 0 &&
9649 upa.not_deleted == 0 && upa.unversioned == 0) {
9650 error = got_error_msg(GOT_ERR_CONFLICTS,
9651 "conflicts must be resolved before rebasing "
9652 "can continue");
9653 } else if (upa.conflicts > 0) {
9654 error = got_error_msg(GOT_ERR_CONFLICTS,
9655 "conflicts must be resolved before rebasing "
9656 "can continue; changes destined for some "
9657 "files were not yet merged and should be "
9658 "merged manually if required before the "
9659 "rebase operation is continued");
9660 } else {
9661 error = got_error_msg(GOT_ERR_CONFLICTS,
9662 "changes destined for some files were not "
9663 "yet merged and should be merged manually "
9664 "if required before the rebase operation "
9665 "is continued");
9667 } else
9668 error = rebase_complete(worktree, fileindex, branch,
9669 new_base_branch, tmp_branch, repo, create_backup);
9670 done:
9671 got_object_id_queue_free(&commits);
9672 free(branch_head_commit_id);
9673 free(resume_commit_id);
9674 free(yca_id);
9675 if (commit)
9676 got_object_commit_close(commit);
9677 if (branch)
9678 got_ref_close(branch);
9679 if (new_base_branch)
9680 got_ref_close(new_base_branch);
9681 if (tmp_branch)
9682 got_ref_close(tmp_branch);
9683 if (worktree)
9684 got_worktree_close(worktree);
9685 if (repo) {
9686 const struct got_error *close_err = got_repo_close(repo);
9687 if (error == NULL)
9688 error = close_err;
9690 return error;
9693 __dead static void
9694 usage_histedit(void)
9696 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
9697 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
9698 getprogname());
9699 exit(1);
9702 #define GOT_HISTEDIT_PICK 'p'
9703 #define GOT_HISTEDIT_EDIT 'e'
9704 #define GOT_HISTEDIT_FOLD 'f'
9705 #define GOT_HISTEDIT_DROP 'd'
9706 #define GOT_HISTEDIT_MESG 'm'
9708 static const struct got_histedit_cmd {
9709 unsigned char code;
9710 const char *name;
9711 const char *desc;
9712 } got_histedit_cmds[] = {
9713 { GOT_HISTEDIT_PICK, "pick", "use commit" },
9714 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
9715 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
9716 "be used" },
9717 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
9718 { GOT_HISTEDIT_MESG, "mesg",
9719 "single-line log message for commit above (open editor if empty)" },
9722 struct got_histedit_list_entry {
9723 TAILQ_ENTRY(got_histedit_list_entry) entry;
9724 struct got_object_id *commit_id;
9725 const struct got_histedit_cmd *cmd;
9726 char *logmsg;
9728 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
9730 static const struct got_error *
9731 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
9732 FILE *f, struct got_repository *repo)
9734 const struct got_error *err = NULL;
9735 char *logmsg = NULL, *id_str = NULL;
9736 struct got_commit_object *commit = NULL;
9737 int n;
9739 err = got_object_open_as_commit(&commit, repo, commit_id);
9740 if (err)
9741 goto done;
9743 err = get_short_logmsg(&logmsg, 34, commit);
9744 if (err)
9745 goto done;
9747 err = got_object_id_str(&id_str, commit_id);
9748 if (err)
9749 goto done;
9751 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
9752 if (n < 0)
9753 err = got_ferror(f, GOT_ERR_IO);
9754 done:
9755 if (commit)
9756 got_object_commit_close(commit);
9757 free(id_str);
9758 free(logmsg);
9759 return err;
9762 static const struct got_error *
9763 histedit_write_commit_list(struct got_object_id_queue *commits,
9764 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
9765 struct got_repository *repo)
9767 const struct got_error *err = NULL;
9768 struct got_object_qid *qid;
9769 const char *histedit_cmd = NULL;
9771 if (STAILQ_EMPTY(commits))
9772 return got_error(GOT_ERR_EMPTY_HISTEDIT);
9774 STAILQ_FOREACH(qid, commits, entry) {
9775 histedit_cmd = got_histedit_cmds[0].name;
9776 if (edit_only)
9777 histedit_cmd = "edit";
9778 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
9779 histedit_cmd = "fold";
9780 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
9781 if (err)
9782 break;
9783 if (edit_logmsg_only) {
9784 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
9785 if (n < 0) {
9786 err = got_ferror(f, GOT_ERR_IO);
9787 break;
9792 return err;
9795 static const struct got_error *
9796 write_cmd_list(FILE *f, const char *branch_name,
9797 struct got_object_id_queue *commits)
9799 const struct got_error *err = NULL;
9800 size_t i;
9801 int n;
9802 char *id_str;
9803 struct got_object_qid *qid;
9805 qid = STAILQ_FIRST(commits);
9806 err = got_object_id_str(&id_str, &qid->id);
9807 if (err)
9808 return err;
9810 n = fprintf(f,
9811 "# Editing the history of branch '%s' starting at\n"
9812 "# commit %s\n"
9813 "# Commits will be processed in order from top to "
9814 "bottom of this file.\n", branch_name, id_str);
9815 if (n < 0) {
9816 err = got_ferror(f, GOT_ERR_IO);
9817 goto done;
9820 n = fprintf(f, "# Available histedit commands:\n");
9821 if (n < 0) {
9822 err = got_ferror(f, GOT_ERR_IO);
9823 goto done;
9826 for (i = 0; i < nitems(got_histedit_cmds); i++) {
9827 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
9828 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
9829 cmd->desc);
9830 if (n < 0) {
9831 err = got_ferror(f, GOT_ERR_IO);
9832 break;
9835 done:
9836 free(id_str);
9837 return err;
9840 static const struct got_error *
9841 histedit_syntax_error(int lineno)
9843 static char msg[42];
9844 int ret;
9846 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
9847 lineno);
9848 if (ret == -1 || ret >= sizeof(msg))
9849 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
9851 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
9854 static const struct got_error *
9855 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
9856 char *logmsg, struct got_repository *repo)
9858 const struct got_error *err;
9859 struct got_commit_object *folded_commit = NULL;
9860 char *id_str, *folded_logmsg = NULL;
9862 err = got_object_id_str(&id_str, hle->commit_id);
9863 if (err)
9864 return err;
9866 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
9867 if (err)
9868 goto done;
9870 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
9871 if (err)
9872 goto done;
9873 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
9874 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
9875 folded_logmsg) == -1) {
9876 err = got_error_from_errno("asprintf");
9878 done:
9879 if (folded_commit)
9880 got_object_commit_close(folded_commit);
9881 free(id_str);
9882 free(folded_logmsg);
9883 return err;
9886 static struct got_histedit_list_entry *
9887 get_folded_commits(struct got_histedit_list_entry *hle)
9889 struct got_histedit_list_entry *prev, *folded = NULL;
9891 prev = TAILQ_PREV(hle, got_histedit_list, entry);
9892 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
9893 prev->cmd->code == GOT_HISTEDIT_DROP)) {
9894 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
9895 folded = prev;
9896 prev = TAILQ_PREV(prev, got_histedit_list, entry);
9899 return folded;
9902 static const struct got_error *
9903 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
9904 struct got_repository *repo)
9906 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
9907 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
9908 const struct got_error *err = NULL;
9909 struct got_commit_object *commit = NULL;
9910 int logmsg_len;
9911 int fd;
9912 struct got_histedit_list_entry *folded = NULL;
9914 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
9915 if (err)
9916 return err;
9918 folded = get_folded_commits(hle);
9919 if (folded) {
9920 while (folded != hle) {
9921 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
9922 folded = TAILQ_NEXT(folded, entry);
9923 continue;
9925 err = append_folded_commit_msg(&new_msg, folded,
9926 logmsg, repo);
9927 if (err)
9928 goto done;
9929 free(logmsg);
9930 logmsg = new_msg;
9931 folded = TAILQ_NEXT(folded, entry);
9935 err = got_object_id_str(&id_str, hle->commit_id);
9936 if (err)
9937 goto done;
9938 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
9939 if (err)
9940 goto done;
9941 logmsg_len = asprintf(&new_msg,
9942 "%s\n# original log message of commit %s: %s",
9943 logmsg ? logmsg : "", id_str, orig_logmsg);
9944 if (logmsg_len == -1) {
9945 err = got_error_from_errno("asprintf");
9946 goto done;
9948 free(logmsg);
9949 logmsg = new_msg;
9951 err = got_object_id_str(&id_str, hle->commit_id);
9952 if (err)
9953 goto done;
9955 err = got_opentemp_named_fd(&logmsg_path, &fd,
9956 GOT_TMPDIR_STR "/got-logmsg");
9957 if (err)
9958 goto done;
9960 write(fd, logmsg, logmsg_len);
9961 close(fd);
9963 err = get_editor(&editor);
9964 if (err)
9965 goto done;
9967 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
9968 logmsg_len, 0);
9969 if (err) {
9970 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
9971 goto done;
9972 err = NULL;
9973 hle->logmsg = strdup(new_msg);
9974 if (hle->logmsg == NULL)
9975 err = got_error_from_errno("strdup");
9977 done:
9978 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
9979 err = got_error_from_errno2("unlink", logmsg_path);
9980 free(logmsg_path);
9981 free(logmsg);
9982 free(orig_logmsg);
9983 free(editor);
9984 if (commit)
9985 got_object_commit_close(commit);
9986 return err;
9989 static const struct got_error *
9990 histedit_parse_list(struct got_histedit_list *histedit_cmds,
9991 FILE *f, struct got_repository *repo)
9993 const struct got_error *err = NULL;
9994 char *line = NULL, *p, *end;
9995 size_t i, size;
9996 ssize_t len;
9997 int lineno = 0;
9998 const struct got_histedit_cmd *cmd;
9999 struct got_object_id *commit_id = NULL;
10000 struct got_histedit_list_entry *hle = NULL;
10002 for (;;) {
10003 len = getline(&line, &size, f);
10004 if (len == -1) {
10005 const struct got_error *getline_err;
10006 if (feof(f))
10007 break;
10008 getline_err = got_error_from_errno("getline");
10009 err = got_ferror(f, getline_err->code);
10010 break;
10012 lineno++;
10013 p = line;
10014 while (isspace((unsigned char)p[0]))
10015 p++;
10016 if (p[0] == '#' || p[0] == '\0') {
10017 free(line);
10018 line = NULL;
10019 continue;
10021 cmd = NULL;
10022 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10023 cmd = &got_histedit_cmds[i];
10024 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10025 isspace((unsigned char)p[strlen(cmd->name)])) {
10026 p += strlen(cmd->name);
10027 break;
10029 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10030 p++;
10031 break;
10034 if (i == nitems(got_histedit_cmds)) {
10035 err = histedit_syntax_error(lineno);
10036 break;
10038 while (isspace((unsigned char)p[0]))
10039 p++;
10040 if (cmd->code == GOT_HISTEDIT_MESG) {
10041 if (hle == NULL || hle->logmsg != NULL) {
10042 err = got_error(GOT_ERR_HISTEDIT_CMD);
10043 break;
10045 if (p[0] == '\0') {
10046 err = histedit_edit_logmsg(hle, repo);
10047 if (err)
10048 break;
10049 } else {
10050 hle->logmsg = strdup(p);
10051 if (hle->logmsg == NULL) {
10052 err = got_error_from_errno("strdup");
10053 break;
10056 free(line);
10057 line = NULL;
10058 continue;
10059 } else {
10060 end = p;
10061 while (end[0] && !isspace((unsigned char)end[0]))
10062 end++;
10063 *end = '\0';
10065 err = got_object_resolve_id_str(&commit_id, repo, p);
10066 if (err) {
10067 /* override error code */
10068 err = histedit_syntax_error(lineno);
10069 break;
10072 hle = malloc(sizeof(*hle));
10073 if (hle == NULL) {
10074 err = got_error_from_errno("malloc");
10075 break;
10077 hle->cmd = cmd;
10078 hle->commit_id = commit_id;
10079 hle->logmsg = NULL;
10080 commit_id = NULL;
10081 free(line);
10082 line = NULL;
10083 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10086 free(line);
10087 free(commit_id);
10088 return err;
10091 static const struct got_error *
10092 histedit_check_script(struct got_histedit_list *histedit_cmds,
10093 struct got_object_id_queue *commits, struct got_repository *repo)
10095 const struct got_error *err = NULL;
10096 struct got_object_qid *qid;
10097 struct got_histedit_list_entry *hle;
10098 static char msg[92];
10099 char *id_str;
10101 if (TAILQ_EMPTY(histedit_cmds))
10102 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10103 "histedit script contains no commands");
10104 if (STAILQ_EMPTY(commits))
10105 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10107 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10108 struct got_histedit_list_entry *hle2;
10109 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10110 if (hle == hle2)
10111 continue;
10112 if (got_object_id_cmp(hle->commit_id,
10113 hle2->commit_id) != 0)
10114 continue;
10115 err = got_object_id_str(&id_str, hle->commit_id);
10116 if (err)
10117 return err;
10118 snprintf(msg, sizeof(msg), "commit %s is listed "
10119 "more than once in histedit script", id_str);
10120 free(id_str);
10121 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10125 STAILQ_FOREACH(qid, commits, entry) {
10126 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10127 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10128 break;
10130 if (hle == NULL) {
10131 err = got_object_id_str(&id_str, &qid->id);
10132 if (err)
10133 return err;
10134 snprintf(msg, sizeof(msg),
10135 "commit %s missing from histedit script", id_str);
10136 free(id_str);
10137 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10141 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10142 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10143 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10144 "last commit in histedit script cannot be folded");
10146 return NULL;
10149 static const struct got_error *
10150 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10151 const char *path, struct got_object_id_queue *commits,
10152 struct got_repository *repo)
10154 const struct got_error *err = NULL;
10155 char *editor;
10156 FILE *f = NULL;
10158 err = get_editor(&editor);
10159 if (err)
10160 return err;
10162 if (spawn_editor(editor, path) == -1) {
10163 err = got_error_from_errno("failed spawning editor");
10164 goto done;
10167 f = fopen(path, "re");
10168 if (f == NULL) {
10169 err = got_error_from_errno("fopen");
10170 goto done;
10172 err = histedit_parse_list(histedit_cmds, f, repo);
10173 if (err)
10174 goto done;
10176 err = histedit_check_script(histedit_cmds, commits, repo);
10177 done:
10178 if (f && fclose(f) == EOF && err == NULL)
10179 err = got_error_from_errno("fclose");
10180 free(editor);
10181 return err;
10184 static const struct got_error *
10185 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10186 struct got_object_id_queue *, const char *, const char *,
10187 struct got_repository *);
10189 static const struct got_error *
10190 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10191 struct got_object_id_queue *commits, const char *branch_name,
10192 int edit_logmsg_only, int fold_only, int edit_only,
10193 struct got_repository *repo)
10195 const struct got_error *err;
10196 FILE *f = NULL;
10197 char *path = NULL;
10199 err = got_opentemp_named(&path, &f, "got-histedit");
10200 if (err)
10201 return err;
10203 err = write_cmd_list(f, branch_name, commits);
10204 if (err)
10205 goto done;
10207 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10208 fold_only, edit_only, repo);
10209 if (err)
10210 goto done;
10212 if (edit_logmsg_only || fold_only || edit_only) {
10213 rewind(f);
10214 err = histedit_parse_list(histedit_cmds, f, repo);
10215 } else {
10216 if (fclose(f) == EOF) {
10217 err = got_error_from_errno("fclose");
10218 goto done;
10220 f = NULL;
10221 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10222 if (err) {
10223 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10224 err->code != GOT_ERR_HISTEDIT_CMD)
10225 goto done;
10226 err = histedit_edit_list_retry(histedit_cmds, err,
10227 commits, path, branch_name, repo);
10230 done:
10231 if (f && fclose(f) == EOF && err == NULL)
10232 err = got_error_from_errno("fclose");
10233 if (path && unlink(path) != 0 && err == NULL)
10234 err = got_error_from_errno2("unlink", path);
10235 free(path);
10236 return err;
10239 static const struct got_error *
10240 histedit_save_list(struct got_histedit_list *histedit_cmds,
10241 struct got_worktree *worktree, struct got_repository *repo)
10243 const struct got_error *err = NULL;
10244 char *path = NULL;
10245 FILE *f = NULL;
10246 struct got_histedit_list_entry *hle;
10247 struct got_commit_object *commit = NULL;
10249 err = got_worktree_get_histedit_script_path(&path, worktree);
10250 if (err)
10251 return err;
10253 f = fopen(path, "we");
10254 if (f == NULL) {
10255 err = got_error_from_errno2("fopen", path);
10256 goto done;
10258 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10259 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10260 repo);
10261 if (err)
10262 break;
10264 if (hle->logmsg) {
10265 int n = fprintf(f, "%c %s\n",
10266 GOT_HISTEDIT_MESG, hle->logmsg);
10267 if (n < 0) {
10268 err = got_ferror(f, GOT_ERR_IO);
10269 break;
10273 done:
10274 if (f && fclose(f) == EOF && err == NULL)
10275 err = got_error_from_errno("fclose");
10276 free(path);
10277 if (commit)
10278 got_object_commit_close(commit);
10279 return err;
10282 void
10283 histedit_free_list(struct got_histedit_list *histedit_cmds)
10285 struct got_histedit_list_entry *hle;
10287 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10288 TAILQ_REMOVE(histedit_cmds, hle, entry);
10289 free(hle);
10293 static const struct got_error *
10294 histedit_load_list(struct got_histedit_list *histedit_cmds,
10295 const char *path, struct got_repository *repo)
10297 const struct got_error *err = NULL;
10298 FILE *f = NULL;
10300 f = fopen(path, "re");
10301 if (f == NULL) {
10302 err = got_error_from_errno2("fopen", path);
10303 goto done;
10306 err = histedit_parse_list(histedit_cmds, f, repo);
10307 done:
10308 if (f && fclose(f) == EOF && err == NULL)
10309 err = got_error_from_errno("fclose");
10310 return err;
10313 static const struct got_error *
10314 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10315 const struct got_error *edit_err, struct got_object_id_queue *commits,
10316 const char *path, const char *branch_name, struct got_repository *repo)
10318 const struct got_error *err = NULL, *prev_err = edit_err;
10319 int resp = ' ';
10321 while (resp != 'c' && resp != 'r' && resp != 'a') {
10322 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10323 "or (a)bort: ", getprogname(), prev_err->msg);
10324 resp = getchar();
10325 if (resp == '\n')
10326 resp = getchar();
10327 if (resp == 'c') {
10328 histedit_free_list(histedit_cmds);
10329 err = histedit_run_editor(histedit_cmds, path, commits,
10330 repo);
10331 if (err) {
10332 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10333 err->code != GOT_ERR_HISTEDIT_CMD)
10334 break;
10335 prev_err = err;
10336 resp = ' ';
10337 continue;
10339 break;
10340 } else if (resp == 'r') {
10341 histedit_free_list(histedit_cmds);
10342 err = histedit_edit_script(histedit_cmds,
10343 commits, branch_name, 0, 0, 0, repo);
10344 if (err) {
10345 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10346 err->code != GOT_ERR_HISTEDIT_CMD)
10347 break;
10348 prev_err = err;
10349 resp = ' ';
10350 continue;
10352 break;
10353 } else if (resp == 'a') {
10354 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
10355 break;
10356 } else
10357 printf("invalid response '%c'\n", resp);
10360 return err;
10363 static const struct got_error *
10364 histedit_complete(struct got_worktree *worktree,
10365 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
10366 struct got_reference *branch, struct got_repository *repo)
10368 printf("Switching work tree to %s\n",
10369 got_ref_get_symref_target(branch));
10370 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
10371 branch, repo);
10374 static const struct got_error *
10375 show_histedit_progress(struct got_commit_object *commit,
10376 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
10378 const struct got_error *err;
10379 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10381 err = got_object_id_str(&old_id_str, hle->commit_id);
10382 if (err)
10383 goto done;
10385 if (new_id) {
10386 err = got_object_id_str(&new_id_str, new_id);
10387 if (err)
10388 goto done;
10391 old_id_str[12] = '\0';
10392 if (new_id_str)
10393 new_id_str[12] = '\0';
10395 if (hle->logmsg) {
10396 logmsg = strdup(hle->logmsg);
10397 if (logmsg == NULL) {
10398 err = got_error_from_errno("strdup");
10399 goto done;
10401 trim_logmsg(logmsg, 42);
10402 } else {
10403 err = get_short_logmsg(&logmsg, 42, commit);
10404 if (err)
10405 goto done;
10408 switch (hle->cmd->code) {
10409 case GOT_HISTEDIT_PICK:
10410 case GOT_HISTEDIT_EDIT:
10411 printf("%s -> %s: %s\n", old_id_str,
10412 new_id_str ? new_id_str : "no-op change", logmsg);
10413 break;
10414 case GOT_HISTEDIT_DROP:
10415 case GOT_HISTEDIT_FOLD:
10416 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
10417 logmsg);
10418 break;
10419 default:
10420 break;
10422 done:
10423 free(old_id_str);
10424 free(new_id_str);
10425 return err;
10428 static const struct got_error *
10429 histedit_commit(struct got_pathlist_head *merged_paths,
10430 struct got_worktree *worktree, struct got_fileindex *fileindex,
10431 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
10432 struct got_repository *repo)
10434 const struct got_error *err;
10435 struct got_commit_object *commit;
10436 struct got_object_id *new_commit_id;
10438 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
10439 && hle->logmsg == NULL) {
10440 err = histedit_edit_logmsg(hle, repo);
10441 if (err)
10442 return err;
10445 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10446 if (err)
10447 return err;
10449 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
10450 worktree, fileindex, tmp_branch, commit, hle->commit_id,
10451 hle->logmsg, repo);
10452 if (err) {
10453 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
10454 goto done;
10455 err = show_histedit_progress(commit, hle, NULL);
10456 } else {
10457 err = show_histedit_progress(commit, hle, new_commit_id);
10458 free(new_commit_id);
10460 done:
10461 got_object_commit_close(commit);
10462 return err;
10465 static const struct got_error *
10466 histedit_skip_commit(struct got_histedit_list_entry *hle,
10467 struct got_worktree *worktree, struct got_repository *repo)
10469 const struct got_error *error;
10470 struct got_commit_object *commit;
10472 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
10473 repo);
10474 if (error)
10475 return error;
10477 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
10478 if (error)
10479 return error;
10481 error = show_histedit_progress(commit, hle, NULL);
10482 got_object_commit_close(commit);
10483 return error;
10486 static const struct got_error *
10487 check_local_changes(void *arg, unsigned char status,
10488 unsigned char staged_status, const char *path,
10489 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
10490 struct got_object_id *commit_id, int dirfd, const char *de_name)
10492 int *have_local_changes = arg;
10494 switch (status) {
10495 case GOT_STATUS_ADD:
10496 case GOT_STATUS_DELETE:
10497 case GOT_STATUS_MODIFY:
10498 case GOT_STATUS_CONFLICT:
10499 *have_local_changes = 1;
10500 return got_error(GOT_ERR_CANCELLED);
10501 default:
10502 break;
10505 switch (staged_status) {
10506 case GOT_STATUS_ADD:
10507 case GOT_STATUS_DELETE:
10508 case GOT_STATUS_MODIFY:
10509 *have_local_changes = 1;
10510 return got_error(GOT_ERR_CANCELLED);
10511 default:
10512 break;
10515 return NULL;
10518 static const struct got_error *
10519 cmd_histedit(int argc, char *argv[])
10521 const struct got_error *error = NULL;
10522 struct got_worktree *worktree = NULL;
10523 struct got_fileindex *fileindex = NULL;
10524 struct got_repository *repo = NULL;
10525 char *cwd = NULL;
10526 struct got_reference *branch = NULL;
10527 struct got_reference *tmp_branch = NULL;
10528 struct got_object_id *resume_commit_id = NULL;
10529 struct got_object_id *base_commit_id = NULL;
10530 struct got_object_id *head_commit_id = NULL;
10531 struct got_commit_object *commit = NULL;
10532 int ch, rebase_in_progress = 0, merge_in_progress = 0;
10533 struct got_update_progress_arg upa;
10534 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
10535 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
10536 int list_backups = 0, delete_backups = 0;
10537 const char *edit_script_path = NULL;
10538 struct got_object_id_queue commits;
10539 struct got_pathlist_head merged_paths;
10540 const struct got_object_id_queue *parent_ids;
10541 struct got_object_qid *pid;
10542 struct got_histedit_list histedit_cmds;
10543 struct got_histedit_list_entry *hle;
10545 STAILQ_INIT(&commits);
10546 TAILQ_INIT(&histedit_cmds);
10547 TAILQ_INIT(&merged_paths);
10548 memset(&upa, 0, sizeof(upa));
10550 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
10551 switch (ch) {
10552 case 'a':
10553 abort_edit = 1;
10554 break;
10555 case 'c':
10556 continue_edit = 1;
10557 break;
10558 case 'e':
10559 edit_only = 1;
10560 break;
10561 case 'f':
10562 fold_only = 1;
10563 break;
10564 case 'F':
10565 edit_script_path = optarg;
10566 break;
10567 case 'm':
10568 edit_logmsg_only = 1;
10569 break;
10570 case 'l':
10571 list_backups = 1;
10572 break;
10573 case 'X':
10574 delete_backups = 1;
10575 break;
10576 default:
10577 usage_histedit();
10578 /* NOTREACHED */
10582 argc -= optind;
10583 argv += optind;
10585 #ifndef PROFILE
10586 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10587 "unveil", NULL) == -1)
10588 err(1, "pledge");
10589 #endif
10590 if (abort_edit && continue_edit)
10591 option_conflict('a', 'c');
10592 if (edit_script_path && edit_logmsg_only)
10593 option_conflict('F', 'm');
10594 if (abort_edit && edit_logmsg_only)
10595 option_conflict('a', 'm');
10596 if (continue_edit && edit_logmsg_only)
10597 option_conflict('c', 'm');
10598 if (abort_edit && fold_only)
10599 option_conflict('a', 'f');
10600 if (continue_edit && fold_only)
10601 option_conflict('c', 'f');
10602 if (fold_only && edit_logmsg_only)
10603 option_conflict('f', 'm');
10604 if (edit_script_path && fold_only)
10605 option_conflict('F', 'f');
10606 if (abort_edit && edit_only)
10607 option_conflict('a', 'e');
10608 if (continue_edit && edit_only)
10609 option_conflict('c', 'e');
10610 if (edit_only && edit_logmsg_only)
10611 option_conflict('e', 'm');
10612 if (edit_script_path && edit_only)
10613 option_conflict('F', 'e');
10614 if (list_backups) {
10615 if (abort_edit)
10616 option_conflict('l', 'a');
10617 if (continue_edit)
10618 option_conflict('l', 'c');
10619 if (edit_script_path)
10620 option_conflict('l', 'F');
10621 if (edit_logmsg_only)
10622 option_conflict('l', 'm');
10623 if (fold_only)
10624 option_conflict('l', 'f');
10625 if (edit_only)
10626 option_conflict('l', 'e');
10627 if (delete_backups)
10628 option_conflict('l', 'X');
10629 if (argc != 0 && argc != 1)
10630 usage_histedit();
10631 } else if (delete_backups) {
10632 if (abort_edit)
10633 option_conflict('X', 'a');
10634 if (continue_edit)
10635 option_conflict('X', 'c');
10636 if (edit_script_path)
10637 option_conflict('X', 'F');
10638 if (edit_logmsg_only)
10639 option_conflict('X', 'm');
10640 if (fold_only)
10641 option_conflict('X', 'f');
10642 if (edit_only)
10643 option_conflict('X', 'e');
10644 if (list_backups)
10645 option_conflict('X', 'l');
10646 if (argc != 0 && argc != 1)
10647 usage_histedit();
10648 } else if (argc != 0)
10649 usage_histedit();
10652 * This command cannot apply unveil(2) in all cases because the
10653 * user may choose to run an editor to edit the histedit script
10654 * and to edit individual commit log messages.
10655 * unveil(2) traverses exec(2); if an editor is used we have to
10656 * apply unveil after edit script and log messages have been written.
10657 * XXX TODO: Make use of unveil(2) where possible.
10660 cwd = getcwd(NULL, 0);
10661 if (cwd == NULL) {
10662 error = got_error_from_errno("getcwd");
10663 goto done;
10665 error = got_worktree_open(&worktree, cwd);
10666 if (error) {
10667 if (list_backups || delete_backups) {
10668 if (error->code != GOT_ERR_NOT_WORKTREE)
10669 goto done;
10670 } else {
10671 if (error->code == GOT_ERR_NOT_WORKTREE)
10672 error = wrap_not_worktree_error(error,
10673 "histedit", cwd);
10674 goto done;
10678 if (list_backups || delete_backups) {
10679 error = got_repo_open(&repo,
10680 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10681 NULL);
10682 if (error != NULL)
10683 goto done;
10684 error = apply_unveil(got_repo_get_path(repo), 0,
10685 worktree ? got_worktree_get_root_path(worktree) : NULL);
10686 if (error)
10687 goto done;
10688 error = process_backup_refs(
10689 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
10690 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10691 goto done; /* nothing else to do */
10694 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
10695 NULL);
10696 if (error != NULL)
10697 goto done;
10699 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10700 if (error)
10701 goto done;
10702 if (rebase_in_progress) {
10703 error = got_error(GOT_ERR_REBASING);
10704 goto done;
10707 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10708 repo);
10709 if (error)
10710 goto done;
10711 if (merge_in_progress) {
10712 error = got_error(GOT_ERR_MERGE_BUSY);
10713 goto done;
10716 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
10717 if (error)
10718 goto done;
10720 if (edit_in_progress && edit_logmsg_only) {
10721 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10722 "histedit operation is in progress in this "
10723 "work tree and must be continued or aborted "
10724 "before the -m option can be used");
10725 goto done;
10727 if (edit_in_progress && fold_only) {
10728 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10729 "histedit operation is in progress in this "
10730 "work tree and must be continued or aborted "
10731 "before the -f option can be used");
10732 goto done;
10734 if (edit_in_progress && edit_only) {
10735 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
10736 "histedit operation is in progress in this "
10737 "work tree and must be continued or aborted "
10738 "before the -e option can be used");
10739 goto done;
10742 if (edit_in_progress && abort_edit) {
10743 error = got_worktree_histedit_continue(&resume_commit_id,
10744 &tmp_branch, &branch, &base_commit_id, &fileindex,
10745 worktree, repo);
10746 if (error)
10747 goto done;
10748 printf("Switching work tree to %s\n",
10749 got_ref_get_symref_target(branch));
10750 error = got_worktree_histedit_abort(worktree, fileindex, repo,
10751 branch, base_commit_id, abort_progress, &upa);
10752 if (error)
10753 goto done;
10754 printf("Histedit of %s aborted\n",
10755 got_ref_get_symref_target(branch));
10756 print_merge_progress_stats(&upa);
10757 goto done; /* nothing else to do */
10758 } else if (abort_edit) {
10759 error = got_error(GOT_ERR_NOT_HISTEDIT);
10760 goto done;
10763 if (continue_edit) {
10764 char *path;
10766 if (!edit_in_progress) {
10767 error = got_error(GOT_ERR_NOT_HISTEDIT);
10768 goto done;
10771 error = got_worktree_get_histedit_script_path(&path, worktree);
10772 if (error)
10773 goto done;
10775 error = histedit_load_list(&histedit_cmds, path, repo);
10776 free(path);
10777 if (error)
10778 goto done;
10780 error = got_worktree_histedit_continue(&resume_commit_id,
10781 &tmp_branch, &branch, &base_commit_id, &fileindex,
10782 worktree, repo);
10783 if (error)
10784 goto done;
10786 error = got_ref_resolve(&head_commit_id, repo, branch);
10787 if (error)
10788 goto done;
10790 error = got_object_open_as_commit(&commit, repo,
10791 head_commit_id);
10792 if (error)
10793 goto done;
10794 parent_ids = got_object_commit_get_parent_ids(commit);
10795 pid = STAILQ_FIRST(parent_ids);
10796 if (pid == NULL) {
10797 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10798 goto done;
10800 error = collect_commits(&commits, head_commit_id, &pid->id,
10801 base_commit_id, got_worktree_get_path_prefix(worktree),
10802 GOT_ERR_HISTEDIT_PATH, repo);
10803 got_object_commit_close(commit);
10804 commit = NULL;
10805 if (error)
10806 goto done;
10807 } else {
10808 if (edit_in_progress) {
10809 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10810 goto done;
10813 error = got_ref_open(&branch, repo,
10814 got_worktree_get_head_ref_name(worktree), 0);
10815 if (error != NULL)
10816 goto done;
10818 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10819 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10820 "will not edit commit history of a branch outside "
10821 "the \"refs/heads/\" reference namespace");
10822 goto done;
10825 error = got_ref_resolve(&head_commit_id, repo, branch);
10826 got_ref_close(branch);
10827 branch = NULL;
10828 if (error)
10829 goto done;
10831 error = got_object_open_as_commit(&commit, repo,
10832 head_commit_id);
10833 if (error)
10834 goto done;
10835 parent_ids = got_object_commit_get_parent_ids(commit);
10836 pid = STAILQ_FIRST(parent_ids);
10837 if (pid == NULL) {
10838 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10839 goto done;
10841 error = collect_commits(&commits, head_commit_id, &pid->id,
10842 got_worktree_get_base_commit_id(worktree),
10843 got_worktree_get_path_prefix(worktree),
10844 GOT_ERR_HISTEDIT_PATH, repo);
10845 got_object_commit_close(commit);
10846 commit = NULL;
10847 if (error)
10848 goto done;
10850 if (STAILQ_EMPTY(&commits)) {
10851 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
10852 goto done;
10855 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
10856 &base_commit_id, &fileindex, worktree, repo);
10857 if (error)
10858 goto done;
10860 if (edit_script_path) {
10861 error = histedit_load_list(&histedit_cmds,
10862 edit_script_path, repo);
10863 if (error) {
10864 got_worktree_histedit_abort(worktree, fileindex,
10865 repo, branch, base_commit_id,
10866 abort_progress, &upa);
10867 print_merge_progress_stats(&upa);
10868 goto done;
10870 } else {
10871 const char *branch_name;
10872 branch_name = got_ref_get_symref_target(branch);
10873 if (strncmp(branch_name, "refs/heads/", 11) == 0)
10874 branch_name += 11;
10875 error = histedit_edit_script(&histedit_cmds, &commits,
10876 branch_name, edit_logmsg_only, fold_only,
10877 edit_only, repo);
10878 if (error) {
10879 got_worktree_histedit_abort(worktree, fileindex,
10880 repo, branch, base_commit_id,
10881 abort_progress, &upa);
10882 print_merge_progress_stats(&upa);
10883 goto done;
10888 error = histedit_save_list(&histedit_cmds, worktree,
10889 repo);
10890 if (error) {
10891 got_worktree_histedit_abort(worktree, fileindex,
10892 repo, branch, base_commit_id,
10893 abort_progress, &upa);
10894 print_merge_progress_stats(&upa);
10895 goto done;
10900 error = histedit_check_script(&histedit_cmds, &commits, repo);
10901 if (error)
10902 goto done;
10904 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
10905 if (resume_commit_id) {
10906 if (got_object_id_cmp(hle->commit_id,
10907 resume_commit_id) != 0)
10908 continue;
10910 resume_commit_id = NULL;
10911 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
10912 hle->cmd->code == GOT_HISTEDIT_FOLD) {
10913 error = histedit_skip_commit(hle, worktree,
10914 repo);
10915 if (error)
10916 goto done;
10917 } else {
10918 struct got_pathlist_head paths;
10919 int have_changes = 0;
10921 TAILQ_INIT(&paths);
10922 error = got_pathlist_append(&paths, "", NULL);
10923 if (error)
10924 goto done;
10925 error = got_worktree_status(worktree, &paths,
10926 repo, 0, check_local_changes, &have_changes,
10927 check_cancelled, NULL);
10928 got_pathlist_free(&paths);
10929 if (error) {
10930 if (error->code != GOT_ERR_CANCELLED)
10931 goto done;
10932 if (sigint_received || sigpipe_received)
10933 goto done;
10935 if (have_changes) {
10936 error = histedit_commit(NULL, worktree,
10937 fileindex, tmp_branch, hle, repo);
10938 if (error)
10939 goto done;
10940 } else {
10941 error = got_object_open_as_commit(
10942 &commit, repo, hle->commit_id);
10943 if (error)
10944 goto done;
10945 error = show_histedit_progress(commit,
10946 hle, NULL);
10947 got_object_commit_close(commit);
10948 commit = NULL;
10949 if (error)
10950 goto done;
10953 continue;
10956 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
10957 error = histedit_skip_commit(hle, worktree, repo);
10958 if (error)
10959 goto done;
10960 continue;
10963 error = got_object_open_as_commit(&commit, repo,
10964 hle->commit_id);
10965 if (error)
10966 goto done;
10967 parent_ids = got_object_commit_get_parent_ids(commit);
10968 pid = STAILQ_FIRST(parent_ids);
10970 error = got_worktree_histedit_merge_files(&merged_paths,
10971 worktree, fileindex, &pid->id, hle->commit_id, repo,
10972 update_progress, &upa, check_cancelled, NULL);
10973 if (error)
10974 goto done;
10975 got_object_commit_close(commit);
10976 commit = NULL;
10978 print_merge_progress_stats(&upa);
10979 if (upa.conflicts > 0 || upa.missing > 0 ||
10980 upa.not_deleted > 0 || upa.unversioned > 0) {
10981 if (upa.conflicts > 0) {
10982 error = show_rebase_merge_conflict(
10983 hle->commit_id, repo);
10984 if (error)
10985 goto done;
10987 got_worktree_rebase_pathlist_free(&merged_paths);
10988 break;
10991 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
10992 char *id_str;
10993 error = got_object_id_str(&id_str, hle->commit_id);
10994 if (error)
10995 goto done;
10996 printf("Stopping histedit for amending commit %s\n",
10997 id_str);
10998 free(id_str);
10999 got_worktree_rebase_pathlist_free(&merged_paths);
11000 error = got_worktree_histedit_postpone(worktree,
11001 fileindex);
11002 goto done;
11005 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11006 error = histedit_skip_commit(hle, worktree, repo);
11007 if (error)
11008 goto done;
11009 continue;
11012 error = histedit_commit(&merged_paths, worktree, fileindex,
11013 tmp_branch, hle, repo);
11014 got_worktree_rebase_pathlist_free(&merged_paths);
11015 if (error)
11016 goto done;
11019 if (upa.conflicts > 0 || upa.missing > 0 ||
11020 upa.not_deleted > 0 || upa.unversioned > 0) {
11021 error = got_worktree_histedit_postpone(worktree, fileindex);
11022 if (error)
11023 goto done;
11024 if (upa.conflicts > 0 && upa.missing == 0 &&
11025 upa.not_deleted == 0 && upa.unversioned == 0) {
11026 error = got_error_msg(GOT_ERR_CONFLICTS,
11027 "conflicts must be resolved before histedit "
11028 "can continue");
11029 } else if (upa.conflicts > 0) {
11030 error = got_error_msg(GOT_ERR_CONFLICTS,
11031 "conflicts must be resolved before histedit "
11032 "can continue; changes destined for some "
11033 "files were not yet merged and should be "
11034 "merged manually if required before the "
11035 "histedit operation is continued");
11036 } else {
11037 error = got_error_msg(GOT_ERR_CONFLICTS,
11038 "changes destined for some files were not "
11039 "yet merged and should be merged manually "
11040 "if required before the histedit operation "
11041 "is continued");
11043 } else
11044 error = histedit_complete(worktree, fileindex, tmp_branch,
11045 branch, repo);
11046 done:
11047 got_object_id_queue_free(&commits);
11048 histedit_free_list(&histedit_cmds);
11049 free(head_commit_id);
11050 free(base_commit_id);
11051 free(resume_commit_id);
11052 if (commit)
11053 got_object_commit_close(commit);
11054 if (branch)
11055 got_ref_close(branch);
11056 if (tmp_branch)
11057 got_ref_close(tmp_branch);
11058 if (worktree)
11059 got_worktree_close(worktree);
11060 if (repo) {
11061 const struct got_error *close_err = got_repo_close(repo);
11062 if (error == NULL)
11063 error = close_err;
11065 return error;
11068 __dead static void
11069 usage_integrate(void)
11071 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11072 exit(1);
11075 static const struct got_error *
11076 cmd_integrate(int argc, char *argv[])
11078 const struct got_error *error = NULL;
11079 struct got_repository *repo = NULL;
11080 struct got_worktree *worktree = NULL;
11081 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11082 const char *branch_arg = NULL;
11083 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11084 struct got_fileindex *fileindex = NULL;
11085 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11086 int ch;
11087 struct got_update_progress_arg upa;
11089 while ((ch = getopt(argc, argv, "")) != -1) {
11090 switch (ch) {
11091 default:
11092 usage_integrate();
11093 /* NOTREACHED */
11097 argc -= optind;
11098 argv += optind;
11100 if (argc != 1)
11101 usage_integrate();
11102 branch_arg = argv[0];
11103 #ifndef PROFILE
11104 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11105 "unveil", NULL) == -1)
11106 err(1, "pledge");
11107 #endif
11108 cwd = getcwd(NULL, 0);
11109 if (cwd == NULL) {
11110 error = got_error_from_errno("getcwd");
11111 goto done;
11114 error = got_worktree_open(&worktree, cwd);
11115 if (error) {
11116 if (error->code == GOT_ERR_NOT_WORKTREE)
11117 error = wrap_not_worktree_error(error, "integrate",
11118 cwd);
11119 goto done;
11122 error = check_rebase_or_histedit_in_progress(worktree);
11123 if (error)
11124 goto done;
11126 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11127 NULL);
11128 if (error != NULL)
11129 goto done;
11131 error = apply_unveil(got_repo_get_path(repo), 0,
11132 got_worktree_get_root_path(worktree));
11133 if (error)
11134 goto done;
11136 error = check_merge_in_progress(worktree, repo);
11137 if (error)
11138 goto done;
11140 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11141 error = got_error_from_errno("asprintf");
11142 goto done;
11145 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11146 &base_branch_ref, worktree, refname, repo);
11147 if (error)
11148 goto done;
11150 refname = strdup(got_ref_get_name(branch_ref));
11151 if (refname == NULL) {
11152 error = got_error_from_errno("strdup");
11153 got_worktree_integrate_abort(worktree, fileindex, repo,
11154 branch_ref, base_branch_ref);
11155 goto done;
11157 base_refname = strdup(got_ref_get_name(base_branch_ref));
11158 if (base_refname == NULL) {
11159 error = got_error_from_errno("strdup");
11160 got_worktree_integrate_abort(worktree, fileindex, repo,
11161 branch_ref, base_branch_ref);
11162 goto done;
11165 error = got_ref_resolve(&commit_id, repo, branch_ref);
11166 if (error)
11167 goto done;
11169 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11170 if (error)
11171 goto done;
11173 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11174 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11175 "specified branch has already been integrated");
11176 got_worktree_integrate_abort(worktree, fileindex, repo,
11177 branch_ref, base_branch_ref);
11178 goto done;
11181 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11182 if (error) {
11183 if (error->code == GOT_ERR_ANCESTRY)
11184 error = got_error(GOT_ERR_REBASE_REQUIRED);
11185 got_worktree_integrate_abort(worktree, fileindex, repo,
11186 branch_ref, base_branch_ref);
11187 goto done;
11190 memset(&upa, 0, sizeof(upa));
11191 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11192 branch_ref, base_branch_ref, update_progress, &upa,
11193 check_cancelled, NULL);
11194 if (error)
11195 goto done;
11197 printf("Integrated %s into %s\n", refname, base_refname);
11198 print_update_progress_stats(&upa);
11199 done:
11200 if (repo) {
11201 const struct got_error *close_err = got_repo_close(repo);
11202 if (error == NULL)
11203 error = close_err;
11205 if (worktree)
11206 got_worktree_close(worktree);
11207 free(cwd);
11208 free(base_commit_id);
11209 free(commit_id);
11210 free(refname);
11211 free(base_refname);
11212 return error;
11215 __dead static void
11216 usage_merge(void)
11218 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11219 getprogname());
11220 exit(1);
11223 static const struct got_error *
11224 cmd_merge(int argc, char *argv[])
11226 const struct got_error *error = NULL;
11227 struct got_worktree *worktree = NULL;
11228 struct got_repository *repo = NULL;
11229 struct got_fileindex *fileindex = NULL;
11230 char *cwd = NULL, *id_str = NULL, *author = NULL;
11231 struct got_reference *branch = NULL, *wt_branch = NULL;
11232 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11233 struct got_object_id *wt_branch_tip = NULL;
11234 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11235 int interrupt_merge = 0;
11236 struct got_update_progress_arg upa;
11237 struct got_object_id *merge_commit_id = NULL;
11238 char *branch_name = NULL;
11240 memset(&upa, 0, sizeof(upa));
11242 while ((ch = getopt(argc, argv, "acn")) != -1) {
11243 switch (ch) {
11244 case 'a':
11245 abort_merge = 1;
11246 break;
11247 case 'c':
11248 continue_merge = 1;
11249 break;
11250 case 'n':
11251 interrupt_merge = 1;
11252 break;
11253 default:
11254 usage_rebase();
11255 /* NOTREACHED */
11259 argc -= optind;
11260 argv += optind;
11262 #ifndef PROFILE
11263 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11264 "unveil", NULL) == -1)
11265 err(1, "pledge");
11266 #endif
11268 if (abort_merge && continue_merge)
11269 option_conflict('a', 'c');
11270 if (abort_merge || continue_merge) {
11271 if (argc != 0)
11272 usage_merge();
11273 } else if (argc != 1)
11274 usage_merge();
11276 cwd = getcwd(NULL, 0);
11277 if (cwd == NULL) {
11278 error = got_error_from_errno("getcwd");
11279 goto done;
11282 error = got_worktree_open(&worktree, cwd);
11283 if (error) {
11284 if (error->code == GOT_ERR_NOT_WORKTREE)
11285 error = wrap_not_worktree_error(error,
11286 "merge", cwd);
11287 goto done;
11290 error = got_repo_open(&repo,
11291 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL);
11292 if (error != NULL)
11293 goto done;
11295 error = apply_unveil(got_repo_get_path(repo), 0,
11296 worktree ? got_worktree_get_root_path(worktree) : NULL);
11297 if (error)
11298 goto done;
11300 error = check_rebase_or_histedit_in_progress(worktree);
11301 if (error)
11302 goto done;
11304 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11305 repo);
11306 if (error)
11307 goto done;
11309 if (abort_merge) {
11310 if (!merge_in_progress) {
11311 error = got_error(GOT_ERR_NOT_MERGING);
11312 goto done;
11314 error = got_worktree_merge_continue(&branch_name,
11315 &branch_tip, &fileindex, worktree, repo);
11316 if (error)
11317 goto done;
11318 error = got_worktree_merge_abort(worktree, fileindex, repo,
11319 abort_progress, &upa);
11320 if (error)
11321 goto done;
11322 printf("Merge of %s aborted\n", branch_name);
11323 goto done; /* nothing else to do */
11326 error = get_author(&author, repo, worktree);
11327 if (error)
11328 goto done;
11330 if (continue_merge) {
11331 if (!merge_in_progress) {
11332 error = got_error(GOT_ERR_NOT_MERGING);
11333 goto done;
11335 error = got_worktree_merge_continue(&branch_name,
11336 &branch_tip, &fileindex, worktree, repo);
11337 if (error)
11338 goto done;
11339 } else {
11340 error = got_ref_open(&branch, repo, argv[0], 0);
11341 if (error != NULL)
11342 goto done;
11343 branch_name = strdup(got_ref_get_name(branch));
11344 if (branch_name == NULL) {
11345 error = got_error_from_errno("strdup");
11346 goto done;
11348 error = got_ref_resolve(&branch_tip, repo, branch);
11349 if (error)
11350 goto done;
11353 error = got_ref_open(&wt_branch, repo,
11354 got_worktree_get_head_ref_name(worktree), 0);
11355 if (error)
11356 goto done;
11357 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
11358 if (error)
11359 goto done;
11360 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11361 wt_branch_tip, branch_tip, 0, repo,
11362 check_cancelled, NULL);
11363 if (error && error->code != GOT_ERR_ANCESTRY)
11364 goto done;
11366 if (!continue_merge) {
11367 error = check_path_prefix(wt_branch_tip, branch_tip,
11368 got_worktree_get_path_prefix(worktree),
11369 GOT_ERR_MERGE_PATH, repo);
11370 if (error)
11371 goto done;
11372 if (yca_id) {
11373 error = check_same_branch(wt_branch_tip, branch,
11374 yca_id, repo);
11375 if (error) {
11376 if (error->code != GOT_ERR_ANCESTRY)
11377 goto done;
11378 error = NULL;
11379 } else {
11380 static char msg[512];
11381 snprintf(msg, sizeof(msg),
11382 "cannot create a merge commit because "
11383 "%s is based on %s; %s can be integrated "
11384 "with 'got integrate' instead", branch_name,
11385 got_worktree_get_head_ref_name(worktree),
11386 branch_name);
11387 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
11388 goto done;
11391 error = got_worktree_merge_prepare(&fileindex, worktree,
11392 branch, repo);
11393 if (error)
11394 goto done;
11396 error = got_worktree_merge_branch(worktree, fileindex,
11397 yca_id, branch_tip, repo, update_progress, &upa,
11398 check_cancelled, NULL);
11399 if (error)
11400 goto done;
11401 print_merge_progress_stats(&upa);
11402 if (!upa.did_something) {
11403 error = got_worktree_merge_abort(worktree, fileindex,
11404 repo, abort_progress, &upa);
11405 if (error)
11406 goto done;
11407 printf("Already up-to-date\n");
11408 goto done;
11412 if (interrupt_merge) {
11413 error = got_worktree_merge_postpone(worktree, fileindex);
11414 if (error)
11415 goto done;
11416 printf("Merge of %s interrupted on request\n", branch_name);
11417 } else if (upa.conflicts > 0 || upa.missing > 0 ||
11418 upa.not_deleted > 0 || upa.unversioned > 0) {
11419 error = got_worktree_merge_postpone(worktree, fileindex);
11420 if (error)
11421 goto done;
11422 if (upa.conflicts > 0 && upa.missing == 0 &&
11423 upa.not_deleted == 0 && upa.unversioned == 0) {
11424 error = got_error_msg(GOT_ERR_CONFLICTS,
11425 "conflicts must be resolved before merging "
11426 "can continue");
11427 } else if (upa.conflicts > 0) {
11428 error = got_error_msg(GOT_ERR_CONFLICTS,
11429 "conflicts must be resolved before merging "
11430 "can continue; changes destined for some "
11431 "files were not yet merged and "
11432 "should be merged manually if required before the "
11433 "merge operation is continued");
11434 } else {
11435 error = got_error_msg(GOT_ERR_CONFLICTS,
11436 "changes destined for some "
11437 "files were not yet merged and should be "
11438 "merged manually if required before the "
11439 "merge operation is continued");
11441 goto done;
11442 } else {
11443 error = got_worktree_merge_commit(&merge_commit_id, worktree,
11444 fileindex, author, NULL, 1, branch_tip, branch_name,
11445 repo, continue_merge ? print_status : NULL, NULL);
11446 if (error)
11447 goto done;
11448 error = got_worktree_merge_complete(worktree, fileindex, repo);
11449 if (error)
11450 goto done;
11451 error = got_object_id_str(&id_str, merge_commit_id);
11452 if (error)
11453 goto done;
11454 printf("Merged %s into %s: %s\n", branch_name,
11455 got_worktree_get_head_ref_name(worktree),
11456 id_str);
11459 done:
11460 free(id_str);
11461 free(merge_commit_id);
11462 free(author);
11463 free(branch_tip);
11464 free(branch_name);
11465 free(yca_id);
11466 if (branch)
11467 got_ref_close(branch);
11468 if (wt_branch)
11469 got_ref_close(wt_branch);
11470 if (worktree)
11471 got_worktree_close(worktree);
11472 if (repo) {
11473 const struct got_error *close_err = got_repo_close(repo);
11474 if (error == NULL)
11475 error = close_err;
11477 return error;
11480 __dead static void
11481 usage_stage(void)
11483 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
11484 "[-S] [file-path ...]\n",
11485 getprogname());
11486 exit(1);
11489 static const struct got_error *
11490 print_stage(void *arg, unsigned char status, unsigned char staged_status,
11491 const char *path, struct got_object_id *blob_id,
11492 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
11493 int dirfd, const char *de_name)
11495 const struct got_error *err = NULL;
11496 char *id_str = NULL;
11498 if (staged_status != GOT_STATUS_ADD &&
11499 staged_status != GOT_STATUS_MODIFY &&
11500 staged_status != GOT_STATUS_DELETE)
11501 return NULL;
11503 if (staged_status == GOT_STATUS_ADD ||
11504 staged_status == GOT_STATUS_MODIFY)
11505 err = got_object_id_str(&id_str, staged_blob_id);
11506 else
11507 err = got_object_id_str(&id_str, blob_id);
11508 if (err)
11509 return err;
11511 printf("%s %c %s\n", id_str, staged_status, path);
11512 free(id_str);
11513 return NULL;
11516 static const struct got_error *
11517 cmd_stage(int argc, char *argv[])
11519 const struct got_error *error = NULL;
11520 struct got_repository *repo = NULL;
11521 struct got_worktree *worktree = NULL;
11522 char *cwd = NULL;
11523 struct got_pathlist_head paths;
11524 struct got_pathlist_entry *pe;
11525 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
11526 FILE *patch_script_file = NULL;
11527 const char *patch_script_path = NULL;
11528 struct choose_patch_arg cpa;
11530 TAILQ_INIT(&paths);
11532 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
11533 switch (ch) {
11534 case 'l':
11535 list_stage = 1;
11536 break;
11537 case 'p':
11538 pflag = 1;
11539 break;
11540 case 'F':
11541 patch_script_path = optarg;
11542 break;
11543 case 'S':
11544 allow_bad_symlinks = 1;
11545 break;
11546 default:
11547 usage_stage();
11548 /* NOTREACHED */
11552 argc -= optind;
11553 argv += optind;
11555 #ifndef PROFILE
11556 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11557 "unveil", NULL) == -1)
11558 err(1, "pledge");
11559 #endif
11560 if (list_stage && (pflag || patch_script_path))
11561 errx(1, "-l option cannot be used with other options");
11562 if (patch_script_path && !pflag)
11563 errx(1, "-F option can only be used together with -p option");
11565 cwd = getcwd(NULL, 0);
11566 if (cwd == NULL) {
11567 error = got_error_from_errno("getcwd");
11568 goto done;
11571 error = got_worktree_open(&worktree, cwd);
11572 if (error) {
11573 if (error->code == GOT_ERR_NOT_WORKTREE)
11574 error = wrap_not_worktree_error(error, "stage", cwd);
11575 goto done;
11578 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11579 NULL);
11580 if (error != NULL)
11581 goto done;
11583 if (patch_script_path) {
11584 patch_script_file = fopen(patch_script_path, "re");
11585 if (patch_script_file == NULL) {
11586 error = got_error_from_errno2("fopen",
11587 patch_script_path);
11588 goto done;
11591 error = apply_unveil(got_repo_get_path(repo), 0,
11592 got_worktree_get_root_path(worktree));
11593 if (error)
11594 goto done;
11596 error = check_merge_in_progress(worktree, repo);
11597 if (error)
11598 goto done;
11600 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11601 if (error)
11602 goto done;
11604 if (list_stage)
11605 error = got_worktree_status(worktree, &paths, repo, 0,
11606 print_stage, NULL, check_cancelled, NULL);
11607 else {
11608 cpa.patch_script_file = patch_script_file;
11609 cpa.action = "stage";
11610 error = got_worktree_stage(worktree, &paths,
11611 pflag ? NULL : print_status, NULL,
11612 pflag ? choose_patch : NULL, &cpa,
11613 allow_bad_symlinks, repo);
11615 done:
11616 if (patch_script_file && fclose(patch_script_file) == EOF &&
11617 error == NULL)
11618 error = got_error_from_errno2("fclose", patch_script_path);
11619 if (repo) {
11620 const struct got_error *close_err = got_repo_close(repo);
11621 if (error == NULL)
11622 error = close_err;
11624 if (worktree)
11625 got_worktree_close(worktree);
11626 TAILQ_FOREACH(pe, &paths, entry)
11627 free((char *)pe->path);
11628 got_pathlist_free(&paths);
11629 free(cwd);
11630 return error;
11633 __dead static void
11634 usage_unstage(void)
11636 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
11637 "[file-path ...]\n",
11638 getprogname());
11639 exit(1);
11643 static const struct got_error *
11644 cmd_unstage(int argc, char *argv[])
11646 const struct got_error *error = NULL;
11647 struct got_repository *repo = NULL;
11648 struct got_worktree *worktree = NULL;
11649 char *cwd = NULL;
11650 struct got_pathlist_head paths;
11651 struct got_pathlist_entry *pe;
11652 int ch, pflag = 0;
11653 struct got_update_progress_arg upa;
11654 FILE *patch_script_file = NULL;
11655 const char *patch_script_path = NULL;
11656 struct choose_patch_arg cpa;
11658 TAILQ_INIT(&paths);
11660 while ((ch = getopt(argc, argv, "pF:")) != -1) {
11661 switch (ch) {
11662 case 'p':
11663 pflag = 1;
11664 break;
11665 case 'F':
11666 patch_script_path = optarg;
11667 break;
11668 default:
11669 usage_unstage();
11670 /* NOTREACHED */
11674 argc -= optind;
11675 argv += optind;
11677 #ifndef PROFILE
11678 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11679 "unveil", NULL) == -1)
11680 err(1, "pledge");
11681 #endif
11682 if (patch_script_path && !pflag)
11683 errx(1, "-F option can only be used together with -p option");
11685 cwd = getcwd(NULL, 0);
11686 if (cwd == NULL) {
11687 error = got_error_from_errno("getcwd");
11688 goto done;
11691 error = got_worktree_open(&worktree, cwd);
11692 if (error) {
11693 if (error->code == GOT_ERR_NOT_WORKTREE)
11694 error = wrap_not_worktree_error(error, "unstage", cwd);
11695 goto done;
11698 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11699 NULL);
11700 if (error != NULL)
11701 goto done;
11703 if (patch_script_path) {
11704 patch_script_file = fopen(patch_script_path, "re");
11705 if (patch_script_file == NULL) {
11706 error = got_error_from_errno2("fopen",
11707 patch_script_path);
11708 goto done;
11712 error = apply_unveil(got_repo_get_path(repo), 0,
11713 got_worktree_get_root_path(worktree));
11714 if (error)
11715 goto done;
11717 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
11718 if (error)
11719 goto done;
11721 cpa.patch_script_file = patch_script_file;
11722 cpa.action = "unstage";
11723 memset(&upa, 0, sizeof(upa));
11724 error = got_worktree_unstage(worktree, &paths, update_progress,
11725 &upa, pflag ? choose_patch : NULL, &cpa, repo);
11726 if (!error)
11727 print_merge_progress_stats(&upa);
11728 done:
11729 if (patch_script_file && fclose(patch_script_file) == EOF &&
11730 error == NULL)
11731 error = got_error_from_errno2("fclose", patch_script_path);
11732 if (repo) {
11733 const struct got_error *close_err = got_repo_close(repo);
11734 if (error == NULL)
11735 error = close_err;
11737 if (worktree)
11738 got_worktree_close(worktree);
11739 TAILQ_FOREACH(pe, &paths, entry)
11740 free((char *)pe->path);
11741 got_pathlist_free(&paths);
11742 free(cwd);
11743 return error;
11746 __dead static void
11747 usage_cat(void)
11749 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
11750 "arg1 [arg2 ...]\n", getprogname());
11751 exit(1);
11754 static const struct got_error *
11755 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11757 const struct got_error *err;
11758 struct got_blob_object *blob;
11760 err = got_object_open_as_blob(&blob, repo, id, 8192);
11761 if (err)
11762 return err;
11764 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
11765 got_object_blob_close(blob);
11766 return err;
11769 static const struct got_error *
11770 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11772 const struct got_error *err;
11773 struct got_tree_object *tree;
11774 int nentries, i;
11776 err = got_object_open_as_tree(&tree, repo, id);
11777 if (err)
11778 return err;
11780 nentries = got_object_tree_get_nentries(tree);
11781 for (i = 0; i < nentries; i++) {
11782 struct got_tree_entry *te;
11783 char *id_str;
11784 if (sigint_received || sigpipe_received)
11785 break;
11786 te = got_object_tree_get_entry(tree, i);
11787 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
11788 if (err)
11789 break;
11790 fprintf(outfile, "%s %.7o %s\n", id_str,
11791 got_tree_entry_get_mode(te),
11792 got_tree_entry_get_name(te));
11793 free(id_str);
11796 got_object_tree_close(tree);
11797 return err;
11800 static void
11801 format_gmtoff(char *buf, size_t sz, time_t gmtoff)
11803 long long h, m;
11804 char sign = '+';
11806 if (gmtoff < 0) {
11807 sign = '-';
11808 gmtoff = -gmtoff;
11811 h = (long long)gmtoff / 3600;
11812 m = ((long long)gmtoff - h*3600) / 60;
11813 snprintf(buf, sz, "%c%02lld%02lld", sign, h, m);
11816 static const struct got_error *
11817 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11819 const struct got_error *err;
11820 struct got_commit_object *commit;
11821 const struct got_object_id_queue *parent_ids;
11822 struct got_object_qid *pid;
11823 char *id_str = NULL;
11824 const char *logmsg = NULL;
11825 char gmtoff[6];
11827 err = got_object_open_as_commit(&commit, repo, id);
11828 if (err)
11829 return err;
11831 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
11832 if (err)
11833 goto done;
11835 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
11836 parent_ids = got_object_commit_get_parent_ids(commit);
11837 fprintf(outfile, "numparents %d\n",
11838 got_object_commit_get_nparents(commit));
11839 STAILQ_FOREACH(pid, parent_ids, entry) {
11840 char *pid_str;
11841 err = got_object_id_str(&pid_str, &pid->id);
11842 if (err)
11843 goto done;
11844 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
11845 free(pid_str);
11847 format_gmtoff(gmtoff, sizeof(gmtoff),
11848 got_object_commit_get_author_gmtoff(commit));
11849 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
11850 got_object_commit_get_author(commit),
11851 (long long)got_object_commit_get_author_time(commit),
11852 gmtoff);
11854 format_gmtoff(gmtoff, sizeof(gmtoff),
11855 got_object_commit_get_committer_gmtoff(commit));
11856 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
11857 got_object_commit_get_author(commit),
11858 (long long)got_object_commit_get_committer_time(commit),
11859 gmtoff);
11861 logmsg = got_object_commit_get_logmsg_raw(commit);
11862 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
11863 fprintf(outfile, "%s", logmsg);
11864 done:
11865 free(id_str);
11866 got_object_commit_close(commit);
11867 return err;
11870 static const struct got_error *
11871 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
11873 const struct got_error *err;
11874 struct got_tag_object *tag;
11875 char *id_str = NULL;
11876 const char *tagmsg = NULL;
11877 char gmtoff[6];
11879 err = got_object_open_as_tag(&tag, repo, id);
11880 if (err)
11881 return err;
11883 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
11884 if (err)
11885 goto done;
11887 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
11889 switch (got_object_tag_get_object_type(tag)) {
11890 case GOT_OBJ_TYPE_BLOB:
11891 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11892 GOT_OBJ_LABEL_BLOB);
11893 break;
11894 case GOT_OBJ_TYPE_TREE:
11895 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11896 GOT_OBJ_LABEL_TREE);
11897 break;
11898 case GOT_OBJ_TYPE_COMMIT:
11899 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11900 GOT_OBJ_LABEL_COMMIT);
11901 break;
11902 case GOT_OBJ_TYPE_TAG:
11903 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
11904 GOT_OBJ_LABEL_TAG);
11905 break;
11906 default:
11907 break;
11910 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
11911 got_object_tag_get_name(tag));
11913 format_gmtoff(gmtoff, sizeof(gmtoff),
11914 got_object_tag_get_tagger_gmtoff(tag));
11915 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
11916 got_object_tag_get_tagger(tag),
11917 (long long)got_object_tag_get_tagger_time(tag),
11918 gmtoff);
11920 tagmsg = got_object_tag_get_message(tag);
11921 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
11922 fprintf(outfile, "%s", tagmsg);
11923 done:
11924 free(id_str);
11925 got_object_tag_close(tag);
11926 return err;
11929 static const struct got_error *
11930 cmd_cat(int argc, char *argv[])
11932 const struct got_error *error;
11933 struct got_repository *repo = NULL;
11934 struct got_worktree *worktree = NULL;
11935 char *cwd = NULL, *repo_path = NULL, *label = NULL;
11936 const char *commit_id_str = NULL;
11937 struct got_object_id *id = NULL, *commit_id = NULL;
11938 struct got_commit_object *commit = NULL;
11939 int ch, obj_type, i, force_path = 0;
11940 struct got_reflist_head refs;
11942 TAILQ_INIT(&refs);
11944 #ifndef PROFILE
11945 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
11946 NULL) == -1)
11947 err(1, "pledge");
11948 #endif
11950 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
11951 switch (ch) {
11952 case 'c':
11953 commit_id_str = optarg;
11954 break;
11955 case 'r':
11956 repo_path = realpath(optarg, NULL);
11957 if (repo_path == NULL)
11958 return got_error_from_errno2("realpath",
11959 optarg);
11960 got_path_strip_trailing_slashes(repo_path);
11961 break;
11962 case 'P':
11963 force_path = 1;
11964 break;
11965 default:
11966 usage_cat();
11967 /* NOTREACHED */
11971 argc -= optind;
11972 argv += optind;
11974 cwd = getcwd(NULL, 0);
11975 if (cwd == NULL) {
11976 error = got_error_from_errno("getcwd");
11977 goto done;
11980 if (repo_path == NULL) {
11981 error = got_worktree_open(&worktree, cwd);
11982 if (error && error->code != GOT_ERR_NOT_WORKTREE)
11983 goto done;
11984 if (worktree) {
11985 repo_path = strdup(
11986 got_worktree_get_repo_path(worktree));
11987 if (repo_path == NULL) {
11988 error = got_error_from_errno("strdup");
11989 goto done;
11992 /* Release work tree lock. */
11993 got_worktree_close(worktree);
11994 worktree = NULL;
11998 if (repo_path == NULL) {
11999 repo_path = strdup(cwd);
12000 if (repo_path == NULL)
12001 return got_error_from_errno("strdup");
12004 error = got_repo_open(&repo, repo_path, NULL);
12005 free(repo_path);
12006 if (error != NULL)
12007 goto done;
12009 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12010 if (error)
12011 goto done;
12013 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12014 if (error)
12015 goto done;
12017 if (commit_id_str == NULL)
12018 commit_id_str = GOT_REF_HEAD;
12019 error = got_repo_match_object_id(&commit_id, NULL,
12020 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12021 if (error)
12022 goto done;
12024 error = got_object_open_as_commit(&commit, repo, commit_id);
12025 if (error)
12026 goto done;
12028 for (i = 0; i < argc; i++) {
12029 if (force_path) {
12030 error = got_object_id_by_path(&id, repo, commit,
12031 argv[i]);
12032 if (error)
12033 break;
12034 } else {
12035 error = got_repo_match_object_id(&id, &label, argv[i],
12036 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12037 repo);
12038 if (error) {
12039 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12040 error->code != GOT_ERR_NOT_REF)
12041 break;
12042 error = got_object_id_by_path(&id, repo,
12043 commit, argv[i]);
12044 if (error)
12045 break;
12049 error = got_object_get_type(&obj_type, repo, id);
12050 if (error)
12051 break;
12053 switch (obj_type) {
12054 case GOT_OBJ_TYPE_BLOB:
12055 error = cat_blob(id, repo, stdout);
12056 break;
12057 case GOT_OBJ_TYPE_TREE:
12058 error = cat_tree(id, repo, stdout);
12059 break;
12060 case GOT_OBJ_TYPE_COMMIT:
12061 error = cat_commit(id, repo, stdout);
12062 break;
12063 case GOT_OBJ_TYPE_TAG:
12064 error = cat_tag(id, repo, stdout);
12065 break;
12066 default:
12067 error = got_error(GOT_ERR_OBJ_TYPE);
12068 break;
12070 if (error)
12071 break;
12072 free(label);
12073 label = NULL;
12074 free(id);
12075 id = NULL;
12077 done:
12078 free(label);
12079 free(id);
12080 free(commit_id);
12081 if (commit)
12082 got_object_commit_close(commit);
12083 if (worktree)
12084 got_worktree_close(worktree);
12085 if (repo) {
12086 const struct got_error *close_err = got_repo_close(repo);
12087 if (error == NULL)
12088 error = close_err;
12090 got_ref_list_free(&refs);
12091 return error;
12094 __dead static void
12095 usage_info(void)
12097 fprintf(stderr, "usage: %s info [path ...]\n",
12098 getprogname());
12099 exit(1);
12102 static const struct got_error *
12103 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12104 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12105 struct got_object_id *commit_id)
12107 const struct got_error *err = NULL;
12108 char *id_str = NULL;
12109 char datebuf[128];
12110 struct tm mytm, *tm;
12111 struct got_pathlist_head *paths = arg;
12112 struct got_pathlist_entry *pe;
12115 * Clear error indication from any of the path arguments which
12116 * would cause this file index entry to be displayed.
12118 TAILQ_FOREACH(pe, paths, entry) {
12119 if (got_path_cmp(path, pe->path, strlen(path),
12120 pe->path_len) == 0 ||
12121 got_path_is_child(path, pe->path, pe->path_len))
12122 pe->data = NULL; /* no error */
12125 printf(GOT_COMMIT_SEP_STR);
12126 if (S_ISLNK(mode))
12127 printf("symlink: %s\n", path);
12128 else if (S_ISREG(mode)) {
12129 printf("file: %s\n", path);
12130 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12131 } else if (S_ISDIR(mode))
12132 printf("directory: %s\n", path);
12133 else
12134 printf("something: %s\n", path);
12136 tm = localtime_r(&mtime, &mytm);
12137 if (tm == NULL)
12138 return NULL;
12139 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12140 return got_error(GOT_ERR_NO_SPACE);
12141 printf("timestamp: %s\n", datebuf);
12143 if (blob_id) {
12144 err = got_object_id_str(&id_str, blob_id);
12145 if (err)
12146 return err;
12147 printf("based on blob: %s\n", id_str);
12148 free(id_str);
12151 if (staged_blob_id) {
12152 err = got_object_id_str(&id_str, staged_blob_id);
12153 if (err)
12154 return err;
12155 printf("based on staged blob: %s\n", id_str);
12156 free(id_str);
12159 if (commit_id) {
12160 err = got_object_id_str(&id_str, commit_id);
12161 if (err)
12162 return err;
12163 printf("based on commit: %s\n", id_str);
12164 free(id_str);
12167 return NULL;
12170 static const struct got_error *
12171 cmd_info(int argc, char *argv[])
12173 const struct got_error *error = NULL;
12174 struct got_worktree *worktree = NULL;
12175 char *cwd = NULL, *id_str = NULL;
12176 struct got_pathlist_head paths;
12177 struct got_pathlist_entry *pe;
12178 char *uuidstr = NULL;
12179 int ch, show_files = 0;
12181 TAILQ_INIT(&paths);
12183 while ((ch = getopt(argc, argv, "")) != -1) {
12184 switch (ch) {
12185 default:
12186 usage_info();
12187 /* NOTREACHED */
12191 argc -= optind;
12192 argv += optind;
12194 #ifndef PROFILE
12195 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12196 NULL) == -1)
12197 err(1, "pledge");
12198 #endif
12199 cwd = getcwd(NULL, 0);
12200 if (cwd == NULL) {
12201 error = got_error_from_errno("getcwd");
12202 goto done;
12205 error = got_worktree_open(&worktree, cwd);
12206 if (error) {
12207 if (error->code == GOT_ERR_NOT_WORKTREE)
12208 error = wrap_not_worktree_error(error, "info", cwd);
12209 goto done;
12212 #ifndef PROFILE
12213 /* Remove "cpath" promise. */
12214 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12215 NULL) == -1)
12216 err(1, "pledge");
12217 #endif
12218 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12219 if (error)
12220 goto done;
12222 if (argc >= 1) {
12223 error = get_worktree_paths_from_argv(&paths, argc, argv,
12224 worktree);
12225 if (error)
12226 goto done;
12227 show_files = 1;
12230 error = got_object_id_str(&id_str,
12231 got_worktree_get_base_commit_id(worktree));
12232 if (error)
12233 goto done;
12235 error = got_worktree_get_uuid(&uuidstr, worktree);
12236 if (error)
12237 goto done;
12239 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12240 printf("work tree base commit: %s\n", id_str);
12241 printf("work tree path prefix: %s\n",
12242 got_worktree_get_path_prefix(worktree));
12243 printf("work tree branch reference: %s\n",
12244 got_worktree_get_head_ref_name(worktree));
12245 printf("work tree UUID: %s\n", uuidstr);
12246 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12248 if (show_files) {
12249 struct got_pathlist_entry *pe;
12250 TAILQ_FOREACH(pe, &paths, entry) {
12251 if (pe->path_len == 0)
12252 continue;
12254 * Assume this path will fail. This will be corrected
12255 * in print_path_info() in case the path does suceeed.
12257 pe->data = (void *)got_error_path(pe->path,
12258 GOT_ERR_BAD_PATH);
12260 error = got_worktree_path_info(worktree, &paths,
12261 print_path_info, &paths, check_cancelled, NULL);
12262 if (error)
12263 goto done;
12264 TAILQ_FOREACH(pe, &paths, entry) {
12265 if (pe->data != NULL) {
12266 error = pe->data; /* bad path */
12267 break;
12271 done:
12272 TAILQ_FOREACH(pe, &paths, entry)
12273 free((char *)pe->path);
12274 got_pathlist_free(&paths);
12275 free(cwd);
12276 free(id_str);
12277 free(uuidstr);
12278 return error;